url
stringlengths 24
122
| repo_url
stringlengths 60
156
| date_extracted
stringdate 2025-08-13 00:00:00
2025-08-13 00:00:00
| root
stringlengths 3
85
| breadcrumbs
listlengths 1
6
| filename
stringlengths 6
60
| stage
stringclasses 33
values | group
stringclasses 81
values | info
stringclasses 22
values | title
stringlengths 3
110
⌀ | description
stringlengths 11
359
⌀ | clean_text
stringlengths 47
3.32M
| rich_text
stringlengths 321
3.32M
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|
https://docs.gitlab.com/development/test_results_tracking
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/test_results_tracking.md
|
2025-08-13
|
doc/development/testing_guide
|
[
"doc",
"development",
"testing_guide"
] |
test_results_tracking.md
|
none
|
unassigned
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Test results tracking
| null |
We developed the [`gitlab_quality-test_tooling`](https://gitlab.com/gitlab-org/ruby/gems/gitlab_quality-test_tooling) gem that includes several commands to automate test results tracking.
The goal of this gem is to have a consolidated set of tooling that we use across our various test suite (for example, GitLab Rails & E2E test suites).
The initial motivation and development was tracked by [this epic](https://gitlab.com/groups/gitlab-org/-/epics/10536).
## Rails test results tracking
We [plan to use](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/122008) the `relate-failure-issue` command from the gem (see the gem's README for details about the command).
## End-to-end test results tracking
This is described specifically in [Test results tracking](https://handbook.gitlab.com/handbook/engineering/quality/#test-results-tracking/).
For the E2E test suite, we use the following commands from the gem (see the gem's README for details about each command):
- `prepare-stage-reports`
- `generate-test-session`
- `report-results`
- `update-screenshot-paths`
- `relate-failure-issue`
|
---
stage: none
group: unassigned
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: Test results tracking
breadcrumbs:
- doc
- development
- testing_guide
---
We developed the [`gitlab_quality-test_tooling`](https://gitlab.com/gitlab-org/ruby/gems/gitlab_quality-test_tooling) gem that includes several commands to automate test results tracking.
The goal of this gem is to have a consolidated set of tooling that we use across our various test suite (for example, GitLab Rails & E2E test suites).
The initial motivation and development was tracked by [this epic](https://gitlab.com/groups/gitlab-org/-/epics/10536).
## Rails test results tracking
We [plan to use](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/122008) the `relate-failure-issue` command from the gem (see the gem's README for details about the command).
## End-to-end test results tracking
This is described specifically in [Test results tracking](https://handbook.gitlab.com/handbook/engineering/quality/#test-results-tracking/).
For the E2E test suite, we use the following commands from the gem (see the gem's README for details about each command):
- `prepare-stage-reports`
- `generate-test-session`
- `report-results`
- `update-screenshot-paths`
- `relate-failure-issue`
|
https://docs.gitlab.com/development/smoke
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/smoke.md
|
2025-08-13
|
doc/development/testing_guide
|
[
"doc",
"development",
"testing_guide"
] |
smoke.md
|
none
|
unassigned
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Smoke Tests
| null |
It is imperative in any testing suite that we have Smoke Tests. In short, smoke
tests run quick end-to-end functional tests from GitLab QA and are
designed to run against the specified environment to ensure that basic
functionality is working.
Our suite consists of this basic functionality coverage:
- User standard authentication
- SSH Key creation and addition to a user
- Project simple creation
- Project creation with Auto-DevOps enabled
- Issue creation
- Issue user mentions
- Merge Request creation
- Snippet creation
Smoke tests have the `:smoke` RSpec metadata.
## Health check suite
This is a very small subset smoke tests with the `:health_check` RSpec metadata.
Its function is to monitor the status and health of the application.
See [End-to-end Testing](end_to_end/_index.md) for more details about
end-to-end tests.
---
[Return to Testing documentation](_index.md)
|
---
stage: none
group: unassigned
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: Smoke Tests
breadcrumbs:
- doc
- development
- testing_guide
---
It is imperative in any testing suite that we have Smoke Tests. In short, smoke
tests run quick end-to-end functional tests from GitLab QA and are
designed to run against the specified environment to ensure that basic
functionality is working.
Our suite consists of this basic functionality coverage:
- User standard authentication
- SSH Key creation and addition to a user
- Project simple creation
- Project creation with Auto-DevOps enabled
- Issue creation
- Issue user mentions
- Merge Request creation
- Snippet creation
Smoke tests have the `:smoke` RSpec metadata.
## Health check suite
This is a very small subset smoke tests with the `:health_check` RSpec metadata.
Its function is to monitor the status and health of the application.
See [End-to-end Testing](end_to_end/_index.md) for more details about
end-to-end tests.
---
[Return to Testing documentation](_index.md)
|
https://docs.gitlab.com/development/testing_ai_features
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/testing_ai_features.md
|
2025-08-13
|
doc/development/testing_guide
|
[
"doc",
"development",
"testing_guide"
] |
testing_ai_features.md
|
none
|
unassigned
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Testing AI features
| null |
This document highlights AI-specific testing considerations that complement GitLab standard [testing guidelines](_index.md). It focuses on the challenges AI features bring to testing, such as non-deterministic responses from third-party providers. Examples are included for each [testing level](testing_levels.md).
AI-powered features depend on system components outside the GitLab monolith, such as the [AI Gateway](https://gitlab.com/gitlab-org/modelops/applied-ml/code-suggestions/ai-assist) and IDE extensions.
In addition to these guidelines, consult any testing guidelines documented in each component project.
## Unit testing
Follow standard [unit testing guidelines](testing_levels.md#unit-tests). For AI features, always mock third-party AI provider calls to ensure fast, reliable tests.
### Unit test examples
- GitLab: [`ee/spec/lib/code_suggestions/tasks/code_completion_spec.rb`](https://gitlab.com/gitlab-org/gitlab/-/blob/904dfcf962234e18f1eef395507e959b42d17251/ee/spec/lib/code_suggestions/tasks/code_completion_spec.rb)
- VS Code extension: [`code_suggestions/code_suggestions.test.ts`](https://gitlab.com/gitlab-org/gitlab-vscode-extension/-/blob/adedfb4189de63e7041c18e5657c048b1adfc28a/src/common/code_suggestions/code_suggestions.test.ts)
## Integration tests
Use [integration tests](testing_levels.md#integration-tests) to verify request construction and response handling for AI providers. Mock AI provider responses to ensure predictable, fast tests that handle various responses, errors, and status codes.
### Integration test examples
- GitLab: [`ee/spec/requests/api/code_suggestions_spec.rb`](https://gitlab.com/gitlab-org/gitlab/-/blob/57d17110ef8f137ec8c1507e8d1a60ec194d6876/ee/spec/requests/api/code_suggestions_spec.rb)
- VS Code extension: [`main/test/integration/chat.test.js`](https://gitlab.com/gitlab-org/gitlab-vscode-extension/-/blob/adedfb4189de63e7041c18e5657c048b1adfc28a/test/integration/chat.test.js)
## Frontend feature tests
Use [frontend feature tests](testing_levels.md#frontend-feature-tests) to validate AI features from an end-user perspective. Mock AI providers to maintain speed and reliability. Focus on happy paths with selective negative path testing for high-risk scenarios.
### Frontend feature test example
- GitLab Duo Chat: [`ee/spec/features/duo_chat_spec.rb`](https://gitlab.com/gitlab-org/gitlab/-/blob/57d17110ef8f137ec8c1507e8d1a60ec194d6876/ee/spec/features/duo_chat_spec.rb)
## End-to-End testing
Use [end-to-end tests](end_to_end/_index.md) sparingly to verify AI features work with real provider responses. Key considerations:
- Keep tests minimal due to slower execution and potential provider outages.
- Account for non-deterministic AI responses in test design. For example, use deterministic assertions on controlled elements like chatbot names, not AI-generated content.
### E2E test examples
- GitLab: [`specs/features/ee/browser_ui/3_create/web_ide/code_suggestions_in_web_ide_spec.rb`](https://gitlab.com/gitlab-org/gitlab/-/blob/57d17110ef8f137ec8c1507e8d1a60ec194d6876/qa/qa/specs/features/ee/browser_ui/3_create/web_ide/code_suggestions_in_web_ide_spec.rb)
- JetBrains:
[`test/kotlin/com/gitlab/plugin/e2eTest/tests/CodeSuggestionTest.kt`](https://gitlab.com/gitlab-org/editor-extensions/gitlab-jetbrains-plugin/-/blob/72bf52a7a652794546e7def85ea30a6fdd40a6f9/src/test/kotlin/com/gitlab/plugin/e2eTest/tests/CodeSuggestionTest.kt)
### Live environment testing
- **GitLab.com**: We run minimal E2E tests continuously against staging and production environments. For example, [Code Suggestions smoke tests](https://gitlab.com/gitlab-org/gitlab/-/blob/57d17110ef8f137ec8c1507e8d1a60ec194d6876/qa/qa/specs/features/ee/browser_ui/3_create/web_ide/code_suggestions_in_web_ide_spec.rb#L75).
- **GitLab Self-Managed**: We use the [`gitlab-qa`](https://gitlab.com/gitlab-org/gitlab-qa) orchestrator with [AI Gateway scenarios](https://gitlab.com/gitlab-org/gitlab-qa/-/blob/master/docs/what_tests_can_be_run.md#aigateway-scenarios) to test AI features on GitLab Self-Managed instances.
## Exploratory testing
Perform exploratory testing before significant milestones to uncover bugs outside expected workflows and UX issues. This is especially important for AI features as they progress through experiment, beta, and GA phases.
## Dogfooding
We [dogfood](https://handbook.gitlab.com/handbook/engineering/development/principles/#dogfooding) everything. This is especially important for AI features given the rapidly changing nature of the field. See the [dogfooding process](https://handbook.gitlab.com/handbook/product/product-processes/dogfooding-for-r-d/) for details.
|
---
stage: none
group: unassigned
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: Testing AI features
breadcrumbs:
- doc
- development
- testing_guide
---
This document highlights AI-specific testing considerations that complement GitLab standard [testing guidelines](_index.md). It focuses on the challenges AI features bring to testing, such as non-deterministic responses from third-party providers. Examples are included for each [testing level](testing_levels.md).
AI-powered features depend on system components outside the GitLab monolith, such as the [AI Gateway](https://gitlab.com/gitlab-org/modelops/applied-ml/code-suggestions/ai-assist) and IDE extensions.
In addition to these guidelines, consult any testing guidelines documented in each component project.
## Unit testing
Follow standard [unit testing guidelines](testing_levels.md#unit-tests). For AI features, always mock third-party AI provider calls to ensure fast, reliable tests.
### Unit test examples
- GitLab: [`ee/spec/lib/code_suggestions/tasks/code_completion_spec.rb`](https://gitlab.com/gitlab-org/gitlab/-/blob/904dfcf962234e18f1eef395507e959b42d17251/ee/spec/lib/code_suggestions/tasks/code_completion_spec.rb)
- VS Code extension: [`code_suggestions/code_suggestions.test.ts`](https://gitlab.com/gitlab-org/gitlab-vscode-extension/-/blob/adedfb4189de63e7041c18e5657c048b1adfc28a/src/common/code_suggestions/code_suggestions.test.ts)
## Integration tests
Use [integration tests](testing_levels.md#integration-tests) to verify request construction and response handling for AI providers. Mock AI provider responses to ensure predictable, fast tests that handle various responses, errors, and status codes.
### Integration test examples
- GitLab: [`ee/spec/requests/api/code_suggestions_spec.rb`](https://gitlab.com/gitlab-org/gitlab/-/blob/57d17110ef8f137ec8c1507e8d1a60ec194d6876/ee/spec/requests/api/code_suggestions_spec.rb)
- VS Code extension: [`main/test/integration/chat.test.js`](https://gitlab.com/gitlab-org/gitlab-vscode-extension/-/blob/adedfb4189de63e7041c18e5657c048b1adfc28a/test/integration/chat.test.js)
## Frontend feature tests
Use [frontend feature tests](testing_levels.md#frontend-feature-tests) to validate AI features from an end-user perspective. Mock AI providers to maintain speed and reliability. Focus on happy paths with selective negative path testing for high-risk scenarios.
### Frontend feature test example
- GitLab Duo Chat: [`ee/spec/features/duo_chat_spec.rb`](https://gitlab.com/gitlab-org/gitlab/-/blob/57d17110ef8f137ec8c1507e8d1a60ec194d6876/ee/spec/features/duo_chat_spec.rb)
## End-to-End testing
Use [end-to-end tests](end_to_end/_index.md) sparingly to verify AI features work with real provider responses. Key considerations:
- Keep tests minimal due to slower execution and potential provider outages.
- Account for non-deterministic AI responses in test design. For example, use deterministic assertions on controlled elements like chatbot names, not AI-generated content.
### E2E test examples
- GitLab: [`specs/features/ee/browser_ui/3_create/web_ide/code_suggestions_in_web_ide_spec.rb`](https://gitlab.com/gitlab-org/gitlab/-/blob/57d17110ef8f137ec8c1507e8d1a60ec194d6876/qa/qa/specs/features/ee/browser_ui/3_create/web_ide/code_suggestions_in_web_ide_spec.rb)
- JetBrains:
[`test/kotlin/com/gitlab/plugin/e2eTest/tests/CodeSuggestionTest.kt`](https://gitlab.com/gitlab-org/editor-extensions/gitlab-jetbrains-plugin/-/blob/72bf52a7a652794546e7def85ea30a6fdd40a6f9/src/test/kotlin/com/gitlab/plugin/e2eTest/tests/CodeSuggestionTest.kt)
### Live environment testing
- **GitLab.com**: We run minimal E2E tests continuously against staging and production environments. For example, [Code Suggestions smoke tests](https://gitlab.com/gitlab-org/gitlab/-/blob/57d17110ef8f137ec8c1507e8d1a60ec194d6876/qa/qa/specs/features/ee/browser_ui/3_create/web_ide/code_suggestions_in_web_ide_spec.rb#L75).
- **GitLab Self-Managed**: We use the [`gitlab-qa`](https://gitlab.com/gitlab-org/gitlab-qa) orchestrator with [AI Gateway scenarios](https://gitlab.com/gitlab-org/gitlab-qa/-/blob/master/docs/what_tests_can_be_run.md#aigateway-scenarios) to test AI features on GitLab Self-Managed instances.
## Exploratory testing
Perform exploratory testing before significant milestones to uncover bugs outside expected workflows and UX issues. This is especially important for AI features as they progress through experiment, beta, and GA phases.
## Dogfooding
We [dogfood](https://handbook.gitlab.com/handbook/engineering/development/principles/#dogfooding) everything. This is especially important for AI features given the rapidly changing nature of the field. See the [dogfooding process](https://handbook.gitlab.com/handbook/product/product-processes/dogfooding-for-r-d/) for details.
|
https://docs.gitlab.com/development/testing_migrations_guide
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/testing_migrations_guide.md
|
2025-08-13
|
doc/development/testing_guide
|
[
"doc",
"development",
"testing_guide"
] |
testing_migrations_guide.md
|
none
|
unassigned
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Testing Rails migrations at GitLab
| null |
In order to reliably check Rails migrations, we need to test them against
a database schema.
## When to write a migration test
- Post migrations (`/db/post_migrate`) and background migrations
(`lib/gitlab/background_migration`) **must** have migration tests performed.
- If your migration is a data migration then it **must** have a migration test.
- Other migrations may have a migration test if necessary.
We don't enforce tests on post migrations that only perform schema changes.
## How does it work?
All specs in `(ee/)spec/migrations/` and `spec/lib/(ee/)background_migrations` are automatically
tagged with the `:migration` RSpec tag. This tag enables some custom RSpec
`before` and `after` hooks in our
[`spec/support/migration.rb`](https://gitlab.com/gitlab-org/gitlab/-/blob/f81fa6ab1dd788b70ef44b85aaba1f31ffafae7d/spec/support/migration.rb)
to run. If performing a migration against a database schema other than
`:gitlab_main` (for example `:gitlab_ci`), then you must explicitly specify it
with an RSpec tag like: `migration: :gitlab_ci`. See
[spec/migrations/change_public_projects_cost_factor_spec.rb](https://gitlab.com/gitlab-org/gitlab/blob/master/spec/migrations/change_public_projects_cost_factor_spec.rb#L6-6)
for an example.
A `before` hook reverts all migrations to the point that a migration
under test is not yet migrated.
In other words, our custom RSpec hooks finds a previous migration, and
migrate the database **down** to the previous migration version.
With this approach you can test a migration against a database schema.
An `after` hook migrates the database **up** and restores the latest
schema version, so that the process does not affect subsequent specs and
ensures proper isolation.
## Testing an `ActiveRecord::Migration` class
To test an `ActiveRecord::Migration` class (for example, a
regular migration `db/migrate` or a post-migration `db/post_migrate`), you
must load the migration file by using the `require_migration!` helper
method because it is not autoloaded by Rails.
Example:
```ruby
require 'spec_helper'
require_migration!
RSpec.describe ...
```
### Test helpers
#### `require_migration!`
Since the migration files are not autoloaded by Rails, you must manually
load the migration file. To do so, you can use the `require_migration!` helper method
which can automatically load the correct migration file based on the spec filename.
You can use `require_migration!` to load migration files from spec files
that contain the schema version in the filename (for example,
`2021101412150000_populate_foo_column_spec.rb`).
```ruby
# frozen_string_literal: true
require 'spec_helper'
require_migration!
RSpec.describe PopulateFooColumn do
...
end
```
In some cases, you must require multiple migration files to use them in your specs. Here, there's no
pattern between your spec file and the other migration file. You can provide the migration filename like so:
```ruby
# frozen_string_literal: true
require 'spec_helper'
require_migration!
require_migration!('populate_bar_column')
RSpec.describe PopulateFooColumn do
...
end
```
#### `table`
Use the `table` helper to create a temporary `ActiveRecord::Base`-derived model
for a table. [FactoryBot](best_practices.md#factories)
**should not** be used to create data for migration specs because it relies on
application code which can change after the migration has run, and cause the test
to fail. For example, to create a record in the `projects` table:
```ruby
project = table(:projects).create!(name: 'gitlab1', path: 'gitlab1')
```
#### `migrate!`
Use the `migrate!` helper to run the migration that is under test. It
runs the migration and bumps the schema version in the `schema_migrations`
table. It is necessary because in the `after` hook we trigger the rest of
the migrations, and we need to know where to start. Example:
```ruby
it 'migrates successfully' do
# ... pre-migration expectations
migrate!
# ... post-migration expectations
end
```
#### `reversible_migration`
Use the `reversible_migration` helper to test migrations with either a
`change` or both `up` and `down` hooks. This tests that the state of
the application and its data after the migration becomes reversed is the
same as it was before the migration ran in the first place. The helper:
1. Runs the `before` expectations before the **up** migration.
1. Migrates **up**.
1. Runs the `after` expectations.
1. Migrates **down**.
1. Runs the `before` expectations a second time.
Example:
```ruby
reversible_migration do |migration|
migration.before -> {
# ... pre-migration expectations
}
migration.after -> {
# ... post-migration expectations
}
end
```
### Custom matchers for post-deployment migrations
We have some custom matchers in
[`spec/support/matchers/background_migrations_matchers.rb`](https://gitlab.com/gitlab-org/gitlab/blob/v14.1.0-ee/spec/support/matchers/background_migrations_matchers.rb)
to verify background migrations were correctly scheduled from a post-deployment migration, and
receive the correct number of arguments.
All of them use the internal matcher `be_background_migration_with_arguments`, which verifies that
the `#perform` method on your migration class doesn't crash when receiving the provided arguments.
#### `be_scheduled_migration`
Verifies that a Sidekiq job was queued with the expected class and arguments.
This matcher usually makes sense if you're queueing jobs manually, rather than going through our helpers.
```ruby
# Migration
BackgroundMigrationWorker.perform_async('MigrationClass', args)
# Spec
expect('MigrationClass').to be_scheduled_migration(*args)
```
#### `be_scheduled_migration_with_multiple_args`
Verifies that a Sidekiq job was queued with the expected class and arguments.
This works the same as `be_scheduled_migration`, except that the order is ignored when comparing
array arguments.
```ruby
# Migration
BackgroundMigrationWorker.perform_async('MigrationClass', ['foo', [3, 2, 1]])
# Spec
expect('MigrationClass').to be_scheduled_migration_with_multiple_args('foo', [1, 2, 3])
```
#### `be_scheduled_delayed_migration`
Verifies that a Sidekiq job was queued with the expected delay, class, and arguments.
This can also be used with `queue_background_migration_jobs_by_range_at_intervals` and related helpers.
```ruby
# Migration
BackgroundMigrationWorker.perform_in(delay, 'MigrationClass', args)
# Spec
expect('MigrationClass').to be_scheduled_delayed_migration(delay, *args)
```
#### `have_scheduled_batched_migration`
Verifies that a `BatchedMigration` record was created with the expected class and arguments.
The `*args` are additional arguments passed to the `MigrationClass`, while `**kwargs` are any other
attributes to be verified on the `BatchedMigration` record (Example: `interval: 2.minutes`).
```ruby
# Migration
queue_batched_background_migration(
'MigrationClass',
table_name,
column_name,
*args,
**kwargs
)
# Spec
expect('MigrationClass').to have_scheduled_batched_migration(
table_name: table_name,
column_name: column_name,
job_arguments: args,
**kwargs
)
```
#### `be_finalize_background_migration_of`
Verifies that a migration calls `finalize_background_migration` with the expected background migration class.
```ruby
# Migration
finalize_background_migration('MigrationClass')
# Spec
expect(described_class).to be_finalize_background_migration_of('MigrationClass')
```
### Examples of migration tests
Migration tests depend on what the migration does exactly, the most common types are data migrations and scheduling background migrations.
#### Example of a data migration test
This spec tests the
[`db/post_migrate/20200723040950_migrate_incident_issues_to_incident_type.rb`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/db/post_migrate/20200723040950_migrate_incident_issues_to_incident_type.rb)
migration. You can find the complete spec in
[`spec/migrations/migrate_incident_issues_to_incident_type_spec.rb`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/spec/migrations/migrate_incident_issues_to_incident_type_spec.rb).
```ruby
# frozen_string_literal: true
require 'spec_helper'
require_migration!
RSpec.describe MigrateIncidentIssuesToIncidentType do
let(:migration) { described_class.new }
let(:projects) { table(:projects) }
let(:namespaces) { table(:namespaces) }
let(:labels) { table(:labels) }
let(:issues) { table(:issues) }
let(:label_links) { table(:label_links) }
let(:label_props) { IncidentManagement::CreateIncidentLabelService::LABEL_PROPERTIES }
let(:namespace) { namespaces.create!(name: 'foo', path: 'foo') }
let!(:project) { projects.create!(namespace_id: namespace.id) }
let(:label) { labels.create!(project_id: project.id, **label_props) }
let!(:incident_issue) { issues.create!(project_id: project.id) }
let!(:other_issue) { issues.create!(project_id: project.id) }
# Issue issue_type enum
let(:issue_type) { 0 }
let(:incident_type) { 1 }
before do
label_links.create!(target_id: incident_issue.id, label_id: label.id, target_type: 'Issue')
end
describe '#up' do
it 'updates the incident issue type' do
expect { migrate! }
.to change { incident_issue.reload.issue_type }
.from(issue_type)
.to(incident_type)
expect(other_issue.reload.issue_type).to eq(issue_type)
end
end
describe '#down' do
let!(:incident_issue) { issues.create!(project_id: project.id, issue_type: issue_type) }
it 'updates the incident issue type' do
migration.up
expect { migration.down }
.to change { incident_issue.reload.issue_type }
.from(incident_type)
.to(issue_type)
expect(other_issue.reload.issue_type).to eql(issue_type)
end
end
end
```
#### Example of a background migration scheduling test
To test these you usually have to:
- Create some records.
- Run the migration.
- Verify that the expected jobs were scheduled, with the correct set
of records, the correct batch size, interval, etc.
The behavior of the background migration itself needs to be verified in a
[separate test for the background migration class](#example-background-migration-test).
This spec tests the
[`db/post_migrate/20210701111909_backfill_issues_upvotes_count.rb`](https://gitlab.com/gitlab-org/gitlab/-/blob/v14.1.0-ee/db/post_migrate/20210701111909_backfill_issues_upvotes_count.rb)
post-deployment migration. You can find the complete spec in
[`spec/migrations/backfill_issues_upvotes_count_spec.rb`](https://gitlab.com/gitlab-org/gitlab/blob/v14.1.0-ee/spec/spec/migrations/backfill_issues_upvotes_count_spec.rb).
```ruby
require 'spec_helper'
require_migration!
RSpec.describe BackfillIssuesUpvotesCount do
let(:migration) { described_class.new }
let(:issues) { table(:issues) }
let(:award_emoji) { table(:award_emoji) }
let!(:issue1) { issues.create! }
let!(:issue2) { issues.create! }
let!(:issue3) { issues.create! }
let!(:issue4) { issues.create! }
let!(:issue4_without_thumbsup) { issues.create! }
let!(:award_emoji1) { award_emoji.create!( name: 'thumbsup', awardable_type: 'Issue', awardable_id: issue1.id) }
let!(:award_emoji2) { award_emoji.create!( name: 'thumbsup', awardable_type: 'Issue', awardable_id: issue2.id) }
let!(:award_emoji3) { award_emoji.create!( name: 'thumbsup', awardable_type: 'Issue', awardable_id: issue3.id) }
let!(:award_emoji4) { award_emoji.create!( name: 'thumbsup', awardable_type: 'Issue', awardable_id: issue4.id) }
it 'correctly schedules background migrations', :aggregate_failures do
stub_const("#{described_class.name}::BATCH_SIZE", 2)
Sidekiq::Testing.fake! do
freeze_time do
migrate!
expect(described_class::MIGRATION).to be_scheduled_migration(issue1.id, issue2.id)
expect(described_class::MIGRATION).to be_scheduled_migration(issue3.id, issue4.id)
expect(BackgroundMigrationWorker.jobs.size).to eq(2)
end
end
end
end
```
## Testing a non-`ActiveRecord::Migration` class
To test a non-`ActiveRecord::Migration` test (a background migration),
you must manually provide a required schema version. Add a
`schema` tag to a context that you want to switch the database schema within.
If not set, `schema` defaults to `:latest`.
Example:
```ruby
describe SomeClass, schema: 20170608152748 do
# ...
end
```
### Example background migration test
This spec tests the
[`lib/gitlab/background_migration/backfill_draft_status_on_merge_requests.rb`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/lib/gitlab/background_migration/backfill_draft_status_on_merge_requests.rb)
background migration. You can find the complete spec on
[`spec/lib/gitlab/background_migration/backfill_draft_status_on_merge_requests_spec.rb`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/spec/lib/gitlab/background_migration/backfill_draft_status_on_merge_requests_spec.rb)
```ruby
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe Gitlab::BackgroundMigration::BackfillDraftStatusOnMergeRequests do
let(:namespaces) { table(:namespaces) }
let(:projects) { table(:projects) }
let(:merge_requests) { table(:merge_requests) }
let(:group) { namespaces.create!(name: 'gitlab', path: 'gitlab') }
let(:project) { projects.create!(namespace_id: group.id) }
let(:draft_prefixes) { ["[Draft]", "(Draft)", "Draft:", "Draft", "[WIP]", "WIP:", "WIP"] }
def create_merge_request(params)
common_params = {
target_project_id: project.id,
target_branch: 'feature1',
source_branch: 'master'
}
merge_requests.create!(common_params.merge(params))
end
context "for MRs with #draft? == true titles but draft attribute false" do
let(:mr_ids) { merge_requests.all.collect(&:id) }
before do
draft_prefixes.each do |prefix|
(1..4).each do |n|
create_merge_request(
title: "#{prefix} This is a title",
draft: false,
state_id: n
)
end
end
end
it "updates all open draft merge request's draft field to true" do
mr_count = merge_requests.all.count
expect { subject.perform(mr_ids.first, mr_ids.last) }
.to change { MergeRequest.where(draft: false).count }
.from(mr_count).to(mr_count - draft_prefixes.length)
end
it "marks successful slices as completed" do
expect(subject).to receive(:mark_job_as_succeeded).with(mr_ids.first, mr_ids.last)
subject.perform(mr_ids.first, mr_ids.last)
end
end
end
```
These tests do not run within a database transaction, as we use a deletion database
cleanup strategy. Do not depend on a transaction being present.
When testing migrations that alter seeded data in `deletion_except_tables`, you may add the
`:migration_with_transaction` metadata so the test runs within a transaction and the data
is rolled back to their original values.
|
---
stage: none
group: unassigned
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: Testing Rails migrations at GitLab
breadcrumbs:
- doc
- development
- testing_guide
---
In order to reliably check Rails migrations, we need to test them against
a database schema.
## When to write a migration test
- Post migrations (`/db/post_migrate`) and background migrations
(`lib/gitlab/background_migration`) **must** have migration tests performed.
- If your migration is a data migration then it **must** have a migration test.
- Other migrations may have a migration test if necessary.
We don't enforce tests on post migrations that only perform schema changes.
## How does it work?
All specs in `(ee/)spec/migrations/` and `spec/lib/(ee/)background_migrations` are automatically
tagged with the `:migration` RSpec tag. This tag enables some custom RSpec
`before` and `after` hooks in our
[`spec/support/migration.rb`](https://gitlab.com/gitlab-org/gitlab/-/blob/f81fa6ab1dd788b70ef44b85aaba1f31ffafae7d/spec/support/migration.rb)
to run. If performing a migration against a database schema other than
`:gitlab_main` (for example `:gitlab_ci`), then you must explicitly specify it
with an RSpec tag like: `migration: :gitlab_ci`. See
[spec/migrations/change_public_projects_cost_factor_spec.rb](https://gitlab.com/gitlab-org/gitlab/blob/master/spec/migrations/change_public_projects_cost_factor_spec.rb#L6-6)
for an example.
A `before` hook reverts all migrations to the point that a migration
under test is not yet migrated.
In other words, our custom RSpec hooks finds a previous migration, and
migrate the database **down** to the previous migration version.
With this approach you can test a migration against a database schema.
An `after` hook migrates the database **up** and restores the latest
schema version, so that the process does not affect subsequent specs and
ensures proper isolation.
## Testing an `ActiveRecord::Migration` class
To test an `ActiveRecord::Migration` class (for example, a
regular migration `db/migrate` or a post-migration `db/post_migrate`), you
must load the migration file by using the `require_migration!` helper
method because it is not autoloaded by Rails.
Example:
```ruby
require 'spec_helper'
require_migration!
RSpec.describe ...
```
### Test helpers
#### `require_migration!`
Since the migration files are not autoloaded by Rails, you must manually
load the migration file. To do so, you can use the `require_migration!` helper method
which can automatically load the correct migration file based on the spec filename.
You can use `require_migration!` to load migration files from spec files
that contain the schema version in the filename (for example,
`2021101412150000_populate_foo_column_spec.rb`).
```ruby
# frozen_string_literal: true
require 'spec_helper'
require_migration!
RSpec.describe PopulateFooColumn do
...
end
```
In some cases, you must require multiple migration files to use them in your specs. Here, there's no
pattern between your spec file and the other migration file. You can provide the migration filename like so:
```ruby
# frozen_string_literal: true
require 'spec_helper'
require_migration!
require_migration!('populate_bar_column')
RSpec.describe PopulateFooColumn do
...
end
```
#### `table`
Use the `table` helper to create a temporary `ActiveRecord::Base`-derived model
for a table. [FactoryBot](best_practices.md#factories)
**should not** be used to create data for migration specs because it relies on
application code which can change after the migration has run, and cause the test
to fail. For example, to create a record in the `projects` table:
```ruby
project = table(:projects).create!(name: 'gitlab1', path: 'gitlab1')
```
#### `migrate!`
Use the `migrate!` helper to run the migration that is under test. It
runs the migration and bumps the schema version in the `schema_migrations`
table. It is necessary because in the `after` hook we trigger the rest of
the migrations, and we need to know where to start. Example:
```ruby
it 'migrates successfully' do
# ... pre-migration expectations
migrate!
# ... post-migration expectations
end
```
#### `reversible_migration`
Use the `reversible_migration` helper to test migrations with either a
`change` or both `up` and `down` hooks. This tests that the state of
the application and its data after the migration becomes reversed is the
same as it was before the migration ran in the first place. The helper:
1. Runs the `before` expectations before the **up** migration.
1. Migrates **up**.
1. Runs the `after` expectations.
1. Migrates **down**.
1. Runs the `before` expectations a second time.
Example:
```ruby
reversible_migration do |migration|
migration.before -> {
# ... pre-migration expectations
}
migration.after -> {
# ... post-migration expectations
}
end
```
### Custom matchers for post-deployment migrations
We have some custom matchers in
[`spec/support/matchers/background_migrations_matchers.rb`](https://gitlab.com/gitlab-org/gitlab/blob/v14.1.0-ee/spec/support/matchers/background_migrations_matchers.rb)
to verify background migrations were correctly scheduled from a post-deployment migration, and
receive the correct number of arguments.
All of them use the internal matcher `be_background_migration_with_arguments`, which verifies that
the `#perform` method on your migration class doesn't crash when receiving the provided arguments.
#### `be_scheduled_migration`
Verifies that a Sidekiq job was queued with the expected class and arguments.
This matcher usually makes sense if you're queueing jobs manually, rather than going through our helpers.
```ruby
# Migration
BackgroundMigrationWorker.perform_async('MigrationClass', args)
# Spec
expect('MigrationClass').to be_scheduled_migration(*args)
```
#### `be_scheduled_migration_with_multiple_args`
Verifies that a Sidekiq job was queued with the expected class and arguments.
This works the same as `be_scheduled_migration`, except that the order is ignored when comparing
array arguments.
```ruby
# Migration
BackgroundMigrationWorker.perform_async('MigrationClass', ['foo', [3, 2, 1]])
# Spec
expect('MigrationClass').to be_scheduled_migration_with_multiple_args('foo', [1, 2, 3])
```
#### `be_scheduled_delayed_migration`
Verifies that a Sidekiq job was queued with the expected delay, class, and arguments.
This can also be used with `queue_background_migration_jobs_by_range_at_intervals` and related helpers.
```ruby
# Migration
BackgroundMigrationWorker.perform_in(delay, 'MigrationClass', args)
# Spec
expect('MigrationClass').to be_scheduled_delayed_migration(delay, *args)
```
#### `have_scheduled_batched_migration`
Verifies that a `BatchedMigration` record was created with the expected class and arguments.
The `*args` are additional arguments passed to the `MigrationClass`, while `**kwargs` are any other
attributes to be verified on the `BatchedMigration` record (Example: `interval: 2.minutes`).
```ruby
# Migration
queue_batched_background_migration(
'MigrationClass',
table_name,
column_name,
*args,
**kwargs
)
# Spec
expect('MigrationClass').to have_scheduled_batched_migration(
table_name: table_name,
column_name: column_name,
job_arguments: args,
**kwargs
)
```
#### `be_finalize_background_migration_of`
Verifies that a migration calls `finalize_background_migration` with the expected background migration class.
```ruby
# Migration
finalize_background_migration('MigrationClass')
# Spec
expect(described_class).to be_finalize_background_migration_of('MigrationClass')
```
### Examples of migration tests
Migration tests depend on what the migration does exactly, the most common types are data migrations and scheduling background migrations.
#### Example of a data migration test
This spec tests the
[`db/post_migrate/20200723040950_migrate_incident_issues_to_incident_type.rb`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/db/post_migrate/20200723040950_migrate_incident_issues_to_incident_type.rb)
migration. You can find the complete spec in
[`spec/migrations/migrate_incident_issues_to_incident_type_spec.rb`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/spec/migrations/migrate_incident_issues_to_incident_type_spec.rb).
```ruby
# frozen_string_literal: true
require 'spec_helper'
require_migration!
RSpec.describe MigrateIncidentIssuesToIncidentType do
let(:migration) { described_class.new }
let(:projects) { table(:projects) }
let(:namespaces) { table(:namespaces) }
let(:labels) { table(:labels) }
let(:issues) { table(:issues) }
let(:label_links) { table(:label_links) }
let(:label_props) { IncidentManagement::CreateIncidentLabelService::LABEL_PROPERTIES }
let(:namespace) { namespaces.create!(name: 'foo', path: 'foo') }
let!(:project) { projects.create!(namespace_id: namespace.id) }
let(:label) { labels.create!(project_id: project.id, **label_props) }
let!(:incident_issue) { issues.create!(project_id: project.id) }
let!(:other_issue) { issues.create!(project_id: project.id) }
# Issue issue_type enum
let(:issue_type) { 0 }
let(:incident_type) { 1 }
before do
label_links.create!(target_id: incident_issue.id, label_id: label.id, target_type: 'Issue')
end
describe '#up' do
it 'updates the incident issue type' do
expect { migrate! }
.to change { incident_issue.reload.issue_type }
.from(issue_type)
.to(incident_type)
expect(other_issue.reload.issue_type).to eq(issue_type)
end
end
describe '#down' do
let!(:incident_issue) { issues.create!(project_id: project.id, issue_type: issue_type) }
it 'updates the incident issue type' do
migration.up
expect { migration.down }
.to change { incident_issue.reload.issue_type }
.from(incident_type)
.to(issue_type)
expect(other_issue.reload.issue_type).to eql(issue_type)
end
end
end
```
#### Example of a background migration scheduling test
To test these you usually have to:
- Create some records.
- Run the migration.
- Verify that the expected jobs were scheduled, with the correct set
of records, the correct batch size, interval, etc.
The behavior of the background migration itself needs to be verified in a
[separate test for the background migration class](#example-background-migration-test).
This spec tests the
[`db/post_migrate/20210701111909_backfill_issues_upvotes_count.rb`](https://gitlab.com/gitlab-org/gitlab/-/blob/v14.1.0-ee/db/post_migrate/20210701111909_backfill_issues_upvotes_count.rb)
post-deployment migration. You can find the complete spec in
[`spec/migrations/backfill_issues_upvotes_count_spec.rb`](https://gitlab.com/gitlab-org/gitlab/blob/v14.1.0-ee/spec/spec/migrations/backfill_issues_upvotes_count_spec.rb).
```ruby
require 'spec_helper'
require_migration!
RSpec.describe BackfillIssuesUpvotesCount do
let(:migration) { described_class.new }
let(:issues) { table(:issues) }
let(:award_emoji) { table(:award_emoji) }
let!(:issue1) { issues.create! }
let!(:issue2) { issues.create! }
let!(:issue3) { issues.create! }
let!(:issue4) { issues.create! }
let!(:issue4_without_thumbsup) { issues.create! }
let!(:award_emoji1) { award_emoji.create!( name: 'thumbsup', awardable_type: 'Issue', awardable_id: issue1.id) }
let!(:award_emoji2) { award_emoji.create!( name: 'thumbsup', awardable_type: 'Issue', awardable_id: issue2.id) }
let!(:award_emoji3) { award_emoji.create!( name: 'thumbsup', awardable_type: 'Issue', awardable_id: issue3.id) }
let!(:award_emoji4) { award_emoji.create!( name: 'thumbsup', awardable_type: 'Issue', awardable_id: issue4.id) }
it 'correctly schedules background migrations', :aggregate_failures do
stub_const("#{described_class.name}::BATCH_SIZE", 2)
Sidekiq::Testing.fake! do
freeze_time do
migrate!
expect(described_class::MIGRATION).to be_scheduled_migration(issue1.id, issue2.id)
expect(described_class::MIGRATION).to be_scheduled_migration(issue3.id, issue4.id)
expect(BackgroundMigrationWorker.jobs.size).to eq(2)
end
end
end
end
```
## Testing a non-`ActiveRecord::Migration` class
To test a non-`ActiveRecord::Migration` test (a background migration),
you must manually provide a required schema version. Add a
`schema` tag to a context that you want to switch the database schema within.
If not set, `schema` defaults to `:latest`.
Example:
```ruby
describe SomeClass, schema: 20170608152748 do
# ...
end
```
### Example background migration test
This spec tests the
[`lib/gitlab/background_migration/backfill_draft_status_on_merge_requests.rb`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/lib/gitlab/background_migration/backfill_draft_status_on_merge_requests.rb)
background migration. You can find the complete spec on
[`spec/lib/gitlab/background_migration/backfill_draft_status_on_merge_requests_spec.rb`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/spec/lib/gitlab/background_migration/backfill_draft_status_on_merge_requests_spec.rb)
```ruby
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe Gitlab::BackgroundMigration::BackfillDraftStatusOnMergeRequests do
let(:namespaces) { table(:namespaces) }
let(:projects) { table(:projects) }
let(:merge_requests) { table(:merge_requests) }
let(:group) { namespaces.create!(name: 'gitlab', path: 'gitlab') }
let(:project) { projects.create!(namespace_id: group.id) }
let(:draft_prefixes) { ["[Draft]", "(Draft)", "Draft:", "Draft", "[WIP]", "WIP:", "WIP"] }
def create_merge_request(params)
common_params = {
target_project_id: project.id,
target_branch: 'feature1',
source_branch: 'master'
}
merge_requests.create!(common_params.merge(params))
end
context "for MRs with #draft? == true titles but draft attribute false" do
let(:mr_ids) { merge_requests.all.collect(&:id) }
before do
draft_prefixes.each do |prefix|
(1..4).each do |n|
create_merge_request(
title: "#{prefix} This is a title",
draft: false,
state_id: n
)
end
end
end
it "updates all open draft merge request's draft field to true" do
mr_count = merge_requests.all.count
expect { subject.perform(mr_ids.first, mr_ids.last) }
.to change { MergeRequest.where(draft: false).count }
.from(mr_count).to(mr_count - draft_prefixes.length)
end
it "marks successful slices as completed" do
expect(subject).to receive(:mark_job_as_succeeded).with(mr_ids.first, mr_ids.last)
subject.perform(mr_ids.first, mr_ids.last)
end
end
end
```
These tests do not run within a database transaction, as we use a deletion database
cleanup strategy. Do not depend on a transaction being present.
When testing migrations that alter seeded data in `deletion_except_tables`, you may add the
`:migration_with_transaction` metadata so the test runs within a transaction and the data
is rolled back to their original values.
|
https://docs.gitlab.com/development/review_apps
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/review_apps.md
|
2025-08-13
|
doc/development/testing_guide
|
[
"doc",
"development",
"testing_guide"
] |
review_apps.md
|
none
|
unassigned
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Using review apps in the development of GitLab
| null |
Review apps are deployed using the `start-review-app-pipeline` job which triggers a child pipeline containing a series of jobs to perform the various tasks needed to deploy a review app.

To start a review-app, add the `pipeline:run-review-app` label on your merge request, and trigger a new CI/CD pipeline.
## Bypass failed review app deployment to merge a broken `master` fix
Maintainers can elect to use the [process for merging during broken `master`](https://handbook.gitlab.com/handbook/engineering/workflow/#instructions-for-the-maintainer) if a customer-critical merge request is blocked by pipelines failing due to review app deployment failures.
## Performance Metrics
On every Review App child pipeline in the `qa` stage, the
`browser_performance` job is automatically started: this job does basic
browser performance testing using a
[Sitespeed.io Container](../../ci/testing/browser_performance_testing.md).
## Sample Data for review apps
Upon deployment of a review app, project data is created from the [`sample-gitlab-project`](https://gitlab.com/gitlab-org/sample-data-templates/sample-gitlab-project) template project. This aims to provide projects with prepopulated resources to facilitate manual and exploratory testing.
The sample projects will be created in the `root` user namespace and can be accessed from the personal projects list for that user.
## How to
### Redeploy review app from a clean slate
To reset review app and redeploy from a clean slate, do the following:
1. Run `review-stop` job.
1. Re-deploy by running or retrying `review-deploy` job.
Doing this will remove all existing data from a previously deployed review app.
### Get access to the GCP review apps cluster
You need to [open an access request (internal link)](https://gitlab.com/gitlab-com/access-requests/-/issues/new)
for the `gcp-review-apps-dev` GCP group and role.
This grants you the following permissions for:
- [Retrieving pod logs](#dig-into-a-pods-logs). Granted by [Viewer (`roles/viewer`)](https://cloud.google.com/iam/docs/understanding-roles#kubernetes-engine-roles).
- [Running a Rails console](#run-a-rails-console). Granted by [Kubernetes Engine Developer (`roles/container.pods.exec`)](https://cloud.google.com/iam/docs/understanding-roles#kubernetes-engine-roles).
### Sign in to my review app
For GitLab Team Members only. If you want to sign in to the review app, review
the GitLab handbook information for the [shared 1Password account](https://handbook.gitlab.com/handbook/security/password-guidelines/#1password-for-teams).
- The default username is `root`.
- The password can be found in the 1Password login item named `GitLab EE Review App`.
### Enable a feature flag for my review app
1. Open your review app and sign in as documented above.
1. Create a personal access token.
1. Enable the feature flag using the [Feature flag API](../../api/features.md).
### Find my review app slug
1. Open the `review-deploy` job.
1. Look for `** Deploying review-*`.
1. For instance for `** Deploying review-1234-abc-defg... **`,
your review app slug would be `review-1234-abc-defg` in this case.
### Run a Rails console
1. Make sure you [have access to the cluster](#get-access-to-the-gcp-review-apps-cluster) and the `container.pods.exec` permission first.
1. [Filter Workloads by your review app slug](https://console.cloud.google.com/kubernetes/workload?project=gitlab-review-apps). For example, `review-qa-raise-e-12chm0`.
1. Find and open the `toolbox` Deployment. For example, `review-qa-raise-e-12chm0-toolbox`.
1. Select the Pod in the "Managed pods" section. For example, `review-qa-raise-e-12chm0-toolbox-d5455cc8-2lsvz`.
1. Select the `KUBECTL` dropdown list, then `Exec` -> `toolbox`.
1. Replace `-c toolbox -- ls` with `-it -- gitlab-rails console` from the
default command or
- Run `kubectl exec --namespace review-qa-raise-e-12chm0 review-qa-raise-e-12chm0-toolbox-d5455cc8-2lsvz -it -- gitlab-rails console` and
- Replace `review-qa-raise-e-12chm0-toolbox-d5455cc8-2lsvz`
with your Pod's name.
### Dig into a Pod's logs
1. Make sure you [have access to the cluster](#get-access-to-the-gcp-review-apps-cluster) and the `container.pods.getLogs` permission first.
1. [Filter Workloads by your review app slug](https://console.cloud.google.com/kubernetes/workload?project=gitlab-review-apps). For example, `review-qa-raise-e-12chm0`.
1. Find and open the `migrations` Deployment. For example, `review-qa-raise-e-12chm0-migrations.1`.
1. Select the Pod in the "Managed pods" section. For example, `review-qa-raise-e-12chm0-migrations.1-nqwtx`.
1. Select `Container logs`.
Alternatively, you could use the [Logs Explorer](https://console.cloud.google.com/logs/query;query=?project=gitlab-review-apps) which provides more utility to search logs. An example query for a pod name is as follows:
```shell
resource.labels.pod_name:"review-qa-raise-e-12chm0-migrations"
```
## How does it work?
### CI/CD architecture diagram
```mermaid
graph TD
A["build-qa-image, compile-production-assets<br/>(canonical default refs only)"];
B1[start-review-app-pipeline];
B[review-build-cng];
C["review-deploy<br><br>Helm deploys the review app using the Cloud<br/>Native images built by the CNG-mirror pipeline.<br><br>Cloud Native images are deployed to the #96;review-apps#96;<br>Kubernetes (GKE) cluster, in the GCP #96;gitlab-review-apps#96; project."];
D[CNG-mirror];
A --> B1
B1 --> B
B -.->|triggers a CNG-mirror pipeline| D
D -.->|depends on the multi-project pipeline| B
B --> C
subgraph "1#46; gitlab-org/gitlab parent pipeline"
A
B1
end
subgraph "2#46; gitlab-org/gitlab child pipeline"
B
C
end
subgraph "CNG-mirror pipeline"
D>Cloud Native images are built];
end
```
### Detailed explanation
1. On every [pipeline](https://gitlab.com/gitlab-org/gitlab/pipelines/125315730) during the `prepare` stage, the
[`compile-production-assets`](https://gitlab.com/gitlab-org/gitlab/-/jobs/641770154) job is automatically started.
- Once it's done, the [`review-build-cng`](https://gitlab.com/gitlab-org/gitlab/-/jobs/467724808)
job starts since the [`CNG-mirror`](https://gitlab.com/gitlab-org/build/CNG-mirror) pipeline triggered in the
following step depends on it.
1. Once `compile-production-assets` is done, the [`review-build-cng`](https://gitlab.com/gitlab-org/gitlab/-/jobs/467724808)
job [triggers a pipeline](https://gitlab.com/gitlab-org/build/CNG-mirror/pipelines/44364657)
in the [`CNG-mirror`](https://gitlab.com/gitlab-org/build/CNG-mirror) project.
- The `review-build-cng` job automatically starts only if your MR includes
[CI or frontend changes](../pipelines/internals.md#changes-patterns). In other cases, the job is manual.
- The [`CNG-mirror`](https://gitlab.com/gitlab-org/build/CNG-mirror/pipelines/44364657) pipeline creates the Docker images of
each component (for example, `gitlab-rails-ee`, `gitlab-shell`, `gitaly` etc.)
based on the commit from the [GitLab pipeline](https://gitlab.com/gitlab-org/gitlab/pipelines/125315730) and stores
them in its [registry](https://gitlab.com/gitlab-org/build/CNG-mirror/container_registry).
- We use the [`CNG-mirror`](https://gitlab.com/gitlab-org/build/CNG-mirror) project so that the `CNG`, (Cloud
Native GitLab), project's registry is not overloaded with a lot of transient Docker images.
1. Once `review-build-cng` is done, the [`review-deploy`](https://gitlab.com/gitlab-org/gitlab/-/jobs/467724810) job
deploys the review app using [the official GitLab Helm chart](https://gitlab.com/gitlab-org/charts/gitlab/) to
the [`review-apps`](https://console.cloud.google.com/kubernetes/clusters/details/us-central1-b/review-apps?project=gitlab-review-apps)
Kubernetes cluster on GCP.
- The actual scripts used to deploy the review app can be found at
[`scripts/review_apps/review-apps.sh`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/scripts/review_apps/review-apps.sh).
- These scripts are basically
[our official Auto DevOps scripts](https://gitlab.com/gitlab-org/gitlab/-/blob/master/lib/gitlab/ci/templates/Auto-DevOps.gitlab-ci.yml) where the
default CNG images are overridden with the images built and stored in the
[`CNG-mirror` project's registry](https://gitlab.com/gitlab-org/build/CNG-mirror/container_registry).
- Since we're using [the official GitLab Helm chart](https://gitlab.com/gitlab-org/charts/gitlab/), this means
you get a dedicated environment for your branch that's very close to what
it would look in production.
- Each review app is deployed to its own Kubernetes namespace. The namespace is based on the review app slug that is
unique to each branch.
1. Once the [`review-deploy`](https://gitlab.com/gitlab-org/gitlab/-/jobs/467724810) job succeeds, you should be able to
use your review app thanks to the direct link to it from the MR widget. To log
into the review app, see "Sign in to my review app?" below.
**Additional notes**:
- If the `review-deploy` job keeps failing (and a manual retry didn't help),
post a message in the `#g_qe_engineering_productivity` channel and/or create a `~"Engineering Productivity"` `~"dx::review apps"` `~"type::bug"`
issue with a link to your merge request. The deployment failure can
reveal an actual problem introduced in your merge request (that is, this isn't
necessarily a transient failure)!
- The manual `review-stop` can be used to
stop a review app manually, and is also started by GitLab once a merge
request's branch is deleted after being merged.
- The Kubernetes cluster is connected to the `gitlab` projects using the
[GitLab Kubernetes integration](../../user/infrastructure/clusters/_index.md). This basically
allows to have a link to the review app directly from the merge request widget.
### Auto-stopping of review apps
Review apps are automatically stopped 2 days after the last deployment thanks to
the [Environment auto-stop](../../ci/environments/_index.md#stop-an-environment-after-a-certain-time-period) feature.
If you need your review app to stay up for a longer time, you can
[pin its environment](../../ci/environments/_index.md#override-an-environments-scheduled-stop-date-and-time) or retry the
`review-deploy` job to update the "latest deployed at" time.
The `review-cleanup` job that automatically runs in scheduled
pipelines stops stale review apps after 5 days,
deletes their environment after 6 days, and cleans up any dangling Helm releases
and Kubernetes resources after 7 days.
## Cluster configuration
The cluster is configured via Terraform in the [`engineering-productivity-infrastructure`](https://gitlab.com/gitlab-org/quality/engineering-productivity-infrastructure) project.
Node pool image type must be `Container-Optimized OS (cos)`, not `Container-Optimized OS with Containerd (cos_containerd)`,
due to this [known issue on the Kubernetes executor for GitLab Runner](https://gitlab.com/gitlab-org/gitlab-runner/-/issues/4755)
### Helm
The Helm version used is defined in the
[`registry.gitlab.com/gitlab-org/gitlab-build-images:gitlab-helm3.5-kubectl1.17` image](https://gitlab.com/gitlab-org/gitlab-build-images/-/blob/master/Dockerfile.gitlab-helm3.5-kubectl1.17#L6)
used by the `review-deploy` and `review-stop` jobs.
## Diagnosing unhealthy review app releases
If [review app stability](https://app.periscopedata.com/app/gitlab/496118/Engineering-Productivity-Sandbox?widget=6690556&udv=785399)
dips this may be a signal that the `review-apps` cluster is unhealthy.
Leading indicators may be health check failures leading to restarts or majority failure for review app deployments.
The [review apps Overview dashboard](https://console.cloud.google.com/monitoring/classic/dashboards/6798952013815386466?project=gitlab-review-apps&timeDomain=1d)
aids in identifying load spikes on the cluster, and if nodes are problematic or the entire cluster is trending towards unhealthy.
See the [review apps page of the Engineering Productivity Runbook](https://gitlab.com/gitlab-org/quality/engineering-productivity/team/-/blob/main/runbook/review-apps.md) for troubleshooting review app releases.
## Frequently Asked Questions
**Isn't it too much to trigger CNG image builds on every test run? This creates
thousands of unused Docker images.**
> We have to start somewhere and improve later. Also, we're using the
> CNG-mirror project to store these Docker images so that we can just wipe out
> the registry at some point, and use a new fresh, empty one.
**How do we secure this from abuse? Apps are open to the world so we need to
find a way to limit it to only us.**
> This isn't enabled for forks.
## Other resources
- [Review apps integration for CE/EE (presentation)](https://docs.google.com/presentation/d/1QPLr6FO4LduROU8pQIPkX1yfGvD13GEJIBOenqoKxR8/edit?usp=sharing)
- [Stability issues](https://gitlab.com/gitlab-org/quality/quality-engineering/team-tasks/-/issues/212)
### Helpful command-line tools
- [K9s](https://github.com/derailed/k9s) - enables CLI dashboard across pods and enabling filtering by labels
- [Stern](https://github.com/stern/stern) - enables cross pod log tailing based on label/field selectors
---
[Return to Testing documentation](_index.md)
|
---
stage: none
group: unassigned
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: Using review apps in the development of GitLab
breadcrumbs:
- doc
- development
- testing_guide
---
Review apps are deployed using the `start-review-app-pipeline` job which triggers a child pipeline containing a series of jobs to perform the various tasks needed to deploy a review app.

To start a review-app, add the `pipeline:run-review-app` label on your merge request, and trigger a new CI/CD pipeline.
## Bypass failed review app deployment to merge a broken `master` fix
Maintainers can elect to use the [process for merging during broken `master`](https://handbook.gitlab.com/handbook/engineering/workflow/#instructions-for-the-maintainer) if a customer-critical merge request is blocked by pipelines failing due to review app deployment failures.
## Performance Metrics
On every Review App child pipeline in the `qa` stage, the
`browser_performance` job is automatically started: this job does basic
browser performance testing using a
[Sitespeed.io Container](../../ci/testing/browser_performance_testing.md).
## Sample Data for review apps
Upon deployment of a review app, project data is created from the [`sample-gitlab-project`](https://gitlab.com/gitlab-org/sample-data-templates/sample-gitlab-project) template project. This aims to provide projects with prepopulated resources to facilitate manual and exploratory testing.
The sample projects will be created in the `root` user namespace and can be accessed from the personal projects list for that user.
## How to
### Redeploy review app from a clean slate
To reset review app and redeploy from a clean slate, do the following:
1. Run `review-stop` job.
1. Re-deploy by running or retrying `review-deploy` job.
Doing this will remove all existing data from a previously deployed review app.
### Get access to the GCP review apps cluster
You need to [open an access request (internal link)](https://gitlab.com/gitlab-com/access-requests/-/issues/new)
for the `gcp-review-apps-dev` GCP group and role.
This grants you the following permissions for:
- [Retrieving pod logs](#dig-into-a-pods-logs). Granted by [Viewer (`roles/viewer`)](https://cloud.google.com/iam/docs/understanding-roles#kubernetes-engine-roles).
- [Running a Rails console](#run-a-rails-console). Granted by [Kubernetes Engine Developer (`roles/container.pods.exec`)](https://cloud.google.com/iam/docs/understanding-roles#kubernetes-engine-roles).
### Sign in to my review app
For GitLab Team Members only. If you want to sign in to the review app, review
the GitLab handbook information for the [shared 1Password account](https://handbook.gitlab.com/handbook/security/password-guidelines/#1password-for-teams).
- The default username is `root`.
- The password can be found in the 1Password login item named `GitLab EE Review App`.
### Enable a feature flag for my review app
1. Open your review app and sign in as documented above.
1. Create a personal access token.
1. Enable the feature flag using the [Feature flag API](../../api/features.md).
### Find my review app slug
1. Open the `review-deploy` job.
1. Look for `** Deploying review-*`.
1. For instance for `** Deploying review-1234-abc-defg... **`,
your review app slug would be `review-1234-abc-defg` in this case.
### Run a Rails console
1. Make sure you [have access to the cluster](#get-access-to-the-gcp-review-apps-cluster) and the `container.pods.exec` permission first.
1. [Filter Workloads by your review app slug](https://console.cloud.google.com/kubernetes/workload?project=gitlab-review-apps). For example, `review-qa-raise-e-12chm0`.
1. Find and open the `toolbox` Deployment. For example, `review-qa-raise-e-12chm0-toolbox`.
1. Select the Pod in the "Managed pods" section. For example, `review-qa-raise-e-12chm0-toolbox-d5455cc8-2lsvz`.
1. Select the `KUBECTL` dropdown list, then `Exec` -> `toolbox`.
1. Replace `-c toolbox -- ls` with `-it -- gitlab-rails console` from the
default command or
- Run `kubectl exec --namespace review-qa-raise-e-12chm0 review-qa-raise-e-12chm0-toolbox-d5455cc8-2lsvz -it -- gitlab-rails console` and
- Replace `review-qa-raise-e-12chm0-toolbox-d5455cc8-2lsvz`
with your Pod's name.
### Dig into a Pod's logs
1. Make sure you [have access to the cluster](#get-access-to-the-gcp-review-apps-cluster) and the `container.pods.getLogs` permission first.
1. [Filter Workloads by your review app slug](https://console.cloud.google.com/kubernetes/workload?project=gitlab-review-apps). For example, `review-qa-raise-e-12chm0`.
1. Find and open the `migrations` Deployment. For example, `review-qa-raise-e-12chm0-migrations.1`.
1. Select the Pod in the "Managed pods" section. For example, `review-qa-raise-e-12chm0-migrations.1-nqwtx`.
1. Select `Container logs`.
Alternatively, you could use the [Logs Explorer](https://console.cloud.google.com/logs/query;query=?project=gitlab-review-apps) which provides more utility to search logs. An example query for a pod name is as follows:
```shell
resource.labels.pod_name:"review-qa-raise-e-12chm0-migrations"
```
## How does it work?
### CI/CD architecture diagram
```mermaid
graph TD
A["build-qa-image, compile-production-assets<br/>(canonical default refs only)"];
B1[start-review-app-pipeline];
B[review-build-cng];
C["review-deploy<br><br>Helm deploys the review app using the Cloud<br/>Native images built by the CNG-mirror pipeline.<br><br>Cloud Native images are deployed to the #96;review-apps#96;<br>Kubernetes (GKE) cluster, in the GCP #96;gitlab-review-apps#96; project."];
D[CNG-mirror];
A --> B1
B1 --> B
B -.->|triggers a CNG-mirror pipeline| D
D -.->|depends on the multi-project pipeline| B
B --> C
subgraph "1#46; gitlab-org/gitlab parent pipeline"
A
B1
end
subgraph "2#46; gitlab-org/gitlab child pipeline"
B
C
end
subgraph "CNG-mirror pipeline"
D>Cloud Native images are built];
end
```
### Detailed explanation
1. On every [pipeline](https://gitlab.com/gitlab-org/gitlab/pipelines/125315730) during the `prepare` stage, the
[`compile-production-assets`](https://gitlab.com/gitlab-org/gitlab/-/jobs/641770154) job is automatically started.
- Once it's done, the [`review-build-cng`](https://gitlab.com/gitlab-org/gitlab/-/jobs/467724808)
job starts since the [`CNG-mirror`](https://gitlab.com/gitlab-org/build/CNG-mirror) pipeline triggered in the
following step depends on it.
1. Once `compile-production-assets` is done, the [`review-build-cng`](https://gitlab.com/gitlab-org/gitlab/-/jobs/467724808)
job [triggers a pipeline](https://gitlab.com/gitlab-org/build/CNG-mirror/pipelines/44364657)
in the [`CNG-mirror`](https://gitlab.com/gitlab-org/build/CNG-mirror) project.
- The `review-build-cng` job automatically starts only if your MR includes
[CI or frontend changes](../pipelines/internals.md#changes-patterns). In other cases, the job is manual.
- The [`CNG-mirror`](https://gitlab.com/gitlab-org/build/CNG-mirror/pipelines/44364657) pipeline creates the Docker images of
each component (for example, `gitlab-rails-ee`, `gitlab-shell`, `gitaly` etc.)
based on the commit from the [GitLab pipeline](https://gitlab.com/gitlab-org/gitlab/pipelines/125315730) and stores
them in its [registry](https://gitlab.com/gitlab-org/build/CNG-mirror/container_registry).
- We use the [`CNG-mirror`](https://gitlab.com/gitlab-org/build/CNG-mirror) project so that the `CNG`, (Cloud
Native GitLab), project's registry is not overloaded with a lot of transient Docker images.
1. Once `review-build-cng` is done, the [`review-deploy`](https://gitlab.com/gitlab-org/gitlab/-/jobs/467724810) job
deploys the review app using [the official GitLab Helm chart](https://gitlab.com/gitlab-org/charts/gitlab/) to
the [`review-apps`](https://console.cloud.google.com/kubernetes/clusters/details/us-central1-b/review-apps?project=gitlab-review-apps)
Kubernetes cluster on GCP.
- The actual scripts used to deploy the review app can be found at
[`scripts/review_apps/review-apps.sh`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/scripts/review_apps/review-apps.sh).
- These scripts are basically
[our official Auto DevOps scripts](https://gitlab.com/gitlab-org/gitlab/-/blob/master/lib/gitlab/ci/templates/Auto-DevOps.gitlab-ci.yml) where the
default CNG images are overridden with the images built and stored in the
[`CNG-mirror` project's registry](https://gitlab.com/gitlab-org/build/CNG-mirror/container_registry).
- Since we're using [the official GitLab Helm chart](https://gitlab.com/gitlab-org/charts/gitlab/), this means
you get a dedicated environment for your branch that's very close to what
it would look in production.
- Each review app is deployed to its own Kubernetes namespace. The namespace is based on the review app slug that is
unique to each branch.
1. Once the [`review-deploy`](https://gitlab.com/gitlab-org/gitlab/-/jobs/467724810) job succeeds, you should be able to
use your review app thanks to the direct link to it from the MR widget. To log
into the review app, see "Sign in to my review app?" below.
**Additional notes**:
- If the `review-deploy` job keeps failing (and a manual retry didn't help),
post a message in the `#g_qe_engineering_productivity` channel and/or create a `~"Engineering Productivity"` `~"dx::review apps"` `~"type::bug"`
issue with a link to your merge request. The deployment failure can
reveal an actual problem introduced in your merge request (that is, this isn't
necessarily a transient failure)!
- The manual `review-stop` can be used to
stop a review app manually, and is also started by GitLab once a merge
request's branch is deleted after being merged.
- The Kubernetes cluster is connected to the `gitlab` projects using the
[GitLab Kubernetes integration](../../user/infrastructure/clusters/_index.md). This basically
allows to have a link to the review app directly from the merge request widget.
### Auto-stopping of review apps
Review apps are automatically stopped 2 days after the last deployment thanks to
the [Environment auto-stop](../../ci/environments/_index.md#stop-an-environment-after-a-certain-time-period) feature.
If you need your review app to stay up for a longer time, you can
[pin its environment](../../ci/environments/_index.md#override-an-environments-scheduled-stop-date-and-time) or retry the
`review-deploy` job to update the "latest deployed at" time.
The `review-cleanup` job that automatically runs in scheduled
pipelines stops stale review apps after 5 days,
deletes their environment after 6 days, and cleans up any dangling Helm releases
and Kubernetes resources after 7 days.
## Cluster configuration
The cluster is configured via Terraform in the [`engineering-productivity-infrastructure`](https://gitlab.com/gitlab-org/quality/engineering-productivity-infrastructure) project.
Node pool image type must be `Container-Optimized OS (cos)`, not `Container-Optimized OS with Containerd (cos_containerd)`,
due to this [known issue on the Kubernetes executor for GitLab Runner](https://gitlab.com/gitlab-org/gitlab-runner/-/issues/4755)
### Helm
The Helm version used is defined in the
[`registry.gitlab.com/gitlab-org/gitlab-build-images:gitlab-helm3.5-kubectl1.17` image](https://gitlab.com/gitlab-org/gitlab-build-images/-/blob/master/Dockerfile.gitlab-helm3.5-kubectl1.17#L6)
used by the `review-deploy` and `review-stop` jobs.
## Diagnosing unhealthy review app releases
If [review app stability](https://app.periscopedata.com/app/gitlab/496118/Engineering-Productivity-Sandbox?widget=6690556&udv=785399)
dips this may be a signal that the `review-apps` cluster is unhealthy.
Leading indicators may be health check failures leading to restarts or majority failure for review app deployments.
The [review apps Overview dashboard](https://console.cloud.google.com/monitoring/classic/dashboards/6798952013815386466?project=gitlab-review-apps&timeDomain=1d)
aids in identifying load spikes on the cluster, and if nodes are problematic or the entire cluster is trending towards unhealthy.
See the [review apps page of the Engineering Productivity Runbook](https://gitlab.com/gitlab-org/quality/engineering-productivity/team/-/blob/main/runbook/review-apps.md) for troubleshooting review app releases.
## Frequently Asked Questions
**Isn't it too much to trigger CNG image builds on every test run? This creates
thousands of unused Docker images.**
> We have to start somewhere and improve later. Also, we're using the
> CNG-mirror project to store these Docker images so that we can just wipe out
> the registry at some point, and use a new fresh, empty one.
**How do we secure this from abuse? Apps are open to the world so we need to
find a way to limit it to only us.**
> This isn't enabled for forks.
## Other resources
- [Review apps integration for CE/EE (presentation)](https://docs.google.com/presentation/d/1QPLr6FO4LduROU8pQIPkX1yfGvD13GEJIBOenqoKxR8/edit?usp=sharing)
- [Stability issues](https://gitlab.com/gitlab-org/quality/quality-engineering/team-tasks/-/issues/212)
### Helpful command-line tools
- [K9s](https://github.com/derailed/k9s) - enables CLI dashboard across pods and enabling filtering by labels
- [Stern](https://github.com/stern/stern) - enables cross pod log tailing based on label/field selectors
---
[Return to Testing documentation](_index.md)
|
https://docs.gitlab.com/development/testing_rake_tasks
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/testing_rake_tasks.md
|
2025-08-13
|
doc/development/testing_guide
|
[
"doc",
"development",
"testing_guide"
] |
testing_rake_tasks.md
|
none
|
unassigned
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Testing Rake tasks
| null |
To make testing Rake tasks a little easier:
- Use RSpec's metadata tag `type: :task` or
- Place your spec in `spec/tasks` or `ee/spec/tasks`
By doing so, `RakeHelpers` is included which exposes a `run_rake_task(<task>)`
method to make executing tasks possible.
See `spec/support/helpers/rake_helpers.rb` for all available methods.
`$stdout` can be redirected by adding `:silence_stdout`.
Example:
```ruby
require 'spec_helper'
describe 'gitlab:shell rake tasks', :silence_stdout do
before do
Rake.application.rake_require 'tasks/gitlab/shell'
stub_warn_user_is_not_gitlab
end
describe 'install task' do
it 'invokes create_hooks task' do
expect(Rake::Task['gitlab:shell:create_hooks']).to receive(:invoke)
run_rake_task('gitlab:shell:install')
end
end
end
```
---
[Return to Testing documentation](_index.md)
|
---
stage: none
group: unassigned
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: Testing Rake tasks
breadcrumbs:
- doc
- development
- testing_guide
---
To make testing Rake tasks a little easier:
- Use RSpec's metadata tag `type: :task` or
- Place your spec in `spec/tasks` or `ee/spec/tasks`
By doing so, `RakeHelpers` is included which exposes a `run_rake_task(<task>)`
method to make executing tasks possible.
See `spec/support/helpers/rake_helpers.rb` for all available methods.
`$stdout` can be redirected by adding `:silence_stdout`.
Example:
```ruby
require 'spec_helper'
describe 'gitlab:shell rake tasks', :silence_stdout do
before do
Rake.application.rake_require 'tasks/gitlab/shell'
stub_warn_user_is_not_gitlab
end
describe 'install task' do
it 'invokes create_hooks task' do
expect(Rake::Task['gitlab:shell:create_hooks']).to receive(:invoke)
run_rake_task('gitlab:shell:install')
end
end
end
```
---
[Return to Testing documentation](_index.md)
|
https://docs.gitlab.com/development/flaky_tests
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/flaky_tests.md
|
2025-08-13
|
doc/development/testing_guide
|
[
"doc",
"development",
"testing_guide"
] |
flaky_tests.md
|
none
|
unassigned
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Flaky tests
| null |
[Consult the Unhealthy tests page for more information](unhealthy_tests.md#flaky-tests).
---
[Return to Testing documentation](_index.md)
|
---
stage: none
group: unassigned
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: Flaky tests
breadcrumbs:
- doc
- development
- testing_guide
---
[Consult the Unhealthy tests page for more information](unhealthy_tests.md#flaky-tests).
---
[Return to Testing documentation](_index.md)
|
https://docs.gitlab.com/development/testing_guide
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/_index.md
|
2025-08-13
|
doc/development/testing_guide
|
[
"doc",
"development",
"testing_guide"
] |
_index.md
|
none
|
unassigned
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Testing standards and style guidelines
| null |
This document describes various guidelines and best practices for automated
testing of the GitLab project.
It is meant to be an extension of the
[thoughtbot testing style guide](https://github.com/thoughtbot/guides/tree/master/testing-rspec). If
this guide defines a rule that contradicts the thoughtbot guide, this guide
takes precedence. Some guidelines may be repeated verbatim to stress their
importance.
## Overview
GitLab is built on top of [Ruby on Rails](https://rubyonrails.org/), and we're using [RSpec](https://github.com/rspec/rspec-rails#feature-specs) for all
the backend tests, with [Capybara](https://github.com/teamcapybara/capybara) for end-to-end integration testing.
On the frontend side, we're using [Jest](https://jestjs.io/) for JavaScript unit and
integration testing.
Following are two great articles that everyone should read to understand what
automated testing means, and what are its principles:
- [Five Factor Testing](https://madeintandem.com/blog/five-factor-testing/): Why do we need tests?
- [Principles of Automated Testing](https://www.lihaoyi.com/post/PrinciplesofAutomatedTesting.html): Levels of testing. Prioritize tests. Cost of tests.
## Testing levels
Learn about the different [testing levels](testing_levels.md), and how to decide at what level your
changes should be tested.
## Testing best practices
Everything you should know about [how to write good tests](best_practices.md): Test Design, RSpec, FactoryBot,
system tests, parameterized tests etc.
## Testing Strategy
[Testing strategy document](testing_strategy.md) defines the blueprint for GitLab automated testing — where tests run, when they execute, and what they block across the development lifecycle.
## Frontend testing standards and style guidelines
Everything you should know about [how to write good Frontend tests](frontend_testing.md): Jest,
testing promises, stubbing etc.
## Getting started with Feature tests
Need to [get started with feature tests](frontend_testing.md#get-started-with-feature-tests)? Here are some general guidelines,
tips and tricks to get the most out of white-box testing.
## Flaky tests
What are [flaky tests](flaky_tests.md), the different kind of flaky tests we encountered, and what
we do about them.
## GitLab pipelines
How GitLab test suite [is run in the CI context](../pipelines/_index.md): setup, caches, artifacts,
parallelization, monitoring.
## Review apps
How [review apps](review_apps.md) are set up for GitLab CE/EE and how to use them.
## Testing Rake tasks
Everything you should know about [how to test Rake tasks](testing_rake_tasks.md).
## End-to-end tests
Everything you should know about [how to run end-to-end tests](end_to_end/_index.md) using
[GitLab QA](https://gitlab.com/gitlab-org/gitlab-qa) testing framework.
## Migrations tests
Everything you should know about [how to test migrations](testing_migrations_guide.md).
## Contract tests
[Introduction to contract testing](contract/_index.md), how to run the tests, and how to write them.
## Test results tracking
How we track our [test suite run results](test_results_tracking.md).
## Testing AI features
Practices to keep in mind when [testing AI-powered features](testing_ai_features.md).
[Return to Development documentation](../_index.md)
|
---
stage: none
group: unassigned
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: Testing standards and style guidelines
breadcrumbs:
- doc
- development
- testing_guide
---
This document describes various guidelines and best practices for automated
testing of the GitLab project.
It is meant to be an extension of the
[thoughtbot testing style guide](https://github.com/thoughtbot/guides/tree/master/testing-rspec). If
this guide defines a rule that contradicts the thoughtbot guide, this guide
takes precedence. Some guidelines may be repeated verbatim to stress their
importance.
## Overview
GitLab is built on top of [Ruby on Rails](https://rubyonrails.org/), and we're using [RSpec](https://github.com/rspec/rspec-rails#feature-specs) for all
the backend tests, with [Capybara](https://github.com/teamcapybara/capybara) for end-to-end integration testing.
On the frontend side, we're using [Jest](https://jestjs.io/) for JavaScript unit and
integration testing.
Following are two great articles that everyone should read to understand what
automated testing means, and what are its principles:
- [Five Factor Testing](https://madeintandem.com/blog/five-factor-testing/): Why do we need tests?
- [Principles of Automated Testing](https://www.lihaoyi.com/post/PrinciplesofAutomatedTesting.html): Levels of testing. Prioritize tests. Cost of tests.
## Testing levels
Learn about the different [testing levels](testing_levels.md), and how to decide at what level your
changes should be tested.
## Testing best practices
Everything you should know about [how to write good tests](best_practices.md): Test Design, RSpec, FactoryBot,
system tests, parameterized tests etc.
## Testing Strategy
[Testing strategy document](testing_strategy.md) defines the blueprint for GitLab automated testing — where tests run, when they execute, and what they block across the development lifecycle.
## Frontend testing standards and style guidelines
Everything you should know about [how to write good Frontend tests](frontend_testing.md): Jest,
testing promises, stubbing etc.
## Getting started with Feature tests
Need to [get started with feature tests](frontend_testing.md#get-started-with-feature-tests)? Here are some general guidelines,
tips and tricks to get the most out of white-box testing.
## Flaky tests
What are [flaky tests](flaky_tests.md), the different kind of flaky tests we encountered, and what
we do about them.
## GitLab pipelines
How GitLab test suite [is run in the CI context](../pipelines/_index.md): setup, caches, artifacts,
parallelization, monitoring.
## Review apps
How [review apps](review_apps.md) are set up for GitLab CE/EE and how to use them.
## Testing Rake tasks
Everything you should know about [how to test Rake tasks](testing_rake_tasks.md).
## End-to-end tests
Everything you should know about [how to run end-to-end tests](end_to_end/_index.md) using
[GitLab QA](https://gitlab.com/gitlab-org/gitlab-qa) testing framework.
## Migrations tests
Everything you should know about [how to test migrations](testing_migrations_guide.md).
## Contract tests
[Introduction to contract testing](contract/_index.md), how to run the tests, and how to write them.
## Test results tracking
How we track our [test suite run results](test_results_tracking.md).
## Testing AI features
Practices to keep in mind when [testing AI-powered features](testing_ai_features.md).
[Return to Development documentation](../_index.md)
|
https://docs.gitlab.com/development/testing_vue3
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/testing_vue3.md
|
2025-08-13
|
doc/development/testing_guide
|
[
"doc",
"development",
"testing_guide"
] |
testing_vue3.md
|
none
|
unassigned
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Vue 3 Testing
| null |
As we transition to using Vue 3, it's important that our tests pass in Vue 3 mode.
We're adding progressively stricter checks to our pipelines to enforce proper Vue 3 testing.
Right now, we fail pipelines if:
1. A new test file is added that fails in Vue 3 mode.
1. An existing test file fails under Vue 3 that was previously passing.
1. One of the known failures on the [quarantine list](#quarantine-list) is now passing and has not been removed from the quarantine list.
## Running unit tests using Vue 3
To run unit tests using Vue 3, set the `VUE_VERSION` environment variable to `3` when executing jest.
```shell
VUE_VERSION=3 yarn jest #[file-path]
```
## Testing Caveats
### Ref management when mocking composables
A common pattern when testing Vue 3 composables is to mock the `ref` or `computed` values that these files return.
Consider the following demo composable:
```javascript
export const useCounter = () => {
const counter = ref(1)
const increase = () => { counter.value += 1 }
return { counter, increase }
}
```
If we have a component that is currently using this composable and exposing the counter, we will want to write a test to cover the functionality. In _some_ cases such as with this simple example we can get away with not mocking the composable at all, but with more complicated features such as Tanstack Query wrappers or Apollo wrappers leveraging `jest.mock` may be necessary.
In such cases the test file will require mocking the composable:
```html
<script setup>
const { counter, increase } = useCounter()
</script>
<template>
<p>Super useful counter: {{ counter }}</p>
<button @click="increase">+</button>
</template>
```
```javascript
import { ref } from 'vue'
import { useCounter } from '~/composables/useCounter'
jest.mock('~/composables/useCounter')
describe('MyComponent', () => {
const increaseMock = jest.fn()
const counter = ref(1)
beforeEach(() => {
useCounter.mockReturnValue({
increase: increaseMock,
counter
})
})
describe('When the counter is 2', () => {
beforeEach(() => {
counter.value = 2
createComponent()
})
it('...', () => {})
})
it('should default to 1', () => {
createComponent()
expect(findSuperUsefulCounter().text()).toBe(1)
// failure
})
})
```
Note in the above example that we are creating both a mock of the function that is returned by the composable and the `counter` ref - however a very important step is missing the example.
The `counter` constant is a `ref`, which means that on every test when we modify it the value we assign to it will be retained. In the example the second `it` block will fail as the `counter` will retain the value assigned in some of our previous tests.
The solution and best practice is to _always_ reset your `ref`s on the top most level `beforeEach` block.
```javascript
import { ref } from 'vue'
import { useCounter } from '~/composables/useCounter'
jest.mock('~/composables/useCounter')
describe('MyComponent', () => {
const increaseMock = jest.fn()
// We can initialize to `undefined` to be extra careful
const counter = ref(undefined)
beforeEach(() => {
counter.value = 1
useCounter.mockReturnValue({
increase: increaseMock,
counter
})
})
describe('When the counter is 2', () => {
beforeEach(() => {
counter.value = 2
createComponent()
})
it('...', () => {})
})
it('should default to 1', () => {
createComponent()
expect(findSuperUsefulCounter().text()).toBe(1)
// pass
})
})
```
### Vue router
If you are testing a Vue Router configuration using a real (not mocked) `VueRouter` object, read the following
[guidelines](https://test-utils.vuejs.org/guide/advanced/vue-router.html#Using-a-Real-Router). A
source of failure is that Vue Router 4 handles routing asynchronously, therefore we should
`await` for the routing operations to be completed. You can use the `waitForPromises` utility to
wait until all promises are flushed.
In the following example, a test asserts that VueRouter navigated to a page after clicking a button. If
`waitForPromises` is not invoked after clicking the button, the assertion would fail because the router's
state hasn't transitioned to the target page.
```javascript
it('navigates to /create when clicking New workspace button', async () => {
expect(findWorkspacesListPage().exists()).toBe(true);
await findNewWorkspaceButton().trigger('click');
await waitForPromises();
expect(findCreateWorkspacePage().exists()).toBe(true);
});
```
### Vue Apollo troubleshooting
You might encounter some unit test failures on components that execute Apollo mutations and
update the in-memory query cache, for example:
```shell
ApolloError: 'get' on proxy: property '[property]' is a read-only and non-configurable data property on the proxy target but the proxy did not return its actual value (expected '#<Object>' but got '#<Object>')
```
This error happens because Apollo tries to modify a [Vue reactive object](https://vuejs.org/guide/essentials/reactivity-fundamentals.html)
when we call the `writeQuery` or `updateQuery` methods. Avoid using objects passed through a component's
property in operations that update Apollo's cache. You should always rely on constructing new objects or
data that already exists in the Apollo's cache. As a last resort, use the `cloneDeep` utility to remove
the Vue's reactivity proxy from the target object.
In the following example, the component updates the Apollo's in-memory cache after the mutation succeeds
by swapping the `agent` object between two arrays. The `agent` object is also available in the `agent`
property, but it is reactive object. The incorrect approach references the `agent` object passed to
the component as a property which causes the proxy error. The correct approach finds the `agent`
object that is already stored in the Apollo's cache.
```html
<script>
import { toRaw } from 'vue';
export default {
props: {
namespace: {
type: String,
required: true,
},
agent: {
type: Object,
required: true,
},
},
methods: {
async execute() {
try {
await this.$apollo.mutate({
mutation: createClusterAgentMappingMutation,
update(store) {
store.updateQuery(
{
query: getAgentsWithAuthorizationStatusQuery,
variables: { namespace },
},
(sourceData) =>
produce(sourceData, (draftData) => {
const { mappedAgents, unmappedAgents } = draftData.namespace;
/*
* BAD: The error described in this section is caused by adding a Vue reactive
* object the nodes array. `this.agent` is a component property hence it is wrapped
* with a reactivity proxy.
*/
mappedAgents.nodes.push(this.agent);
unmappedAgents.nodes = removeFrom.nodes.filter((node) => node.id !== agent.id);
/*
* PREFERRED FIX: Only use data that already exists in the in-memory cache.
*/
const targetAgentIndex = removeFrom.nodes.findIndex((node) => node.id === agent.id);
mappedAgents.nodes.push(removeFrom.nodes[targetAgentIndex]);
unmappedAgents.nodes.splice(targetAgentIndex, 1);
/*
* ALTERNATIVE (LAST RESORT) FIX: Use lodash `cloneDeep` to create a clone
* of the object without Vue reactivity:
*/
mappedAgents.nodes.push(cloneDeep(this.agent));
unmappedAgents.nodes = removeFrom.nodes.filter((node) => node.id !== agent.id);
}),
);
},
});
} catch (e) {
Sentry.captureException(e);
this.$emit('error', e);
}
},
},
};
</script>
```
### Testing Vue router
When testing a full non-mocked `vue-router@4` there are a few caveats to keep in consideration for compatibility with Vue 2.
#### Window location
`vue-router@4` will not detect changes in window location, so setting a current URL with helpers such as `setWindowLocation` will not have an effect.
Instead, set an initial route or navigate to another route manually.
#### Initial route
When setting an initial route for your tests, `vue-router@4` will default to a `/` route. If the router configuration doesn't define a route for `/` path the test will error out by default. In this case, it is important to navigate to one of the defined routes before a component is created.
```javascript
router = createRouter();
await router.push({ name: 'tab', params: { tabId }})
```
Note the `await` is necessary, since [all navigations are always asynchronous](https://router.vuejs.org/guide/migration/#All-navigations-are-now-always-asynchronous).
#### Navigating to another route
To navigate to another route on an already mounted component, it is necessary to `await` calls to `push` or `replace` on the router.
```javascript
createComponent()
await router.push('/different-route')
```
When access to the `push` method is not available, for example in cases where we are triggering a `push` _inside the component's code_ through an event, `await waitForPromises` will be sufficient.
Consider the following component:
```html
<script>
export default {
methods: {
nextPage() {
this.$router.push({
path: 'some path'
})
}
}
}
</script>
<template>
<gl-keyset-pagination @push="nextPage" />
</template>
```
If we want to be able to test that the `$router.push` call is made, we must trigger the navigation through the `next` even on the `gl-keyset-pagination` component.
```javascript
wrapper.findComponent(GlKeysetNavigation).vm.$emit('push');
// $router.push is triggered in the component
await waitForPromises()
```
#### Navigation guards
Navigation guards must call their third argument `next` exactly once in any given pass through the navigation guard. This is necessary in both `vue-router@3` and `vue-router@4`, but is more important in `vue-router@4` as all navigations are asynchronous and must be awaited.
Failing to call `next` can produce [hard to debug errors](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/181946#note_2355522500). For example:
```shell
Timeout - Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout
```
#### Debugging
More often than not you will find yourself running into cryptic errors like the one below.
```shell
Unexpected calls to console (1) with:
[1] warn: [Vue Router warn]: uncaught error during route navigation:
23 | .join('\n');
24 |
> 25 | throw new Error(
| ^
26 | `Unexpected calls to console (${consoleCalls.length}) with:\n${consoleCallsList}\n`,
27 | );
28 | };
```
In order to better understand what Vue router needs, use `jest.fn()` to override `console.warn` so you can see the output of the error.
```javascript
console.warn = jest.fn()
afterEach(() => {
console.log(console.warn.mock.calls)
})
```
This will turn the above into a digestible error. Don't forget to remove this code before you submit your MR.
```shell
'[Vue Router warn]: Record with path "/" is either missing a "component(s)" or "children" property.'
```
#### Component and Children property
Unlike Vue router 3 (Vue 2), Vue router 4 requires a `component` or `children` property (with their respective `component`) to be defined. In some scenarios we have historically used Vue router to manage router query variables without a `router-view`, for example in `app/assets/javascripts/projects/your_work/components/app.vue`.
This is an anti-pattern, as Vue router is overkill, a preferable approach would be to use vanilla JS to manage query routes with [URL searchParams](https://developer.mozilla.org/en-US/docs/Web/API/URL/searchParams) for example.
When rewriting the component is not possible, passing the `App` component that the application is rendering without the use of `router-view` will let the tests pass, however, this opens up the possibility of introducing unwanted behavior in the future if a `<router-view />` is added to the component and should be used with care.
## Quarantine list
The `scripts/frontend/quarantined_vue3_specs.txt` file is built up of all the known failing Vue 3 test files.
In order to not overwhelm us with failing pipelines, these files are skipped on the Vue 3 test job.
If you're reading this, it's likely you were sent here by a failing quarantine job.
This job is confusing as it fails when a test passes and it passes if they all fail.
The reason for this is because all newly passing tests should be [removed from the quarantine list](#removing-from-the-quarantine-list).
Congratulate yourself on fixing a previously failing test and remove it from the quarantine list to get this pipeline passing again.
### Removing from the quarantine list
If your pipeline is failing because of the `vue3 check quarantined` jobs, good news!
You fixed a previously failing test!
What you need to do now is remove the newly-passing test from the quarantine list.
This ensures that the test will continue to pass and prevent any further regressions.
### Adding to the quarantine list
Don't do it.
This list should only get smaller, not larger.
If your MR introduces a new test file or breaks a currently passing one, then you should fix it.
If you are moving a test file from one location to another, then it's okay to modify the location in the quarantine list.
However, before doing so, consider fixing the test first.
|
---
stage: none
group: unassigned
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: Vue 3 Testing
breadcrumbs:
- doc
- development
- testing_guide
---
As we transition to using Vue 3, it's important that our tests pass in Vue 3 mode.
We're adding progressively stricter checks to our pipelines to enforce proper Vue 3 testing.
Right now, we fail pipelines if:
1. A new test file is added that fails in Vue 3 mode.
1. An existing test file fails under Vue 3 that was previously passing.
1. One of the known failures on the [quarantine list](#quarantine-list) is now passing and has not been removed from the quarantine list.
## Running unit tests using Vue 3
To run unit tests using Vue 3, set the `VUE_VERSION` environment variable to `3` when executing jest.
```shell
VUE_VERSION=3 yarn jest #[file-path]
```
## Testing Caveats
### Ref management when mocking composables
A common pattern when testing Vue 3 composables is to mock the `ref` or `computed` values that these files return.
Consider the following demo composable:
```javascript
export const useCounter = () => {
const counter = ref(1)
const increase = () => { counter.value += 1 }
return { counter, increase }
}
```
If we have a component that is currently using this composable and exposing the counter, we will want to write a test to cover the functionality. In _some_ cases such as with this simple example we can get away with not mocking the composable at all, but with more complicated features such as Tanstack Query wrappers or Apollo wrappers leveraging `jest.mock` may be necessary.
In such cases the test file will require mocking the composable:
```html
<script setup>
const { counter, increase } = useCounter()
</script>
<template>
<p>Super useful counter: {{ counter }}</p>
<button @click="increase">+</button>
</template>
```
```javascript
import { ref } from 'vue'
import { useCounter } from '~/composables/useCounter'
jest.mock('~/composables/useCounter')
describe('MyComponent', () => {
const increaseMock = jest.fn()
const counter = ref(1)
beforeEach(() => {
useCounter.mockReturnValue({
increase: increaseMock,
counter
})
})
describe('When the counter is 2', () => {
beforeEach(() => {
counter.value = 2
createComponent()
})
it('...', () => {})
})
it('should default to 1', () => {
createComponent()
expect(findSuperUsefulCounter().text()).toBe(1)
// failure
})
})
```
Note in the above example that we are creating both a mock of the function that is returned by the composable and the `counter` ref - however a very important step is missing the example.
The `counter` constant is a `ref`, which means that on every test when we modify it the value we assign to it will be retained. In the example the second `it` block will fail as the `counter` will retain the value assigned in some of our previous tests.
The solution and best practice is to _always_ reset your `ref`s on the top most level `beforeEach` block.
```javascript
import { ref } from 'vue'
import { useCounter } from '~/composables/useCounter'
jest.mock('~/composables/useCounter')
describe('MyComponent', () => {
const increaseMock = jest.fn()
// We can initialize to `undefined` to be extra careful
const counter = ref(undefined)
beforeEach(() => {
counter.value = 1
useCounter.mockReturnValue({
increase: increaseMock,
counter
})
})
describe('When the counter is 2', () => {
beforeEach(() => {
counter.value = 2
createComponent()
})
it('...', () => {})
})
it('should default to 1', () => {
createComponent()
expect(findSuperUsefulCounter().text()).toBe(1)
// pass
})
})
```
### Vue router
If you are testing a Vue Router configuration using a real (not mocked) `VueRouter` object, read the following
[guidelines](https://test-utils.vuejs.org/guide/advanced/vue-router.html#Using-a-Real-Router). A
source of failure is that Vue Router 4 handles routing asynchronously, therefore we should
`await` for the routing operations to be completed. You can use the `waitForPromises` utility to
wait until all promises are flushed.
In the following example, a test asserts that VueRouter navigated to a page after clicking a button. If
`waitForPromises` is not invoked after clicking the button, the assertion would fail because the router's
state hasn't transitioned to the target page.
```javascript
it('navigates to /create when clicking New workspace button', async () => {
expect(findWorkspacesListPage().exists()).toBe(true);
await findNewWorkspaceButton().trigger('click');
await waitForPromises();
expect(findCreateWorkspacePage().exists()).toBe(true);
});
```
### Vue Apollo troubleshooting
You might encounter some unit test failures on components that execute Apollo mutations and
update the in-memory query cache, for example:
```shell
ApolloError: 'get' on proxy: property '[property]' is a read-only and non-configurable data property on the proxy target but the proxy did not return its actual value (expected '#<Object>' but got '#<Object>')
```
This error happens because Apollo tries to modify a [Vue reactive object](https://vuejs.org/guide/essentials/reactivity-fundamentals.html)
when we call the `writeQuery` or `updateQuery` methods. Avoid using objects passed through a component's
property in operations that update Apollo's cache. You should always rely on constructing new objects or
data that already exists in the Apollo's cache. As a last resort, use the `cloneDeep` utility to remove
the Vue's reactivity proxy from the target object.
In the following example, the component updates the Apollo's in-memory cache after the mutation succeeds
by swapping the `agent` object between two arrays. The `agent` object is also available in the `agent`
property, but it is reactive object. The incorrect approach references the `agent` object passed to
the component as a property which causes the proxy error. The correct approach finds the `agent`
object that is already stored in the Apollo's cache.
```html
<script>
import { toRaw } from 'vue';
export default {
props: {
namespace: {
type: String,
required: true,
},
agent: {
type: Object,
required: true,
},
},
methods: {
async execute() {
try {
await this.$apollo.mutate({
mutation: createClusterAgentMappingMutation,
update(store) {
store.updateQuery(
{
query: getAgentsWithAuthorizationStatusQuery,
variables: { namespace },
},
(sourceData) =>
produce(sourceData, (draftData) => {
const { mappedAgents, unmappedAgents } = draftData.namespace;
/*
* BAD: The error described in this section is caused by adding a Vue reactive
* object the nodes array. `this.agent` is a component property hence it is wrapped
* with a reactivity proxy.
*/
mappedAgents.nodes.push(this.agent);
unmappedAgents.nodes = removeFrom.nodes.filter((node) => node.id !== agent.id);
/*
* PREFERRED FIX: Only use data that already exists in the in-memory cache.
*/
const targetAgentIndex = removeFrom.nodes.findIndex((node) => node.id === agent.id);
mappedAgents.nodes.push(removeFrom.nodes[targetAgentIndex]);
unmappedAgents.nodes.splice(targetAgentIndex, 1);
/*
* ALTERNATIVE (LAST RESORT) FIX: Use lodash `cloneDeep` to create a clone
* of the object without Vue reactivity:
*/
mappedAgents.nodes.push(cloneDeep(this.agent));
unmappedAgents.nodes = removeFrom.nodes.filter((node) => node.id !== agent.id);
}),
);
},
});
} catch (e) {
Sentry.captureException(e);
this.$emit('error', e);
}
},
},
};
</script>
```
### Testing Vue router
When testing a full non-mocked `vue-router@4` there are a few caveats to keep in consideration for compatibility with Vue 2.
#### Window location
`vue-router@4` will not detect changes in window location, so setting a current URL with helpers such as `setWindowLocation` will not have an effect.
Instead, set an initial route or navigate to another route manually.
#### Initial route
When setting an initial route for your tests, `vue-router@4` will default to a `/` route. If the router configuration doesn't define a route for `/` path the test will error out by default. In this case, it is important to navigate to one of the defined routes before a component is created.
```javascript
router = createRouter();
await router.push({ name: 'tab', params: { tabId }})
```
Note the `await` is necessary, since [all navigations are always asynchronous](https://router.vuejs.org/guide/migration/#All-navigations-are-now-always-asynchronous).
#### Navigating to another route
To navigate to another route on an already mounted component, it is necessary to `await` calls to `push` or `replace` on the router.
```javascript
createComponent()
await router.push('/different-route')
```
When access to the `push` method is not available, for example in cases where we are triggering a `push` _inside the component's code_ through an event, `await waitForPromises` will be sufficient.
Consider the following component:
```html
<script>
export default {
methods: {
nextPage() {
this.$router.push({
path: 'some path'
})
}
}
}
</script>
<template>
<gl-keyset-pagination @push="nextPage" />
</template>
```
If we want to be able to test that the `$router.push` call is made, we must trigger the navigation through the `next` even on the `gl-keyset-pagination` component.
```javascript
wrapper.findComponent(GlKeysetNavigation).vm.$emit('push');
// $router.push is triggered in the component
await waitForPromises()
```
#### Navigation guards
Navigation guards must call their third argument `next` exactly once in any given pass through the navigation guard. This is necessary in both `vue-router@3` and `vue-router@4`, but is more important in `vue-router@4` as all navigations are asynchronous and must be awaited.
Failing to call `next` can produce [hard to debug errors](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/181946#note_2355522500). For example:
```shell
Timeout - Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout
```
#### Debugging
More often than not you will find yourself running into cryptic errors like the one below.
```shell
Unexpected calls to console (1) with:
[1] warn: [Vue Router warn]: uncaught error during route navigation:
23 | .join('\n');
24 |
> 25 | throw new Error(
| ^
26 | `Unexpected calls to console (${consoleCalls.length}) with:\n${consoleCallsList}\n`,
27 | );
28 | };
```
In order to better understand what Vue router needs, use `jest.fn()` to override `console.warn` so you can see the output of the error.
```javascript
console.warn = jest.fn()
afterEach(() => {
console.log(console.warn.mock.calls)
})
```
This will turn the above into a digestible error. Don't forget to remove this code before you submit your MR.
```shell
'[Vue Router warn]: Record with path "/" is either missing a "component(s)" or "children" property.'
```
#### Component and Children property
Unlike Vue router 3 (Vue 2), Vue router 4 requires a `component` or `children` property (with their respective `component`) to be defined. In some scenarios we have historically used Vue router to manage router query variables without a `router-view`, for example in `app/assets/javascripts/projects/your_work/components/app.vue`.
This is an anti-pattern, as Vue router is overkill, a preferable approach would be to use vanilla JS to manage query routes with [URL searchParams](https://developer.mozilla.org/en-US/docs/Web/API/URL/searchParams) for example.
When rewriting the component is not possible, passing the `App` component that the application is rendering without the use of `router-view` will let the tests pass, however, this opens up the possibility of introducing unwanted behavior in the future if a `<router-view />` is added to the component and should be used with care.
## Quarantine list
The `scripts/frontend/quarantined_vue3_specs.txt` file is built up of all the known failing Vue 3 test files.
In order to not overwhelm us with failing pipelines, these files are skipped on the Vue 3 test job.
If you're reading this, it's likely you were sent here by a failing quarantine job.
This job is confusing as it fails when a test passes and it passes if they all fail.
The reason for this is because all newly passing tests should be [removed from the quarantine list](#removing-from-the-quarantine-list).
Congratulate yourself on fixing a previously failing test and remove it from the quarantine list to get this pipeline passing again.
### Removing from the quarantine list
If your pipeline is failing because of the `vue3 check quarantined` jobs, good news!
You fixed a previously failing test!
What you need to do now is remove the newly-passing test from the quarantine list.
This ensures that the test will continue to pass and prevent any further regressions.
### Adding to the quarantine list
Don't do it.
This list should only get smaller, not larger.
If your MR introduces a new test file or breaks a currently passing one, then you should fix it.
If you are moving a test file from one location to another, then it's okay to modify the location in the quarantine list.
However, before doing so, consider fixing the test first.
|
https://docs.gitlab.com/development/testing_strategy
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/testing_strategy.md
|
2025-08-13
|
doc/development/testing_guide
|
[
"doc",
"development",
"testing_guide"
] |
testing_strategy.md
|
none
|
unassigned
|
GitLab Testing Strategy
|
GitLab development guidelines - testing strategy
|
## Core Principles
**Fast Feedback**
Prioritize speed by running the most relevant tests first—fail fast, fix fast.
**Progressive Testing**
Start narrow, expand wide. Build confidence through incremental coverage.
**Resource Efficiency**
Every test should earn its keep. No duplication, no waste.
**Clear Ownership**
Every test suite needs an owner. Undefined responsibility leads to decay.
**Test Stability**
If a test can't reliably block a merge, deployment, or release, it shouldn't exist. Fix it or delete it.
## Test Suite Placement Guidelines
{{< alert type="note" >}}
Please see [testing levels](testing_levels.md) for detailed information on the test pyramid and [pipeline tiers](../pipelines/_index.md#pipeline-tiers) for understanding merge request pipeline tiers.
{{< /alert >}}
| Test Type | Purpose | When to Run | Blocking |
|-----------|---------|-------------|----------|
| **Unit Tests** | Validate individual components in isolation | All MR pipelines (predictive in Tier 1, full suite in Tier 2+) | Yes |
| **Integration Tests** | Verify interactions across components | Tier 2+ MRs, stable branches, deployments | Yes in Tier 2+ |
| **System/Feature Tests** | Validate a single feature functionality via UI | Tier 2+ MRs, stable branches | Yes in Tier 2+ |
| **End-to-end (E2E) Tests** | Validate full critical user journey | • Smoke: Deploy pipelines, feature flag toggles<br>• Full: Tier 3 MRs, scheduled pipelines | Yes in Tier 3, Smoke tests block deployments |
## Pipeline Type Requirements
### Merge Request Pipelines
| Tier | Frontend Changes | Backend Changes | Database Changes |
|------|-----------------|-----------------|------------------|
| **Tier 1** | Jest predictive only | RSpec predictive only | Migration tests + predictive |
| **Tier 2** | Full Jest suite + selective E2E | Full RSpec unit/integration + selective E2E | Full test suite |
| **Tier 3** | Full Jest + E2E | Full RSpec + E2E | Full suite + E2E |
### Deployment Pipelines
| Stage | Required Tests | Blocking |
|-------|---------------|----------|
| Staging | E2E smoke suite | ✅ |
| Canary | E2E smoke suite | ✅ |
| Production | Post-deploy smoke | ❌ |
### Stable/Security Branches
| Pipeline Type | Frontend | Backend | Database | E2E |
|---------------|----------|---------|----------|-----|
| **Backport MRs** | Full Jest suite | Full RSpec unit/integration | Migration, DB schema check | Full suite on Omnibus and GDK |
| **Stable/[Security Branches](https://gitlab.com/gitlab-org/security/gitlab)** (post-merge) | Jest unite/integration | RSpec unit/integration/system | Migration and background migration tests| None |
## Development Workflow
### Adding a New Test
**Test Type Selection**
Start at the lowest level possible: Unit → Integration → System → E2E.
**Coverage Assessment**
Scan existing tests before writing new ones. Don't test the same thing twice.
**Suite Placement**
Match your test to the correct suite and stage. Follow established patterns.
**Default to Blocking**
New tests _block by default_. Non-blocking tests are the exception, not the rule.
### Modifying Test Execution in Pipeline
**Shift Left**
Move tests earlier in the pipeline whenever possible. Faster feedback saves time.
**Preserve Blocking Status**
Once a test blocks at the right stage, it stays blocking. Demotion requires strong justification.
**Document Impact**
Every change to test execution patterns needs an impact assessment. No silent modifications.
## Maintenance and Monitoring
Teams should establish regular practices to maintain test suite health:
**Flaky and quarantined tests**
Review regularly, fix or remove immediately. See [unhealthy tests](unhealthy_tests.md) for details.
**Test suite health**
Periodically assess test suite performance and identify redundant coverage.
|
---
stage: none
group: unassigned
info: ''
description: GitLab development guidelines - testing strategy
title: GitLab Testing Strategy
breadcrumbs:
- doc
- development
- testing_guide
---
## Core Principles
**Fast Feedback**
Prioritize speed by running the most relevant tests first—fail fast, fix fast.
**Progressive Testing**
Start narrow, expand wide. Build confidence through incremental coverage.
**Resource Efficiency**
Every test should earn its keep. No duplication, no waste.
**Clear Ownership**
Every test suite needs an owner. Undefined responsibility leads to decay.
**Test Stability**
If a test can't reliably block a merge, deployment, or release, it shouldn't exist. Fix it or delete it.
## Test Suite Placement Guidelines
{{< alert type="note" >}}
Please see [testing levels](testing_levels.md) for detailed information on the test pyramid and [pipeline tiers](../pipelines/_index.md#pipeline-tiers) for understanding merge request pipeline tiers.
{{< /alert >}}
| Test Type | Purpose | When to Run | Blocking |
|-----------|---------|-------------|----------|
| **Unit Tests** | Validate individual components in isolation | All MR pipelines (predictive in Tier 1, full suite in Tier 2+) | Yes |
| **Integration Tests** | Verify interactions across components | Tier 2+ MRs, stable branches, deployments | Yes in Tier 2+ |
| **System/Feature Tests** | Validate a single feature functionality via UI | Tier 2+ MRs, stable branches | Yes in Tier 2+ |
| **End-to-end (E2E) Tests** | Validate full critical user journey | • Smoke: Deploy pipelines, feature flag toggles<br>• Full: Tier 3 MRs, scheduled pipelines | Yes in Tier 3, Smoke tests block deployments |
## Pipeline Type Requirements
### Merge Request Pipelines
| Tier | Frontend Changes | Backend Changes | Database Changes |
|------|-----------------|-----------------|------------------|
| **Tier 1** | Jest predictive only | RSpec predictive only | Migration tests + predictive |
| **Tier 2** | Full Jest suite + selective E2E | Full RSpec unit/integration + selective E2E | Full test suite |
| **Tier 3** | Full Jest + E2E | Full RSpec + E2E | Full suite + E2E |
### Deployment Pipelines
| Stage | Required Tests | Blocking |
|-------|---------------|----------|
| Staging | E2E smoke suite | ✅ |
| Canary | E2E smoke suite | ✅ |
| Production | Post-deploy smoke | ❌ |
### Stable/Security Branches
| Pipeline Type | Frontend | Backend | Database | E2E |
|---------------|----------|---------|----------|-----|
| **Backport MRs** | Full Jest suite | Full RSpec unit/integration | Migration, DB schema check | Full suite on Omnibus and GDK |
| **Stable/[Security Branches](https://gitlab.com/gitlab-org/security/gitlab)** (post-merge) | Jest unite/integration | RSpec unit/integration/system | Migration and background migration tests| None |
## Development Workflow
### Adding a New Test
**Test Type Selection**
Start at the lowest level possible: Unit → Integration → System → E2E.
**Coverage Assessment**
Scan existing tests before writing new ones. Don't test the same thing twice.
**Suite Placement**
Match your test to the correct suite and stage. Follow established patterns.
**Default to Blocking**
New tests _block by default_. Non-blocking tests are the exception, not the rule.
### Modifying Test Execution in Pipeline
**Shift Left**
Move tests earlier in the pipeline whenever possible. Faster feedback saves time.
**Preserve Blocking Status**
Once a test blocks at the right stage, it stays blocking. Demotion requires strong justification.
**Document Impact**
Every change to test execution patterns needs an impact assessment. No silent modifications.
## Maintenance and Monitoring
Teams should establish regular practices to maintain test suite health:
**Flaky and quarantined tests**
Review regularly, fix or remove immediately. See [unhealthy tests](unhealthy_tests.md) for details.
**Test suite health**
Periodically assess test suite performance and identify redundant coverage.
|
|
https://docs.gitlab.com/development/unhealthy_tests
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/unhealthy_tests.md
|
2025-08-13
|
doc/development/testing_guide
|
[
"doc",
"development",
"testing_guide"
] |
unhealthy_tests.md
|
none
|
unassigned
|
See the Technical Writers assigned to Development Guidelines: https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments-to-development-guidelines
|
Unhealthy tests
|
GitLab development guidelines - Unhealthy tests.
|
## Flaky tests
### What's a flaky test?
It's a test that sometimes fails, but if you retry it enough times, it passes,
eventually.
### What are the potential cause for a test to be flaky?
#### State leak
**Label**: `flaky-test::state leak`
**Description**: Data state has leaked from a previous test. The actual cause is probably not the flaky test here.
**Difficulty to reproduce**: Moderate. Usually, running the same spec files until the one that's failing reproduces the problem.
**Resolution**: Fix the previous tests and/or places where the test data or environment is modified, so that
it's reset to a pristine test after each test.
**Examples**:
- [Example 1](https://gitlab.com/gitlab-org/gitlab/-/issues/402915): State leakage can result from
data records created with `let_it_be` shared between test examples, while some test modifies the model
either deliberately or unwillingly causing out-of-sync data in test examples. This can result in `PG::QueryCanceled: ERROR` in the subsequent test examples or retries.
For more information about state leakages and resolution options, see [GitLab testing best practices](best_practices.md#lets-talk-about-let).
- [Example 2](https://gitlab.com/gitlab-org/gitlab/-/issues/378414#note_1142026988): A migration
test might roll-back the database, perform its testing, and then roll-up the database in an
inconsistent state, so that following tests might not know about certain columns.
- [Example 3](https://gitlab.com/gitlab-org/gitlab/-/issues/368500): A test modifies data that is
used by a following test.
- [Example 4](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/103434#note_1172316521): A test for a database query passes in a fresh database, but in a
CI/CD pipeline where the database is used to process previous test sequences, the test fails. This likely
means that the query itself needs to be updated to work in a non-clean database.
- [Example 5](https://gitlab.com/gitlab-org/gitlab/-/issues/416663#note_1457867234): Unrelated database connections
in asynchronous requests checked back in, causing the tests to accidentally
use these unrelated database connections. The failure was resolved in this
[merge request](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/125742).
- [Example 6](https://gitlab.com/gitlab-org/gitlab/-/issues/418757#note_1502138269): The maximum time to live
for a database connection causes these connections to be disconnected, which
in turn causes tests that rely on the transactions on these connections to
in turn causes tests that rely on the transactions on these connections to
fail. The issue was fixed in this [merge request](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/128567).
- [Example 7](https://gitlab.com/gitlab-org/quality/engineering-productivity/master-broken-incidents/-/issues/3389#note_1534827164):
A TCP socket used in a test was not closed before the next test, which also used
the same port with another TCP socket.
[Example 8](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/179302#note_2324238692): A `let_it_be` depended on a stub defined in a `before` block. `let_it_be` executes during `before(:all)`, so the stub was not yet set. This exposed the tests to the actual method call, which happened to use a method cache.
#### Dataset-specific
**Label**: `flaky-test::dataset-specific`
**Description**: The test assumes the dataset is in a particular (usually limited) state or order, which
might not be true depending on when the test run during the test suite.
**Difficulty to reproduce**: Moderate, as the amount of data needed to reproduce the issue might be
difficult to achieve locally. Ordering issues are easier to reproduce by repeatedly running the tests several times.
**Resolution**:
- Fix the test to not assume that the dataset is in a particular state, don't hardcode IDs.
- Loosen the assertion if the test shouldn't care about ordering but only on the elements.
- Fix the test by specifying a deterministic ordering.
- Fix the app code by specifying a deterministic ordering.
**Examples**:
- [Example 1](https://gitlab.com/gitlab-org/gitlab/-/issues/378381): The database is recreated when
any table has more than 500 columns. It could pass in the merge request, but fail later in
`master` if the order of tests changes.
- [Example 2](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/91016/diffs): A test asserts
that trying to find a record with a nonexistent ID returns an error message. The test uses an
hardcoded ID that's supposed to not exist (for example, `42`). If the test is run early in the test
suite, it might pass as not enough records were created before it, but as soon as it would run
later in the suite, there could be a record that actually has the ID `42`, hence the test would
start to fail.
- [Example 3](https://gitlab.com/gitlab-org/gitlab-foss/-/merge_requests/10148/diffs): Without
specifying `ORDER BY`, database is not given deterministic ordering, or data race can happen
in the tests.
- [Example 4](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/106936/diffs).
#### Too Many SQL queries
**Label**: `flaky-test::too-many-sql-queries`
**Description**: SQL Query limit has reached triggering `Gitlab::QueryLimiting::Transaction::ThresholdExceededError`.
**Difficulty to reproduce**: Moderate, this failure may depend on the state of query cache which can be impacted by order of specs.
**Resolution**: See [query count limits docs](../database/query_count_limits.md#solving-failing-tests).
#### Random input
**Label**: `flaky-test::random input`
**Description**: The test use random values, that sometimes match the expectations, and sometimes not.
**Difficulty to reproduce**: Easy, as the test can be modified locally to use the "random value"
used at the time the test failed
**Resolution**: Once the problem is reproduced, it should be easy to debug and fix either the test
or the app.
**Examples**:
- [Example 1](https://gitlab.com/gitlab-org/gitlab-foss/-/issues/20121): The test isn't robust enough to handle a specific data, that only appears sporadically since the data input is random.
#### Unreliable DOM Selector
**Label**: `flaky-test::unreliable dom selector`
**Description**: The DOM selector used in the test is unreliable.
**Difficulty to reproduce**: Moderate to difficult. Depending on whether the DOM selector is duplicated, or appears after a delay etc.
Adding a delay in API or controller could help reproducing the issue.
**Resolution**: It really depends on the problem here. It could be to wait for requests to finish, to scroll down the page etc.
**Examples**:
- [Example 1](https://gitlab.com/gitlab-org/gitlab/-/issues/338341): A non-unique CSS selector
matching more than one element, or a non-waiting selector method that does not allow rendering
time before throwing an `element not found` error.
- [Example 2](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/101728/diffs): A CSS selector
only appears after a GraphQL requests has finished, and the UI has updated.
- [Example 3](https://gitlab.com/gitlab-org/gitlab/-/issues/408215): A false-positive test, Capybara immediately returns true after
page visit and page is not fully loaded, or if the element is not detectable by webdriver (such as being rendered outside the viewport or behind other elements).
#### Datetime-sensitive
**Label**: `flaky-test::datetime-sensitive`
**Description**: The test is assuming a specific date or time.
**Difficulty to reproduce**: Easy to moderate, depending on whether the test consistently fails after a certain date, or only fails at a given time or date.
**Resolution**: Freezing the time is usually a good solution.
**Examples**:
- [Example 1](https://gitlab.com/gitlab-org/gitlab/-/issues/118612): A test that breaks after some time passed.
- [Example 2](https://gitlab.com/gitlab-org/gitlab/-/issues/403332): A test that breaks in the last day of the month.
#### Unstable infrastructure
**Label**: `flaky-test::unstable infrastructure`
**Description**: The test fails from time to time due to infrastructure issues.
**Difficulty to reproduce**: Hard. It's really hard to reproduce CI infrastructure issues. It might
be possible by using containers locally.
**Resolution**: Starting a conversation with the Infrastructure department in a dedicated issue is
usually a good idea.
**Examples**:
- [Example 1](https://gitlab.com/gitlab-org/gitlab/-/issues/363214): The runner is under heavy load at this time.
- [Example 2](https://gitlab.com/gitlab-org/gitlab/-/issues/360559): The runner is having networking issues, making a job failing early
#### Improper Synchronization
**Label**: `flaky-test::improper synchronization`
**Description**: A flaky test issue arising from timing-related factors, such as delays, eventual consistency, asynchronous operations, or race conditions.
These issues may stem from shortcomings in the test logic, the system under test, or their interaction.
While tests can sometimes address these issues through improved synchronization, they may also reveal underlying system bugs that require resolution.
**Difficulty to reproduce**: Moderate. It can be reproduced, for example, in feature tests by attempting to reference an
element on a page that is not yet rendered, or in unit tests by failing to wait for an asynchronous operation to complete.
**Resolution**: In the end-to-end test suite, using [an eventually matcher](end_to_end/best_practices/_index.md#use-eventually_-matchers-for-expectations-that-require-waiting).
**Examples**:
- [Example 1](https://gitlab.com/gitlab-org/gitlab/-/issues/502844): Text was not appearing on a page in time.
- [Example 2](https://gitlab.com/gitlab-org/gitlab/-/issues/496393): Text was not appearing on a page in time.
### How to reproduce a flaky test locally?
1. Reproduce the failure locally
- Find RSpec `seed` from the CI job log
- OR Run `while :; do bin/rspec <spec> || break; done` in a loop to find a `seed`
1. Reduce the examples by bisecting the spec failure with
`bin/rspec --seed <previously found> --require ./config/initializers/macos.rb --bisect <spec>`
1. Look at the remaining examples and watch for state leakage
- For example, updating records created with `let_it_be` is a common source of problems
1. Once fixed, rerun the specs with `seed`
1. Run `scripts/rspec_check_order_dependence` to ensure the spec can be run in [random order](best_practices.md#test-order)
1. Run `while :; do bin/rspec <spec> || break; done` in a loop again (and grab lunch) to verify it's no longer flaky
### Quarantined tests
When we have a flaky test in `master`:
1. Create [a ~"failure::flaky-test" issue](https://handbook.gitlab.com/handbook/engineering/workflow/#broken-master) with the relevant group label.
1. Quarantine the test after the first failure.
If the test cannot be fixed in a timely fashion, there is an impact on the
productivity of all the developers, so it should be quarantined.
#### RSpec
##### Fast quarantine
Unless you really need to have a test disabled very fast (`< 10min`), consider [using the `~pipeline::expedited` label instead](../pipelines/_index.md#the-pipelineexpedited-label).
To quickly quarantine a test without having to open a merge request and wait for pipelines,
you can follow [the fast quarantining process](https://gitlab.com/gitlab-org/quality/engineering-productivity/fast-quarantine/-/tree/main/#fast-quarantine-a-test).
**Always proceed** to [open a long-term quarantine merge request](#long-term-quarantine) after fast-quarantining a test! This is to ensure the fast-quarantined test was correctly fixed by running tests from the CI/CD pipelines (which are not run in the context of the fast-quarantine project).
##### Long-term quarantine
Once a test is fast-quarantined, you can proceed with the long-term quarantining process. This can be done by opening a merge request.
First, ensure the test file has a [`feature_category` metadata](../feature_categorization/_index.md#rspec-examples), to ensure correct attribution of the test file.
Then, you can use the `quarantine: '<issue url>'` metadata with the URL of the
~"failure::flaky-test" issue you created previously.
```ruby
# Quarantine a single spec
it 'succeeds', quarantine: 'https://gitlab.com/gitlab-org/gitlab/-/issues/12345' do
expect(response).to have_gitlab_http_status(:ok)
end
# Quarantine a describe/context block
describe '#flaky-method', quarantine: 'https://gitlab.com/gitlab-org/gitlab/-/issues/12345' do
[...]
end
```
This means it will be skipped in CI. By default, the quarantined tests will run locally.
We can skip them in local development as well by running with `--tag ~quarantine`:
```shell
# Bash
bin/rspec --tag ~quarantine
# ZSH
bin/rspec --tag \~quarantine
```
Also, ensure that:
1. The ~"quarantine" label is present on the merge request.
1. The MR description mentions the flaky test issue with [the usual terms to link a merge request to an issue](https://gitlab.com/gitlab-org/quality/triage-ops/-/blob/8b8621ba5c0db3c044a771ebf84887a0a07353b3/triage/triage/related_issue_finder.rb#L8-18).
Note that we [should not quarantine a shared example/context](https://gitlab.com/gitlab-org/gitlab/-/issues/404388), and [we cannot quarantine a call to `it_behaves_like` or `include_examples`](https://github.com/rspec/rspec-core/pull/2307#issuecomment-236006902):
```ruby
# Will be flagged by Rubocop
shared_examples 'loads all the users when opened', quarantine: 'https://gitlab.com/gitlab-org/gitlab/-/issues/12345' do
[...]
end
# Does not work
it_behaves_like 'a shared example', quarantine: 'https://gitlab.com/gitlab-org/gitlab/-/issues/12345'
# Does not work
include_examples 'a shared example', quarantine: 'https://gitlab.com/gitlab-org/gitlab/-/issues/12345'
```
After the long-term quarantining MR has reached production, you should revert the fast-quarantine MR you created earlier.
##### Find quarantined tests by feature category
To find all quarantined tests for a feature category, use `ripgrep`:
```shell
rg -l --multiline -w "(?s)feature_category:\s+:global_search.+quarantine:"
```
#### Jest
For Jest specs, you can use the `.skip` method along with the `eslint-disable-next-line` comment to disable the `jest/no-disabled-tests` ESLint rule and include the issue URL. Here's an example:
```javascript
// quarantine: https://gitlab.com/gitlab-org/gitlab/-/issues/56789
// eslint-disable-next-line jest/no-disabled-tests
it.skip('should throw an error', () => {
expect(response).toThrowError(expected_error)
});
```
This means it is skipped unless the test suit is run with `--runInBand` Jest command line option:
```shell
jest --runInBand
```
A list of files with quarantined specs in them can be found with the command:
```shell
yarn jest:quarantine
```
For both test frameworks, make sure to add the `~"quarantined test"` label to the issue.
Once a test is in quarantine, there are 3 choices:
- Fix the test (that is, get rid of its flakiness).
- Move the test to a lower level of testing.
- Remove the test entirely (for example, because there's already a
lower-level test, or it's duplicating another same-level test, or it's testing
too much etc.).
### Automatic retries and flaky tests detection
On our CI, we use [`RSpec::Retry`](https://github.com/NoRedInk/rspec-retry) to automatically retry a failing example a few
times (see [`spec/spec_helper.rb`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/spec/spec_helper.rb) for the precise retries count).
We also use a custom [`Gitlab::RspecFlaky::Listener`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/gems/gitlab-rspec_flaky/lib/gitlab/rspec_flaky/listener.rb).
This listener runs in the `update-tests-metadata` job in `maintenance` scheduled pipelines
on the `master` branch, and saves flaky examples to `rspec/flaky/report-suite.json`.
The report file is then retrieved by the `retrieve-tests-metadata` job in all pipelines.
This was originally implemented in: <https://gitlab.com/gitlab-org/gitlab-foss/-/merge_requests/13021>.
If you want to enable retries locally, you can use the `RETRIES` environment variable.
For instance `RETRIES=1 bin/rspec ...` would retry the failing examples once.
To generate the reports locally, use the `FLAKY_RSPEC_GENERATE_REPORT` environment variable.
For example, `FLAKY_RSPEC_GENERATE_REPORT=1 bin/rspec ...`.
#### Usage of the `rspec/flaky/report-suite.json` report
The `rspec/flaky/report-suite.json` report is
[imported into Snowflake](https://gitlab.com/gitlab-data/analytics/-/blob/7085bea51bb2f8f823e073393934ba5f97259459/extract/gitlab_flaky_tests/upload.py#L19)
once per day, for monitoring with the
[internal dashboard](https://app.periscopedata.com/app/gitlab/888968/EP---Flaky-tests).
### Problems we had in the past at GitLab
- [`rspec-retry` is biting us when some API specs fail](https://gitlab.com/gitlab-org/gitlab-foss/-/issues/29242): <https://gitlab.com/gitlab-org/gitlab-foss/-/merge_requests/9825>
- [Sporadic RSpec failures due to `PG::UniqueViolation`](https://gitlab.com/gitlab-org/gitlab-foss/-/issues/28307#note_24958837): <https://gitlab.com/gitlab-org/gitlab-foss/-/merge_requests/9846>
- Follow-up: <https://gitlab.com/gitlab-org/gitlab-foss/-/merge_requests/10688>
- [Capybara.reset_session! should be called before requests are blocked](https://gitlab.com/gitlab-org/gitlab-foss/-/issues/33779): <https://gitlab.com/gitlab-org/gitlab-foss/-/merge_requests/12224>
- ffaker generates funky data that tests are not ready to handle (and tests should be predictable so that's bad!):
- [Make `spec/mailers/notify_spec.rb` more robust](https://gitlab.com/gitlab-org/gitlab-foss/-/issues/20121): <https://gitlab.com/gitlab-org/gitlab-foss/-/merge_requests/10015>
- [Transient failure in `spec/requests/api/commits_spec.rb`](https://gitlab.com/gitlab-org/gitlab-foss/-/issues/27988#note_25342521): <https://gitlab.com/gitlab-org/gitlab-foss/-/merge_requests/9944>
- [Replace ffaker factory data with sequences](https://gitlab.com/gitlab-org/gitlab-foss/-/issues/29643): <https://gitlab.com/gitlab-org/gitlab-foss/-/merge_requests/10184>
- [Transient failure in spec/finders/issues_finder_spec.rb](https://gitlab.com/gitlab-org/gitlab-foss/-/issues/30211#note_26707685): <https://gitlab.com/gitlab-org/gitlab-foss/-/merge_requests/10404>
#### Order-dependent flaky tests
To identify ordering issues in a single file read about
[how to reproduce a flaky test locally](#how-to-reproduce-a-flaky-test-locally).
Some flaky tests can fail depending on the order they run with other tests. For example:
- <https://gitlab.com/gitlab-org/gitlab/-/issues/327668>
To identify the ordering issues across different files, you can use `scripts/rspec_bisect_flaky`,
which would give us the minimal test combination to reproduce the failure:
1. First obtain the list of specs that ran before the flaky test. You can search
for the list under `Knapsack node specs:` in the CI job output log.
1. Save the list of specs as a file, and run:
```shell
cat knapsack_specs.txt | xargs scripts/rspec_bisect_flaky
```
If there is an order-dependency issue, the script above will print the minimal
reproduction.
#### Time-sensitive flaky tests
- <https://gitlab.com/gitlab-org/gitlab-foss/-/merge_requests/10046>
- <https://gitlab.com/gitlab-org/gitlab-foss/-/merge_requests/10306>
#### Array order expectation
- <https://gitlab.com/gitlab-org/gitlab-foss/-/merge_requests/10148>
#### Feature tests
- [Be sure to create all the data the test need before starting exercise](https://gitlab.com/gitlab-org/gitlab-foss/-/issues/32622#note_31128195): <https://gitlab.com/gitlab-org/gitlab-foss/-/merge_requests/12059>
- [Bis](https://gitlab.com/gitlab-org/gitlab-foss/-/issues/34609#note_34048715): <https://gitlab.com/gitlab-org/gitlab-foss/-/merge_requests/12604>
- [Bis](https://gitlab.com/gitlab-org/gitlab-foss/-/issues/34698#note_34276286): <https://gitlab.com/gitlab-org/gitlab-foss/-/merge_requests/12664>
- [Assert against the underlying database state instead of against a page's content](https://gitlab.com/gitlab-org/gitlab-foss/-/issues/31437): <https://gitlab.com/gitlab-org/gitlab-foss/-/merge_requests/10934>
- In JS tests, shifting elements can cause Capybara to mis-click when the element moves at the exact time Capybara sends the click
- [Dropdowns rendering upward or downward due to window size and scroll position](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/17660)
- [Lazy loaded images can cause Capybara to mis-click](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/18713)
- [Triggering JS events before the event handlers are set up](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/18742)
- [Wait for the image to be lazy-loaded when asserting on a Markdown image's `src` attribute](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/25408)
- [Avoid asserting against flash notice banners](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/79432)
##### Capybara viewport size related issues
- [Transient failure of spec/features/issues/filtered_search/filter_issues_spec.rb](https://gitlab.com/gitlab-org/gitlab-foss/-/issues/29241#note_26743936): <https://gitlab.com/gitlab-org/gitlab-foss/-/merge_requests/10411>
##### Capybara JS driver related issues
- [Don't wait for AJAX when no AJAX request is fired](https://gitlab.com/gitlab-org/gitlab-foss/-/issues/30461): <https://gitlab.com/gitlab-org/gitlab-foss/-/merge_requests/10454>
- [Bis](https://gitlab.com/gitlab-org/gitlab-foss/-/issues/34647): <https://gitlab.com/gitlab-org/gitlab-foss/-/merge_requests/12626>
##### Capybara expectation times out
- [Test imports a project (via Sidekiq) that is growing over time, leading to timeouts when the import takes longer than 60 seconds](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/22599)
#### Hanging specs
If a spec hangs, or times out in CI, it might be caused by a
[LoadInterlockAwareMonitor deadlock bug in Rails](https://github.com/rails/rails/issues/45994).
To diagnose, you can use
[sigdump](https://github.com/fluent/sigdump/blob/master/README.md#usage)
to print the Ruby thread dump :
1. Run the hanging spec locally.
1. Trigger the Ruby thread dump by running this command:
```shell
kill -CONT <pid>
```
1. The thread dump will be saved to the `/tmp/sigdump-<pid>.log` file.
If you see lines with `load_interlock_aware_monitor.rb`, this is likely related:
```shell
/builds/gitlab-org/gitlab/vendor/ruby/3.2.0/gems/activesupport-7.0.8.4/lib/active_support/concurrency/load_interlock_aware_monitor.rb:17:in `mon_enter'
/builds/gitlab-org/gitlab/vendor/ruby/3.2.0/gems/activesupport-7.0.8.4/lib/active_support/concurrency/load_interlock_aware_monitor.rb:22:in `block in synchronize'
/builds/gitlab-org/gitlab/vendor/ruby/3.2.0/gems/activesupport-7.0.8.4/lib/active_support/concurrency/load_interlock_aware_monitor.rb:21:in `handle_interrupt'
/builds/gitlab-org/gitlab/vendor/ruby/3.2.0/gems/activesupport-7.0.8.4/lib/active_support/concurrency/load_interlock_aware_monitor.rb:21:in `synchronize'
```
See examples where we worked around by creating the factories before making
requests:
- <https://gitlab.com/gitlab-org/gitlab/-/merge_requests/81112>
- <https://gitlab.com/gitlab-org/gitlab/-/merge_requests/158890>
- <https://gitlab.com/gitlab-org/gitlab/-/issues/337039>
### Suggestions
#### Split the test file
It could help to split the large RSpec files in multiple files in order to narrow down the context and identify the problematic tests.
#### Recreate job failure in CI by forcing the job to run the same set of test files
Reproducing a job failure in CI always helps with troubleshooting why and how a test fails. This require us running the same test files with the same spec order. Since we use Knapsack to distribute tests across parallelized jobs, and files can be distributed differently between two pipelines, we can hardcode this job distribution through the following steps:
1. Find a job that you want to reproduce, identify the commit that it ran against, set your local `gitlab-org/gitlab` branch to the same commit to ensure we are running with the same copy of the project.
1. In the job log, locate the list of spec files that were distributed by Knapsack - you can search for `Running command: bundle exec rspec`, the last argument of this command should contain a list of filenames. Copy this list.
1. Go to `tooling/lib/tooling/parallel_rspec_runner.rb` where the test file distribution happens. Have a look at [this merge request](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/137924/diffs) as an example, store the file list you copied from step 2 into a `TEST_FILES` constant and have RSpec run this list by updating the `rspec_command` method as done in the example MR.
1. Skip the tests in `spec/tooling/lib/tooling/parallel_rspec_runner_spec.rb` so it doesn't cause your pipeline to fail early.
1. Since we want to force the pipeline to run against a specific version, we do not want to run a merged results pipeline. We can introduce a merge conflict into the MR to achieve this.
1. To preserve spec ordering, update the `spec/support/rspec_order.rb` file by hard coding `Kernel.srand` with the value shown in the originally failing job, as done [here](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/128428/diffs#32f6fa4961481518204e227252552dba7483c3b0_62_62). You can fine the srand value in the job log by searching `Randomized with seed` which is followed by this value.
### Metrics & Tracking
- [(Snowflake) Flaky tests Dashboard](https://app.snowflake.com/ys68254/gitlab/#/flaky-tests-dcwtdvVO6) (internal)
- [(Snowflake) Unhealthy tests Dashboard](https://app.snowflake.com/ys68254/gitlab/#/dx-unhealthy-tests-d9MEFZz14) (internal)
- [(GitLab) GitLab.org Group Flaky Test Issue Board](https://gitlab.com/groups/gitlab-org/-/boards/1487067?label_name%5B%5D=failure::flaky-test)
- [(GitLab) "Most flaky tests" Issue Board](https://gitlab.com/groups/gitlab-org/-/boards/7518854?label_name%5B%5D=flakiness::1)
- [(Grafana) End-to-end test flakiness Dashboard](https://dashboards.quality.gitlab.net/d/tR_SmBDVk/main-runs?orgId=1) (internal)
- [(Tableau) Flaky test issues](https://10az.online.tableau.com/#/site/gitlab/workbooks/2283052/views) (internal)
### Resources
- [Flaky Tests: Are You Sure You Want to Rerun Them?](https://semaphoreci.com/blog/2017/04/20/flaky-tests.html)
- [How to Deal With and Eliminate Flaky Tests](https://semaphoreci.com/community/tutorials/how-to-deal-with-and-eliminate-flaky-tests)
- [Tips on Treating Flakiness in your Rails Test Suite](https://semaphoreci.com/blog/2017/08/03/tips-on-treating-flakiness-in-your-test-suite.html)
- ['Flaky' tests: a short story](https://www.ombulabs.com/blog/rspec/continuous-integration/how-to-track-down-a-flaky-test.html)
- [Test Insights](https://circleci.com/docs/insights-tests/)
## Slow tests
### Top slow tests
We collect information about tests duration in [`rspec_profiling_stats`](https://gitlab.com/gitlab-org/rspec_profiling_stats) project. The data is showed using GitLab Pages in this
[UI](https://gitlab-org.gitlab.io/rspec_profiling_stats/)
In this [issue](https://gitlab.com/gitlab-org/gitlab/-/issues/375983), we defined thresholds for tests duration that can act as a guide.
For tests that are above the thresholds, we automatically report slowness occurrences in [Test issues](https://gitlab.com/gitlab-org/gitlab/-/issues/?sort=created_date&state=opened&label_name%5B%5D=rspec%3Aslow%20test&first_page_size=100) so that groups can improve them.
For tests that are slow for a legitimate reason and to skip issue creation, add `allowed_to_be_slow: true`.
| Date | Feature tests | Controllers and Requests tests | Unit | Other | Method |
|:----------:|:-------------:|:------------------------------:|:-----:|:-------------:|:------:|
| 2023-02-15 | 67.42 seconds | 44.66 seconds | - | 76.86 seconds | Top slow test eliminating the maximum |
| 2023-06-15 | 50.13 seconds | 19.20 seconds | 27.12 | 45.40 seconds | Avg for top 100 slow tests |
## Handling issues for flaky or slow tests
The process around these issues is very lightweight. Feel free to close them or not, they're [managed automatically](https://gitlab.com/gitlab-org/ruby/gems/gitlab_quality-test_tooling/-/blob/main/lib/gitlab_quality/test_tooling/report/flaky_test_issue.rb):
- If a flaky or slow test is fixed and the associated `[Test]` issue isn't closed manually, it will be closed automatically after [30 days of inactivity](https://gitlab.com/gitlab-org/quality/triage-ops/-/blob/master/policies/stages/hygiene/close-stale-unhealthy-test-issues.yml).
- If the problem reoccurs, the closed issue is reopened automatically. This means, it is also okay to close an issue when you think you fixed it.
---
[Return to Testing documentation](_index.md)
|
---
stage: none
group: unassigned
info: 'See the Technical Writers assigned to Development Guidelines: https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments-to-development-guidelines'
description: GitLab development guidelines - Unhealthy tests.
title: Unhealthy tests
breadcrumbs:
- doc
- development
- testing_guide
---
## Flaky tests
### What's a flaky test?
It's a test that sometimes fails, but if you retry it enough times, it passes,
eventually.
### What are the potential cause for a test to be flaky?
#### State leak
**Label**: `flaky-test::state leak`
**Description**: Data state has leaked from a previous test. The actual cause is probably not the flaky test here.
**Difficulty to reproduce**: Moderate. Usually, running the same spec files until the one that's failing reproduces the problem.
**Resolution**: Fix the previous tests and/or places where the test data or environment is modified, so that
it's reset to a pristine test after each test.
**Examples**:
- [Example 1](https://gitlab.com/gitlab-org/gitlab/-/issues/402915): State leakage can result from
data records created with `let_it_be` shared between test examples, while some test modifies the model
either deliberately or unwillingly causing out-of-sync data in test examples. This can result in `PG::QueryCanceled: ERROR` in the subsequent test examples or retries.
For more information about state leakages and resolution options, see [GitLab testing best practices](best_practices.md#lets-talk-about-let).
- [Example 2](https://gitlab.com/gitlab-org/gitlab/-/issues/378414#note_1142026988): A migration
test might roll-back the database, perform its testing, and then roll-up the database in an
inconsistent state, so that following tests might not know about certain columns.
- [Example 3](https://gitlab.com/gitlab-org/gitlab/-/issues/368500): A test modifies data that is
used by a following test.
- [Example 4](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/103434#note_1172316521): A test for a database query passes in a fresh database, but in a
CI/CD pipeline where the database is used to process previous test sequences, the test fails. This likely
means that the query itself needs to be updated to work in a non-clean database.
- [Example 5](https://gitlab.com/gitlab-org/gitlab/-/issues/416663#note_1457867234): Unrelated database connections
in asynchronous requests checked back in, causing the tests to accidentally
use these unrelated database connections. The failure was resolved in this
[merge request](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/125742).
- [Example 6](https://gitlab.com/gitlab-org/gitlab/-/issues/418757#note_1502138269): The maximum time to live
for a database connection causes these connections to be disconnected, which
in turn causes tests that rely on the transactions on these connections to
in turn causes tests that rely on the transactions on these connections to
fail. The issue was fixed in this [merge request](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/128567).
- [Example 7](https://gitlab.com/gitlab-org/quality/engineering-productivity/master-broken-incidents/-/issues/3389#note_1534827164):
A TCP socket used in a test was not closed before the next test, which also used
the same port with another TCP socket.
[Example 8](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/179302#note_2324238692): A `let_it_be` depended on a stub defined in a `before` block. `let_it_be` executes during `before(:all)`, so the stub was not yet set. This exposed the tests to the actual method call, which happened to use a method cache.
#### Dataset-specific
**Label**: `flaky-test::dataset-specific`
**Description**: The test assumes the dataset is in a particular (usually limited) state or order, which
might not be true depending on when the test run during the test suite.
**Difficulty to reproduce**: Moderate, as the amount of data needed to reproduce the issue might be
difficult to achieve locally. Ordering issues are easier to reproduce by repeatedly running the tests several times.
**Resolution**:
- Fix the test to not assume that the dataset is in a particular state, don't hardcode IDs.
- Loosen the assertion if the test shouldn't care about ordering but only on the elements.
- Fix the test by specifying a deterministic ordering.
- Fix the app code by specifying a deterministic ordering.
**Examples**:
- [Example 1](https://gitlab.com/gitlab-org/gitlab/-/issues/378381): The database is recreated when
any table has more than 500 columns. It could pass in the merge request, but fail later in
`master` if the order of tests changes.
- [Example 2](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/91016/diffs): A test asserts
that trying to find a record with a nonexistent ID returns an error message. The test uses an
hardcoded ID that's supposed to not exist (for example, `42`). If the test is run early in the test
suite, it might pass as not enough records were created before it, but as soon as it would run
later in the suite, there could be a record that actually has the ID `42`, hence the test would
start to fail.
- [Example 3](https://gitlab.com/gitlab-org/gitlab-foss/-/merge_requests/10148/diffs): Without
specifying `ORDER BY`, database is not given deterministic ordering, or data race can happen
in the tests.
- [Example 4](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/106936/diffs).
#### Too Many SQL queries
**Label**: `flaky-test::too-many-sql-queries`
**Description**: SQL Query limit has reached triggering `Gitlab::QueryLimiting::Transaction::ThresholdExceededError`.
**Difficulty to reproduce**: Moderate, this failure may depend on the state of query cache which can be impacted by order of specs.
**Resolution**: See [query count limits docs](../database/query_count_limits.md#solving-failing-tests).
#### Random input
**Label**: `flaky-test::random input`
**Description**: The test use random values, that sometimes match the expectations, and sometimes not.
**Difficulty to reproduce**: Easy, as the test can be modified locally to use the "random value"
used at the time the test failed
**Resolution**: Once the problem is reproduced, it should be easy to debug and fix either the test
or the app.
**Examples**:
- [Example 1](https://gitlab.com/gitlab-org/gitlab-foss/-/issues/20121): The test isn't robust enough to handle a specific data, that only appears sporadically since the data input is random.
#### Unreliable DOM Selector
**Label**: `flaky-test::unreliable dom selector`
**Description**: The DOM selector used in the test is unreliable.
**Difficulty to reproduce**: Moderate to difficult. Depending on whether the DOM selector is duplicated, or appears after a delay etc.
Adding a delay in API or controller could help reproducing the issue.
**Resolution**: It really depends on the problem here. It could be to wait for requests to finish, to scroll down the page etc.
**Examples**:
- [Example 1](https://gitlab.com/gitlab-org/gitlab/-/issues/338341): A non-unique CSS selector
matching more than one element, or a non-waiting selector method that does not allow rendering
time before throwing an `element not found` error.
- [Example 2](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/101728/diffs): A CSS selector
only appears after a GraphQL requests has finished, and the UI has updated.
- [Example 3](https://gitlab.com/gitlab-org/gitlab/-/issues/408215): A false-positive test, Capybara immediately returns true after
page visit and page is not fully loaded, or if the element is not detectable by webdriver (such as being rendered outside the viewport or behind other elements).
#### Datetime-sensitive
**Label**: `flaky-test::datetime-sensitive`
**Description**: The test is assuming a specific date or time.
**Difficulty to reproduce**: Easy to moderate, depending on whether the test consistently fails after a certain date, or only fails at a given time or date.
**Resolution**: Freezing the time is usually a good solution.
**Examples**:
- [Example 1](https://gitlab.com/gitlab-org/gitlab/-/issues/118612): A test that breaks after some time passed.
- [Example 2](https://gitlab.com/gitlab-org/gitlab/-/issues/403332): A test that breaks in the last day of the month.
#### Unstable infrastructure
**Label**: `flaky-test::unstable infrastructure`
**Description**: The test fails from time to time due to infrastructure issues.
**Difficulty to reproduce**: Hard. It's really hard to reproduce CI infrastructure issues. It might
be possible by using containers locally.
**Resolution**: Starting a conversation with the Infrastructure department in a dedicated issue is
usually a good idea.
**Examples**:
- [Example 1](https://gitlab.com/gitlab-org/gitlab/-/issues/363214): The runner is under heavy load at this time.
- [Example 2](https://gitlab.com/gitlab-org/gitlab/-/issues/360559): The runner is having networking issues, making a job failing early
#### Improper Synchronization
**Label**: `flaky-test::improper synchronization`
**Description**: A flaky test issue arising from timing-related factors, such as delays, eventual consistency, asynchronous operations, or race conditions.
These issues may stem from shortcomings in the test logic, the system under test, or their interaction.
While tests can sometimes address these issues through improved synchronization, they may also reveal underlying system bugs that require resolution.
**Difficulty to reproduce**: Moderate. It can be reproduced, for example, in feature tests by attempting to reference an
element on a page that is not yet rendered, or in unit tests by failing to wait for an asynchronous operation to complete.
**Resolution**: In the end-to-end test suite, using [an eventually matcher](end_to_end/best_practices/_index.md#use-eventually_-matchers-for-expectations-that-require-waiting).
**Examples**:
- [Example 1](https://gitlab.com/gitlab-org/gitlab/-/issues/502844): Text was not appearing on a page in time.
- [Example 2](https://gitlab.com/gitlab-org/gitlab/-/issues/496393): Text was not appearing on a page in time.
### How to reproduce a flaky test locally?
1. Reproduce the failure locally
- Find RSpec `seed` from the CI job log
- OR Run `while :; do bin/rspec <spec> || break; done` in a loop to find a `seed`
1. Reduce the examples by bisecting the spec failure with
`bin/rspec --seed <previously found> --require ./config/initializers/macos.rb --bisect <spec>`
1. Look at the remaining examples and watch for state leakage
- For example, updating records created with `let_it_be` is a common source of problems
1. Once fixed, rerun the specs with `seed`
1. Run `scripts/rspec_check_order_dependence` to ensure the spec can be run in [random order](best_practices.md#test-order)
1. Run `while :; do bin/rspec <spec> || break; done` in a loop again (and grab lunch) to verify it's no longer flaky
### Quarantined tests
When we have a flaky test in `master`:
1. Create [a ~"failure::flaky-test" issue](https://handbook.gitlab.com/handbook/engineering/workflow/#broken-master) with the relevant group label.
1. Quarantine the test after the first failure.
If the test cannot be fixed in a timely fashion, there is an impact on the
productivity of all the developers, so it should be quarantined.
#### RSpec
##### Fast quarantine
Unless you really need to have a test disabled very fast (`< 10min`), consider [using the `~pipeline::expedited` label instead](../pipelines/_index.md#the-pipelineexpedited-label).
To quickly quarantine a test without having to open a merge request and wait for pipelines,
you can follow [the fast quarantining process](https://gitlab.com/gitlab-org/quality/engineering-productivity/fast-quarantine/-/tree/main/#fast-quarantine-a-test).
**Always proceed** to [open a long-term quarantine merge request](#long-term-quarantine) after fast-quarantining a test! This is to ensure the fast-quarantined test was correctly fixed by running tests from the CI/CD pipelines (which are not run in the context of the fast-quarantine project).
##### Long-term quarantine
Once a test is fast-quarantined, you can proceed with the long-term quarantining process. This can be done by opening a merge request.
First, ensure the test file has a [`feature_category` metadata](../feature_categorization/_index.md#rspec-examples), to ensure correct attribution of the test file.
Then, you can use the `quarantine: '<issue url>'` metadata with the URL of the
~"failure::flaky-test" issue you created previously.
```ruby
# Quarantine a single spec
it 'succeeds', quarantine: 'https://gitlab.com/gitlab-org/gitlab/-/issues/12345' do
expect(response).to have_gitlab_http_status(:ok)
end
# Quarantine a describe/context block
describe '#flaky-method', quarantine: 'https://gitlab.com/gitlab-org/gitlab/-/issues/12345' do
[...]
end
```
This means it will be skipped in CI. By default, the quarantined tests will run locally.
We can skip them in local development as well by running with `--tag ~quarantine`:
```shell
# Bash
bin/rspec --tag ~quarantine
# ZSH
bin/rspec --tag \~quarantine
```
Also, ensure that:
1. The ~"quarantine" label is present on the merge request.
1. The MR description mentions the flaky test issue with [the usual terms to link a merge request to an issue](https://gitlab.com/gitlab-org/quality/triage-ops/-/blob/8b8621ba5c0db3c044a771ebf84887a0a07353b3/triage/triage/related_issue_finder.rb#L8-18).
Note that we [should not quarantine a shared example/context](https://gitlab.com/gitlab-org/gitlab/-/issues/404388), and [we cannot quarantine a call to `it_behaves_like` or `include_examples`](https://github.com/rspec/rspec-core/pull/2307#issuecomment-236006902):
```ruby
# Will be flagged by Rubocop
shared_examples 'loads all the users when opened', quarantine: 'https://gitlab.com/gitlab-org/gitlab/-/issues/12345' do
[...]
end
# Does not work
it_behaves_like 'a shared example', quarantine: 'https://gitlab.com/gitlab-org/gitlab/-/issues/12345'
# Does not work
include_examples 'a shared example', quarantine: 'https://gitlab.com/gitlab-org/gitlab/-/issues/12345'
```
After the long-term quarantining MR has reached production, you should revert the fast-quarantine MR you created earlier.
##### Find quarantined tests by feature category
To find all quarantined tests for a feature category, use `ripgrep`:
```shell
rg -l --multiline -w "(?s)feature_category:\s+:global_search.+quarantine:"
```
#### Jest
For Jest specs, you can use the `.skip` method along with the `eslint-disable-next-line` comment to disable the `jest/no-disabled-tests` ESLint rule and include the issue URL. Here's an example:
```javascript
// quarantine: https://gitlab.com/gitlab-org/gitlab/-/issues/56789
// eslint-disable-next-line jest/no-disabled-tests
it.skip('should throw an error', () => {
expect(response).toThrowError(expected_error)
});
```
This means it is skipped unless the test suit is run with `--runInBand` Jest command line option:
```shell
jest --runInBand
```
A list of files with quarantined specs in them can be found with the command:
```shell
yarn jest:quarantine
```
For both test frameworks, make sure to add the `~"quarantined test"` label to the issue.
Once a test is in quarantine, there are 3 choices:
- Fix the test (that is, get rid of its flakiness).
- Move the test to a lower level of testing.
- Remove the test entirely (for example, because there's already a
lower-level test, or it's duplicating another same-level test, or it's testing
too much etc.).
### Automatic retries and flaky tests detection
On our CI, we use [`RSpec::Retry`](https://github.com/NoRedInk/rspec-retry) to automatically retry a failing example a few
times (see [`spec/spec_helper.rb`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/spec/spec_helper.rb) for the precise retries count).
We also use a custom [`Gitlab::RspecFlaky::Listener`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/gems/gitlab-rspec_flaky/lib/gitlab/rspec_flaky/listener.rb).
This listener runs in the `update-tests-metadata` job in `maintenance` scheduled pipelines
on the `master` branch, and saves flaky examples to `rspec/flaky/report-suite.json`.
The report file is then retrieved by the `retrieve-tests-metadata` job in all pipelines.
This was originally implemented in: <https://gitlab.com/gitlab-org/gitlab-foss/-/merge_requests/13021>.
If you want to enable retries locally, you can use the `RETRIES` environment variable.
For instance `RETRIES=1 bin/rspec ...` would retry the failing examples once.
To generate the reports locally, use the `FLAKY_RSPEC_GENERATE_REPORT` environment variable.
For example, `FLAKY_RSPEC_GENERATE_REPORT=1 bin/rspec ...`.
#### Usage of the `rspec/flaky/report-suite.json` report
The `rspec/flaky/report-suite.json` report is
[imported into Snowflake](https://gitlab.com/gitlab-data/analytics/-/blob/7085bea51bb2f8f823e073393934ba5f97259459/extract/gitlab_flaky_tests/upload.py#L19)
once per day, for monitoring with the
[internal dashboard](https://app.periscopedata.com/app/gitlab/888968/EP---Flaky-tests).
### Problems we had in the past at GitLab
- [`rspec-retry` is biting us when some API specs fail](https://gitlab.com/gitlab-org/gitlab-foss/-/issues/29242): <https://gitlab.com/gitlab-org/gitlab-foss/-/merge_requests/9825>
- [Sporadic RSpec failures due to `PG::UniqueViolation`](https://gitlab.com/gitlab-org/gitlab-foss/-/issues/28307#note_24958837): <https://gitlab.com/gitlab-org/gitlab-foss/-/merge_requests/9846>
- Follow-up: <https://gitlab.com/gitlab-org/gitlab-foss/-/merge_requests/10688>
- [Capybara.reset_session! should be called before requests are blocked](https://gitlab.com/gitlab-org/gitlab-foss/-/issues/33779): <https://gitlab.com/gitlab-org/gitlab-foss/-/merge_requests/12224>
- ffaker generates funky data that tests are not ready to handle (and tests should be predictable so that's bad!):
- [Make `spec/mailers/notify_spec.rb` more robust](https://gitlab.com/gitlab-org/gitlab-foss/-/issues/20121): <https://gitlab.com/gitlab-org/gitlab-foss/-/merge_requests/10015>
- [Transient failure in `spec/requests/api/commits_spec.rb`](https://gitlab.com/gitlab-org/gitlab-foss/-/issues/27988#note_25342521): <https://gitlab.com/gitlab-org/gitlab-foss/-/merge_requests/9944>
- [Replace ffaker factory data with sequences](https://gitlab.com/gitlab-org/gitlab-foss/-/issues/29643): <https://gitlab.com/gitlab-org/gitlab-foss/-/merge_requests/10184>
- [Transient failure in spec/finders/issues_finder_spec.rb](https://gitlab.com/gitlab-org/gitlab-foss/-/issues/30211#note_26707685): <https://gitlab.com/gitlab-org/gitlab-foss/-/merge_requests/10404>
#### Order-dependent flaky tests
To identify ordering issues in a single file read about
[how to reproduce a flaky test locally](#how-to-reproduce-a-flaky-test-locally).
Some flaky tests can fail depending on the order they run with other tests. For example:
- <https://gitlab.com/gitlab-org/gitlab/-/issues/327668>
To identify the ordering issues across different files, you can use `scripts/rspec_bisect_flaky`,
which would give us the minimal test combination to reproduce the failure:
1. First obtain the list of specs that ran before the flaky test. You can search
for the list under `Knapsack node specs:` in the CI job output log.
1. Save the list of specs as a file, and run:
```shell
cat knapsack_specs.txt | xargs scripts/rspec_bisect_flaky
```
If there is an order-dependency issue, the script above will print the minimal
reproduction.
#### Time-sensitive flaky tests
- <https://gitlab.com/gitlab-org/gitlab-foss/-/merge_requests/10046>
- <https://gitlab.com/gitlab-org/gitlab-foss/-/merge_requests/10306>
#### Array order expectation
- <https://gitlab.com/gitlab-org/gitlab-foss/-/merge_requests/10148>
#### Feature tests
- [Be sure to create all the data the test need before starting exercise](https://gitlab.com/gitlab-org/gitlab-foss/-/issues/32622#note_31128195): <https://gitlab.com/gitlab-org/gitlab-foss/-/merge_requests/12059>
- [Bis](https://gitlab.com/gitlab-org/gitlab-foss/-/issues/34609#note_34048715): <https://gitlab.com/gitlab-org/gitlab-foss/-/merge_requests/12604>
- [Bis](https://gitlab.com/gitlab-org/gitlab-foss/-/issues/34698#note_34276286): <https://gitlab.com/gitlab-org/gitlab-foss/-/merge_requests/12664>
- [Assert against the underlying database state instead of against a page's content](https://gitlab.com/gitlab-org/gitlab-foss/-/issues/31437): <https://gitlab.com/gitlab-org/gitlab-foss/-/merge_requests/10934>
- In JS tests, shifting elements can cause Capybara to mis-click when the element moves at the exact time Capybara sends the click
- [Dropdowns rendering upward or downward due to window size and scroll position](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/17660)
- [Lazy loaded images can cause Capybara to mis-click](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/18713)
- [Triggering JS events before the event handlers are set up](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/18742)
- [Wait for the image to be lazy-loaded when asserting on a Markdown image's `src` attribute](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/25408)
- [Avoid asserting against flash notice banners](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/79432)
##### Capybara viewport size related issues
- [Transient failure of spec/features/issues/filtered_search/filter_issues_spec.rb](https://gitlab.com/gitlab-org/gitlab-foss/-/issues/29241#note_26743936): <https://gitlab.com/gitlab-org/gitlab-foss/-/merge_requests/10411>
##### Capybara JS driver related issues
- [Don't wait for AJAX when no AJAX request is fired](https://gitlab.com/gitlab-org/gitlab-foss/-/issues/30461): <https://gitlab.com/gitlab-org/gitlab-foss/-/merge_requests/10454>
- [Bis](https://gitlab.com/gitlab-org/gitlab-foss/-/issues/34647): <https://gitlab.com/gitlab-org/gitlab-foss/-/merge_requests/12626>
##### Capybara expectation times out
- [Test imports a project (via Sidekiq) that is growing over time, leading to timeouts when the import takes longer than 60 seconds](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/22599)
#### Hanging specs
If a spec hangs, or times out in CI, it might be caused by a
[LoadInterlockAwareMonitor deadlock bug in Rails](https://github.com/rails/rails/issues/45994).
To diagnose, you can use
[sigdump](https://github.com/fluent/sigdump/blob/master/README.md#usage)
to print the Ruby thread dump :
1. Run the hanging spec locally.
1. Trigger the Ruby thread dump by running this command:
```shell
kill -CONT <pid>
```
1. The thread dump will be saved to the `/tmp/sigdump-<pid>.log` file.
If you see lines with `load_interlock_aware_monitor.rb`, this is likely related:
```shell
/builds/gitlab-org/gitlab/vendor/ruby/3.2.0/gems/activesupport-7.0.8.4/lib/active_support/concurrency/load_interlock_aware_monitor.rb:17:in `mon_enter'
/builds/gitlab-org/gitlab/vendor/ruby/3.2.0/gems/activesupport-7.0.8.4/lib/active_support/concurrency/load_interlock_aware_monitor.rb:22:in `block in synchronize'
/builds/gitlab-org/gitlab/vendor/ruby/3.2.0/gems/activesupport-7.0.8.4/lib/active_support/concurrency/load_interlock_aware_monitor.rb:21:in `handle_interrupt'
/builds/gitlab-org/gitlab/vendor/ruby/3.2.0/gems/activesupport-7.0.8.4/lib/active_support/concurrency/load_interlock_aware_monitor.rb:21:in `synchronize'
```
See examples where we worked around by creating the factories before making
requests:
- <https://gitlab.com/gitlab-org/gitlab/-/merge_requests/81112>
- <https://gitlab.com/gitlab-org/gitlab/-/merge_requests/158890>
- <https://gitlab.com/gitlab-org/gitlab/-/issues/337039>
### Suggestions
#### Split the test file
It could help to split the large RSpec files in multiple files in order to narrow down the context and identify the problematic tests.
#### Recreate job failure in CI by forcing the job to run the same set of test files
Reproducing a job failure in CI always helps with troubleshooting why and how a test fails. This require us running the same test files with the same spec order. Since we use Knapsack to distribute tests across parallelized jobs, and files can be distributed differently between two pipelines, we can hardcode this job distribution through the following steps:
1. Find a job that you want to reproduce, identify the commit that it ran against, set your local `gitlab-org/gitlab` branch to the same commit to ensure we are running with the same copy of the project.
1. In the job log, locate the list of spec files that were distributed by Knapsack - you can search for `Running command: bundle exec rspec`, the last argument of this command should contain a list of filenames. Copy this list.
1. Go to `tooling/lib/tooling/parallel_rspec_runner.rb` where the test file distribution happens. Have a look at [this merge request](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/137924/diffs) as an example, store the file list you copied from step 2 into a `TEST_FILES` constant and have RSpec run this list by updating the `rspec_command` method as done in the example MR.
1. Skip the tests in `spec/tooling/lib/tooling/parallel_rspec_runner_spec.rb` so it doesn't cause your pipeline to fail early.
1. Since we want to force the pipeline to run against a specific version, we do not want to run a merged results pipeline. We can introduce a merge conflict into the MR to achieve this.
1. To preserve spec ordering, update the `spec/support/rspec_order.rb` file by hard coding `Kernel.srand` with the value shown in the originally failing job, as done [here](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/128428/diffs#32f6fa4961481518204e227252552dba7483c3b0_62_62). You can fine the srand value in the job log by searching `Randomized with seed` which is followed by this value.
### Metrics & Tracking
- [(Snowflake) Flaky tests Dashboard](https://app.snowflake.com/ys68254/gitlab/#/flaky-tests-dcwtdvVO6) (internal)
- [(Snowflake) Unhealthy tests Dashboard](https://app.snowflake.com/ys68254/gitlab/#/dx-unhealthy-tests-d9MEFZz14) (internal)
- [(GitLab) GitLab.org Group Flaky Test Issue Board](https://gitlab.com/groups/gitlab-org/-/boards/1487067?label_name%5B%5D=failure::flaky-test)
- [(GitLab) "Most flaky tests" Issue Board](https://gitlab.com/groups/gitlab-org/-/boards/7518854?label_name%5B%5D=flakiness::1)
- [(Grafana) End-to-end test flakiness Dashboard](https://dashboards.quality.gitlab.net/d/tR_SmBDVk/main-runs?orgId=1) (internal)
- [(Tableau) Flaky test issues](https://10az.online.tableau.com/#/site/gitlab/workbooks/2283052/views) (internal)
### Resources
- [Flaky Tests: Are You Sure You Want to Rerun Them?](https://semaphoreci.com/blog/2017/04/20/flaky-tests.html)
- [How to Deal With and Eliminate Flaky Tests](https://semaphoreci.com/community/tutorials/how-to-deal-with-and-eliminate-flaky-tests)
- [Tips on Treating Flakiness in your Rails Test Suite](https://semaphoreci.com/blog/2017/08/03/tips-on-treating-flakiness-in-your-test-suite.html)
- ['Flaky' tests: a short story](https://www.ombulabs.com/blog/rspec/continuous-integration/how-to-track-down-a-flaky-test.html)
- [Test Insights](https://circleci.com/docs/insights-tests/)
## Slow tests
### Top slow tests
We collect information about tests duration in [`rspec_profiling_stats`](https://gitlab.com/gitlab-org/rspec_profiling_stats) project. The data is showed using GitLab Pages in this
[UI](https://gitlab-org.gitlab.io/rspec_profiling_stats/)
In this [issue](https://gitlab.com/gitlab-org/gitlab/-/issues/375983), we defined thresholds for tests duration that can act as a guide.
For tests that are above the thresholds, we automatically report slowness occurrences in [Test issues](https://gitlab.com/gitlab-org/gitlab/-/issues/?sort=created_date&state=opened&label_name%5B%5D=rspec%3Aslow%20test&first_page_size=100) so that groups can improve them.
For tests that are slow for a legitimate reason and to skip issue creation, add `allowed_to_be_slow: true`.
| Date | Feature tests | Controllers and Requests tests | Unit | Other | Method |
|:----------:|:-------------:|:------------------------------:|:-----:|:-------------:|:------:|
| 2023-02-15 | 67.42 seconds | 44.66 seconds | - | 76.86 seconds | Top slow test eliminating the maximum |
| 2023-06-15 | 50.13 seconds | 19.20 seconds | 27.12 | 45.40 seconds | Avg for top 100 slow tests |
## Handling issues for flaky or slow tests
The process around these issues is very lightweight. Feel free to close them or not, they're [managed automatically](https://gitlab.com/gitlab-org/ruby/gems/gitlab_quality-test_tooling/-/blob/main/lib/gitlab_quality/test_tooling/report/flaky_test_issue.rb):
- If a flaky or slow test is fixed and the associated `[Test]` issue isn't closed manually, it will be closed automatically after [30 days of inactivity](https://gitlab.com/gitlab-org/quality/triage-ops/-/blob/master/policies/stages/hygiene/close-stale-unhealthy-test-issues.yml).
- If the problem reoccurs, the closed issue is reopened automatically. This means, it is also okay to close an issue when you think you fixed it.
---
[Return to Testing documentation](_index.md)
|
https://docs.gitlab.com/development/best_practices
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/best_practices.md
|
2025-08-13
|
doc/development/testing_guide
|
[
"doc",
"development",
"testing_guide"
] |
best_practices.md
|
none
|
unassigned
|
See the Technical Writers assigned to Development Guidelines: https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments-to-development-guidelines
|
Testing best practices
|
GitLab development guidelines - testing best practices.
|
## Test Design
Testing at GitLab is a first class citizen, not an afterthought. It's important we consider the design of our tests
as we do the design of our features.
When implementing a feature, we think about developing the right capabilities the right way. This helps us
narrow our scope to a manageable level. When implementing tests for a feature, we must think about developing
the right tests, but then cover all the important ways the test may fail. This can quickly widen our scope to
a level that is difficult to manage.
Test heuristics can help solve this problem. They concisely address many of the common ways bugs
manifest themselves in our code. When designing our tests, take time to review known test heuristics to inform
our test design. We can find some helpful heuristics documented in the Handbook in the
[Test Engineering](https://handbook.gitlab.com/handbook/engineering/infrastructure/test-platform/test-engineering/#test-heuristics) section.
## RSpec
To run RSpec tests:
```shell
# run test for a file
bin/rspec spec/models/project_spec.rb
# run test for the example on line 10 on that file
bin/rspec spec/models/project_spec.rb:10
# run tests matching the example name has that string
bin/rspec spec/models/project_spec.rb -e associations
# run all tests, will take hours for GitLab codebase!
bin/rspec
```
Use [Guard](https://github.com/guard/guard) to continuously monitor for changes and only run matching tests:
```shell
bundle exec guard
```
When using spring and guard together, use `SPRING=1 bundle exec guard` instead to make use of spring.
### General guidelines
- Use a single, top-level `RSpec.describe ClassName` block.
- Use `.method` to describe class methods and `#method` to describe instance
methods.
- Use `context` to test branching logic (`RSpec/AvoidConditionalStatements` RuboCop Cop - [MR](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/117152)).
- Try to match the ordering of tests to the ordering in the class.
- Try to follow the [Four-Phase Test](https://thoughtbot.com/blog/four-phase-test) pattern, using newlines
to separate phases.
- Use `Gitlab.config.gitlab.host` rather than hard coding `'localhost'`.
- For literal URLs in tests, use `example.com`, `gitlab.example.com`. This will ensure that we do not utilize any real URLs.
- Don't assert against the absolute value of a sequence-generated attribute (see
[Gotchas](../gotchas.md#do-not-assert-against-the-absolute-value-of-a-sequence-generated-attribute)).
- Avoid using `expect_any_instance_of` or `allow_any_instance_of` (see
[Gotchas](../gotchas.md#avoid-using-expect_any_instance_of-or-allow_any_instance_of-in-rspec)).
- Don't supply the `:each` argument to hooks because it's the default.
- On `before` and `after` hooks, prefer it scoped to `:context` over `:all`.
- When using `evaluate_script("$('.js-foo').testSomething()")` (or `execute_script`) which acts on a given element,
use a Capybara matcher beforehand (such as `find('.js-foo')`) to ensure the element actually exists.
- Use `focus: true` to isolate parts of the specs you want to run.
- Use [`:aggregate_failures`](https://rspec.info/features/3-12/rspec-core/expectation-framework-integration/aggregating-failures/) when there is more than one expectation in a test.
- For [empty test description blocks](https://github.com/rubocop-hq/rspec-style-guide#it-and-specify), use `specify` rather than `it do` if the test is self-explanatory.
- Use `non_existing_record_id`/`non_existing_record_iid`/`non_existing_record_access_level`
when you need an ID/IID/access level that doesn't actually exist. Using 123, 1234,
or even 999 is brittle as these IDs could actually exist in the database in the
context of a CI run.
### Eager loading the application code
By default, the application code:
- Isn't eagerly loaded in the `test` environment.
- Is eagerly loaded in CI/CD (when `ENV['CI'].present?`) to surface any potential loading issues.
If you need to enable eager loading when executing tests,
use the `GITLAB_TEST_EAGER_LOAD` environment variable:
```shell
GITLAB_TEST_EAGER_LOAD=1 bin/rspec spec/models/project_spec.rb
```
If your test depends on all the application code that is being loaded, add the `:eager_load` tag.
This ensures that the application code is eagerly loaded before the test execution.
### Ruby warnings
We've enabled [deprecation warnings](https://ruby-doc.org/core-2.7.4/Warning.html)
by default when running specs. Making these warnings more visible to developers
helps upgrading to newer Ruby versions.
You can silence deprecation warnings by setting the environment variable
`SILENCE_DEPRECATIONS`, for example:
```shell
# silence all deprecation warnings
SILENCE_DEPRECATIONS=1 bin/rspec spec/models/project_spec.rb
```
### Test order
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/93137) in GitLab 15.4.
{{< /history >}}
All new spec files are run in [random order](https://gitlab.com/gitlab-org/gitlab/-/issues/337399)
to surface flaky tests that are dependent on test order.
When randomized:
- The string `# order random` is added below the example group description.
- The used seed is shown in the spec output below the test suite summary. For example, `Randomized with seed 27443`.
For a list of spec files which are still run in defined order, see [`rspec_order_todo.yml`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/spec/support/rspec_order_todo.yml).
To make spec files run in random order, check their order dependency with:
```shell
scripts/rspec_check_order_dependence spec/models/project_spec.rb
```
If the specs pass the check the script removes them from
[`rspec_order_todo.yml`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/spec/support/rspec_order_todo.yml) automatically.
If the specs fail the check they must be fixed before than can run in random order.
### Test flakiness
[Consult the Unhealthy tests page for more information about processes that are in place to avoid flaky tests](unhealthy_tests.md#flaky-tests).
### Test slowness
GitLab has a massive test suite that, without [parallelization](../pipelines/_index.md#test-suite-parallelization), can take hours
to run. It's important that we make an effort to write tests that are accurate
and effective _as well as_ fast.
Test performance is important to maintaining quality and velocity, and has a
direct impact on CI build times and thus fixed costs. We want thorough, correct,
and fast tests. Here you can find some information about tools and techniques
available to you to achieve that.
[Consult the Unhealthy tests page for more information about processes that are in place to avoid slow tests](unhealthy_tests.md#slow-tests).
#### Don't request capabilities you don't need
We make it easy to add capabilities to our examples by annotating the example or
a parent context. Examples of these are:
- `:js` in feature specs, which runs a full JavaScript capable headless browser.
- `:clean_gitlab_redis_cache` which provides a clean Redis cache to the examples.
- `:request_store` which provides a request store to the examples.
We should reduce test dependencies, and avoiding
capabilities also reduces the amount of set-up needed.
`:js` is particularly important to avoid. This must only be used if the feature
test requires JavaScript reactivity in the browser (for example, clicking a Vue.js component). Using a headless
browser is much slower than parsing the HTML response from the app.
#### Profiling: see where your test spend its time
[`rspec-stackprof`](https://github.com/dkhroad/rspec-stackprof) can be used to generate a flame graph that shows you where you test spend its time.
The gem generates a JSON report that we can upload to <https://www.speedscope.app> for an interactive visualization.
##### Installation
`stackprof` gem is [already installed with GitLab](https://gitlab.com/gitlab-org/gitlab/-/blob/695fcee0c5541b4ead0a90eb9b8bf0b69bee796c/Gemfile#L487), and we also have a script available that generates the JSON report (`bin/rspec-stackprof`).
```shell
# Optional: install the `speedscope` package to easily upload the JSON report to https://www.speedscope.app
npm install -g speedscope
```
##### Generate the JSON report
```shell
bin/rspec-stackprof --speedscope=true <your_slow_spec>
# There will be the name of the report displayed when the script ends.
# Upload the JSON report to speedscope.app
speedscope tmp/<your-json-report>.json
```
##### How to interpret the flamegraph
Below are some useful tips to interpret and navigate the flamegraph:
- There are [several views available](https://github.com/jlfwong/speedscope#views) for the flamegraph. `Left Heavy` is particularly useful when there are a lot of function calls (for example, feature specs).
- You can zoom in or out! See [the navigation documentation](https://github.com/jlfwong/speedscope#navigation)
- If you are working on a slow feature test, search for `Capybara::DSL#` in the search to see the capybara actions that are made, and how long they take!
See [#414929](https://gitlab.com/gitlab-org/gitlab/-/issues/414929#note_1425239887) or [#375004](https://gitlab.com/gitlab-org/gitlab/-/issues/375004#note_1109867718) for some analysis examples.
#### Optimize factory usage
A common cause of slow tests is excessive creation of objects, and thus
computation and DB time. Factories are essential to development, but they can
make inserting data into the DB so easy that we may be able to optimize.
The two basic techniques to bear in mind here are:
- **Reduce**: avoid creating objects, and avoid persisting them.
- **Reuse**: shared objects, especially nested ones we do not examine, can generally be shared.
To avoid creation, it is worth bearing in mind that:
- `instance_double` and `spy` are faster than `FactoryBot.build(...)`.
- `FactoryBot.build(...)` and `.build_stubbed` are faster than `.create`.
- Don't `create` an object when you can use `build`, `build_stubbed`, `attributes_for`,
`spy`, or `instance_double`. Database persistence is slow!
Use [Factory Doctor](https://test-prof.evilmartians.io/#/profilers/factory_doctor) to find cases where database persistence is not needed in a given test.
Examples of factories optimization [1](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/106796), [2](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/105329).
```shell
# run test for path
FDOC=1 bin/rspec spec/[path]/[to]/[spec].rb
```
A common change is to use `build` or `build_stubbed` instead of `create`:
```ruby
# Old
let(:project) { create(:project) }
# New
let(:project) { build(:project) }
```
[Factory Profiler](https://test-prof.evilmartians.io/#/profilers/factory_prof) can help to identify repetitive database persistence via factories.
```shell
# run test for path
FPROF=1 bin/rspec spec/[path]/[to]/[spec].rb
# to visualize with a flamegraph
FPROF=flamegraph bin/rspec spec/[path]/[to]/[spec].rb
```
A common cause of a large number of created factories is [factory cascades](https://github.com/test-prof/test-prof/blob/master/docs/profilers/factory_prof.md#factory-flamegraph), which result when factories create and recreate associations.
They can be identified by a noticeable difference between `total time` and `top-level time` numbers:
```plaintext
total top-level total time time per call top-level time name
208 0 9.5812s 0.0461s 0.0000s namespace
208 76 37.4214s 0.1799s 13.8749s project
```
The table above shows us that we never create any `namespace` objects explicitly
(`top-level == 0`) - they are all created implicitly for us. But we still end up
with 208 of them (one for each project) and this takes 9.5 seconds.
In order to reuse a single object for all calls to a named factory in implicit parent associations,
[`FactoryDefault`](https://github.com/test-prof/test-prof/blob/master/docs/recipes/factory_default.md)
can be used:
```ruby
RSpec.describe API::Search, factory_default: :keep do
let_it_be(:namespace) { create_default(:namespace) }
```
Then every project we create uses this `namespace`, without us having to pass
it as `namespace: namespace`. In order to make it work along with `let_it_be`, `factory_default: :keep`
must be explicitly specified. That keeps the default factory for every example in a suite instead of
recreating it for each example.
To prevent accidental reliance between test examples, objects created
with `create_default` are
[frozen](https://gitlab.com/gitlab-org/gitlab/-/blob/master/spec/support/factory_default.rb).
Maybe we don't need to create 208 different projects - we
can create one and reuse it. In addition, we can see that only about 1/3 of the
projects we create are ones we ask for (76/208). There is benefit in setting
a default value for projects as well:
```ruby
let_it_be(:project) { create_default(:project) }
```
In this case, the `total time` and `top-level time` numbers match more closely:
```plaintext
total top-level total time time per call top-level time name
31 30 4.6378s 0.1496s 4.5366s project
8 8 0.0477s 0.0477s 0.0477s namespace
```
##### Let's talk about `let`
There are various ways to create objects and store them in variables in your tests. They are, from least efficient to most efficient:
- `let!` creates the object before each example runs. It also creates a new object for every example. You should only use this option if you need to create a clean object before each example without explicitly referring to it.
- `let` lazily creates the object. It isn't created until the object is called. `let` is generally inefficient as it creates a new object for every example. `let` is fine for simple values. However, more efficient variants of `let` are best when dealing with database models such as factories.
- `let_it_be_with_refind` works similar to `let_it_be_with_reload`, but the [former calls `ActiveRecord::Base#find`](https://github.com/test-prof/test-prof/blob/936b29f87b36f88a134e064aa6d8ade143ae7a13/lib/test_prof/ext/active_record_refind.rb#L15) instead of `ActiveRecord::Base#reload`. `reload` is usually faster than `refind`.
- `let_it_be_with_reload` creates an object one time for all examples in the same context, but after each example, the database changes are rolled back, and `object.reload` will be called to restore the object to its original state. This means you can make changes to the object before or during an example. However, there are cases where [state leaks across other models](https://github.com/test-prof/test-prof/blob/master/docs/recipes/let_it_be.md#state-leakage-detection) can occur. In these cases, `let` may be an easier option, especially if only a few examples exist.
- `let_it_be` creates an object one time for all of the examples in the same context. This is a great alternative to `let` and `let!` for objects that do not need to change from one example to another. Using `let_it_be` can dramatically speed up tests that create database models. See <https://github.com/test-prof/test-prof/blob/master/docs/recipes/let_it_be.md#let-it-be> for more details and examples.
Pro-tip: When writing tests, it is best to consider the objects inside a `let_it_be` as **immutable**, as there are some important caveats when modifying objects inside a `let_it_be` declaration ([1](https://github.com/test-prof/test-prof/blob/master/docs/recipes/let_it_be.md#database-is-rolled-back-to-a-pristine-state-but-the-objects-are-not), [2](https://github.com/test-prof/test-prof/blob/master/docs/recipes/let_it_be.md#modifiers)). To make your `let_it_be` objects immutable, consider using `freeze: true`:
```shell
# Before
let_it_be(:namespace) { create_default(:namespace) }
# After
let_it_be(:namespace, freeze: true) { create_default(:namespace) }
```
See <https://github.com/test-prof/test-prof/blob/master/docs/recipes/let_it_be.md#state-leakage-detection> for more information on `let_it_be` freezing.
`let_it_be` is the most optimized option since it instantiates an object once and shares its instance across examples. If you find yourself needing `let` instead of `let_it_be`, try `let_it_be_with_reload`.
```ruby
# Old
let(:project) { create(:project) }
# New
let_it_be(:project) { create(:project) }
# If you need to expect changes to the object in the test
let_it_be_with_reload(:project) { create(:project) }
```
Here is an example of when `let_it_be` cannot be used, but `let_it_be_with_reload` allows for more efficiency than `let`:
```ruby
let_it_be(:user) { create(:user) }
let_it_be_with_reload(:project) { create(:project) } # The test will fail if `let_it_be` is used
context 'with a developer' do
before do
project.add_developer(user)
end
it 'project has an owner and a developer' do
expect(project.members.map(&:access_level)).to match_array([Gitlab::Access::OWNER, Gitlab::Access::DEVELOPER])
end
end
context 'with a maintainer' do
before do
project.add_maintainer(user)
end
it 'project has an owner and a maintainer' do
expect(project.members.map(&:access_level)).to match_array([Gitlab::Access::OWNER, Gitlab::Access::MAINTAINER])
end
end
```
#### Stubbing methods within factories
You should avoid using `allow(object).to receive(:method)` in factories, as this makes the factory unable to be used with `let_it_be`, as described in [common test setup](#common-test-setup).
Instead, you can use `stub_method` to stub the method:
```ruby
before(:create) do |user, evaluator|
# Stub a method.
stub_method(user, :some_method) { 'stubbed!' }
# Or with arguments, including named ones
stub_method(user, :some_method) { |var1| "Returning #{var1}!" }
stub_method(user, :some_method) { |var1: 'default'| "Returning #{var1}!" }
end
# Un-stub the method.
# This may be useful where the stubbed object is created with `let_it_be`
# and you want to reset the method between tests.
after(:create) do |user, evaluator|
restore_original_method(user, :some_method)
# or
restore_original_methods(user)
end
```
{{< alert type="note" >}}
`stub_method` does not work when used in conjunction with `let_it_be_with_refind`. This is because `stub_method` will stub a method on an instance and `let_it_be_with_refind` will create a new instance of the object for each run.
{{< /alert >}}
`stub_method` does not support method existence and method arity checks.
{{< alert type="warning" >}}
`stub_method` is supposed to be used in factories only. It's strongly discouraged to be used elsewhere. Consider using [RSpec mocks](https://rspec.info/features/3-12/rspec-mocks/) if available.
{{< /alert >}}
#### Stubbing member access level
To stub [member access level](../../user/permissions.md#roles) for factory stubs like `Project` or `Group` use
[`stub_member_access_level`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/spec/support/stub_member_access_level.rb):
```ruby
let(:project) { build_stubbed(:project) }
let(:maintainer) { build_stubbed(:user) }
let(:policy) { ProjectPolicy.new(maintainer, project) }
it 'allows admin_project ability' do
stub_member_access_level(project, maintainer: maintainer)
expect(policy).to be_allowed(:admin_project)
end
```
{{< alert type="note" >}}
Refrain from using this stub helper if the test code relies on persisting
`project_authorizations` or `Member` records. Use `Project#add_member` or `Group#add_member` instead.
{{< /alert >}}
#### Additional profiling metrics
We can use the `rspec_profiling` gem to diagnose, for instance, the number of SQL queries we're making when running a test.
This could be caused by some application side SQL queries **triggered by a test that could mock parts that are not under test** (for example, [!123810](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/123810)).
[See the instructions in the performance docs](../performance.md#rspec-profiling).
#### Troubleshoot slow feature test
A slow feature test can generally be optimized the same way as any other test. However, there are some specific techniques that can make the troubleshooting session more fruitful.
##### See what the feature test is doing in the UI
```shell
# Before
bin/rspec ./spec/features/admin/admin_settings_spec.rb:992
# After
WEBDRIVER_HEADLESS=0 bin/rspec ./spec/features/admin/admin_settings_spec.rb:992
```
See [Run `:js` spec in a visible browser](#run-js-spec-in-a-visible-browser) for more info.
##### Search for `Capybara::DSL#` when using profiling
<!-- TODO: Add the search keywords -->
When using [`stackprof` flamegraphs](#profiling-see-where-your-test-spend-its-time), search for `Capybara::DSL#` in the search to see the capybara actions that are made, and how long they take!
#### Identify slow tests
Running a spec with profiling is a good way to start optimizing a spec. This can
be done with:
```shell
bundle exec rspec --profile -- path/to/spec_file.rb
```
Which includes information like the following:
```plaintext
Top 10 slowest examples (10.69 seconds, 7.7% of total time):
Issue behaves like an editable mentionable creates new cross-reference notes when the mentionable text is edited
1.62 seconds ./spec/support/shared_examples/models/mentionable_shared_examples.rb:164
Issue relative positioning behaves like a class that supports relative positioning .move_nulls_to_end manages to move nulls to the end, stacking if we cannot create enough space
1.39 seconds ./spec/support/shared_examples/models/relative_positioning_shared_examples.rb:88
Issue relative positioning behaves like a class that supports relative positioning .move_nulls_to_start manages to move nulls to the end, stacking if we cannot create enough space
1.27 seconds ./spec/support/shared_examples/models/relative_positioning_shared_examples.rb:180
Issue behaves like an editable mentionable behaves like a mentionable extracts references from its reference property
0.99253 seconds ./spec/support/shared_examples/models/mentionable_shared_examples.rb:69
Issue behaves like an editable mentionable behaves like a mentionable creates cross-reference notes
0.94987 seconds ./spec/support/shared_examples/models/mentionable_shared_examples.rb:101
Issue behaves like an editable mentionable behaves like a mentionable when there are cached markdown fields sends in cached markdown fields when appropriate
0.94148 seconds ./spec/support/shared_examples/models/mentionable_shared_examples.rb:86
Issue behaves like an editable mentionable when there are cached markdown fields when the markdown cache is stale persists the refreshed cache so that it does not have to be refreshed every time
0.92833 seconds ./spec/support/shared_examples/models/mentionable_shared_examples.rb:153
Issue behaves like an editable mentionable when there are cached markdown fields refreshes markdown cache if necessary
0.88153 seconds ./spec/support/shared_examples/models/mentionable_shared_examples.rb:130
Issue behaves like an editable mentionable behaves like a mentionable generates a descriptive back-reference
0.86914 seconds ./spec/support/shared_examples/models/mentionable_shared_examples.rb:65
Issue#related_issues returns only authorized related issues for given user
0.84242 seconds ./spec/models/issue_spec.rb:335
Finished in 2 minutes 19 seconds (files took 1 minute 4.42 seconds to load)
277 examples, 0 failures, 1 pending
```
From this result, we can see the most expensive examples in our spec, giving us
a place to start. The most expensive examples here are in
shared examples; any reductions generally have a larger impact as
they are called in multiple places.
#### Avoid repeating expensive actions
While isolated examples are very clear, and help serve the purpose of specs as
specification, the following example shows how we can combine expensive
actions:
```ruby
subject { described_class.new(arg_0, arg_1) }
it 'creates an event' do
expect { subject.execute }.to change(Event, :count).by(1)
end
it 'sets the frobulance' do
expect { subject.execute }.to change { arg_0.reset.frobulance }.to('wibble')
end
it 'schedules a background job' do
expect(BackgroundJob).to receive(:perform_async)
subject.execute
end
```
If the call to `subject.execute` is expensive, then we are repeating the same
action just to make different assertions. We can reduce this repetition by
combining the examples:
```ruby
it 'performs the expected side-effects' do
expect(BackgroundJob).to receive(:perform_async)
expect { subject.execute }
.to change(Event, :count).by(1)
.and change { arg_0.frobulance }.to('wibble')
end
```
Be careful doing this, as this sacrifices clarity and test independence for
performance gains.
When combining tests, consider using `:aggregate_failures`, so that the full
results are available, and not just the first failure.
#### In case you're stuck
We have a `backend_testing_performance` [domain expertise](https://handbook.gitlab.com/handbook/engineering/workflow/code-review/#domain-experts) to list people that could help refactor slow backend specs.
To find people that could help, search for `backend testing performance` on the [Engineering Projects page](https://handbook.gitlab.com/handbook/engineering/projects/), or look directly in [the `www-gitlab-org` project](https://gitlab.com/search?group_id=6543&nav_source=navbar&project_id=7764&repository_ref=master&scope=blobs&search=backend_testing_performance+path%3Adata%2Fteam_members%2F*&search_code=true).
### Feature category metadata
You must [set feature category metadata for each RSpec example](../feature_categorization/_index.md#rspec-examples).
### Tests depending on EE license
You can use `if: Gitlab.ee?` or `unless: Gitlab.ee?` on context/spec blocks to execute tests depending on whether running with `FOSS_ONLY=1`.
### Tests depending on SaaS
You can use the `:saas` RSpec metadata tag helper on context/spec blocks to test code that only runs on GitLab.com. This helper sets `Gitlab.config.gitlab['url']` to `Gitlab::Saas.com_url`.
### Coverage
[`simplecov`](https://github.com/colszowka/simplecov) is used to generate code test coverage reports.
These are generated automatically on the CI, but not when running tests locally. To generate partial reports
when you run a spec file on your machine, set the `SIMPLECOV` environment variable:
```shell
SIMPLECOV=1 bundle exec rspec spec/models/repository_spec.rb
```
Coverage reports are generated into the `coverage` folder in the app root, and you can open these in your browser, for example:
```shell
firefox coverage/index.html
```
Use the coverage reports to ensure your tests cover 100% of your code.
### System / Feature tests
{{< alert type="note" >}}
Before writing a new system test,
[consider this guide around their use](testing_levels.md#white-box-tests-at-the-system-level-formerly-known-as-system--feature-tests)
{{< /alert >}}
- Feature specs should be named `ROLE_ACTION_spec.rb`, such as
`user_changes_password_spec.rb`.
- Use scenario titles that describe the success and failure paths.
- Avoid scenario titles that add no information, such as "successfully".
- Avoid scenario titles that repeat the feature title.
- Create only the necessary records in the database
- Test a happy path and a less happy path but that's it
- Every other possible path should be tested with Unit or Integration tests
- Test what's displayed on the page, not the internals of ActiveRecord models.
For instance, if you want to verify that a record was created, add
expectations that its attributes are displayed on the page, not that
`Model.count` increased by one.
- It's ok to look for DOM elements, but don't abuse it, because it makes the tests
more brittle
#### UI testing
When testing the UI, write tests that simulate what a user sees and how they interact with the UI.
This means preferring Capybara's semantic methods and avoiding querying by IDs, classes, or attributes.
The benefits of testing in this way are that:
- It ensures all interactive elements have an [accessible name](../fe_guide/accessibility/best_practices.md#provide-accessible-names-for-screen-readers).
- It is more readable, as it uses more natural language.
- It is less brittle, as it avoids querying by IDs, classes, and attributes, which are not visible to the user.
We strongly recommend that you query by the element's text label instead of by ID, class name, or `data-testid`.
If needed, you can scope interactions within a specific area of the page by using `within`.
As you will likely be scoping to an element such as a `div`, which typically does not have a label,
you may use a `data-testid` selector in this case.
You can use the `be_axe_clean` matcher to run [axe automated accessibility testing](../fe_guide/accessibility/automated_testing.md) in feature tests.
##### Externalized contents
For RSpec tests, expectations against externalized contents should call the same
externalizing method to match the translation. For example, you should use the `_`
method in Ruby.
See [Internationalization for GitLab - Test files (RSpec)](../i18n/externalization.md#test-files-rspec) for details.
##### Actions
Where possible, use more specific [actions](https://rubydoc.info/github/teamcapybara/capybara/master/Capybara/Node/Actions), such as the ones below.
```ruby
# good
click_button _('Submit review')
click_link _('UI testing docs')
fill_in _('Search projects'), with: 'gitlab' # fill in text input with text
select _('Updated date'), from: 'Sort by' # select an option from a select input
check _('Checkbox label')
uncheck _('Checkbox label')
choose _('Radio input label')
attach_file(_('Attach a file'), '/path/to/file.png')
# bad - interactive elements must have accessible names, so
# we should be able to use one of the specific actions above
find('.group-name', text: group.name).click
find('.js-show-diff-settings').click
find('[data-testid="submit-review"]').click
find('input[type="checkbox"]').click
find('.search').native.send_keys('gitlab')
```
##### Finders
Where possible, use more specific [finders](https://rubydoc.info/github/teamcapybara/capybara/master/Capybara/Node/Finders), such as the ones below.
```ruby
# good
find_button _('Submit review')
find_button _('Submit review'), disabled: true
find_link _('UI testing docs')
find_link _('UI testing docs'), href: docs_url
find_field _('Search projects')
find_field _('Search projects'), with: 'gitlab' # find the input field with text
find_field _('Search projects'), disabled: true
find_field _('Checkbox label'), checked: true
find_field _('Checkbox label'), unchecked: true
# acceptable when finding a element that is not a button, link, or field
find_by_testid('element')
```
##### Matchers
Where possible, use more specific [matchers](https://rubydoc.info/github/teamcapybara/capybara/master/Capybara/RSpecMatchers), such as the ones below.
```ruby
# good
expect(page).to have_button _('Submit review')
expect(page).to have_button _('Submit review'), disabled: true
expect(page).to have_button _('Notifications'), class: 'is-checked' # assert the "Notifications" GlToggle is checked
expect(page).to have_link _('UI testing docs')
expect(page).to have_link _('UI testing docs'), href: docs_url # assert the link has an href
expect(page).to have_field _('Search projects')
expect(page).to have_field _('Search projects'), disabled: true
expect(page).to have_field _('Search projects'), with: 'gitlab' # assert the input field has text
expect(page).to have_checked_field _('Checkbox label')
expect(page).to have_unchecked_field _('Radio input label')
expect(page).to have_select _('Sort by')
expect(page).to have_select _('Sort by'), selected: 'Updated date' # assert the option is selected
expect(page).to have_select _('Sort by'), options: ['Updated date', 'Created date', 'Due date'] # assert an exact list of options
expect(page).to have_select _('Sort by'), with_options: ['Created date', 'Due date'] # assert a partial list of options
expect(page).to have_text _('Some paragraph text.')
expect(page).to have_text _('Some paragraph text.'), exact: true # assert exact match
expect(page).to have_current_path 'gitlab/gitlab-test/-/issues'
expect(page).to have_title _('Not Found')
# acceptable when a more specific matcher above is not possible
expect(page).to have_css 'h2', text: 'Issue title'
expect(page).to have_css 'p', text: 'Issue description', exact: true
expect(page).to have_css '[data-testid="weight"]', text: 2
expect(page).to have_css '.atwho-view ul', visible: true
```
##### Interacting with modals
Use the `within_modal` helper to interact with [GitLab UI modals](https://gitlab-org.gitlab.io/gitlab-ui/?path=/story/base-modal--default).
```ruby
include Spec::Support::Helpers::ModalHelpers
within_modal do
expect(page).to have_link _('UI testing docs')
fill_in _('Search projects'), with: 'gitlab'
click_button 'Continue'
end
```
Furthermore, you can use `accept_gl_confirm` for confirmation modals that only need to be accepted.
This is helpful when migrating [`window.confirm()`](https://developer.mozilla.org/en-US/docs/Web/API/Window/confirm) to [`confirmAction`](https://gitlab.com/gitlab-org/gitlab/-/blob/ee280ed2b763d1278ad38c6e7e8a0aff092f617a/app/assets/javascripts/lib/utils/confirm_via_gl_modal/confirm_via_gl_modal.js#L3).
```ruby
include Spec::Support::Helpers::ModalHelpers
accept_gl_confirm do
click_button 'Delete user'
end
```
You can also pass the expected confirmation message and button text to `accept_gl_confirm`.
```ruby
include Spec::Support::Helpers::ModalHelpers
accept_gl_confirm('Are you sure you want to delete this user?', button_text: 'Delete') do
click_button 'Delete user'
end
```
##### Other useful methods
After you retrieve an element using a [finder method](#finders), you can invoke a number of
[element methods](https://rubydoc.info/github/teamcapybara/capybara/master/Capybara/Node/Element)
on it, such as `hover`.
Capybara tests also have a number of [session methods](https://rubydoc.info/github/teamcapybara/capybara/master/Capybara/Session) available, such as `accept_confirm`.
Some other useful methods are shown below:
```ruby
refresh # refresh the page
send_keys([:shift, 'i']) # press Shift+I keys to go to the Issues dashboard page
current_window.resize_to(1000, 1000) # resize the window
scroll_to(find_field('Comment')) # scroll to an element
```
You can also find a number of GitLab custom helpers in the `spec/support/helpers/` directory.
#### Live debug
Sometimes you may need to debug Capybara tests by observing browser behavior.
You can pause Capybara and view the website on the browser by using the
`live_debug` method in your spec. The current page is automatically opened
in your default browser.
You may need to sign in first (the current user's credentials are displayed in
the terminal).
To resume the test run, press any key.
For example:
```shell
$ bin/rspec spec/features/auto_deploy_spec.rb:34
Running via Spring preloader in process 8999
Run options: include {:locations=>{"./spec/features/auto_deploy_spec.rb"=>[34]}}
Current example is paused for live debugging
The current user credentials are: user2 / 12345678
Press any key to resume the execution of the example!
Back to the example!
.
Finished in 34.51 seconds (files took 0.76702 seconds to load)
1 example, 0 failures
```
`live_debug` only works on JavaScript enabled specs.
#### Run `:js` spec in a visible browser
Run the spec with `WEBDRIVER_HEADLESS=0`, like this:
```shell
WEBDRIVER_HEADLESS=0 bin/rspec some_spec.rb
```
The test completes quickly, but this gives you an idea of what's happening.
Using `live_debug` with `WEBDRIVER_HEADLESS=0` pauses the open browser, and does not
open the page again. This can be used to debug and inspect elements.
You can also add `byebug` or `binding.pry` to pause execution and [step through](../pry_debugging.md#stepping)
the test.
#### Screenshots
We use the `capybara-screenshot` gem to automatically take a screenshot on
failure. In CI you can download these files as job artifacts.
Also, you can manually take screenshots at any point in a test by adding the
methods below. Be sure to remove them when they are no longer needed! See
<https://github.com/mattheworiordan/capybara-screenshot#manual-screenshots> for
more.
Add `screenshot_and_save_page` in a `:js` spec to screenshot what Capybara
"sees", and save the page source.
Add `screenshot_and_open_image` in a `:js` spec to screenshot what Capybara
"sees", and automatically open the image.
The HTML dumps created by this are missing CSS.
This results in them looking very different from the actual application.
There is a [small hack](https://gitlab.com/gitlab-org/gitlab-foss/snippets/1718469) to add CSS which makes debugging easier.
### Fast unit tests
Some classes are well-isolated from Rails. You should be able to test them
without the overhead added by the Rails environment and Bundler's `:default`
group's gem loading. In these cases, you can `require 'fast_spec_helper'`
instead of `require 'spec_helper'` in your test file, and your test should run
really fast because:
- Gem loading is skipped
- Rails app boot is skipped
- GitLab Shell and Gitaly setup are skipped
- Test repositories setup are skipped
It takes around one second to load tests that are using `fast_spec_helper`
instead of 30+ seconds in case of a regular `spec_helper`.
`fast_spec_helper` also support autoloading classes that are located inside the
`lib/` directory. If your class or module is using only
code from the `lib/` directory, you don't need to explicitly load any
dependencies. `fast_spec_helper` also loads all ActiveSupport extensions,
including core extensions that are commonly used in the Rails environment.
Note that in some cases, you might still have to load some dependencies using
`require_dependency` when a code is using gems or a dependency is not located
in `lib/`.
For example, if you want to test your code that is calling the
`Gitlab::UntrustedRegexp` class, which under the hood uses `re2` library, you
should either:
- Add `require_dependency 're2'` to files in your library that need `re2` gem,
to make this requirement explicit. This approach is preferred.
- Add it to the spec itself.
Alternately, if it is a dependency which is required by many different `fast_spec_helper`
specs in your domain, and you don't want to have to manually add the dependency many
times, you can add it to be called directly from `fast_spec_helper` itself. To do
this, you can create a `spec/support/fast_spec/YOUR_DOMAIN/fast_spec_helper_support.rb`
file, and require it from `fast_spec_helper`. There are existing examples of this
you can follow.
Use `rubocop_spec_helper` for RuboCop related specs.
{{< alert type="warning" >}}
To verify that code and its specs are well-isolated from Rails, run the spec
individually via `bin/rspec`. Don't use `bin/spring rspec` as it loads
`spec_helper` automatically.
{{< /alert >}}
#### Maintaining fast_spec_helper specs
There is a utility script `scripts/run-fast-specs.sh` which can be used to run
all specs which use `fast_spec_helper`, in various ways. This script is useful
to help identify `fast_spec_helper` specs which have problems, such as not
running successfully in isolation. See the script for more details.
### `subject` and `let` variables
The GitLab RSpec suite has made extensive use of `let`(along with its strict, non-lazy
version `let!`) variables to reduce duplication. However, this sometimes [comes at the cost of clarity](https://thoughtbot.com/blog/lets-not),
so we need to set some guidelines for their use going forward:
- `let!` variables are preferable to instance variables. `let` variables
are preferable to `let!` variables. Local variables are preferable to
`let` variables.
- Use `let` to reduce duplication throughout an entire spec file.
- Don't use `let` to define variables used by a single test; define them as
local variables inside the test's `it` block.
- Don't define a `let` variable inside the top-level `describe` block that's
only used in a more deeply-nested `context` or `describe` block. Keep the
definition as close as possible to where it's used.
- Try to avoid overriding the definition of one `let` variable with another.
- Don't define a `let` variable that's only used by the definition of another.
Use a helper method instead.
- `let!` variables should be used only in case if strict evaluation with defined
order is required, otherwise `let` suffices. Remember that `let` is lazy and won't
be evaluated until it is referenced.
- Avoid referencing `subject` in examples. Use a named subject `subject(:name)`, or a `let` variable instead, so
the variable has a contextual name.
- If the `subject` is never referenced inside examples, then it's acceptable to define the `subject` without a name.
### Common test setup
{{< alert type="note" >}}
`let_it_be` and `before_all` do not work with DatabaseCleaner's deletion strategy. This includes migration specs, Rake task specs, and specs that have the `:delete` RSpec metadata tag.
For more information, see [issue 420379](https://gitlab.com/gitlab-org/gitlab/-/issues/420379).
{{< /alert >}}
In some cases, there is no need to recreate the same object for tests
again for each example. For example, a project and a guest of that project
are needed to test issues on the same project, so one project and user are enough for the entire file.
As much as possible, do not implement this using `before(:all)` or `before(:context)`. If you do,
you would need to manually clean up the data as those hooks run outside a database transaction.
Instead, this can be achieved by using
[`let_it_be`](https://test-prof.evilmartians.io/#/recipes/let_it_be) variables and the
[`before_all`](https://test-prof.evilmartians.io/#/recipes/before_all) hook
from the [`test-prof` gem](https://rubygems.org/gems/test-prof).
```ruby
let_it_be(:project) { create(:project) }
let_it_be(:user) { create(:user) }
before_all do
project.add_guest(user)
end
```
This results in only one `Project`, `User`, and `ProjectMember` created for this context.
`let_it_be` and `before_all` are also available in nested contexts. Cleanup after the context
is handled automatically using a transaction rollback.
Note that if you modify an object defined inside a `let_it_be` block,
then you must do one of the following:
- Reload the object as needed.
- Use the `let_it_be_with_reload` alias.
- Specify the `reload` option to reload for every example.
```ruby
let_it_be_with_reload(:project) { create(:project) }
let_it_be(:project, reload: true) { create(:project) }
```
You can also use the `let_it_be_with_refind` alias, or specify the `refind`
option as well to completely load a new object.
```ruby
let_it_be_with_refind(:project) { create(:project) }
let_it_be(:project, refind: true) { create(:project) }
```
Note that `let_it_be` cannot be used with factories that has stubs, such as `allow`.
The reason is that `let_it_be` happens in a `before(:all)` block, and RSpec does not
allow stubs in `before(:all)`.
See this [issue](https://gitlab.com/gitlab-org/gitlab/-/issues/340487) for more details.
To resolve, use `let`, or change the factory to not use stubs.
### `let_it_be` must not depend on a before block
When using `let_it_be` in the middle of a spec, make sure that it does not depend on a `before` block, since the `let_it_be` will be executed first during `before(:all)`.
In [this example](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/179302#note_2323774955), `create(:bar)` ran a callback which depended on the stub:
```ruby
let_it_be(:node) { create(:geo_node, :secondary) }
before do
stub_current_geo_node(node)
end
context 'foo' do
let_it_be(:bar) { create(:bar) }
...
end
```
The stub isn't set when `create(:bar)` executes, so the tests are flaky.
In this example, `before` cannot be replaced with `before_all` because you cannot use doubles or partial doubles from RSpec-mocks outside of the per-test lifecycle.
Therefore, the solution is to use `let` or `let!` instead of `let_it_be(:bar)`.
### Time-sensitive tests
[`ActiveSupport::Testing::TimeHelpers`](https://api.rubyonrails.org/classes/ActiveSupport/Testing/TimeHelpers.html)
can be used to verify things that are time-sensitive. Any test that exercises or verifies something time-sensitive
should make use of these helpers to prevent transient test failures.
Example:
```ruby
it 'is overdue' do
issue = build(:issue, due_date: Date.tomorrow)
travel_to(3.days.from_now) do
expect(issue).to be_overdue
end
end
```
#### RSpec helpers
You can use the `:freeze_time` and `:time_travel_to` RSpec metadata tag helpers to help reduce the amount of
boilerplate code needed to wrap entire specs with the [`ActiveSupport::Testing::TimeHelpers`](https://api.rubyonrails.org/classes/ActiveSupport/Testing/TimeHelpers.html)
methods.
```ruby
describe 'specs which require time to be frozen', :freeze_time do
it 'freezes time' do
right_now = Time.now
expect(Time.now).to eq(right_now)
end
end
describe 'specs which require time to be frozen to a specific date and/or time', time_travel_to: '2020-02-02 10:30:45 -0700' do
it 'freezes time to the specified date and time' do
expect(Time.now).to eq(Time.new(2020, 2, 2, 17, 30, 45, '+00:00'))
end
end
```
[Under the hood](https://gitlab.com/gitlab-org/gitlab/-/blob/master/gems/gitlab-rspec/lib/gitlab/rspec/configurations/time_travel.rb), these helpers use the `around(:each)` hook and the block syntax of the
[`ActiveSupport::Testing::TimeHelpers`](https://api.rubyonrails.org/classes/ActiveSupport/Testing/TimeHelpers.html)
methods:
```ruby
around(:each) do |example|
freeze_time { example.run }
end
around(:each) do |example|
travel_to(date_or_time) { example.run }
end
```
Remember that any objects created before the examples run (such as objects created via `let_it_be`) will be outside spec scope.
If the time for everything needs to be frozen, `before :all` can be used to encapsulate the setup as well.
```ruby
before :all do
freeze_time
end
after :all do
unfreeze_time
end
```
#### Timestamp truncation
Active Record timestamps are [set by the Rails' `ActiveRecord::Timestamp`](https://github.com/rails/rails/blob/1eb5cc13a2ed8922b47df4ae47faf5f23faf3d35/activerecord/lib/active_record/timestamp.rb#L105)
module [using `Time.now`](https://github.com/rails/rails/blob/1eb5cc13a2ed8922b47df4ae47faf5f23faf3d35/activerecord/lib/active_record/timestamp.rb#L78).
Time precision is [OS-dependent](https://ruby-doc.org/core-2.6.3/Time.html#method-c-new),
and as the docs state, may include fractional seconds.
When Rails models are saved to the database,
any timestamps they have are stored using a type in PostgreSQL called `timestamp without time zone`,
which has microsecond resolution (six digits after the decimal).
So if `1577987974.6472975` is sent to PostgreSQL,
it truncates the last digit of the fractional part and instead saves `1577987974.647297`.
The results of this can be a simple test like:
```ruby
let_it_be(:contact) { create(:contact) }
data = Gitlab::HookData::IssueBuilder.new(issue).build
expect(data).to include('customer_relations_contacts' => [contact.hook_attrs])
```
Failing with an error along the lines of:
```shell
expected {
"assignee_id" => nil, "...1 +0000 } to include {"customer_relations_contacts" => [{:created_at => "2023-08-04T13:30:20Z", :first_name => "Sidney Jones3" }]}
Diff:
@@ -1,35 +1,69 @@
-"customer_relations_contacts" => [{:created_at=>"2023-08-04T13:30:20Z", :first_name=>"Sidney Jones3" }],
+"customer_relations_contacts" => [{"created_at"=>2023-08-04 13:30:20.245964000 +0000, "first_name"=>"Sidney Jones3" }],
```
The fix is to ensure we `.reload` the object from the database to get the timestamp with correct precision:
```ruby
let_it_be(:contact) { create(:contact) }
data = Gitlab::HookData::IssueBuilder.new(issue).build
expect(data).to include('customer_relations_contacts' => [contact.reload.hook_attrs])
```
This explanation was taken from [a blog post](https://www.toptal.com/ruby-on-rails/timestamp-truncation-rails-activerecord-tale)
by Maciek Rząsa.
You can see a [merge request](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/126530#note_1500580985)
where this problem arose and the [backend pairing session](https://www.youtube.com/watch?v=nMCjEeuYFDA)
where it was discussed.
### Feature flags in tests
This section was moved to [developing with feature flags](../feature_flags/_index.md).
### Pristine test environments
The code exercised by a single GitLab test may access and modify many items of
data. Without careful preparation before a test runs, and cleanup afterward,
a test can change data in a way that affects the behavior of
following tests. This should be avoided at all costs! Fortunately, the existing
test framework handles most cases already.
When the test environment does get polluted, a common outcome is
[flaky tests](unhealthy_tests.md#flaky-tests). Pollution often manifests as an order
dependency: running spec A followed by spec B reliably fails, but running
spec B followed by spec A reliably succeeds. In these cases, you can use
`rspec --bisect` (or a manual pairwise bisect of spec files) to determine which
spec is at fault. Fixing the problem requires some understanding of how the test
suite ensures the environment is pristine. Read on to discover more about each
data store!
#### SQL database
This is managed for us by the `database_cleaner` gem. Each spec is surrounded in
a transaction, which is rolled back after the test completes. Certain specs
instead issue `DELETE FROM` queries against every table after completion. This
allows the created rows to be viewed from multiple database connections, which
is important for specs that run in a browser, or migration specs, among others.
One consequence of using these strategies, instead of the well-known
`TRUNCATE TABLES` approach, is that primary keys and other sequences are **not**
reset across specs. So if you create a project in spec A, then create a project
in spec B, the first has `id=1`, while the second has `id=2`.
This means that specs should **never** rely on the value of an ID, or any other
sequence-generated column. To avoid accidental conflicts, specs should also
avoid manually specifying any values in these kinds of columns. Instead, leave
them unspecified, and look up the value after the row is created.
##### TestProf in migration specs
Because of what is described above, migration specs can't be run inside
a database transaction. Our test suite uses
[TestProf](https://github.com/test-prof/test-prof) to improve the runtime of the
test suite, but `TestProf` uses database transactions to perform these optimizations.
For this reason, we can't use `TestProf` methods in our migration specs.
These are the methods that should not be used and should be replaced with
default RSpec methods instead:
- `let_it_be`: use `let` or `let!` instead.
- `let_it_be_with_reload`: use `let` or `let!` instead.
- `let_it_be_with_refind`: use `let` or `let!` instead.
- `before_all`: use `before` or `before(:all)` instead.
#### Redis
GitLab stores two main categories of data in Redis: cached items, and Sidekiq
jobs. [View the full list of `Gitlab::Redis::Wrapper` descendants](https://gitlab.com/gitlab-org/gitlab/-/tree/master/lib/gitlab/redis.rb) that are backed by
a separate Redis instance.
In most specs, the Rails cache is actually an in-memory store. This is replaced
between specs, so calls to `Rails.cache.read` and `Rails.cache.write` are safe.
However, if a spec makes direct Redis calls, it should mark itself with the
`:clean_gitlab_redis_cache`, `:clean_gitlab_redis_shared_state` or
`:clean_gitlab_redis_queues` traits depending on
[which Redis instance](../redis.md#gitlabrediscachesharedstatequeues) is being used.
#### Background jobs / Sidekiq
By default, Sidekiq jobs are enqueued into a jobs array and aren't processed.
If a test queues Sidekiq jobs and need them to be processed, the
`:sidekiq_inline` trait can be used.
The `:sidekiq_might_not_need_inline` trait was added when
[Sidekiq inline mode was changed to fake mode](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/15479)
to all the tests that needed Sidekiq to actually process jobs. Tests with
this trait should be either fixed to not rely on Sidekiq processing jobs, or their
`:sidekiq_might_not_need_inline` trait should be updated to `:sidekiq_inline` if
the processing of background jobs is needed/expected.
The usage of `perform_enqueued_jobs` is useful only for testing delayed mail
deliveries, because our Sidekiq workers aren't inheriting from `ApplicationJob`
/ `ActiveJob::Base`.
#### DNS
DNS requests are stubbed universally in the test suite
(as of [!22368](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/22368)), as DNS can
cause issues depending on the developer's local network. There are RSpec labels
available in `spec/support/dns.rb` which you can apply to tests if you need to
bypass the DNS stubbing, like this:
```ruby
it "really connects to Prometheus", :permit_dns do
```
And if you need more specific control, the DNS blocking is implemented in
`spec/support/helpers/dns_helpers.rb` and these methods can be called elsewhere.
#### Rate Limiting
[Rate limiting](../../security/rate_limits.md) is enabled in the test suite. Rate limits
may be triggered in feature specs that use the `:js` trait. In most cases, triggering rate
limiting can be avoided by marking the spec with the `:clean_gitlab_redis_rate_limiting`
trait. This trait clears the rate limiting data stored in Redis cache between specs. If
a single test triggers the rate limit, the `:disable_rate_limit` can be used instead.
#### Stubbing File methods
In the situations where you need to
[stub](https://rspec.info/features/3-12/rspec-mocks/basics/allowing-messages/)
the contents of a file use the `stub_file_read`, and
`expect_file_read` helper methods which handle the stubbing for
`File.read` correctly. These methods stub `File.read` for the given
filename, and also stub `File.exist?` to return `true`.
If you need to manually stub `File.read` for any reason be sure to:
1. Stub and call the original implementation for other file paths.
1. Then stub `File.read` for only the file path you are interested in.
Otherwise `File.read` calls from other parts of the codebase get
stubbed incorrectly.
```ruby
# bad, all Files will read and return nothing
allow(File).to receive(:read)
# good
stub_file_read(my_filepath, content: "fake file content")
# also OK
allow(File).to receive(:read).and_call_original
allow(File).to receive(:read).with(my_filepath).and_return("fake file_content")
```
#### File system
File system data can be roughly split into "repositories", and "everything else".
Repositories are stored in `tmp/tests/repositories`. This directory is emptied
before a test run starts, and after the test run ends. It is not emptied between
specs, so created repositories accumulate in this directory over the
lifetime of the process. Deleting them is expensive, but this could lead to
pollution unless carefully managed.
To avoid this, [hashed storage](../../administration/repository_storage_paths.md)
is enabled in the test suite. This means that repositories are given a unique
path that depends on their project's ID. Because the project IDs are not reset
between specs, each spec gets its own repository on disk,
and prevents changes from being visible between specs.
If a spec manually specifies a project ID, or inspects the state of the
`tmp/tests/repositories/` directory directly, then it should clean up the
directory both before and after it runs. In general, these patterns should be
completely avoided.
Other classes of file linked to database objects, such as uploads, are generally
managed in the same way. With hashed storage enabled in the specs, they are
written to disk in locations determined by ID, so conflicts should not occur.
Some specs disable hashed storage by passing the `:legacy_storage` trait to the
`projects` factory. Specs that do this must **never** override the `path` of the
project, or any of its groups. The default path includes the project ID, so it
does not conflict. If two specs create a `:legacy_storage` project with the same
path, they use the same repository on disk and lead to test environment
pollution.
Other files must be managed manually by the spec. If you run code that creates a
`tmp/test-file.csv` file, for instance, the spec must ensure that the file is
removed as part of cleanup.
#### Persistent in-memory application state
All the specs in a given `rspec` run share the same Ruby process, which means
they can affect each other by modifying Ruby objects that are accessible between
specs. In practice, this means global variables, and constants (which includes
Ruby classes, modules, etc).
Global variables should generally not be modified. If absolutely necessary, a
block like this can be used to ensure the change is rolled back afterwards:
```ruby
around(:each) do |example|
old_value = $0
begin
$0 = "new-value"
example.run
ensure
$0 = old_value
end
end
```
If a spec needs to modify a constant, it should use the `stub_const` helper to
ensure the change is rolled back.
If you need to modify the contents of the `ENV` constant, you can use the
`stub_env` helper method instead.
While most Ruby **instances** are not shared between specs, **classes**
and **modules** generally are. Class and module instance variables, accessors,
class variables, and other stateful idioms, should be treated in the same way as
global variables. Don't modify them unless you have to! In particular, prefer
using expectations, or dependency injection along with stubs, to avoid the need
for modifications. If you have no other choice, an `around` block like the global
variables example can be used, but avoid this if at all possible.
#### Elasticsearch specs
Specs that require Elasticsearch must be marked with the `:elastic` or `:elastic_delete_by_query` metadata. The `:elastic`
metadata creates and deletes indices before and after all examples.
The `:elastic_delete_by_query` metadata was added to reduce runtime for pipelines by creating and deleting indices at the
start and end of each context only. The [Elasticsearch delete by query API](https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-delete-by-query.html)
is used to delete data in all indices (except the migrations index) between examples to ensure a clean index.
The `:elastic_clean` metadata creates and deletes indices between examples to ensure a clean index. This way, tests are not
polluted with non-essential data. If using the `:elastic` or `:elastic_delete_by_query` metadata
is causing issues, use `:elastic_clean` instead. `:elastic_clean` is significantly slower than the other traits
and should be used sparingly.
Most tests for Elasticsearch logic relate to:
- Creating data in PostgreSQL and waiting for it to be indexed in Elasticsearch.
- Searching for that data.
- Ensuring that the test gives the expected result.
There are some exceptions, such as checking for structural changes rather than individual records in an index.
{{< alert type="note" >}}
Elasticsearch indexing uses [`Gitlab::Redis::SharedState`](../redis.md#gitlabrediscachesharedstatequeues).
Therefore, the Elasticsearch metadata dynamically uses `:clean_gitlab_redis_shared_state`.
You do not need to add `:clean_gitlab_redis_shared_state` manually.
{{< /alert >}}
Specs using Elasticsearch require that you:
- Create data in PostgreSQL and then index it into Elasticsearch.
- Enable Application Settings for Elasticsearch (which is disabled by default).
To do so, use:
```ruby
before do
stub_ee_application_setting(elasticsearch_search: true, elasticsearch_indexing: true)
end
```
Additionally, you can use the `ensure_elasticsearch_index!` method to overcome the asynchronous nature of Elasticsearch.
It uses the [Elasticsearch Refresh API](https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-refresh.html#refresh-api-desc)
to make sure all operations performed on an index since the last refresh are available for search. This method is typically
called after loading data into PostgreSQL to ensure the data is indexed and searchable.
Helper methods from `ElasticsearchHelpers` are automatically included when using any of the Elasticsearch metadata. You
can include them directly with the `:elastic_helpers` metadata.
You can use the `SEARCH_SPEC_BENCHMARK` environment variable to benchmark test setup steps:
```console
SEARCH_SPEC_BENCHMARK=1 bundle exec rspec ee/spec/lib/elastic/latest/merge_request_class_proxy_spec.rb
```
#### Test Legacy Snowplow events
This section describes how to test with events that have yet to convert to
[internal events](../internal_analytics/internal_event_instrumentation/quick_start.md).
##### Backend
{{< alert type="warning" >}}
Snowplow performs **runtime type checks** by using the [contracts gem](https://rubygems.org/gems/contracts).
Because Snowplow is **by default disabled in tests and development**, it can be hard to
**catch exceptions** when mocking `Gitlab::Tracking`.
{{< /alert >}}
To catch runtime errors due to type checks you can use `expect_snowplow_event`, which checks for
calls to `Gitlab::Tracking#event`.
```ruby
describe '#show' do
it 'tracks snowplow events' do
get :show
expect_snowplow_event(
category: 'Experiment',
action: 'start',
namespace: group,
project: project
)
expect_snowplow_event(
category: 'Experiment',
action: 'sent',
property: 'property',
label: 'label',
namespace: group,
project: project
)
end
end
```
When you want to ensure that no event got called, you can use `expect_no_snowplow_event`.
```ruby
describe '#show' do
it 'does not track any snowplow events' do
get :show
expect_no_snowplow_event(category: described_class.name, action: 'some_action')
end
end
```
Even though `category` and `action` can be omitted, you should at least
specify a `category` to avoid flaky tests. For example,
`Users::ActivityService` may track a Snowplow event after an API
request, and `expect_no_snowplow_event` will fail if that happens to run
when no arguments are specified.
##### View layer with data attributes
If you are using the data attributes to register tracking at the Haml layer,
you can use the `have_tracking` matcher method to assert if expected data attributes are assigned.
For example, if we need to test the below Haml,
```ruby
%div{ data: { testid: '_testid_', track_action: 'render', track_label: '_tracking_label_' } }
```
- [RSpec view specs](https://rspec.info/features/6-0/rspec-rails/view-specs/view-spec/)
```ruby
it 'assigns the tracking items' do
render
expect(rendered).to have_tracking(action: 'render', label: '_tracking_label_', testid: '_testid_')
end
```
- [ViewComponent](https://viewcomponent.org/) specs
```ruby
it 'assigns the tracking items' do
render_inline(component)
expect(page).to have_tracking(action: 'render', label: '_tracking_label_', testid: '_testid_')
end
```
When you want to ensure that tracking isn't assigned, you can use `not_to` with the above matchers.
#### Test Snowplow context against the schema
The [Snowplow schema matcher](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/60480)
helps to reduce validation errors by testing Snowplow context against the JSON schema.
The schema matcher accepts the following parameters:
- `schema path`
- `context`
To add a schema matcher spec:
1. Add a new schema to the [Iglu repository](https://gitlab.com/gitlab-org/iglu),
then copy the same schema to the `spec/fixtures/product_intelligence/` directory.
1. In the copied schema, remove the `"$schema"` key and value. We do not need it for specs
and the spec fails if we keep the key, as it tries to look for the schema in the URL.
1. Use the following snippet to call the schema matcher:
```ruby
match_snowplow_context_schema(schema_path: '<filename from step 1>', context: <Context Hash> )
```
### Table-based / Parameterized tests
This style of testing is used to exercise one piece of code with a comprehensive
range of inputs. By specifying the test case once, alongside a table of inputs
and the expected output for each, your tests can be made easier to read and more
compact.
We use the [RSpec::Parameterized](https://github.com/tomykaira/rspec-parameterized)
gem. A short example, using the table syntax and checking Ruby equality for a
range of inputs, might look like this:
```ruby
describe "#==" do
using RSpec::Parameterized::TableSyntax
let(:one) { 1 }
let(:two) { 2 }
where(:a, :b, :result) do
1 | 1 | true
1 | 2 | false
true | true | true
true | false | false
ref(:one) | ref(:one) | true # let variables must be referenced using `ref`
ref(:one) | ref(:two) | false
end
with_them do
it { expect(a == b).to eq(result) }
it 'is isomorphic' do
expect(b == a).to eq(result)
end
end
end
```
If, after creating a table-based test, you see an error that looks like this:
```ruby
NoMethodError:
undefined method `to_params'
param_sets = extracted.is_a?(Array) ? extracted : extracted.to_params
^^^^^^^^^^
Did you mean? to_param
```
That indicates that you need to include the line `using RSpec::Parameterized::TableSyntax` in the spec file.
<!-- vale gitlab_base.Spelling = NO -->
{{< alert type="warning" >}}
Only use simple values as input in the `where` block. Using procs, stateful
objects, FactoryBot-created objects, and similar items can lead to
[unexpected results](https://github.com/tomykaira/rspec-parameterized/issues/8).
{{< /alert >}}
<!-- vale gitlab_base.Spelling = YES -->
### Prometheus tests
Prometheus metrics may be preserved from one test run to another. To ensure that metrics are
reset before each example, add the `:prometheus` tag to the RSpec test.
### Matchers
Custom matchers should be created to clarify the intent and/or hide the
complexity of RSpec expectations. They should be placed under
`spec/support/matchers/`. Matchers can be placed in subfolder if they apply to
a certain type of specs only (such as features or requests) but shouldn't be if
they apply to multiple type of specs.
#### `be_like_time`
Time returned from a database can differ in precision from time objects
in Ruby, so we need flexible tolerances when comparing in specs.
The PostgreSQL time and timestamp types
have [the resolution of 1 microsecond](https://www.postgresql.org/docs/16/datatype-datetime.html).
However, the precision of Ruby `Time` can vary [depending on the OS.](https://blog.paulswartz.net/post/142749676062/ruby-time-precision-os-x-vs-linux)
Consider the following snippet:
```ruby
project = create(:project)
expect(project.created_at).to eq(Project.find(project.id).created_at)
```
On Linux, `Time` can have the maximum precision of 9 and
`project.created_at` has a value (like `2023-04-28 05:53:30.808033064`) with the same precision.
However, the actual value `created_at` (like `2023-04-28 05:53:30.808033`) stored to and loaded from the database
doesn't have the same precision, and the match would fail.
On macOS X, the precision of `Time` matches that of the PostgreSQL timestamp type
and the match could succeed.
To avoid the issue, we can use `be_like_time` or `be_within` to compare
that times are within one second of each other.
Example:
```ruby
expect(metrics.merged_at).to be_like_time(time)
```
Example for `be_within`:
```ruby
expect(violation.reload.merged_at).to be_within(0.00001.seconds).of(merge_request.merged_at)
```
#### `have_gitlab_http_status`
Prefer `have_gitlab_http_status` over `have_http_status` and
`expect(response.status).to` because the former
could also show the response body whenever the status mismatched. This would
be very useful whenever some tests start breaking and we would love to know
why without editing the source and rerun the tests.
This is especially useful whenever it's showing 500 internal server error.
Prefer named HTTP status like `:no_content` over its numeric representation
`206`. See a list of [supported status codes](https://github.com/rack/rack/blob/f2d2df4016a906beec755b63b4edfcc07b58ee05/lib/rack/utils.rb#L490).
Example:
```ruby
expect(response).to have_gitlab_http_status(:ok)
```
#### `match_schema` and `match_response_schema`
The `match_schema` matcher allows validating that the subject matches a
[JSON schema](https://json-schema.org/). The item inside `expect` can be
a JSON string or a JSON-compatible data structure.
`match_response_schema` is a convenience matcher for using with a
response object. from a [request spec](testing_levels.md#integration-tests).
Examples:
```ruby
# Matches against spec/fixtures/api/schemas/prometheus/additional_metrics_query_result.json
expect(data).to match_schema('prometheus/additional_metrics_query_result')
# Matches against ee/spec/fixtures/api/schemas/board.json
expect(data).to match_schema('board', dir: 'ee')
# Matches against a schema made up of Ruby data structures
expect(data).to match_schema(Atlassian::Schemata.build_info)
```
#### `be_valid_json`
`be_valid_json` allows validating that a string parses as JSON and gives
a non-empty result. To combine it with the schema matching above, use
`and`:
```ruby
expect(json_string).to be_valid_json
expect(json_string).to be_valid_json.and match_schema(schema)
```
#### `be_one_of(collection)`
The inverse of `include`, tests that the `collection` includes the expected
value:
```ruby
expect(:a).to be_one_of(%i[a b c])
expect(:z).not_to be_one_of(%i[a b c])
```
### Testing query performance
Testing query performance allows us to:
- Assert that N+1 problems do not exist in a block of code.
- Ensure that the number of queries in a block of code does not increase unnoticed.
#### QueryRecorder
`QueryRecorder` allows profiling and testing of the number of database queries
performed in a given block of code.
See the [`QueryRecorder`](../database/query_recorder.md) section for more details.
#### GitalyClient
`Gitlab::GitalyClient.get_request_count` allows tests of the number of Gitaly queries
made by a given block of code:
See the [`Gitaly Request Counts`](../gitaly.md#request-counts) section for more details.
### Shared contexts
Shared contexts only used in one spec file can be declared inline.
Any shared contexts used by more than one spec file:
- Should be placed under `spec/support/shared_contexts/`.
- Can be placed in subfolder if they apply to a certain type of specs only
(such as features or requests) but shouldn't be if they apply to multiple type of specs.
Each file should include only one context and have a descriptive name, such as
`spec/support/shared_contexts/controllers/githubish_import_controller_shared_context.rb`.
### Shared examples
Shared examples only used in one spec file can be declared inline.
Any shared examples used by more than one spec file:
- Should be placed under `spec/support/shared_examples/`.
- Can be placed in subfolder if they apply to a certain type of specs only
(such as features or requests) but shouldn't be if they apply to multiple type of specs.
Each file should include only one context and have a descriptive name, such as
`spec/support/shared_examples/controllers/githubish_import_controller_shared_example.rb`.
### Helpers
Helpers are usually modules that provide some methods to hide the complexity of
specific RSpec examples. You can define helpers in RSpec files if they're not
intended to be shared with other specs. Otherwise, they should be placed
under `spec/support/helpers/`. Helpers can be placed in a subfolder if they apply
to a certain type of specs only (such as features or requests) but shouldn't be
if they apply to multiple type of specs.
Helpers should follow the Rails naming / namespacing convention, where
`spec/support/helpers/` is the root. For instance
`spec/support/helpers/features/iteration_helpers.rb` should define:
```ruby
# frozen_string_literal: true
module Features
module IterationHelpers
def iteration_period(iteration)
"#{iteration.start_date.to_fs(:medium)} - #{iteration.due_date.to_fs(:medium)}"
end
end
end
```
Helpers should not change the RSpec configuration. For instance, the helpers module
described above should not include:
```ruby
# bad
RSpec.configure do |config|
config.include Features::IterationHelpers
end
# good, include in specific spec
RSpec.describe 'Issue Sidebar', feature_category: :team_planning do
include Features::IterationHelpers
end
```
### Testing Ruby constants
When testing code that uses Ruby constants, focus the test on the behavior that depends on the constant,
rather than testing the values of the constant.
For example, the following is preferred because it tests the behavior of the class method `.categories`.
```ruby
describe '.categories' do
it 'gets CE unique category names' do
expect(described_class.categories).to include(
'deploy_token_packages',
'user_packages',
# ...
'kubernetes_agent'
)
end
end
```
On the other hand, testing the value of the constant itself, often only repeats the values
in the code and the test, which provides little value.
```ruby
describe CATEGORIES do
it 'has values' do
expect(CATEGORIES).to eq([
'deploy_token_packages',
'user_packages',
# ...
'kubernetes_agent'
])
end
end
```
In critical cases where an error on a constant could have a catastrophic impact,
testing the constant values might be useful as an added safeguard. For example,
if it could bring down the entire GitLab service, cause a customer to be billed more than they should be,
or [cause the universe to implode](../contributing/verify/_index.md#do-not-cause-our-universe-to-implode).
### Factories
GitLab uses [`factory_bot`](https://github.com/thoughtbot/factory_bot) as a test fixture replacement.
- Factory definitions live in `spec/factories/`, named using the pluralization
of their corresponding model (`User` factories are defined in `users.rb`).
- There should be only one top-level factory definition per file.
- FactoryBot methods are mixed in to all RSpec groups. This means you can (and
should) call `create(...)` instead of `FactoryBot.create(...)`.
- Make use of [traits](https://www.rubydoc.info/gems/factory_bot/file/GETTING_STARTED.md#traits) to clean up definitions and usages.
- When defining a factory, don't define attributes that are not required for the
resulting record to pass validation.
- When instantiating from a factory, don't supply attributes that aren't
required by the test.
- Use [implicit](https://github.com/thoughtbot/factory_bot/blob/master/GETTING_STARTED.md#implicit-definition),
[explicit](https://github.com/thoughtbot/factory_bot/blob/master/GETTING_STARTED.md#explicit-definition), or
[inline](https://github.com/thoughtbot/factory_bot/blob/master/GETTING_STARTED.md#inline-definition) associations
instead of `create` / `build` for association setup in callbacks.
See [issue #262624](https://gitlab.com/gitlab-org/gitlab/-/issues/262624) for further context.
When creating factories with a [`has_many`](https://github.com/thoughtbot/factory_bot/blob/master/GETTING_STARTED.md#has_many-associations) and `belongs_to` association, use the `instance` method to refer to the object being built.
This prevents [creation of unnecessary records](https://gitlab.com/gitlab-org/gitlab/-/issues/378183) by using [interconnected associations](https://github.com/thoughtbot/factory_bot/blob/master/GETTING_STARTED.md#interconnected-associations).
For example, if we have the following classes:
```ruby
class Car < ApplicationRecord
has_many :wheels, inverse_of: :car, foreign_key: :car_id
end
class Wheel < ApplicationRecord
belongs_to :car, foreign_key: :car_id, inverse_of: :wheel, optional: false
end
```
We can create the following factories:
```ruby
FactoryBot.define do
factory :car do
transient do
wheels_count { 2 }
end
wheels do
Array.new(wheels_count) do
association(:wheel, car: instance)
end
end
end
end
FactoryBot.define do
factory :wheel do
car { association :car }
end
end
```
- Factories don't have to be limited to `ActiveRecord` objects.
[See example](https://gitlab.com/gitlab-org/gitlab-foss/commit/0b8cefd3b2385a21cfed779bd659978c0402766d).
- Avoid the use of [`skip_callback`](https://api.rubyonrails.org/classes/ActiveSupport/Callbacks/ClassMethods.html#method-i-skip_callback) in factories.
See [issue #247865](https://gitlab.com/gitlab-org/gitlab/-/issues/247865) for details.
### Fixtures
All fixtures should be placed under `spec/fixtures/`.
### Repositories
Testing some functionality, such as merging a merge request, requires a Git
repository with a certain state to be present in the test environment. GitLab
maintains the [`gitlab-test`](https://gitlab.com/gitlab-org/gitlab-test)
repository for certain common cases - you can ensure a copy of the repository is
used with the `:repository` trait for project factories:
```ruby
let(:project) { create(:project, :repository) }
```
Where you can, consider using the `:custom_repo` trait instead of `:repository`.
This allows you to specify exactly what files appear in the `main` branch
of the project's repository. For example:
```ruby
let(:project) do
create(
:project, :custom_repo,
files: {
'README.md' => 'Content here',
'foo/bar/baz.txt' => 'More content here'
}
)
end
```
This creates a repository containing two files, with default permissions and
the specified content.
### Configuration
RSpec configuration files are files that change the RSpec configuration (like
`RSpec.configure do |config|` blocks). They should be placed under
`spec/support/`.
Each file should be related to a specific domain, such as
`spec/support/capybara.rb` or `spec/support/carrierwave.rb`.
If a helpers module applies only to a certain kind of specs, it should add
modifiers to the `config.include` call. For instance if
`spec/support/helpers/cycle_analytics_helpers.rb` applies to `:lib` and
`type: :model` specs only, you would write the following:
```ruby
RSpec.configure do |config|
config.include Spec::Support::Helpers::CycleAnalyticsHelpers, :lib
config.include Spec::Support::Helpers::CycleAnalyticsHelpers, type: :model
end
```
If a configuration file only consists of `config.include`, you can add these
`config.include` directly in `spec/spec_helper.rb`.
For very generic helpers, consider including them in the `spec/support/rspec.rb`
file which is used by the `spec/fast_spec_helper.rb` file. See
[Fast unit tests](#fast-unit-tests) for more details about the
`spec/fast_spec_helper.rb` file.
### Test environment logging
Services for the test environment are automatically configured and started when
tests are run, including Gitaly, Workhorse, Elasticsearch, and Capybara. When run in CI, or
if the service needs to be installed, the test environment logs information
about set-up time, producing log messages like the following:
```plaintext
==> Setting up Gitaly...
Gitaly set up in 31.459649 seconds...
==> Setting up GitLab Workhorse...
GitLab Workhorse set up in 29.695619 seconds...
fatal: update refs/heads/diff-files-symlink-to-image: invalid <newvalue>: 8cfca84
From https://gitlab.com/gitlab-org/gitlab-test
* [new branch] diff-files-image-to-symlink -> origin/diff-files-image-to-symlink
* [new branch] diff-files-symlink-to-image -> origin/diff-files-symlink-to-image
* [new branch] diff-files-symlink-to-text -> origin/diff-files-symlink-to-text
* [new branch] diff-files-text-to-symlink -> origin/diff-files-text-to-symlink
b80faa8..40232f7 snippet/multiple-files -> origin/snippet/multiple-files
* [new branch] testing/branch-with-#-hash -> origin/testing/branch-with-#-hash
==> Setting up GitLab Elasticsearch Indexer...
GitLab Elasticsearch Indexer set up in 26.514623 seconds...
```
This information is omitted when running locally and when no action needs
to be performed. If you would always like to see these messages, set the
following environment variable:
```shell
GITLAB_TESTING_LOG_LEVEL=debug
```
---
[Return to Testing documentation](_index.md)
|
---
stage: none
group: unassigned
info: 'See the Technical Writers assigned to Development Guidelines: https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments-to-development-guidelines'
description: GitLab development guidelines - testing best practices.
title: Testing best practices
breadcrumbs:
- doc
- development
- testing_guide
---
## Test Design
Testing at GitLab is a first class citizen, not an afterthought. It's important we consider the design of our tests
as we do the design of our features.
When implementing a feature, we think about developing the right capabilities the right way. This helps us
narrow our scope to a manageable level. When implementing tests for a feature, we must think about developing
the right tests, but then cover all the important ways the test may fail. This can quickly widen our scope to
a level that is difficult to manage.
Test heuristics can help solve this problem. They concisely address many of the common ways bugs
manifest themselves in our code. When designing our tests, take time to review known test heuristics to inform
our test design. We can find some helpful heuristics documented in the Handbook in the
[Test Engineering](https://handbook.gitlab.com/handbook/engineering/infrastructure/test-platform/test-engineering/#test-heuristics) section.
## RSpec
To run RSpec tests:
```shell
# run test for a file
bin/rspec spec/models/project_spec.rb
# run test for the example on line 10 on that file
bin/rspec spec/models/project_spec.rb:10
# run tests matching the example name has that string
bin/rspec spec/models/project_spec.rb -e associations
# run all tests, will take hours for GitLab codebase!
bin/rspec
```
Use [Guard](https://github.com/guard/guard) to continuously monitor for changes and only run matching tests:
```shell
bundle exec guard
```
When using spring and guard together, use `SPRING=1 bundle exec guard` instead to make use of spring.
### General guidelines
- Use a single, top-level `RSpec.describe ClassName` block.
- Use `.method` to describe class methods and `#method` to describe instance
methods.
- Use `context` to test branching logic (`RSpec/AvoidConditionalStatements` RuboCop Cop - [MR](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/117152)).
- Try to match the ordering of tests to the ordering in the class.
- Try to follow the [Four-Phase Test](https://thoughtbot.com/blog/four-phase-test) pattern, using newlines
to separate phases.
- Use `Gitlab.config.gitlab.host` rather than hard coding `'localhost'`.
- For literal URLs in tests, use `example.com`, `gitlab.example.com`. This will ensure that we do not utilize any real URLs.
- Don't assert against the absolute value of a sequence-generated attribute (see
[Gotchas](../gotchas.md#do-not-assert-against-the-absolute-value-of-a-sequence-generated-attribute)).
- Avoid using `expect_any_instance_of` or `allow_any_instance_of` (see
[Gotchas](../gotchas.md#avoid-using-expect_any_instance_of-or-allow_any_instance_of-in-rspec)).
- Don't supply the `:each` argument to hooks because it's the default.
- On `before` and `after` hooks, prefer it scoped to `:context` over `:all`.
- When using `evaluate_script("$('.js-foo').testSomething()")` (or `execute_script`) which acts on a given element,
use a Capybara matcher beforehand (such as `find('.js-foo')`) to ensure the element actually exists.
- Use `focus: true` to isolate parts of the specs you want to run.
- Use [`:aggregate_failures`](https://rspec.info/features/3-12/rspec-core/expectation-framework-integration/aggregating-failures/) when there is more than one expectation in a test.
- For [empty test description blocks](https://github.com/rubocop-hq/rspec-style-guide#it-and-specify), use `specify` rather than `it do` if the test is self-explanatory.
- Use `non_existing_record_id`/`non_existing_record_iid`/`non_existing_record_access_level`
when you need an ID/IID/access level that doesn't actually exist. Using 123, 1234,
or even 999 is brittle as these IDs could actually exist in the database in the
context of a CI run.
### Eager loading the application code
By default, the application code:
- Isn't eagerly loaded in the `test` environment.
- Is eagerly loaded in CI/CD (when `ENV['CI'].present?`) to surface any potential loading issues.
If you need to enable eager loading when executing tests,
use the `GITLAB_TEST_EAGER_LOAD` environment variable:
```shell
GITLAB_TEST_EAGER_LOAD=1 bin/rspec spec/models/project_spec.rb
```
If your test depends on all the application code that is being loaded, add the `:eager_load` tag.
This ensures that the application code is eagerly loaded before the test execution.
### Ruby warnings
We've enabled [deprecation warnings](https://ruby-doc.org/core-2.7.4/Warning.html)
by default when running specs. Making these warnings more visible to developers
helps upgrading to newer Ruby versions.
You can silence deprecation warnings by setting the environment variable
`SILENCE_DEPRECATIONS`, for example:
```shell
# silence all deprecation warnings
SILENCE_DEPRECATIONS=1 bin/rspec spec/models/project_spec.rb
```
### Test order
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/93137) in GitLab 15.4.
{{< /history >}}
All new spec files are run in [random order](https://gitlab.com/gitlab-org/gitlab/-/issues/337399)
to surface flaky tests that are dependent on test order.
When randomized:
- The string `# order random` is added below the example group description.
- The used seed is shown in the spec output below the test suite summary. For example, `Randomized with seed 27443`.
For a list of spec files which are still run in defined order, see [`rspec_order_todo.yml`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/spec/support/rspec_order_todo.yml).
To make spec files run in random order, check their order dependency with:
```shell
scripts/rspec_check_order_dependence spec/models/project_spec.rb
```
If the specs pass the check the script removes them from
[`rspec_order_todo.yml`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/spec/support/rspec_order_todo.yml) automatically.
If the specs fail the check they must be fixed before than can run in random order.
### Test flakiness
[Consult the Unhealthy tests page for more information about processes that are in place to avoid flaky tests](unhealthy_tests.md#flaky-tests).
### Test slowness
GitLab has a massive test suite that, without [parallelization](../pipelines/_index.md#test-suite-parallelization), can take hours
to run. It's important that we make an effort to write tests that are accurate
and effective _as well as_ fast.
Test performance is important to maintaining quality and velocity, and has a
direct impact on CI build times and thus fixed costs. We want thorough, correct,
and fast tests. Here you can find some information about tools and techniques
available to you to achieve that.
[Consult the Unhealthy tests page for more information about processes that are in place to avoid slow tests](unhealthy_tests.md#slow-tests).
#### Don't request capabilities you don't need
We make it easy to add capabilities to our examples by annotating the example or
a parent context. Examples of these are:
- `:js` in feature specs, which runs a full JavaScript capable headless browser.
- `:clean_gitlab_redis_cache` which provides a clean Redis cache to the examples.
- `:request_store` which provides a request store to the examples.
We should reduce test dependencies, and avoiding
capabilities also reduces the amount of set-up needed.
`:js` is particularly important to avoid. This must only be used if the feature
test requires JavaScript reactivity in the browser (for example, clicking a Vue.js component). Using a headless
browser is much slower than parsing the HTML response from the app.
#### Profiling: see where your test spend its time
[`rspec-stackprof`](https://github.com/dkhroad/rspec-stackprof) can be used to generate a flame graph that shows you where you test spend its time.
The gem generates a JSON report that we can upload to <https://www.speedscope.app> for an interactive visualization.
##### Installation
`stackprof` gem is [already installed with GitLab](https://gitlab.com/gitlab-org/gitlab/-/blob/695fcee0c5541b4ead0a90eb9b8bf0b69bee796c/Gemfile#L487), and we also have a script available that generates the JSON report (`bin/rspec-stackprof`).
```shell
# Optional: install the `speedscope` package to easily upload the JSON report to https://www.speedscope.app
npm install -g speedscope
```
##### Generate the JSON report
```shell
bin/rspec-stackprof --speedscope=true <your_slow_spec>
# There will be the name of the report displayed when the script ends.
# Upload the JSON report to speedscope.app
speedscope tmp/<your-json-report>.json
```
##### How to interpret the flamegraph
Below are some useful tips to interpret and navigate the flamegraph:
- There are [several views available](https://github.com/jlfwong/speedscope#views) for the flamegraph. `Left Heavy` is particularly useful when there are a lot of function calls (for example, feature specs).
- You can zoom in or out! See [the navigation documentation](https://github.com/jlfwong/speedscope#navigation)
- If you are working on a slow feature test, search for `Capybara::DSL#` in the search to see the capybara actions that are made, and how long they take!
See [#414929](https://gitlab.com/gitlab-org/gitlab/-/issues/414929#note_1425239887) or [#375004](https://gitlab.com/gitlab-org/gitlab/-/issues/375004#note_1109867718) for some analysis examples.
#### Optimize factory usage
A common cause of slow tests is excessive creation of objects, and thus
computation and DB time. Factories are essential to development, but they can
make inserting data into the DB so easy that we may be able to optimize.
The two basic techniques to bear in mind here are:
- **Reduce**: avoid creating objects, and avoid persisting them.
- **Reuse**: shared objects, especially nested ones we do not examine, can generally be shared.
To avoid creation, it is worth bearing in mind that:
- `instance_double` and `spy` are faster than `FactoryBot.build(...)`.
- `FactoryBot.build(...)` and `.build_stubbed` are faster than `.create`.
- Don't `create` an object when you can use `build`, `build_stubbed`, `attributes_for`,
`spy`, or `instance_double`. Database persistence is slow!
Use [Factory Doctor](https://test-prof.evilmartians.io/#/profilers/factory_doctor) to find cases where database persistence is not needed in a given test.
Examples of factories optimization [1](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/106796), [2](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/105329).
```shell
# run test for path
FDOC=1 bin/rspec spec/[path]/[to]/[spec].rb
```
A common change is to use `build` or `build_stubbed` instead of `create`:
```ruby
# Old
let(:project) { create(:project) }
# New
let(:project) { build(:project) }
```
[Factory Profiler](https://test-prof.evilmartians.io/#/profilers/factory_prof) can help to identify repetitive database persistence via factories.
```shell
# run test for path
FPROF=1 bin/rspec spec/[path]/[to]/[spec].rb
# to visualize with a flamegraph
FPROF=flamegraph bin/rspec spec/[path]/[to]/[spec].rb
```
A common cause of a large number of created factories is [factory cascades](https://github.com/test-prof/test-prof/blob/master/docs/profilers/factory_prof.md#factory-flamegraph), which result when factories create and recreate associations.
They can be identified by a noticeable difference between `total time` and `top-level time` numbers:
```plaintext
total top-level total time time per call top-level time name
208 0 9.5812s 0.0461s 0.0000s namespace
208 76 37.4214s 0.1799s 13.8749s project
```
The table above shows us that we never create any `namespace` objects explicitly
(`top-level == 0`) - they are all created implicitly for us. But we still end up
with 208 of them (one for each project) and this takes 9.5 seconds.
In order to reuse a single object for all calls to a named factory in implicit parent associations,
[`FactoryDefault`](https://github.com/test-prof/test-prof/blob/master/docs/recipes/factory_default.md)
can be used:
```ruby
RSpec.describe API::Search, factory_default: :keep do
let_it_be(:namespace) { create_default(:namespace) }
```
Then every project we create uses this `namespace`, without us having to pass
it as `namespace: namespace`. In order to make it work along with `let_it_be`, `factory_default: :keep`
must be explicitly specified. That keeps the default factory for every example in a suite instead of
recreating it for each example.
To prevent accidental reliance between test examples, objects created
with `create_default` are
[frozen](https://gitlab.com/gitlab-org/gitlab/-/blob/master/spec/support/factory_default.rb).
Maybe we don't need to create 208 different projects - we
can create one and reuse it. In addition, we can see that only about 1/3 of the
projects we create are ones we ask for (76/208). There is benefit in setting
a default value for projects as well:
```ruby
let_it_be(:project) { create_default(:project) }
```
In this case, the `total time` and `top-level time` numbers match more closely:
```plaintext
total top-level total time time per call top-level time name
31 30 4.6378s 0.1496s 4.5366s project
8 8 0.0477s 0.0477s 0.0477s namespace
```
##### Let's talk about `let`
There are various ways to create objects and store them in variables in your tests. They are, from least efficient to most efficient:
- `let!` creates the object before each example runs. It also creates a new object for every example. You should only use this option if you need to create a clean object before each example without explicitly referring to it.
- `let` lazily creates the object. It isn't created until the object is called. `let` is generally inefficient as it creates a new object for every example. `let` is fine for simple values. However, more efficient variants of `let` are best when dealing with database models such as factories.
- `let_it_be_with_refind` works similar to `let_it_be_with_reload`, but the [former calls `ActiveRecord::Base#find`](https://github.com/test-prof/test-prof/blob/936b29f87b36f88a134e064aa6d8ade143ae7a13/lib/test_prof/ext/active_record_refind.rb#L15) instead of `ActiveRecord::Base#reload`. `reload` is usually faster than `refind`.
- `let_it_be_with_reload` creates an object one time for all examples in the same context, but after each example, the database changes are rolled back, and `object.reload` will be called to restore the object to its original state. This means you can make changes to the object before or during an example. However, there are cases where [state leaks across other models](https://github.com/test-prof/test-prof/blob/master/docs/recipes/let_it_be.md#state-leakage-detection) can occur. In these cases, `let` may be an easier option, especially if only a few examples exist.
- `let_it_be` creates an object one time for all of the examples in the same context. This is a great alternative to `let` and `let!` for objects that do not need to change from one example to another. Using `let_it_be` can dramatically speed up tests that create database models. See <https://github.com/test-prof/test-prof/blob/master/docs/recipes/let_it_be.md#let-it-be> for more details and examples.
Pro-tip: When writing tests, it is best to consider the objects inside a `let_it_be` as **immutable**, as there are some important caveats when modifying objects inside a `let_it_be` declaration ([1](https://github.com/test-prof/test-prof/blob/master/docs/recipes/let_it_be.md#database-is-rolled-back-to-a-pristine-state-but-the-objects-are-not), [2](https://github.com/test-prof/test-prof/blob/master/docs/recipes/let_it_be.md#modifiers)). To make your `let_it_be` objects immutable, consider using `freeze: true`:
```shell
# Before
let_it_be(:namespace) { create_default(:namespace) }
# After
let_it_be(:namespace, freeze: true) { create_default(:namespace) }
```
See <https://github.com/test-prof/test-prof/blob/master/docs/recipes/let_it_be.md#state-leakage-detection> for more information on `let_it_be` freezing.
`let_it_be` is the most optimized option since it instantiates an object once and shares its instance across examples. If you find yourself needing `let` instead of `let_it_be`, try `let_it_be_with_reload`.
```ruby
# Old
let(:project) { create(:project) }
# New
let_it_be(:project) { create(:project) }
# If you need to expect changes to the object in the test
let_it_be_with_reload(:project) { create(:project) }
```
Here is an example of when `let_it_be` cannot be used, but `let_it_be_with_reload` allows for more efficiency than `let`:
```ruby
let_it_be(:user) { create(:user) }
let_it_be_with_reload(:project) { create(:project) } # The test will fail if `let_it_be` is used
context 'with a developer' do
before do
project.add_developer(user)
end
it 'project has an owner and a developer' do
expect(project.members.map(&:access_level)).to match_array([Gitlab::Access::OWNER, Gitlab::Access::DEVELOPER])
end
end
context 'with a maintainer' do
before do
project.add_maintainer(user)
end
it 'project has an owner and a maintainer' do
expect(project.members.map(&:access_level)).to match_array([Gitlab::Access::OWNER, Gitlab::Access::MAINTAINER])
end
end
```
#### Stubbing methods within factories
You should avoid using `allow(object).to receive(:method)` in factories, as this makes the factory unable to be used with `let_it_be`, as described in [common test setup](#common-test-setup).
Instead, you can use `stub_method` to stub the method:
```ruby
before(:create) do |user, evaluator|
# Stub a method.
stub_method(user, :some_method) { 'stubbed!' }
# Or with arguments, including named ones
stub_method(user, :some_method) { |var1| "Returning #{var1}!" }
stub_method(user, :some_method) { |var1: 'default'| "Returning #{var1}!" }
end
# Un-stub the method.
# This may be useful where the stubbed object is created with `let_it_be`
# and you want to reset the method between tests.
after(:create) do |user, evaluator|
restore_original_method(user, :some_method)
# or
restore_original_methods(user)
end
```
{{< alert type="note" >}}
`stub_method` does not work when used in conjunction with `let_it_be_with_refind`. This is because `stub_method` will stub a method on an instance and `let_it_be_with_refind` will create a new instance of the object for each run.
{{< /alert >}}
`stub_method` does not support method existence and method arity checks.
{{< alert type="warning" >}}
`stub_method` is supposed to be used in factories only. It's strongly discouraged to be used elsewhere. Consider using [RSpec mocks](https://rspec.info/features/3-12/rspec-mocks/) if available.
{{< /alert >}}
#### Stubbing member access level
To stub [member access level](../../user/permissions.md#roles) for factory stubs like `Project` or `Group` use
[`stub_member_access_level`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/spec/support/stub_member_access_level.rb):
```ruby
let(:project) { build_stubbed(:project) }
let(:maintainer) { build_stubbed(:user) }
let(:policy) { ProjectPolicy.new(maintainer, project) }
it 'allows admin_project ability' do
stub_member_access_level(project, maintainer: maintainer)
expect(policy).to be_allowed(:admin_project)
end
```
{{< alert type="note" >}}
Refrain from using this stub helper if the test code relies on persisting
`project_authorizations` or `Member` records. Use `Project#add_member` or `Group#add_member` instead.
{{< /alert >}}
#### Additional profiling metrics
We can use the `rspec_profiling` gem to diagnose, for instance, the number of SQL queries we're making when running a test.
This could be caused by some application side SQL queries **triggered by a test that could mock parts that are not under test** (for example, [!123810](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/123810)).
[See the instructions in the performance docs](../performance.md#rspec-profiling).
#### Troubleshoot slow feature test
A slow feature test can generally be optimized the same way as any other test. However, there are some specific techniques that can make the troubleshooting session more fruitful.
##### See what the feature test is doing in the UI
```shell
# Before
bin/rspec ./spec/features/admin/admin_settings_spec.rb:992
# After
WEBDRIVER_HEADLESS=0 bin/rspec ./spec/features/admin/admin_settings_spec.rb:992
```
See [Run `:js` spec in a visible browser](#run-js-spec-in-a-visible-browser) for more info.
##### Search for `Capybara::DSL#` when using profiling
<!-- TODO: Add the search keywords -->
When using [`stackprof` flamegraphs](#profiling-see-where-your-test-spend-its-time), search for `Capybara::DSL#` in the search to see the capybara actions that are made, and how long they take!
#### Identify slow tests
Running a spec with profiling is a good way to start optimizing a spec. This can
be done with:
```shell
bundle exec rspec --profile -- path/to/spec_file.rb
```
Which includes information like the following:
```plaintext
Top 10 slowest examples (10.69 seconds, 7.7% of total time):
Issue behaves like an editable mentionable creates new cross-reference notes when the mentionable text is edited
1.62 seconds ./spec/support/shared_examples/models/mentionable_shared_examples.rb:164
Issue relative positioning behaves like a class that supports relative positioning .move_nulls_to_end manages to move nulls to the end, stacking if we cannot create enough space
1.39 seconds ./spec/support/shared_examples/models/relative_positioning_shared_examples.rb:88
Issue relative positioning behaves like a class that supports relative positioning .move_nulls_to_start manages to move nulls to the end, stacking if we cannot create enough space
1.27 seconds ./spec/support/shared_examples/models/relative_positioning_shared_examples.rb:180
Issue behaves like an editable mentionable behaves like a mentionable extracts references from its reference property
0.99253 seconds ./spec/support/shared_examples/models/mentionable_shared_examples.rb:69
Issue behaves like an editable mentionable behaves like a mentionable creates cross-reference notes
0.94987 seconds ./spec/support/shared_examples/models/mentionable_shared_examples.rb:101
Issue behaves like an editable mentionable behaves like a mentionable when there are cached markdown fields sends in cached markdown fields when appropriate
0.94148 seconds ./spec/support/shared_examples/models/mentionable_shared_examples.rb:86
Issue behaves like an editable mentionable when there are cached markdown fields when the markdown cache is stale persists the refreshed cache so that it does not have to be refreshed every time
0.92833 seconds ./spec/support/shared_examples/models/mentionable_shared_examples.rb:153
Issue behaves like an editable mentionable when there are cached markdown fields refreshes markdown cache if necessary
0.88153 seconds ./spec/support/shared_examples/models/mentionable_shared_examples.rb:130
Issue behaves like an editable mentionable behaves like a mentionable generates a descriptive back-reference
0.86914 seconds ./spec/support/shared_examples/models/mentionable_shared_examples.rb:65
Issue#related_issues returns only authorized related issues for given user
0.84242 seconds ./spec/models/issue_spec.rb:335
Finished in 2 minutes 19 seconds (files took 1 minute 4.42 seconds to load)
277 examples, 0 failures, 1 pending
```
From this result, we can see the most expensive examples in our spec, giving us
a place to start. The most expensive examples here are in
shared examples; any reductions generally have a larger impact as
they are called in multiple places.
#### Avoid repeating expensive actions
While isolated examples are very clear, and help serve the purpose of specs as
specification, the following example shows how we can combine expensive
actions:
```ruby
subject { described_class.new(arg_0, arg_1) }
it 'creates an event' do
expect { subject.execute }.to change(Event, :count).by(1)
end
it 'sets the frobulance' do
expect { subject.execute }.to change { arg_0.reset.frobulance }.to('wibble')
end
it 'schedules a background job' do
expect(BackgroundJob).to receive(:perform_async)
subject.execute
end
```
If the call to `subject.execute` is expensive, then we are repeating the same
action just to make different assertions. We can reduce this repetition by
combining the examples:
```ruby
it 'performs the expected side-effects' do
expect(BackgroundJob).to receive(:perform_async)
expect { subject.execute }
.to change(Event, :count).by(1)
.and change { arg_0.frobulance }.to('wibble')
end
```
Be careful doing this, as this sacrifices clarity and test independence for
performance gains.
When combining tests, consider using `:aggregate_failures`, so that the full
results are available, and not just the first failure.
#### In case you're stuck
We have a `backend_testing_performance` [domain expertise](https://handbook.gitlab.com/handbook/engineering/workflow/code-review/#domain-experts) to list people that could help refactor slow backend specs.
To find people that could help, search for `backend testing performance` on the [Engineering Projects page](https://handbook.gitlab.com/handbook/engineering/projects/), or look directly in [the `www-gitlab-org` project](https://gitlab.com/search?group_id=6543&nav_source=navbar&project_id=7764&repository_ref=master&scope=blobs&search=backend_testing_performance+path%3Adata%2Fteam_members%2F*&search_code=true).
### Feature category metadata
You must [set feature category metadata for each RSpec example](../feature_categorization/_index.md#rspec-examples).
### Tests depending on EE license
You can use `if: Gitlab.ee?` or `unless: Gitlab.ee?` on context/spec blocks to execute tests depending on whether running with `FOSS_ONLY=1`.
### Tests depending on SaaS
You can use the `:saas` RSpec metadata tag helper on context/spec blocks to test code that only runs on GitLab.com. This helper sets `Gitlab.config.gitlab['url']` to `Gitlab::Saas.com_url`.
### Coverage
[`simplecov`](https://github.com/colszowka/simplecov) is used to generate code test coverage reports.
These are generated automatically on the CI, but not when running tests locally. To generate partial reports
when you run a spec file on your machine, set the `SIMPLECOV` environment variable:
```shell
SIMPLECOV=1 bundle exec rspec spec/models/repository_spec.rb
```
Coverage reports are generated into the `coverage` folder in the app root, and you can open these in your browser, for example:
```shell
firefox coverage/index.html
```
Use the coverage reports to ensure your tests cover 100% of your code.
### System / Feature tests
{{< alert type="note" >}}
Before writing a new system test,
[consider this guide around their use](testing_levels.md#white-box-tests-at-the-system-level-formerly-known-as-system--feature-tests)
{{< /alert >}}
- Feature specs should be named `ROLE_ACTION_spec.rb`, such as
`user_changes_password_spec.rb`.
- Use scenario titles that describe the success and failure paths.
- Avoid scenario titles that add no information, such as "successfully".
- Avoid scenario titles that repeat the feature title.
- Create only the necessary records in the database
- Test a happy path and a less happy path but that's it
- Every other possible path should be tested with Unit or Integration tests
- Test what's displayed on the page, not the internals of ActiveRecord models.
For instance, if you want to verify that a record was created, add
expectations that its attributes are displayed on the page, not that
`Model.count` increased by one.
- It's ok to look for DOM elements, but don't abuse it, because it makes the tests
more brittle
#### UI testing
When testing the UI, write tests that simulate what a user sees and how they interact with the UI.
This means preferring Capybara's semantic methods and avoiding querying by IDs, classes, or attributes.
The benefits of testing in this way are that:
- It ensures all interactive elements have an [accessible name](../fe_guide/accessibility/best_practices.md#provide-accessible-names-for-screen-readers).
- It is more readable, as it uses more natural language.
- It is less brittle, as it avoids querying by IDs, classes, and attributes, which are not visible to the user.
We strongly recommend that you query by the element's text label instead of by ID, class name, or `data-testid`.
If needed, you can scope interactions within a specific area of the page by using `within`.
As you will likely be scoping to an element such as a `div`, which typically does not have a label,
you may use a `data-testid` selector in this case.
You can use the `be_axe_clean` matcher to run [axe automated accessibility testing](../fe_guide/accessibility/automated_testing.md) in feature tests.
##### Externalized contents
For RSpec tests, expectations against externalized contents should call the same
externalizing method to match the translation. For example, you should use the `_`
method in Ruby.
See [Internationalization for GitLab - Test files (RSpec)](../i18n/externalization.md#test-files-rspec) for details.
##### Actions
Where possible, use more specific [actions](https://rubydoc.info/github/teamcapybara/capybara/master/Capybara/Node/Actions), such as the ones below.
```ruby
# good
click_button _('Submit review')
click_link _('UI testing docs')
fill_in _('Search projects'), with: 'gitlab' # fill in text input with text
select _('Updated date'), from: 'Sort by' # select an option from a select input
check _('Checkbox label')
uncheck _('Checkbox label')
choose _('Radio input label')
attach_file(_('Attach a file'), '/path/to/file.png')
# bad - interactive elements must have accessible names, so
# we should be able to use one of the specific actions above
find('.group-name', text: group.name).click
find('.js-show-diff-settings').click
find('[data-testid="submit-review"]').click
find('input[type="checkbox"]').click
find('.search').native.send_keys('gitlab')
```
##### Finders
Where possible, use more specific [finders](https://rubydoc.info/github/teamcapybara/capybara/master/Capybara/Node/Finders), such as the ones below.
```ruby
# good
find_button _('Submit review')
find_button _('Submit review'), disabled: true
find_link _('UI testing docs')
find_link _('UI testing docs'), href: docs_url
find_field _('Search projects')
find_field _('Search projects'), with: 'gitlab' # find the input field with text
find_field _('Search projects'), disabled: true
find_field _('Checkbox label'), checked: true
find_field _('Checkbox label'), unchecked: true
# acceptable when finding a element that is not a button, link, or field
find_by_testid('element')
```
##### Matchers
Where possible, use more specific [matchers](https://rubydoc.info/github/teamcapybara/capybara/master/Capybara/RSpecMatchers), such as the ones below.
```ruby
# good
expect(page).to have_button _('Submit review')
expect(page).to have_button _('Submit review'), disabled: true
expect(page).to have_button _('Notifications'), class: 'is-checked' # assert the "Notifications" GlToggle is checked
expect(page).to have_link _('UI testing docs')
expect(page).to have_link _('UI testing docs'), href: docs_url # assert the link has an href
expect(page).to have_field _('Search projects')
expect(page).to have_field _('Search projects'), disabled: true
expect(page).to have_field _('Search projects'), with: 'gitlab' # assert the input field has text
expect(page).to have_checked_field _('Checkbox label')
expect(page).to have_unchecked_field _('Radio input label')
expect(page).to have_select _('Sort by')
expect(page).to have_select _('Sort by'), selected: 'Updated date' # assert the option is selected
expect(page).to have_select _('Sort by'), options: ['Updated date', 'Created date', 'Due date'] # assert an exact list of options
expect(page).to have_select _('Sort by'), with_options: ['Created date', 'Due date'] # assert a partial list of options
expect(page).to have_text _('Some paragraph text.')
expect(page).to have_text _('Some paragraph text.'), exact: true # assert exact match
expect(page).to have_current_path 'gitlab/gitlab-test/-/issues'
expect(page).to have_title _('Not Found')
# acceptable when a more specific matcher above is not possible
expect(page).to have_css 'h2', text: 'Issue title'
expect(page).to have_css 'p', text: 'Issue description', exact: true
expect(page).to have_css '[data-testid="weight"]', text: 2
expect(page).to have_css '.atwho-view ul', visible: true
```
##### Interacting with modals
Use the `within_modal` helper to interact with [GitLab UI modals](https://gitlab-org.gitlab.io/gitlab-ui/?path=/story/base-modal--default).
```ruby
include Spec::Support::Helpers::ModalHelpers
within_modal do
expect(page).to have_link _('UI testing docs')
fill_in _('Search projects'), with: 'gitlab'
click_button 'Continue'
end
```
Furthermore, you can use `accept_gl_confirm` for confirmation modals that only need to be accepted.
This is helpful when migrating [`window.confirm()`](https://developer.mozilla.org/en-US/docs/Web/API/Window/confirm) to [`confirmAction`](https://gitlab.com/gitlab-org/gitlab/-/blob/ee280ed2b763d1278ad38c6e7e8a0aff092f617a/app/assets/javascripts/lib/utils/confirm_via_gl_modal/confirm_via_gl_modal.js#L3).
```ruby
include Spec::Support::Helpers::ModalHelpers
accept_gl_confirm do
click_button 'Delete user'
end
```
You can also pass the expected confirmation message and button text to `accept_gl_confirm`.
```ruby
include Spec::Support::Helpers::ModalHelpers
accept_gl_confirm('Are you sure you want to delete this user?', button_text: 'Delete') do
click_button 'Delete user'
end
```
##### Other useful methods
After you retrieve an element using a [finder method](#finders), you can invoke a number of
[element methods](https://rubydoc.info/github/teamcapybara/capybara/master/Capybara/Node/Element)
on it, such as `hover`.
Capybara tests also have a number of [session methods](https://rubydoc.info/github/teamcapybara/capybara/master/Capybara/Session) available, such as `accept_confirm`.
Some other useful methods are shown below:
```ruby
refresh # refresh the page
send_keys([:shift, 'i']) # press Shift+I keys to go to the Issues dashboard page
current_window.resize_to(1000, 1000) # resize the window
scroll_to(find_field('Comment')) # scroll to an element
```
You can also find a number of GitLab custom helpers in the `spec/support/helpers/` directory.
#### Live debug
Sometimes you may need to debug Capybara tests by observing browser behavior.
You can pause Capybara and view the website on the browser by using the
`live_debug` method in your spec. The current page is automatically opened
in your default browser.
You may need to sign in first (the current user's credentials are displayed in
the terminal).
To resume the test run, press any key.
For example:
```shell
$ bin/rspec spec/features/auto_deploy_spec.rb:34
Running via Spring preloader in process 8999
Run options: include {:locations=>{"./spec/features/auto_deploy_spec.rb"=>[34]}}
Current example is paused for live debugging
The current user credentials are: user2 / 12345678
Press any key to resume the execution of the example!
Back to the example!
.
Finished in 34.51 seconds (files took 0.76702 seconds to load)
1 example, 0 failures
```
`live_debug` only works on JavaScript enabled specs.
#### Run `:js` spec in a visible browser
Run the spec with `WEBDRIVER_HEADLESS=0`, like this:
```shell
WEBDRIVER_HEADLESS=0 bin/rspec some_spec.rb
```
The test completes quickly, but this gives you an idea of what's happening.
Using `live_debug` with `WEBDRIVER_HEADLESS=0` pauses the open browser, and does not
open the page again. This can be used to debug and inspect elements.
You can also add `byebug` or `binding.pry` to pause execution and [step through](../pry_debugging.md#stepping)
the test.
#### Screenshots
We use the `capybara-screenshot` gem to automatically take a screenshot on
failure. In CI you can download these files as job artifacts.
Also, you can manually take screenshots at any point in a test by adding the
methods below. Be sure to remove them when they are no longer needed! See
<https://github.com/mattheworiordan/capybara-screenshot#manual-screenshots> for
more.
Add `screenshot_and_save_page` in a `:js` spec to screenshot what Capybara
"sees", and save the page source.
Add `screenshot_and_open_image` in a `:js` spec to screenshot what Capybara
"sees", and automatically open the image.
The HTML dumps created by this are missing CSS.
This results in them looking very different from the actual application.
There is a [small hack](https://gitlab.com/gitlab-org/gitlab-foss/snippets/1718469) to add CSS which makes debugging easier.
### Fast unit tests
Some classes are well-isolated from Rails. You should be able to test them
without the overhead added by the Rails environment and Bundler's `:default`
group's gem loading. In these cases, you can `require 'fast_spec_helper'`
instead of `require 'spec_helper'` in your test file, and your test should run
really fast because:
- Gem loading is skipped
- Rails app boot is skipped
- GitLab Shell and Gitaly setup are skipped
- Test repositories setup are skipped
It takes around one second to load tests that are using `fast_spec_helper`
instead of 30+ seconds in case of a regular `spec_helper`.
`fast_spec_helper` also support autoloading classes that are located inside the
`lib/` directory. If your class or module is using only
code from the `lib/` directory, you don't need to explicitly load any
dependencies. `fast_spec_helper` also loads all ActiveSupport extensions,
including core extensions that are commonly used in the Rails environment.
Note that in some cases, you might still have to load some dependencies using
`require_dependency` when a code is using gems or a dependency is not located
in `lib/`.
For example, if you want to test your code that is calling the
`Gitlab::UntrustedRegexp` class, which under the hood uses `re2` library, you
should either:
- Add `require_dependency 're2'` to files in your library that need `re2` gem,
to make this requirement explicit. This approach is preferred.
- Add it to the spec itself.
Alternately, if it is a dependency which is required by many different `fast_spec_helper`
specs in your domain, and you don't want to have to manually add the dependency many
times, you can add it to be called directly from `fast_spec_helper` itself. To do
this, you can create a `spec/support/fast_spec/YOUR_DOMAIN/fast_spec_helper_support.rb`
file, and require it from `fast_spec_helper`. There are existing examples of this
you can follow.
Use `rubocop_spec_helper` for RuboCop related specs.
{{< alert type="warning" >}}
To verify that code and its specs are well-isolated from Rails, run the spec
individually via `bin/rspec`. Don't use `bin/spring rspec` as it loads
`spec_helper` automatically.
{{< /alert >}}
#### Maintaining fast_spec_helper specs
There is a utility script `scripts/run-fast-specs.sh` which can be used to run
all specs which use `fast_spec_helper`, in various ways. This script is useful
to help identify `fast_spec_helper` specs which have problems, such as not
running successfully in isolation. See the script for more details.
### `subject` and `let` variables
The GitLab RSpec suite has made extensive use of `let`(along with its strict, non-lazy
version `let!`) variables to reduce duplication. However, this sometimes [comes at the cost of clarity](https://thoughtbot.com/blog/lets-not),
so we need to set some guidelines for their use going forward:
- `let!` variables are preferable to instance variables. `let` variables
are preferable to `let!` variables. Local variables are preferable to
`let` variables.
- Use `let` to reduce duplication throughout an entire spec file.
- Don't use `let` to define variables used by a single test; define them as
local variables inside the test's `it` block.
- Don't define a `let` variable inside the top-level `describe` block that's
only used in a more deeply-nested `context` or `describe` block. Keep the
definition as close as possible to where it's used.
- Try to avoid overriding the definition of one `let` variable with another.
- Don't define a `let` variable that's only used by the definition of another.
Use a helper method instead.
- `let!` variables should be used only in case if strict evaluation with defined
order is required, otherwise `let` suffices. Remember that `let` is lazy and won't
be evaluated until it is referenced.
- Avoid referencing `subject` in examples. Use a named subject `subject(:name)`, or a `let` variable instead, so
the variable has a contextual name.
- If the `subject` is never referenced inside examples, then it's acceptable to define the `subject` without a name.
### Common test setup
{{< alert type="note" >}}
`let_it_be` and `before_all` do not work with DatabaseCleaner's deletion strategy. This includes migration specs, Rake task specs, and specs that have the `:delete` RSpec metadata tag.
For more information, see [issue 420379](https://gitlab.com/gitlab-org/gitlab/-/issues/420379).
{{< /alert >}}
In some cases, there is no need to recreate the same object for tests
again for each example. For example, a project and a guest of that project
are needed to test issues on the same project, so one project and user are enough for the entire file.
As much as possible, do not implement this using `before(:all)` or `before(:context)`. If you do,
you would need to manually clean up the data as those hooks run outside a database transaction.
Instead, this can be achieved by using
[`let_it_be`](https://test-prof.evilmartians.io/#/recipes/let_it_be) variables and the
[`before_all`](https://test-prof.evilmartians.io/#/recipes/before_all) hook
from the [`test-prof` gem](https://rubygems.org/gems/test-prof).
```ruby
let_it_be(:project) { create(:project) }
let_it_be(:user) { create(:user) }
before_all do
project.add_guest(user)
end
```
This results in only one `Project`, `User`, and `ProjectMember` created for this context.
`let_it_be` and `before_all` are also available in nested contexts. Cleanup after the context
is handled automatically using a transaction rollback.
Note that if you modify an object defined inside a `let_it_be` block,
then you must do one of the following:
- Reload the object as needed.
- Use the `let_it_be_with_reload` alias.
- Specify the `reload` option to reload for every example.
```ruby
let_it_be_with_reload(:project) { create(:project) }
let_it_be(:project, reload: true) { create(:project) }
```
You can also use the `let_it_be_with_refind` alias, or specify the `refind`
option as well to completely load a new object.
```ruby
let_it_be_with_refind(:project) { create(:project) }
let_it_be(:project, refind: true) { create(:project) }
```
Note that `let_it_be` cannot be used with factories that has stubs, such as `allow`.
The reason is that `let_it_be` happens in a `before(:all)` block, and RSpec does not
allow stubs in `before(:all)`.
See this [issue](https://gitlab.com/gitlab-org/gitlab/-/issues/340487) for more details.
To resolve, use `let`, or change the factory to not use stubs.
### `let_it_be` must not depend on a before block
When using `let_it_be` in the middle of a spec, make sure that it does not depend on a `before` block, since the `let_it_be` will be executed first during `before(:all)`.
In [this example](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/179302#note_2323774955), `create(:bar)` ran a callback which depended on the stub:
```ruby
let_it_be(:node) { create(:geo_node, :secondary) }
before do
stub_current_geo_node(node)
end
context 'foo' do
let_it_be(:bar) { create(:bar) }
...
end
```
The stub isn't set when `create(:bar)` executes, so the tests are flaky.
In this example, `before` cannot be replaced with `before_all` because you cannot use doubles or partial doubles from RSpec-mocks outside of the per-test lifecycle.
Therefore, the solution is to use `let` or `let!` instead of `let_it_be(:bar)`.
### Time-sensitive tests
[`ActiveSupport::Testing::TimeHelpers`](https://api.rubyonrails.org/classes/ActiveSupport/Testing/TimeHelpers.html)
can be used to verify things that are time-sensitive. Any test that exercises or verifies something time-sensitive
should make use of these helpers to prevent transient test failures.
Example:
```ruby
it 'is overdue' do
issue = build(:issue, due_date: Date.tomorrow)
travel_to(3.days.from_now) do
expect(issue).to be_overdue
end
end
```
#### RSpec helpers
You can use the `:freeze_time` and `:time_travel_to` RSpec metadata tag helpers to help reduce the amount of
boilerplate code needed to wrap entire specs with the [`ActiveSupport::Testing::TimeHelpers`](https://api.rubyonrails.org/classes/ActiveSupport/Testing/TimeHelpers.html)
methods.
```ruby
describe 'specs which require time to be frozen', :freeze_time do
it 'freezes time' do
right_now = Time.now
expect(Time.now).to eq(right_now)
end
end
describe 'specs which require time to be frozen to a specific date and/or time', time_travel_to: '2020-02-02 10:30:45 -0700' do
it 'freezes time to the specified date and time' do
expect(Time.now).to eq(Time.new(2020, 2, 2, 17, 30, 45, '+00:00'))
end
end
```
[Under the hood](https://gitlab.com/gitlab-org/gitlab/-/blob/master/gems/gitlab-rspec/lib/gitlab/rspec/configurations/time_travel.rb), these helpers use the `around(:each)` hook and the block syntax of the
[`ActiveSupport::Testing::TimeHelpers`](https://api.rubyonrails.org/classes/ActiveSupport/Testing/TimeHelpers.html)
methods:
```ruby
around(:each) do |example|
freeze_time { example.run }
end
around(:each) do |example|
travel_to(date_or_time) { example.run }
end
```
Remember that any objects created before the examples run (such as objects created via `let_it_be`) will be outside spec scope.
If the time for everything needs to be frozen, `before :all` can be used to encapsulate the setup as well.
```ruby
before :all do
freeze_time
end
after :all do
unfreeze_time
end
```
#### Timestamp truncation
Active Record timestamps are [set by the Rails' `ActiveRecord::Timestamp`](https://github.com/rails/rails/blob/1eb5cc13a2ed8922b47df4ae47faf5f23faf3d35/activerecord/lib/active_record/timestamp.rb#L105)
module [using `Time.now`](https://github.com/rails/rails/blob/1eb5cc13a2ed8922b47df4ae47faf5f23faf3d35/activerecord/lib/active_record/timestamp.rb#L78).
Time precision is [OS-dependent](https://ruby-doc.org/core-2.6.3/Time.html#method-c-new),
and as the docs state, may include fractional seconds.
When Rails models are saved to the database,
any timestamps they have are stored using a type in PostgreSQL called `timestamp without time zone`,
which has microsecond resolution (six digits after the decimal).
So if `1577987974.6472975` is sent to PostgreSQL,
it truncates the last digit of the fractional part and instead saves `1577987974.647297`.
The results of this can be a simple test like:
```ruby
let_it_be(:contact) { create(:contact) }
data = Gitlab::HookData::IssueBuilder.new(issue).build
expect(data).to include('customer_relations_contacts' => [contact.hook_attrs])
```
Failing with an error along the lines of:
```shell
expected {
"assignee_id" => nil, "...1 +0000 } to include {"customer_relations_contacts" => [{:created_at => "2023-08-04T13:30:20Z", :first_name => "Sidney Jones3" }]}
Diff:
@@ -1,35 +1,69 @@
-"customer_relations_contacts" => [{:created_at=>"2023-08-04T13:30:20Z", :first_name=>"Sidney Jones3" }],
+"customer_relations_contacts" => [{"created_at"=>2023-08-04 13:30:20.245964000 +0000, "first_name"=>"Sidney Jones3" }],
```
The fix is to ensure we `.reload` the object from the database to get the timestamp with correct precision:
```ruby
let_it_be(:contact) { create(:contact) }
data = Gitlab::HookData::IssueBuilder.new(issue).build
expect(data).to include('customer_relations_contacts' => [contact.reload.hook_attrs])
```
This explanation was taken from [a blog post](https://www.toptal.com/ruby-on-rails/timestamp-truncation-rails-activerecord-tale)
by Maciek Rząsa.
You can see a [merge request](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/126530#note_1500580985)
where this problem arose and the [backend pairing session](https://www.youtube.com/watch?v=nMCjEeuYFDA)
where it was discussed.
### Feature flags in tests
This section was moved to [developing with feature flags](../feature_flags/_index.md).
### Pristine test environments
The code exercised by a single GitLab test may access and modify many items of
data. Without careful preparation before a test runs, and cleanup afterward,
a test can change data in a way that affects the behavior of
following tests. This should be avoided at all costs! Fortunately, the existing
test framework handles most cases already.
When the test environment does get polluted, a common outcome is
[flaky tests](unhealthy_tests.md#flaky-tests). Pollution often manifests as an order
dependency: running spec A followed by spec B reliably fails, but running
spec B followed by spec A reliably succeeds. In these cases, you can use
`rspec --bisect` (or a manual pairwise bisect of spec files) to determine which
spec is at fault. Fixing the problem requires some understanding of how the test
suite ensures the environment is pristine. Read on to discover more about each
data store!
#### SQL database
This is managed for us by the `database_cleaner` gem. Each spec is surrounded in
a transaction, which is rolled back after the test completes. Certain specs
instead issue `DELETE FROM` queries against every table after completion. This
allows the created rows to be viewed from multiple database connections, which
is important for specs that run in a browser, or migration specs, among others.
One consequence of using these strategies, instead of the well-known
`TRUNCATE TABLES` approach, is that primary keys and other sequences are **not**
reset across specs. So if you create a project in spec A, then create a project
in spec B, the first has `id=1`, while the second has `id=2`.
This means that specs should **never** rely on the value of an ID, or any other
sequence-generated column. To avoid accidental conflicts, specs should also
avoid manually specifying any values in these kinds of columns. Instead, leave
them unspecified, and look up the value after the row is created.
##### TestProf in migration specs
Because of what is described above, migration specs can't be run inside
a database transaction. Our test suite uses
[TestProf](https://github.com/test-prof/test-prof) to improve the runtime of the
test suite, but `TestProf` uses database transactions to perform these optimizations.
For this reason, we can't use `TestProf` methods in our migration specs.
These are the methods that should not be used and should be replaced with
default RSpec methods instead:
- `let_it_be`: use `let` or `let!` instead.
- `let_it_be_with_reload`: use `let` or `let!` instead.
- `let_it_be_with_refind`: use `let` or `let!` instead.
- `before_all`: use `before` or `before(:all)` instead.
#### Redis
GitLab stores two main categories of data in Redis: cached items, and Sidekiq
jobs. [View the full list of `Gitlab::Redis::Wrapper` descendants](https://gitlab.com/gitlab-org/gitlab/-/tree/master/lib/gitlab/redis.rb) that are backed by
a separate Redis instance.
In most specs, the Rails cache is actually an in-memory store. This is replaced
between specs, so calls to `Rails.cache.read` and `Rails.cache.write` are safe.
However, if a spec makes direct Redis calls, it should mark itself with the
`:clean_gitlab_redis_cache`, `:clean_gitlab_redis_shared_state` or
`:clean_gitlab_redis_queues` traits depending on
[which Redis instance](../redis.md#gitlabrediscachesharedstatequeues) is being used.
#### Background jobs / Sidekiq
By default, Sidekiq jobs are enqueued into a jobs array and aren't processed.
If a test queues Sidekiq jobs and need them to be processed, the
`:sidekiq_inline` trait can be used.
The `:sidekiq_might_not_need_inline` trait was added when
[Sidekiq inline mode was changed to fake mode](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/15479)
to all the tests that needed Sidekiq to actually process jobs. Tests with
this trait should be either fixed to not rely on Sidekiq processing jobs, or their
`:sidekiq_might_not_need_inline` trait should be updated to `:sidekiq_inline` if
the processing of background jobs is needed/expected.
The usage of `perform_enqueued_jobs` is useful only for testing delayed mail
deliveries, because our Sidekiq workers aren't inheriting from `ApplicationJob`
/ `ActiveJob::Base`.
#### DNS
DNS requests are stubbed universally in the test suite
(as of [!22368](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/22368)), as DNS can
cause issues depending on the developer's local network. There are RSpec labels
available in `spec/support/dns.rb` which you can apply to tests if you need to
bypass the DNS stubbing, like this:
```ruby
it "really connects to Prometheus", :permit_dns do
```
And if you need more specific control, the DNS blocking is implemented in
`spec/support/helpers/dns_helpers.rb` and these methods can be called elsewhere.
#### Rate Limiting
[Rate limiting](../../security/rate_limits.md) is enabled in the test suite. Rate limits
may be triggered in feature specs that use the `:js` trait. In most cases, triggering rate
limiting can be avoided by marking the spec with the `:clean_gitlab_redis_rate_limiting`
trait. This trait clears the rate limiting data stored in Redis cache between specs. If
a single test triggers the rate limit, the `:disable_rate_limit` can be used instead.
#### Stubbing File methods
In the situations where you need to
[stub](https://rspec.info/features/3-12/rspec-mocks/basics/allowing-messages/)
the contents of a file use the `stub_file_read`, and
`expect_file_read` helper methods which handle the stubbing for
`File.read` correctly. These methods stub `File.read` for the given
filename, and also stub `File.exist?` to return `true`.
If you need to manually stub `File.read` for any reason be sure to:
1. Stub and call the original implementation for other file paths.
1. Then stub `File.read` for only the file path you are interested in.
Otherwise `File.read` calls from other parts of the codebase get
stubbed incorrectly.
```ruby
# bad, all Files will read and return nothing
allow(File).to receive(:read)
# good
stub_file_read(my_filepath, content: "fake file content")
# also OK
allow(File).to receive(:read).and_call_original
allow(File).to receive(:read).with(my_filepath).and_return("fake file_content")
```
#### File system
File system data can be roughly split into "repositories", and "everything else".
Repositories are stored in `tmp/tests/repositories`. This directory is emptied
before a test run starts, and after the test run ends. It is not emptied between
specs, so created repositories accumulate in this directory over the
lifetime of the process. Deleting them is expensive, but this could lead to
pollution unless carefully managed.
To avoid this, [hashed storage](../../administration/repository_storage_paths.md)
is enabled in the test suite. This means that repositories are given a unique
path that depends on their project's ID. Because the project IDs are not reset
between specs, each spec gets its own repository on disk,
and prevents changes from being visible between specs.
If a spec manually specifies a project ID, or inspects the state of the
`tmp/tests/repositories/` directory directly, then it should clean up the
directory both before and after it runs. In general, these patterns should be
completely avoided.
Other classes of file linked to database objects, such as uploads, are generally
managed in the same way. With hashed storage enabled in the specs, they are
written to disk in locations determined by ID, so conflicts should not occur.
Some specs disable hashed storage by passing the `:legacy_storage` trait to the
`projects` factory. Specs that do this must **never** override the `path` of the
project, or any of its groups. The default path includes the project ID, so it
does not conflict. If two specs create a `:legacy_storage` project with the same
path, they use the same repository on disk and lead to test environment
pollution.
Other files must be managed manually by the spec. If you run code that creates a
`tmp/test-file.csv` file, for instance, the spec must ensure that the file is
removed as part of cleanup.
#### Persistent in-memory application state
All the specs in a given `rspec` run share the same Ruby process, which means
they can affect each other by modifying Ruby objects that are accessible between
specs. In practice, this means global variables, and constants (which includes
Ruby classes, modules, etc).
Global variables should generally not be modified. If absolutely necessary, a
block like this can be used to ensure the change is rolled back afterwards:
```ruby
around(:each) do |example|
old_value = $0
begin
$0 = "new-value"
example.run
ensure
$0 = old_value
end
end
```
If a spec needs to modify a constant, it should use the `stub_const` helper to
ensure the change is rolled back.
If you need to modify the contents of the `ENV` constant, you can use the
`stub_env` helper method instead.
While most Ruby **instances** are not shared between specs, **classes**
and **modules** generally are. Class and module instance variables, accessors,
class variables, and other stateful idioms, should be treated in the same way as
global variables. Don't modify them unless you have to! In particular, prefer
using expectations, or dependency injection along with stubs, to avoid the need
for modifications. If you have no other choice, an `around` block like the global
variables example can be used, but avoid this if at all possible.
#### Elasticsearch specs
Specs that require Elasticsearch must be marked with the `:elastic` or `:elastic_delete_by_query` metadata. The `:elastic`
metadata creates and deletes indices before and after all examples.
The `:elastic_delete_by_query` metadata was added to reduce runtime for pipelines by creating and deleting indices at the
start and end of each context only. The [Elasticsearch delete by query API](https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-delete-by-query.html)
is used to delete data in all indices (except the migrations index) between examples to ensure a clean index.
The `:elastic_clean` metadata creates and deletes indices between examples to ensure a clean index. This way, tests are not
polluted with non-essential data. If using the `:elastic` or `:elastic_delete_by_query` metadata
is causing issues, use `:elastic_clean` instead. `:elastic_clean` is significantly slower than the other traits
and should be used sparingly.
Most tests for Elasticsearch logic relate to:
- Creating data in PostgreSQL and waiting for it to be indexed in Elasticsearch.
- Searching for that data.
- Ensuring that the test gives the expected result.
There are some exceptions, such as checking for structural changes rather than individual records in an index.
{{< alert type="note" >}}
Elasticsearch indexing uses [`Gitlab::Redis::SharedState`](../redis.md#gitlabrediscachesharedstatequeues).
Therefore, the Elasticsearch metadata dynamically uses `:clean_gitlab_redis_shared_state`.
You do not need to add `:clean_gitlab_redis_shared_state` manually.
{{< /alert >}}
Specs using Elasticsearch require that you:
- Create data in PostgreSQL and then index it into Elasticsearch.
- Enable Application Settings for Elasticsearch (which is disabled by default).
To do so, use:
```ruby
before do
stub_ee_application_setting(elasticsearch_search: true, elasticsearch_indexing: true)
end
```
Additionally, you can use the `ensure_elasticsearch_index!` method to overcome the asynchronous nature of Elasticsearch.
It uses the [Elasticsearch Refresh API](https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-refresh.html#refresh-api-desc)
to make sure all operations performed on an index since the last refresh are available for search. This method is typically
called after loading data into PostgreSQL to ensure the data is indexed and searchable.
Helper methods from `ElasticsearchHelpers` are automatically included when using any of the Elasticsearch metadata. You
can include them directly with the `:elastic_helpers` metadata.
You can use the `SEARCH_SPEC_BENCHMARK` environment variable to benchmark test setup steps:
```console
SEARCH_SPEC_BENCHMARK=1 bundle exec rspec ee/spec/lib/elastic/latest/merge_request_class_proxy_spec.rb
```
#### Test Legacy Snowplow events
This section describes how to test with events that have yet to convert to
[internal events](../internal_analytics/internal_event_instrumentation/quick_start.md).
##### Backend
{{< alert type="warning" >}}
Snowplow performs **runtime type checks** by using the [contracts gem](https://rubygems.org/gems/contracts).
Because Snowplow is **by default disabled in tests and development**, it can be hard to
**catch exceptions** when mocking `Gitlab::Tracking`.
{{< /alert >}}
To catch runtime errors due to type checks you can use `expect_snowplow_event`, which checks for
calls to `Gitlab::Tracking#event`.
```ruby
describe '#show' do
it 'tracks snowplow events' do
get :show
expect_snowplow_event(
category: 'Experiment',
action: 'start',
namespace: group,
project: project
)
expect_snowplow_event(
category: 'Experiment',
action: 'sent',
property: 'property',
label: 'label',
namespace: group,
project: project
)
end
end
```
When you want to ensure that no event got called, you can use `expect_no_snowplow_event`.
```ruby
describe '#show' do
it 'does not track any snowplow events' do
get :show
expect_no_snowplow_event(category: described_class.name, action: 'some_action')
end
end
```
Even though `category` and `action` can be omitted, you should at least
specify a `category` to avoid flaky tests. For example,
`Users::ActivityService` may track a Snowplow event after an API
request, and `expect_no_snowplow_event` will fail if that happens to run
when no arguments are specified.
##### View layer with data attributes
If you are using the data attributes to register tracking at the Haml layer,
you can use the `have_tracking` matcher method to assert if expected data attributes are assigned.
For example, if we need to test the below Haml,
```ruby
%div{ data: { testid: '_testid_', track_action: 'render', track_label: '_tracking_label_' } }
```
- [RSpec view specs](https://rspec.info/features/6-0/rspec-rails/view-specs/view-spec/)
```ruby
it 'assigns the tracking items' do
render
expect(rendered).to have_tracking(action: 'render', label: '_tracking_label_', testid: '_testid_')
end
```
- [ViewComponent](https://viewcomponent.org/) specs
```ruby
it 'assigns the tracking items' do
render_inline(component)
expect(page).to have_tracking(action: 'render', label: '_tracking_label_', testid: '_testid_')
end
```
When you want to ensure that tracking isn't assigned, you can use `not_to` with the above matchers.
#### Test Snowplow context against the schema
The [Snowplow schema matcher](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/60480)
helps to reduce validation errors by testing Snowplow context against the JSON schema.
The schema matcher accepts the following parameters:
- `schema path`
- `context`
To add a schema matcher spec:
1. Add a new schema to the [Iglu repository](https://gitlab.com/gitlab-org/iglu),
then copy the same schema to the `spec/fixtures/product_intelligence/` directory.
1. In the copied schema, remove the `"$schema"` key and value. We do not need it for specs
and the spec fails if we keep the key, as it tries to look for the schema in the URL.
1. Use the following snippet to call the schema matcher:
```ruby
match_snowplow_context_schema(schema_path: '<filename from step 1>', context: <Context Hash> )
```
### Table-based / Parameterized tests
This style of testing is used to exercise one piece of code with a comprehensive
range of inputs. By specifying the test case once, alongside a table of inputs
and the expected output for each, your tests can be made easier to read and more
compact.
We use the [RSpec::Parameterized](https://github.com/tomykaira/rspec-parameterized)
gem. A short example, using the table syntax and checking Ruby equality for a
range of inputs, might look like this:
```ruby
describe "#==" do
using RSpec::Parameterized::TableSyntax
let(:one) { 1 }
let(:two) { 2 }
where(:a, :b, :result) do
1 | 1 | true
1 | 2 | false
true | true | true
true | false | false
ref(:one) | ref(:one) | true # let variables must be referenced using `ref`
ref(:one) | ref(:two) | false
end
with_them do
it { expect(a == b).to eq(result) }
it 'is isomorphic' do
expect(b == a).to eq(result)
end
end
end
```
If, after creating a table-based test, you see an error that looks like this:
```ruby
NoMethodError:
undefined method `to_params'
param_sets = extracted.is_a?(Array) ? extracted : extracted.to_params
^^^^^^^^^^
Did you mean? to_param
```
That indicates that you need to include the line `using RSpec::Parameterized::TableSyntax` in the spec file.
<!-- vale gitlab_base.Spelling = NO -->
{{< alert type="warning" >}}
Only use simple values as input in the `where` block. Using procs, stateful
objects, FactoryBot-created objects, and similar items can lead to
[unexpected results](https://github.com/tomykaira/rspec-parameterized/issues/8).
{{< /alert >}}
<!-- vale gitlab_base.Spelling = YES -->
### Prometheus tests
Prometheus metrics may be preserved from one test run to another. To ensure that metrics are
reset before each example, add the `:prometheus` tag to the RSpec test.
### Matchers
Custom matchers should be created to clarify the intent and/or hide the
complexity of RSpec expectations. They should be placed under
`spec/support/matchers/`. Matchers can be placed in subfolder if they apply to
a certain type of specs only (such as features or requests) but shouldn't be if
they apply to multiple type of specs.
#### `be_like_time`
Time returned from a database can differ in precision from time objects
in Ruby, so we need flexible tolerances when comparing in specs.
The PostgreSQL time and timestamp types
have [the resolution of 1 microsecond](https://www.postgresql.org/docs/16/datatype-datetime.html).
However, the precision of Ruby `Time` can vary [depending on the OS.](https://blog.paulswartz.net/post/142749676062/ruby-time-precision-os-x-vs-linux)
Consider the following snippet:
```ruby
project = create(:project)
expect(project.created_at).to eq(Project.find(project.id).created_at)
```
On Linux, `Time` can have the maximum precision of 9 and
`project.created_at` has a value (like `2023-04-28 05:53:30.808033064`) with the same precision.
However, the actual value `created_at` (like `2023-04-28 05:53:30.808033`) stored to and loaded from the database
doesn't have the same precision, and the match would fail.
On macOS X, the precision of `Time` matches that of the PostgreSQL timestamp type
and the match could succeed.
To avoid the issue, we can use `be_like_time` or `be_within` to compare
that times are within one second of each other.
Example:
```ruby
expect(metrics.merged_at).to be_like_time(time)
```
Example for `be_within`:
```ruby
expect(violation.reload.merged_at).to be_within(0.00001.seconds).of(merge_request.merged_at)
```
#### `have_gitlab_http_status`
Prefer `have_gitlab_http_status` over `have_http_status` and
`expect(response.status).to` because the former
could also show the response body whenever the status mismatched. This would
be very useful whenever some tests start breaking and we would love to know
why without editing the source and rerun the tests.
This is especially useful whenever it's showing 500 internal server error.
Prefer named HTTP status like `:no_content` over its numeric representation
`206`. See a list of [supported status codes](https://github.com/rack/rack/blob/f2d2df4016a906beec755b63b4edfcc07b58ee05/lib/rack/utils.rb#L490).
Example:
```ruby
expect(response).to have_gitlab_http_status(:ok)
```
#### `match_schema` and `match_response_schema`
The `match_schema` matcher allows validating that the subject matches a
[JSON schema](https://json-schema.org/). The item inside `expect` can be
a JSON string or a JSON-compatible data structure.
`match_response_schema` is a convenience matcher for using with a
response object. from a [request spec](testing_levels.md#integration-tests).
Examples:
```ruby
# Matches against spec/fixtures/api/schemas/prometheus/additional_metrics_query_result.json
expect(data).to match_schema('prometheus/additional_metrics_query_result')
# Matches against ee/spec/fixtures/api/schemas/board.json
expect(data).to match_schema('board', dir: 'ee')
# Matches against a schema made up of Ruby data structures
expect(data).to match_schema(Atlassian::Schemata.build_info)
```
#### `be_valid_json`
`be_valid_json` allows validating that a string parses as JSON and gives
a non-empty result. To combine it with the schema matching above, use
`and`:
```ruby
expect(json_string).to be_valid_json
expect(json_string).to be_valid_json.and match_schema(schema)
```
#### `be_one_of(collection)`
The inverse of `include`, tests that the `collection` includes the expected
value:
```ruby
expect(:a).to be_one_of(%i[a b c])
expect(:z).not_to be_one_of(%i[a b c])
```
### Testing query performance
Testing query performance allows us to:
- Assert that N+1 problems do not exist in a block of code.
- Ensure that the number of queries in a block of code does not increase unnoticed.
#### QueryRecorder
`QueryRecorder` allows profiling and testing of the number of database queries
performed in a given block of code.
See the [`QueryRecorder`](../database/query_recorder.md) section for more details.
#### GitalyClient
`Gitlab::GitalyClient.get_request_count` allows tests of the number of Gitaly queries
made by a given block of code:
See the [`Gitaly Request Counts`](../gitaly.md#request-counts) section for more details.
### Shared contexts
Shared contexts only used in one spec file can be declared inline.
Any shared contexts used by more than one spec file:
- Should be placed under `spec/support/shared_contexts/`.
- Can be placed in subfolder if they apply to a certain type of specs only
(such as features or requests) but shouldn't be if they apply to multiple type of specs.
Each file should include only one context and have a descriptive name, such as
`spec/support/shared_contexts/controllers/githubish_import_controller_shared_context.rb`.
### Shared examples
Shared examples only used in one spec file can be declared inline.
Any shared examples used by more than one spec file:
- Should be placed under `spec/support/shared_examples/`.
- Can be placed in subfolder if they apply to a certain type of specs only
(such as features or requests) but shouldn't be if they apply to multiple type of specs.
Each file should include only one context and have a descriptive name, such as
`spec/support/shared_examples/controllers/githubish_import_controller_shared_example.rb`.
### Helpers
Helpers are usually modules that provide some methods to hide the complexity of
specific RSpec examples. You can define helpers in RSpec files if they're not
intended to be shared with other specs. Otherwise, they should be placed
under `spec/support/helpers/`. Helpers can be placed in a subfolder if they apply
to a certain type of specs only (such as features or requests) but shouldn't be
if they apply to multiple type of specs.
Helpers should follow the Rails naming / namespacing convention, where
`spec/support/helpers/` is the root. For instance
`spec/support/helpers/features/iteration_helpers.rb` should define:
```ruby
# frozen_string_literal: true
module Features
module IterationHelpers
def iteration_period(iteration)
"#{iteration.start_date.to_fs(:medium)} - #{iteration.due_date.to_fs(:medium)}"
end
end
end
```
Helpers should not change the RSpec configuration. For instance, the helpers module
described above should not include:
```ruby
# bad
RSpec.configure do |config|
config.include Features::IterationHelpers
end
# good, include in specific spec
RSpec.describe 'Issue Sidebar', feature_category: :team_planning do
include Features::IterationHelpers
end
```
### Testing Ruby constants
When testing code that uses Ruby constants, focus the test on the behavior that depends on the constant,
rather than testing the values of the constant.
For example, the following is preferred because it tests the behavior of the class method `.categories`.
```ruby
describe '.categories' do
it 'gets CE unique category names' do
expect(described_class.categories).to include(
'deploy_token_packages',
'user_packages',
# ...
'kubernetes_agent'
)
end
end
```
On the other hand, testing the value of the constant itself, often only repeats the values
in the code and the test, which provides little value.
```ruby
describe CATEGORIES do
it 'has values' do
expect(CATEGORIES).to eq([
'deploy_token_packages',
'user_packages',
# ...
'kubernetes_agent'
])
end
end
```
In critical cases where an error on a constant could have a catastrophic impact,
testing the constant values might be useful as an added safeguard. For example,
if it could bring down the entire GitLab service, cause a customer to be billed more than they should be,
or [cause the universe to implode](../contributing/verify/_index.md#do-not-cause-our-universe-to-implode).
### Factories
GitLab uses [`factory_bot`](https://github.com/thoughtbot/factory_bot) as a test fixture replacement.
- Factory definitions live in `spec/factories/`, named using the pluralization
of their corresponding model (`User` factories are defined in `users.rb`).
- There should be only one top-level factory definition per file.
- FactoryBot methods are mixed in to all RSpec groups. This means you can (and
should) call `create(...)` instead of `FactoryBot.create(...)`.
- Make use of [traits](https://www.rubydoc.info/gems/factory_bot/file/GETTING_STARTED.md#traits) to clean up definitions and usages.
- When defining a factory, don't define attributes that are not required for the
resulting record to pass validation.
- When instantiating from a factory, don't supply attributes that aren't
required by the test.
- Use [implicit](https://github.com/thoughtbot/factory_bot/blob/master/GETTING_STARTED.md#implicit-definition),
[explicit](https://github.com/thoughtbot/factory_bot/blob/master/GETTING_STARTED.md#explicit-definition), or
[inline](https://github.com/thoughtbot/factory_bot/blob/master/GETTING_STARTED.md#inline-definition) associations
instead of `create` / `build` for association setup in callbacks.
See [issue #262624](https://gitlab.com/gitlab-org/gitlab/-/issues/262624) for further context.
When creating factories with a [`has_many`](https://github.com/thoughtbot/factory_bot/blob/master/GETTING_STARTED.md#has_many-associations) and `belongs_to` association, use the `instance` method to refer to the object being built.
This prevents [creation of unnecessary records](https://gitlab.com/gitlab-org/gitlab/-/issues/378183) by using [interconnected associations](https://github.com/thoughtbot/factory_bot/blob/master/GETTING_STARTED.md#interconnected-associations).
For example, if we have the following classes:
```ruby
class Car < ApplicationRecord
has_many :wheels, inverse_of: :car, foreign_key: :car_id
end
class Wheel < ApplicationRecord
belongs_to :car, foreign_key: :car_id, inverse_of: :wheel, optional: false
end
```
We can create the following factories:
```ruby
FactoryBot.define do
factory :car do
transient do
wheels_count { 2 }
end
wheels do
Array.new(wheels_count) do
association(:wheel, car: instance)
end
end
end
end
FactoryBot.define do
factory :wheel do
car { association :car }
end
end
```
- Factories don't have to be limited to `ActiveRecord` objects.
[See example](https://gitlab.com/gitlab-org/gitlab-foss/commit/0b8cefd3b2385a21cfed779bd659978c0402766d).
- Avoid the use of [`skip_callback`](https://api.rubyonrails.org/classes/ActiveSupport/Callbacks/ClassMethods.html#method-i-skip_callback) in factories.
See [issue #247865](https://gitlab.com/gitlab-org/gitlab/-/issues/247865) for details.
### Fixtures
All fixtures should be placed under `spec/fixtures/`.
### Repositories
Testing some functionality, such as merging a merge request, requires a Git
repository with a certain state to be present in the test environment. GitLab
maintains the [`gitlab-test`](https://gitlab.com/gitlab-org/gitlab-test)
repository for certain common cases - you can ensure a copy of the repository is
used with the `:repository` trait for project factories:
```ruby
let(:project) { create(:project, :repository) }
```
Where you can, consider using the `:custom_repo` trait instead of `:repository`.
This allows you to specify exactly what files appear in the `main` branch
of the project's repository. For example:
```ruby
let(:project) do
create(
:project, :custom_repo,
files: {
'README.md' => 'Content here',
'foo/bar/baz.txt' => 'More content here'
}
)
end
```
This creates a repository containing two files, with default permissions and
the specified content.
### Configuration
RSpec configuration files are files that change the RSpec configuration (like
`RSpec.configure do |config|` blocks). They should be placed under
`spec/support/`.
Each file should be related to a specific domain, such as
`spec/support/capybara.rb` or `spec/support/carrierwave.rb`.
If a helpers module applies only to a certain kind of specs, it should add
modifiers to the `config.include` call. For instance if
`spec/support/helpers/cycle_analytics_helpers.rb` applies to `:lib` and
`type: :model` specs only, you would write the following:
```ruby
RSpec.configure do |config|
config.include Spec::Support::Helpers::CycleAnalyticsHelpers, :lib
config.include Spec::Support::Helpers::CycleAnalyticsHelpers, type: :model
end
```
If a configuration file only consists of `config.include`, you can add these
`config.include` directly in `spec/spec_helper.rb`.
For very generic helpers, consider including them in the `spec/support/rspec.rb`
file which is used by the `spec/fast_spec_helper.rb` file. See
[Fast unit tests](#fast-unit-tests) for more details about the
`spec/fast_spec_helper.rb` file.
### Test environment logging
Services for the test environment are automatically configured and started when
tests are run, including Gitaly, Workhorse, Elasticsearch, and Capybara. When run in CI, or
if the service needs to be installed, the test environment logs information
about set-up time, producing log messages like the following:
```plaintext
==> Setting up Gitaly...
Gitaly set up in 31.459649 seconds...
==> Setting up GitLab Workhorse...
GitLab Workhorse set up in 29.695619 seconds...
fatal: update refs/heads/diff-files-symlink-to-image: invalid <newvalue>: 8cfca84
From https://gitlab.com/gitlab-org/gitlab-test
* [new branch] diff-files-image-to-symlink -> origin/diff-files-image-to-symlink
* [new branch] diff-files-symlink-to-image -> origin/diff-files-symlink-to-image
* [new branch] diff-files-symlink-to-text -> origin/diff-files-symlink-to-text
* [new branch] diff-files-text-to-symlink -> origin/diff-files-text-to-symlink
b80faa8..40232f7 snippet/multiple-files -> origin/snippet/multiple-files
* [new branch] testing/branch-with-#-hash -> origin/testing/branch-with-#-hash
==> Setting up GitLab Elasticsearch Indexer...
GitLab Elasticsearch Indexer set up in 26.514623 seconds...
```
This information is omitted when running locally and when no action needs
to be performed. If you would always like to see these messages, set the
following environment variable:
```shell
GITLAB_TESTING_LOG_LEVEL=debug
```
---
[Return to Testing documentation](_index.md)
|
https://docs.gitlab.com/development/frontend_testing
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/frontend_testing.md
|
2025-08-13
|
doc/development/testing_guide
|
[
"doc",
"development",
"testing_guide"
] |
frontend_testing.md
|
none
|
unassigned
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Frontend testing standards and style guidelines
| null |
There are two types of test suites encountered while developing frontend code
at GitLab. We use Jest for JavaScript unit and integration testing,
and RSpec feature tests with Capybara for e2e (end-to-end) integration testing.
Unit and feature tests need to be written for all new features.
Most of the time, you should use [RSpec](https://github.com/rspec/rspec-rails#feature-specs) for your feature tests. For more information on how to get started with feature tests, see [get started with feature tests](#get-started-with-feature-tests)
Regression tests should be written for bug fixes to prevent them from recurring
in the future.
See the [Testing Standards and Style Guidelines](_index.md) page for more
information on general testing practices at GitLab.
## Vue.js testing
If you are looking for a guide on Vue component testing, you can jump right away to this [section](../fe_guide/vue.md#testing-vue-components).
Information on testing Vue 3 is contained in [this page](testing_vue3.md).
## Jest
We use Jest to write frontend unit and integration tests.
Jest tests can be found in `/spec/frontend` and `/ee/spec/frontend` in EE.
### `jsdom`
Jest uses `jsdom` instead of a browser for running tests.
Known issues include:
- [No scrolling support](https://github.com/jsdom/jsdom/blob/15.1.1/lib/jsdom/browser/Window.js#L623-L625)
- [No element sizes or positions](https://github.com/jsdom/jsdom/blob/15.1.1/lib/jsdom/living/nodes/Element-impl.js#L334-L371)
- [No layout engine](https://github.com/jsdom/jsdom/issues/1322) in general
See also the issue for [support running Jest tests in browsers](https://gitlab.com/gitlab-org/gitlab/-/issues/26982).
### Debugging Jest tests
Running `yarn jest-debug` runs Jest in debug mode, allowing you to debug/inspect as described in the [Jest documentation](https://jestjs.io/docs/troubleshooting#tests-are-failing-and-you-don-t-know-why).
### Timeout error
The default timeout for Jest is set in
[`/jest.config.base.js`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/jest.config.base.js).
If your test exceeds that time, it fails.
If you cannot improve the performance of the tests, you can increase the timeout
for the whole suite using [`jest.setTimeout`](https://jestjs.io/docs/next/jest-object#jestsettimeouttimeout)
```javascript
jest.setTimeout(500);
describe('Component', () => {
it('does something amazing', () => {
// ...
});
});
```
or for a specific test by providing a third argument to [`it`](https://jestjs.io/docs/next/api#testname-fn-timeout)
```javascript
describe('Component', () => {
it('does something amazing', () => {
// ...
}, 500)
})
```
Remember that the performance of each test depends on the environment.
### Test-specific stylesheets
To help facilitate RSpec integration tests we have two test-specific stylesheets. These can be used to do things like disable animations to improve test speed, or to make elements visible when they need to be targeted by Capybara click events:
- `app/assets/stylesheets/disable_animations.scss`
- `app/assets/stylesheets/test_environment.scss`
Because the test environment should match the production environment as much as possible, use these minimally and only add to them when necessary.
## What and how to test
Before jumping into more gritty details about Jest-specific workflows like mocks and spies, we should briefly cover what to test with Jest.
### Don't test the library
Libraries are an integral part of any JavaScript developer's life. The general advice would be to not test library internals, but expect that the library knows what it's supposed to do and has test coverage on its own.
A general example could be something like this
```javascript
import { convertToFahrenheit } from 'temperatureLibrary'
function getFahrenheit(celsius) {
return convertToFahrenheit(celsius)
}
```
It does not make sense to test our `getFahrenheit` function because underneath it does nothing else but invoking the library function, and we can expect that one is working as intended.
Let's take a short look into Vue land. Vue is a critical part of the GitLab JavaScript codebase. When writing specs for Vue components, a common gotcha is to actually end up testing Vue provided functionality, because it appears to be the easiest thing to test. Here's an example taken from our codebase.
```javascript
// Component script
{
computed: {
hasMetricTypes() {
return this.metricTypes.length;
},
}
```
```html
<!-- Component template -->
<template>
<gl-dropdown v-if="hasMetricTypes">
<!-- Dropdown content -->
</gl-dropdown>
</template>
```
Testing the `hasMetricTypes` computed prop would seem like a given here. But to test if the computed property is returning the length of `metricTypes`, is testing the Vue library itself. There is no value in this, besides it adding to the test suite. It's better to test a component in the way the user interacts with it: checking the rendered template.
```javascript
// Bad
describe('computed', () => {
describe('hasMetricTypes', () => {
it('returns true if metricTypes exist', () => {
factory({ metricTypes });
expect(wrapper.vm.hasMetricTypes).toBe(2);
});
it('returns true if no metricTypes exist', () => {
factory();
expect(wrapper.vm.hasMetricTypes).toBe(0);
});
});
});
// Good
it('displays a dropdown if metricTypes exist', () => {
factory({ metricTypes });
expect(wrapper.findComponent(GlDropdown).exists()).toBe(true);
});
it('does not display a dropdown if no metricTypes exist', () => {
factory();
expect(wrapper.findComponent(GlDropdown).exists()).toBe(false);
});
```
Keep an eye out for these kinds of tests, as they just make updating logic more fragile and tedious than it needs to be. This is also true for other libraries. A suggestion here is: if you are checking a `wrapper.vm` property, you should probably stop and rethink the test to check the rendered template instead.
Some more examples can be found in the [Frontend unit tests section](testing_levels.md#frontend-unit-tests)
### Don't test your mock
Another common gotcha is that the specs end up verifying the mock is working. If you are using mocks, the mock should support the test, but not be the target of the test.
```javascript
const spy = jest.spyOn(idGenerator, 'create')
spy.mockImplementation = () = '1234'
// Bad
expect(idGenerator.create()).toBe('1234')
// Good: actually focusing on the logic of your component and just leverage the controllable mocks output
expect(wrapper.find('div').html()).toBe('<div id="1234">...</div>')
```
### Don't use imported values in assertions
Prefer literal values in assertions rather than importing constants. This makes tests easier to read, and resilient to changes. This is discussed further in [internationalization recommendations](../i18n/externalization.md#recommendations).
```javascript
// Bad: MY_CONSTANT could accidentally be set to undefined, have a typo etc. and test would still pass
import { MY_CONSTANT } from '../constants';
it('returns the correct value', () => {
expect(ding()).toBe(MY_CONSTANT);
});
// Good: explicit value is asserted
it('returns the correct value', () => {
expect(ding()).toBe('expected literal value');
});
```
### Follow the user
The line between unit and integration tests can be quite blurry in a component heavy world. The most important guideline to give is the following:
- Write clean unit tests if there is actual value in testing a complex piece of logic in isolation to prevent it from breaking in the future
- Otherwise, try to write your specs as close to the user's flow as possible
For example, it's better to use the generated markup to trigger a button click and validate the markup changed accordingly than to call a method manually and verify data structures or computed properties. There's always the chance of accidentally breaking the user flow, while the tests pass and provide a false sense of security.
## Common practices
These some general common practices included as part of our test suite. Should you stumble over something not following this guide, ideally fix it right away. 🎉
### How to query DOM elements
When it comes to querying DOM elements in your tests, it is best to uniquely and semantically target
the element.
Preferentially, this is done by targeting what the user actually sees using [DOM Testing Library](https://testing-library.com/docs/dom-testing-library/intro/).
When selecting by text it is best to use the [`byRole`](https://testing-library.com/docs/queries/byrole/) query
as it helps enforce accessibility best practices. `findByRole` and the other [DOM Testing Library queries](https://testing-library.com/docs/queries/about/) are available when using [`shallowMountExtended` or `mountExtended`](#shallowmountextended-and-mountextended).
When writing Vue component unit tests, it can be wise to query children by component, so that the unit test can focus on comprehensive value coverage
rather than dealing with the complexity of a child component's behavior.
Sometimes, neither of the above are feasible. In these cases, adding test attributes to simplify the selectors might be the best option. A list of
possible selectors include:
- A semantic attribute like `name` (also verifies that `name` was setup properly)
- A `data-testid` attribute ([recommended by maintainers of `@vue/test-utils`](https://github.com/vuejs/vue-test-utils/issues/1498#issuecomment-610133465))
optionally combined with [`shallowMountExtended` or `mountExtended`](#shallowmountextended-and-mountextended)
```javascript
import { shallowMountExtended } from 'helpers/vue_test_utils_helper'
const wrapper = shallowMountExtended(ExampleComponent);
it('exists', () => {
// Best (especially for integration tests)
wrapper.findByRole('link', { name: /Click Me/i })
wrapper.findByRole('link', { name: 'Click Me' })
wrapper.findByText('Click Me')
wrapper.findByText(/Click Me/i)
// Good (especially for unit tests)
wrapper.findComponent(FooComponent);
wrapper.find('input[name=foo]');
wrapper.find('[data-testid="my-foo-id"]');
wrapper.findByTestId('my-foo-id'); // with shallowMountExtended or mountExtended, check below
// Bad
wrapper.find({ ref: 'foo'});
wrapper.find('.js-foo');
wrapper.find('.gl-button');
});
```
You should use `kebab-case` for `data-testid` attribute.
It is not recommended that you add `.js-*` classes just for testing purposes. Only do this if there are no other feasible options available.
Avoid using Vue template refs to query DOM elements in tests because they're an implementation detail of the component, not a public API.
### Querying for child components
When testing Vue components with `@vue/test-utils` another possible approach is querying for child
components instead of querying for DOM nodes. This assumes that implementation details of behavior
under test should be covered by that component's individual unit test. There is no strong preference
in writing DOM or component queries as long as your tests reliably cover expected behavior for the
component under test.
Example:
```javascript
it('exists', () => {
wrapper.findComponent(FooComponent);
});
```
### Naming unit/component tests
Unit/Component tests should be named `${componentName}_spec.js`
If the test name is not specific enough, consider renaming the component.
For Example:
`diff_stats_dropdown.vue` should have a unit/component test named `diff_stats_dropdown_spec.js`
### Describe block naming
When writing describe test blocks to test specific functions/methods,
use the method name as the describe block name.
**Bad**:
```javascript
describe('#methodName', () => {
it('passes', () => {
expect(true).toEqual(true);
});
});
describe('.methodName', () => {
it('passes', () => {
expect(true).toEqual(true);
});
});
```
**Good**:
```javascript
describe('methodName', () => {
it('passes', () => {
expect(true).toEqual(true);
});
});
```
### Testing promises
When testing Promises you should always make sure that the test is asynchronous and rejections are handled. It's now possible to use the `async/await` syntax in the test suite:
```javascript
it('tests a promise', async () => {
const users = await fetchUsers()
expect(users.length).toBe(42)
});
it('tests a promise rejection', async () => {
await expect(user.getUserName(1)).rejects.toThrow('User with 1 not found.');
});
```
You can also return a promise from the test function.
Using the `done` and `done.fail` callbacks is discouraged when working with
promises. They should not be used.
**Bad**:
```javascript
// missing return
it('tests a promise', () => {
promise.then(data => {
expect(data).toBe(asExpected);
});
});
// uses done/done.fail
it('tests a promise', done => {
promise
.then(data => {
expect(data).toBe(asExpected);
})
.then(done)
.catch(done.fail);
});
```
**Good**:
```javascript
// verifying a resolved promise
it('tests a promise', () => {
return promise
.then(data => {
expect(data).toBe(asExpected);
});
});
// verifying a resolved promise using Jest's `resolves` matcher
it('tests a promise', () => {
return expect(promise).resolves.toBe(asExpected);
});
// verifying a rejected promise using Jest's `rejects` matcher
it('tests a promise rejection', () => {
return expect(promise).rejects.toThrow(expectedError);
});
```
### Manipulating Time
Sometimes we have to test time-sensitive code. For example, recurring events that run every X amount of seconds or similar. Here are some strategies to deal with that:
#### `setTimeout()` / `setInterval()` in application
If the application itself is waiting for some time, mock await the waiting. In Jest this is already
[done by default](https://gitlab.com/gitlab-org/gitlab/-/blob/a2128edfee799e49a8732bfa235e2c5e14949c68/jest.config.js#L47)
(see also [Jest Timer Mocks](https://jestjs.io/docs/timer-mocks)).
```javascript
const doSomethingLater = () => {
setTimeout(() => {
// do something
}, 4000);
};
```
**In Jest**:
```javascript
it('does something', () => {
doSomethingLater();
jest.runAllTimers();
expect(something).toBe('done');
});
```
### Mocking the current location in Jest
{{< alert type="note" >}}
The value of `window.location.href` is reset before every test to avoid earlier
tests affecting later ones.
{{< /alert >}}
If your tests require `window.location.href` to take a particular value, use
the `setWindowLocation` helper:
```javascript
import setWindowLocation from 'helpers/set_window_location_helper';
it('passes', () => {
setWindowLocation('https://gitlab.test/foo?bar=true');
expect(window.location).toMatchObject({
hostname: 'gitlab.test',
pathname: '/foo',
search: '?bar=true',
});
});
```
To modify only the hash, use either the `setWindowLocation` helper, or assign
directly to `window.location.hash`, for example:
```javascript
it('passes', () => {
window.location.hash = '#foo';
expect(window.location.href).toBe('http://test.host/#foo');
});
```
If your tests need to assert that certain `window.location` methods were
called, use the `useMockLocationHelper` helper:
```javascript
import { useMockLocationHelper } from 'helpers/mock_window_location_helper';
useMockLocationHelper();
it('passes', () => {
window.location.reload();
expect(window.location.reload).toHaveBeenCalled();
});
```
### Testing clean-up of event listeners and timeouts
Often times in components we create event listeners or timeouts on the `beforeDestroy` (`beforeUnmount` for Vue 3) hooks. It is important to test that both listeners and timeouts are cleared when the component instance is destroyed, as forgetting to clean up these events can cause problems like memory leaks and broken references on event listeners.
Consider the following example:
```javascript
beforeDestroy() {
removeEventListener('keydown', someListener)
clearTimeout(timeoutPointer)
}
```
In the above example, a component is both clearing a `keydown` event listener and a timeout that was created elsewhere.
Let's take a look at the relevant tests.
```javascript
describe('Cleanup before destroy', () => {
beforeEach(() => {
createComponent()
// Destroy the component immediately to invoke the `beforeDestroy` hook
wrapper.destroy()
})
it('removes the event listener', () => {
const spy = jest.spyOn(window, 'removeEventListener')
expect(spy).toHaveBeenCalledTimes(1)
expect(spy).toHaveBeenCalledWith('keydown', expect.any(Function))
})
it('clears the pending timeouts', () => {
const spy = jest.spyOn(window, 'clearTimeout')
expect(spy).toHaveBeenCalledTimes(1)
})
})
```
The above example does not explicitly check for the function that is called on the `keydown` listener as it will usually be an implementation detail. The same happens with the `clearTimeout` call, as the parameter will be a pointer to a timer created internally in the component.
Due to this, it is usually sufficient to check that the spies have been called, with the recommended addition of checking the _times_ that they have been called.
### Waiting in tests
Sometimes a test needs to wait for something to happen in the application before it continues.
You should try to avoid:
- [`setTimeout`](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout) because it makes the reason for waiting unclear. Additionally, it is faked in our tests so its usage is tricky.
- [`setImmediate`](https://developer.mozilla.org/en-US/docs/Web/API/Window/setImmediate) because it is no longer supported in Jest 27 and later. See [this epic](https://gitlab.com/groups/gitlab-org/-/epics/7002) for details.
#### Promises and Ajax calls
Register handler functions to wait for the `Promise` to be resolved.
```javascript
const askTheServer = () => {
return axios
.get('/endpoint')
.then(response => {
// do something
})
.catch(error => {
// do something else
});
};
```
**In Jest**:
```javascript
it('waits for an Ajax call', async () => {
await askTheServer()
expect(something).toBe('done');
});
```
If you cannot register handlers to the `Promise`, for example because it is executed in a synchronous Vue lifecycle hook, take a look at the [`waitFor`](#wait-until-axios-requests-finish) helpers or flush all pending `Promise`s with:
**In Jest**:
```javascript
it('waits for an Ajax call', async () => {
synchronousFunction();
await waitForPromises();
expect(something).toBe('done');
});
```
#### Vue rendering
Use [`nextTick()`](https://v2.vuejs.org/v2/api/#Vue-nextTick) to wait until a Vue component is
re-rendered.
**In Jest**:
```javascript
import { nextTick } from 'vue';
// ...
it('renders something', async () => {
wrapper.setProps({ value: 'new value' });
await nextTick();
expect(wrapper.text()).toBe('new value');
});
```
#### Events
If the application triggers an event that you need to wait for in your test, register an event handler which contains
the assertions:
```javascript
it('waits for an event', () => {
eventHub.$once('someEvent', eventHandler);
someFunction();
return new Promise((resolve) => {
function expectEventHandler() {
expect(something).toBe('done');
resolve();
}
});
});
```
In Jest you can also use a `Promise` for this:
```javascript
it('waits for an event', () => {
const eventTriggered = new Promise(resolve => eventHub.$once('someEvent', resolve));
someFunction();
return eventTriggered.then(() => {
expect(something).toBe('done');
});
});
```
### Manipulate `gon` object
`gon` (or `window.gon`) is a global object used to pass data from the backend. If your test depends
on its value you can directly modify it:
```javascript
describe('when logged in', () => {
beforeEach(() => {
gon.current_user_id = 1;
});
it('shows message', () => {
expect(wrapper.text()).toBe('Logged in!');
});
})
```
`gon` is reset in every test to ensure tests are isolated.
### Ensuring that tests are isolated
Tests are typically architected in a pattern which requires a recurring setup of the component under test. This is often achieved by making use of the `beforeEach` hook.
Example
```javascript
let wrapper;
beforeEach(() => {
wrapper = mount(Component);
});
```
With [enableAutoDestroy](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/100389), it is no longer necessary to manually call `wrapper.destroy()`.
However, some mocks, spies, and fixtures do need to be torn down, and we can leverage the `afterEach` hook.
Example
```javascript
let wrapper;
afterEach(() => {
fakeApollo = null;
store = null;
});
```
### Testing local-only Apollo queries and mutations
To add a new query or mutation before it is added to the backend, we can use the `@client` directive. For example:
```graphql
mutation setActiveBoardItemEE($boardItem: LocalBoardItem, $isIssue: Boolean = true) {
setActiveBoardItem(boardItem: $boardItem) @client {
...Issue @include(if: $isIssue)
...EpicDetailed @skip(if: $isIssue)
}
}
```
When writing test cases for such calls, we can use resolvers to make sure they are called with the correct parameters.
For example, when creating the wrapper, we should make sure the resolver is mapped to the query or mutation.
The mutation we are mocking here is `setActiveBoardItem`:
```javascript
const mockSetActiveBoardItemResolver = jest.fn();
const mockApollo = createMockApollo([], {
Mutation: {
setActiveBoardItem: mockSetActiveBoardItemResolver,
},
});
```
In the following code, we must pass four arguments. The second one must be the collection of input variables of the query or mutation mocked.
To test that the mutation is called with the correct parameters:
```javascript
it('calls setActiveBoardItemMutation on close', async () => {
wrapper.findComponent(GlDrawer).vm.$emit('close');
await waitForPromises();
expect(mockSetActiveBoardItemResolver).toHaveBeenCalledWith(
{},
{
boardItem: null,
},
expect.anything(),
expect.anything(),
);
});
```
### Jest best practices
#### Prefer `toBe` over `toEqual` when comparing primitive values
Jest has [`toBe`](https://jestjs.io/docs/expect#tobevalue) and
[`toEqual`](https://jestjs.io/docs/expect#toequalvalue) matchers.
As [`toBe`](https://jestjs.io/docs/expect#tobevalue) uses
[`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is)
to compare values, it's faster (by default) than using `toEqual`.
While the latter eventually falls back to leverage [`Object.is`](https://github.com/facebook/jest/blob/master/packages/expect/src/jasmineUtils.ts#L91),
for primitive values, it should only be used when complex objects need a comparison.
Examples:
```javascript
const foo = 1;
// Bad
expect(foo).toEqual(1);
// Good
expect(foo).toBe(1);
```
#### Prefer more befitting matchers
Jest provides useful matchers like `toHaveLength` or `toBeUndefined` to make your tests more
readable and to produce more understandable error messages. Check their docs for the
[full list of matchers](https://jestjs.io/docs/expect#methods).
Examples:
```javascript
const arr = [1, 2];
// prints:
// Expected length: 1
// Received length: 2
expect(arr).toHaveLength(1);
// prints:
// Expected: 1
// Received: 2
expect(arr.length).toBe(1);
// prints:
// expect(received).toBe(expected) // Object.is equality
// Expected: undefined
// Received: "bar"
const foo = 'bar';
expect(foo).toBe(undefined);
// prints:
// expect(received).toBeUndefined()
// Received: "bar"
const foo = 'bar';
expect(foo).toBeUndefined();
```
#### Avoid using `toBeTruthy` or `toBeFalsy`
Jest also provides following matchers: `toBeTruthy` and `toBeFalsy`. We should not use them because
they make tests weaker and produce false-positive results.
For example, `expect(someBoolean).toBeFalsy()` passes when `someBoolean === null`, and when
`someBoolean === false`.
#### Tricky `toBeDefined` matcher
Jest has the tricky `toBeDefined` matcher that can produce false positive test. Because it
[validates](https://github.com/facebook/jest/blob/master/packages/expect/src/matchers.ts#L204)
the given value for `undefined` only.
```javascript
// Bad: if finder returns null, the test will pass
expect(wrapper.find('foo')).toBeDefined();
// Good
expect(wrapper.find('foo').exists()).toBe(true);
```
#### Avoid using `setImmediate`
Try to avoid using `setImmediate`. `setImmediate` is an ad-hoc solution to run your callback after
the I/O completes. And it's not part of the Web API, hence, we target NodeJS environments in our
unit tests.
Instead of `setImmediate`, use `jest.runAllTimers` or `jest.runOnlyPendingTimers` to run pending timers.
The latter is useful when you have `setInterval` in the code. **Remember**: our Jest configuration uses fake timers.
## Avoid non-deterministic specs
Non-determinism is the breeding ground for flaky and brittle specs. Such specs end up breaking the CI pipeline, interrupting the work flow of other contributors.
1. Make sure your test subject's collaborators (for example, Axios, Apollo, Lodash helpers) and test environment (for example, Date) behave consistently across systems and over time.
1. Make sure tests are focused and not doing "extra work" (for example, needlessly creating the test subject more than once in an individual test).
### Faking `Date` for determinism
`Date` is faked by default in our Jest environment. This means every call to `Date()` or `Date.now()` returns a fixed deterministic value.
If you really need to change the default fake date, you can call `useFakeDate` within any `describe` block, and
the date will be replaced for that specs within that `describe` context only:
```javascript
import { useFakeDate } from 'helpers/fake_date';
describe('cool/component', () => {
// Default fake `Date`
const TODAY = new Date();
// NOTE: `useFakeDate` cannot be called during test execution (that is, inside `it`, `beforeEach`, `beforeAll`, etc.).
describe("on Ada Lovelace's Birthday", () => {
useFakeDate(1815, 11, 10)
it('Date is no longer default', () => {
expect(new Date()).not.toEqual(TODAY);
});
});
it('Date is still default in this scope', () => {
expect(new Date()).toEqual(TODAY)
});
})
```
Similarly, if you really need to use the real `Date` class, then you can import and call `useRealDate` within any `describe` block:
```javascript
import { useRealDate } from 'helpers/fake_date';
// NOTE: `useRealDate` cannot be called during test execution (that is, inside `it`, `beforeEach`, `beforeAll`, etc.).
describe('with real date', () => {
useRealDate();
});
```
### Faking `Math.random` for determinism
Consider replacing `Math.random` with a fake when the test subject depends on it.
```javascript
beforeEach(() => {
// https://xkcd.com/221/
jest.spyOn(Math, 'random').mockReturnValue(0.4);
});
```
## Console warnings and errors in tests
Unexpected console warnings and errors are indicative of problems in our production code.
We want our test environment to be strict, so your tests should fail when unexpected
`console.error` or `console.warn` calls are made.
### Ignoring console messages from watcher
Since there's a lot of code outside of our control, there are some console messages that
are ignored by default and will **not** fail a test if used. This list of ignored
messages can be maintained where we call `setupConsoleWatcher`. Example:
```javascript
setupConsoleWatcher({
ignores: [
...,
// Any call to `console.error('Foo bar')` or `console.warn('Foo bar')` will be ignored by our console watcher.
'Foo bar',
// Use regex to allow for flexible message matching.
/Lorem ipsum/,
]
});
```
If a specific test needs to ignore a specific message for a `describe` block, use the
`ignoreConsoleMessages` helper near the top of the `describe`. This automatically
calls `beforeAll` and `afterAll` to set up/teardown this set of ignored for the test
context.
Use this sparingly and only if absolutely necessary for test maintainability. Example:
```javascript
import { ignoreConsoleMessages } from 'helpers/console_watcher';
describe('foos/components/foo.vue', () => {
describe('when blooped', () => {
// Will not fail a test if `console.warn('Lorem ipsum')` is called
ignoreConsoleMessages([
/^Lorem ipsum/
]);
});
describe('default', () => {
// Will fail a test if `console.warn('Lorem ipsum')` is called
});
});
```
## Factories
TBU
## Mocking Strategies with Jest
### Stubbing and Mocking
Stubs or spies are often used synonymously. In Jest it's quite easy thanks to the `.spyOn` method.
[Official docs](https://jestjs.io/docs/jest-object#jestspyonobject-methodname)
The more challenging part are mocks, which can be used for functions or even dependencies.
### Manual module mocks
Manual mocks are used to mock modules across the entire Jest environment. This is a very powerful testing tool that helps simplify
unit testing by mocking out modules that cannot be easily consumed in our test environment.
{{< alert type="warning" >}}
Do not use manual mocks if a mock should not be consistently applied in every spec (that is, it's only needed by a few specs).
Instead, consider using [`jest.mock(..)`](https://jestjs.io/docs/jest-object#jestmockmodulename-factory-options)
(or a similar mocking function) in the relevant spec file.
{{< /alert >}}
#### Where should you put manual mocks?
Jest supports [manual module mocks](https://jestjs.io/docs/manual-mocks) by placing a mock in a `__mocks__/` directory next to the source module
(for example, `app/assets/javascripts/ide/__mocks__`). **Don't do this.** We want to keep all of our test-related code in one place (the `spec/` folder).
If a manual mock is needed for a `node_modules` package, use the `spec/frontend/__mocks__` folder. Here's an example of
a [Jest mock for the package `monaco-editor`](https://gitlab.com/gitlab-org/gitlab/-/blob/b7f914cddec9fc5971238cdf12766e79fa1629d7/spec/frontend/__mocks__/monaco-editor/index.js#L1).
If a manual mock is needed for a CE module, place the implementation in
`spec/frontend/__helpers__/mocks` and add a line to the `frontend/test_setup`
(or the `frontend/shared_test_setup`) that looks something like:
```javascript
// "~/lib/utils/axios_utils" is the path to the real module
// "helpers/mocks/axios_utils" is the path to the mocked implementation
jest.mock('~/lib/utils/axios_utils', () => jest.requireActual('helpers/mocks/axios_utils'));
```
#### Manual mock examples
- [`__helpers__/mocks/axios_utils`](https://gitlab.com/gitlab-org/gitlab/-/blob/a50edd12b3b1531389624086b6381a042c8143ef/spec/frontend/__helpers__/mocks/axios_utils.js#L1) -
This mock is helpful because we don't want any unmocked requests to pass any tests. Also, we are able to inject some test helpers such as `axios.waitForAll`.
- [`__mocks__/mousetrap/index.js`](https://gitlab.com/gitlab-org/gitlab/-/blob/cd4c086d894226445be9d18294a060ba46572435/spec/frontend/__mocks__/mousetrap/index.js#L1) -
This mock is helpful because the module itself uses AMD format which webpack understands, but is incompatible with the jest environment. This mock doesn't remove
any behavior, only provides a nice es6 compatible wrapper.
- [`__mocks__/monaco-editor/index.js`](https://gitlab.com/gitlab-org/gitlab/-/blob/b7f914cddec9fc5971238cdf12766e79fa1629d7/spec/frontend/__mocks__/monaco-editor/index.js) -
This mock is helpful because the Monaco package is completely incompatible in a Jest environment. In fact, webpack requires a special loader to make it work. This mock
makes this package consumable by Jest.
### Keep mocks light
Global mocks introduce magic and technically can reduce test coverage. When mocking is deemed profitable:
- Keep the mock short and focused.
- Leave a top-level comment in the mock on why it is necessary.
### Additional mocking techniques
Consult the [official Jest docs](https://jestjs.io/docs/jest-object#mock-modules) for a full overview of the available mocking features.
## Running Frontend Tests
Before generating fixtures, make sure you have a running GDK instance.
For running the frontend tests, you need the following commands:
- `rake frontend:fixtures` (re-)generates [fixtures](#frontend-test-fixtures). Make sure that
fixtures are up-to-date before running tests that require them.
- `yarn jest` runs Jest tests.
### Running CE and EE tests
Whenever you create tests for both CE and EE environments, because your changes have EE features, you need to take some steps to ensure that both tests pass locally and on the pipeline when run.
Check [this section](../ee_features.md#running-ee-vs-ce-tests) to learn more about testing both environments.
### Live testing and focused testing -- Jest
While you work on a test suite, you may want to run these specs in watch mode, so they rerun automatically on every save.
```shell
# Watch and rerun all specs matching the name icon
yarn jest --watch icon
# Watch and rerun one specific file
yarn jest --watch path/to/spec/file.spec.js
```
You can also run some focused tests without the `--watch` flag
```shell
# Run specific jest file
yarn jest ./path/to/local_spec.js
# Run specific jest folder
yarn jest ./path/to/folder/
# Run all jest files which path contain term
yarn jest term
```
## Frontend test fixtures
Frontend fixtures are files containing responses from backend controllers. These responses can be either HTML
generated from HAML templates or JSON payloads. Frontend tests that rely on these responses are
often using fixtures to validate correct integration with the backend code.
### Use fixtures
To import a JSON or HTML fixture, `import` it using the `test_fixtures` alias.
```javascript
import responseBody from 'test_fixtures/some/fixture.json' // loads tmp/tests/frontend/fixtures-ee/some/fixture.json
it('makes a request', () => {
axiosMock.onGet(endpoint).reply(200, responseBody);
myButton.click();
// ...
});
```
### Generate fixtures
You can find code to generate test fixtures in:
- `spec/frontend/fixtures/`, for running tests in CE.
- `ee/spec/frontend/fixtures/`, for running tests in EE.
You can generate fixtures by running:
- `bin/rake frontend:fixtures` to generate all fixtures
- `bin/rspec spec/frontend/fixtures/merge_requests.rb` to generate specific fixtures (in this case for `merge_request.rb`)
You can find generated fixtures are in `tmp/tests/frontend/fixtures-ee`.
To generate a single fixture for a _spec.js file identify the import from `test_fixtures/` directory:
```javascript
// spec/frontend/authentication/webauthn/authenticate_spec.js
import htmlWebauthnAuthenticate from 'test_fixtures/webauthn/authenticate.html';
```
The corresponding fixture file is `spec/frontend/fixtures/webauthn.rb`
To generate the single fixture from the command line run `bin/rspec spec/frontend/fixtures/webauthn.rb`
### Download fixtures
We generate fixtures in GitLab CI, and store them in the package registry.
The `scripts/frontend/download_fixtures.sh` script is meant to download and extract those fixtures for local use:
```shell
# Checks if a frontend fixture package exists in the gitlab-org/gitlab
# package registry by looking at the commits on a local branch.
#
# The package is downloaded and extracted if it exists
$ scripts/frontend/download_fixtures.sh
# Same as above, but only looks at the last 10 commits of the currently checked-out branch
$ scripts/frontend/download_fixtures.sh --max-commits=10
# Looks at the commits on the local master branch instead of the currently checked-out branch
$ scripts/frontend/download_fixtures.sh --branch master
```
#### Creating new fixtures
For each fixture, you can find the content of the `response` variable in the output file.
For example, a test named `"merge_requests/diff_discussion.json"` in `spec/frontend/fixtures/merge_requests.rb`
produces an output file `tmp/tests/frontend/fixtures-ee/merge_requests/diff_discussion.json`.
The `response` variable gets automatically set if the test is marked as `type: :request` or `type: :controller`.
When creating a new fixture, it often makes sense to take a look at the corresponding tests for the
endpoint in `(ee/)spec/controllers/` or `(ee/)spec/requests/`.
##### GraphQL query fixtures
You can create a fixture that represents the result of a GraphQL query using the `get_graphql_query_as_string`
helper method. For example:
```ruby
# spec/frontend/fixtures/releases.rb
describe GraphQL::Query, type: :request do
include GraphqlHelpers
all_releases_query_path = 'releases/graphql/queries/all_releases.query.graphql'
it "graphql/#{all_releases_query_path}.json" do
query = get_graphql_query_as_string(all_releases_query_path)
post_graphql(query, current_user: admin, variables: { fullPath: project.full_path })
expect_graphql_errors_to_be_empty
end
end
```
This will create a new fixture located at
`tmp/tests/frontend/fixtures-ee/graphql/releases/graphql/queries/all_releases.query.graphql.json`.
You can import the JSON fixture in a Jest test using the `test_fixtures` alias
[as described previously](#use-fixtures).
## Data-driven tests
Similar to [RSpec's parameterized tests](best_practices.md#table-based--parameterized-tests),
Jest supports data-driven tests for:
- Individual tests using [`test.each`](https://jestjs.io/docs/api#testeachtable-name-fn-timeout) (aliased to `it.each`).
- Groups of tests using [`describe.each`](https://jestjs.io/docs/api#describeeachtable-name-fn-timeout).
These can be useful for reducing repetition within tests. Each option can take an array of
data values or a tagged template literal.
For example:
```javascript
// function to test
const icon = status => status ? 'pipeline-passed' : 'pipeline-failed'
const message = status => status ? 'pipeline-passed' : 'pipeline-failed'
// test with array block
it.each([
[false, 'pipeline-failed'],
[true, 'pipeline-passed']
])('icon with %s will return %s',
(status, icon) => {
expect(renderPipeline(status)).toEqual(icon)
}
);
```
{{< alert type="note" >}}
Only use template literal block if pretty print is not needed for spec output. For example, empty strings, nested objects etc.
{{< /alert >}}
For example, when testing the difference between an empty search string and a non-empty search string, the use of the array block syntax with the pretty print option would be preferred. That way the differences between an empty string (`''`) and a non-empty string (`'search string'`) would be visible in the spec output. Whereas with a template literal block, the empty string would be shown as a space, which could lead to a confusing developer experience.
```javascript
// bad
it.each`
searchTerm | expected
${''} | ${{ issue: { users: { nodes: [] } } }}
${'search term'} | ${{ issue: { other: { nested: [] } } }}
`('when search term is $searchTerm, it returns $expected', ({ searchTerm, expected }) => {
expect(search(searchTerm)).toEqual(expected)
});
// good
it.each([
['', { issue: { users: { nodes: [] } } }],
['search term', { issue: { other: { nested: [] } } }],
])('when search term is %p, expect to return %p',
(searchTerm, expected) => {
expect(search(searchTerm)).toEqual(expected)
}
);
```
```javascript
// test suite with tagged template literal block
describe.each`
status | icon | message
${false} | ${'pipeline-failed'} | ${'Pipeline failed - boo-urns'}
${true} | ${'pipeline-passed'} | ${'Pipeline succeeded - win!'}
`('pipeline component', ({ status, icon, message }) => {
it(`returns icon ${icon} with status ${status}`, () => {
expect(icon(status)).toEqual(message)
})
it(`returns message ${message} with status ${status}`, () => {
expect(message(status)).toEqual(message)
})
});
```
## Gotchas
### RSpec errors due to JavaScript
By default RSpec unit tests don't run JavaScript in the headless browser
and rely on inspecting the HTML generated by rails.
If an integration test depends on JavaScript to run correctly, you need to make
sure the spec is configured to enable JavaScript when the tests are run. If you
don't do this, the spec runner displays vague error messages.
To enable a JavaScript driver in an `RSpec` test, add `:js` to the
individual spec or the context block containing multiple specs that need
JavaScript enabled:
```ruby
# For one spec
it 'presents information about abuse report', :js do
# assertions...
end
describe "Admin::AbuseReports", :js do
it 'presents information about abuse report' do
# assertions...
end
it 'shows buttons for adding to abuse report' do
# assertions...
end
end
```
### Jest test timeout due to asynchronous imports
If a module asynchronously imports some other modules at runtime, these modules must be
transpiled by the Jest loaders at runtime. It's possible that this can cause [Jest to timeout](https://gitlab.com/gitlab-org/gitlab/-/issues/280809).
If you run into this issue, consider eager importing the module so that Jest compiles
and caches it at compile-time, fixing the runtime timeout.
Consider the following example:
```javascript
// the_subject.js
export default {
components: {
// Async import Thing because it is large and isn't always needed.
Thing: () => import(/* webpackChunkName: 'thing' */ './path/to/thing.vue'),
}
};
```
Jest doesn't automatically transpile the `thing.vue` module, and depending on its size, could
cause Jest to time out. We can force Jest to transpile and cache this module by eagerly importing
it like so:
```javascript
// the_subject_spec.js
import Subject from '~/feature/the_subject.vue';
// Force Jest to transpile and cache
// eslint-disable-next-line no-unused-vars
import _Thing from '~/feature/path/to/thing.vue';
```
{{< alert type="note" >}}
Do not disregard test timeouts. This could be a sign that there's
actually a production problem. Use this opportunity to analyze the production webpack bundles and
chunks and confirm that there is not a production issue with the asynchronous imports.
{{< /alert >}}
## Overview of Frontend Testing Levels
Main information on frontend testing levels can be found in the [Testing Levels page](testing_levels.md).
Tests relevant for frontend development can be found at the following places:
- `spec/frontend/`, for Jest tests
- `spec/features/`, for RSpec tests
RSpec runs complete [feature tests](testing_levels.md#frontend-feature-tests), while the Jest directories contain [frontend unit tests](testing_levels.md#frontend-unit-tests), [frontend component tests](testing_levels.md#frontend-component-tests), and [frontend integration tests](testing_levels.md#frontend-integration-tests).
Before May 2018, `features/` also contained feature tests run by Spinach. These tests were removed from the codebase in May 2018 ([#23036](https://gitlab.com/gitlab-org/gitlab-foss/-/issues/23036)).
See also [Notes on testing Vue components](../fe_guide/vue.md#testing-vue-components).
## Test helpers
Test helpers can be found in [`spec/frontend/__helpers__`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/spec/frontend/__helpers__).
If you introduce new helpers, place them in that directory.
### Vuex Helper: `testAction`
We have a helper available to make testing actions easier, as per [official documentation](https://vuex.vuejs.org/guide/testing.html):
```javascript
// prefer using like this, a single object argument so parameters are obvious from reading the test
await testAction({
action: actions.actionName,
payload: { deleteListId: 1 },
state: { lists: [1, 2, 3] },
expectedMutations: [ { type: types.MUTATION} ],
expectedActions: [],
});
// old way, don't do this for new tests
testAction(
actions.actionName, // action
{ }, // params to be passed to action
state, // state
[
{ type: types.MUTATION},
{ type: types.MUTATION_1, payload: {}},
], // mutations committed
[
{ type: 'actionName', payload: {}},
{ type: 'actionName1', payload: {}},
] // actions dispatched
done,
);
```
### Wait until Axios requests finish
<!-- vale gitlab_base.Spelling = NO -->
The Axios Utils mock module located in `spec/frontend/__helpers__/mocks/axios_utils.js` contains two helper methods for Jest tests that spawn HTTP requests.
These are very useful if you don't have a handle to the request's Promise, for example when a Vue component does a request as part of its lifecycle.
<!-- vale gitlab_base.Spelling = YES -->
- `waitFor(url, callback)`: Runs `callback` after a request to `url` finishes (either successfully or unsuccessfully).
- `waitForAll(callback)`: Runs `callback` once all pending requests have finished. If no requests are pending, runs `callback` on the next tick.
Both functions run `callback` on the next tick after the requests finish (using `setImmediate()`), to allow any `.then()` or `.catch()` handlers to run.
### `shallowMountExtended` and `mountExtended`
The `shallowMountExtended` and `mountExtended` utilities provide you with the ability to perform
any of the available [DOM Testing Library queries](https://testing-library.com/docs/queries/about/)
by prefixing them with `find` or `findAll`.
```javascript
import { shallowMountExtended } from 'helpers/vue_test_utils_helper';
describe('FooComponent', () => {
const wrapper = shallowMountExtended({
template: `
<div data-testid="gitlab-frontend-stack">
<p>GitLab frontend stack</p>
<div role="tablist">
<button role="tab" aria-selected="true">Vue.js</button>
<button role="tab" aria-selected="false">GraphQL</button>
<button role="tab" aria-selected="false">SCSS</button>
</div>
</div>
`,
});
it('finds elements with `findByTestId`', () => {
expect(wrapper.findByTestId('gitlab-frontend-stack').exists()).toBe(true);
});
it('finds elements with `findByText`', () => {
expect(wrapper.findByText('GitLab frontend stack').exists()).toBe(true);
expect(wrapper.findByText('TypeScript').exists()).toBe(false);
});
it('finds elements with `findAllByRole`', () => {
expect(wrapper.findAllByRole('tab').length).toBe(3);
});
});
```
Check an example in [`spec/frontend/alert_management/components/alert_details_spec.js`](https://gitlab.com/gitlab-org/gitlab/-/blob/ac1c9fa4c5b3b45f9566147b1c88fd1339cd7c25/spec/frontend/alert_management/components/alert_details_spec.js#L32).
## Testing with older browsers
Some regressions only affect a specific browser version. We can install and test in particular browsers with either Firefox or BrowserStack using the following steps:
### BrowserStack
[BrowserStack](https://www.browserstack.com/) allows you to test more than 1200 mobile devices and browsers.
You can use it directly through the [live app](https://www.browserstack.com/live) or you can install the [chrome extension](https://chromewebstore.google.com/detail/browserstack/nkihdmlheodkdfojglpcjjmioefjahjb) for easy access.
Sign in to BrowserStack with the credentials saved in the **Engineering** vault of the GitLab
[shared 1Password account](https://handbook.gitlab.com/handbook/security/password-guidelines/#1password-for-teams).
### Firefox
#### macOS
You can download any older version of Firefox from the releases FTP server, <https://ftp.mozilla.org/pub/firefox/releases/>:
1. From the website, select a version, in this case `50.0.1`.
1. Go to the mac folder.
1. Select your preferred language. The DMG package is inside. Download it.
1. Drag and drop the application to any other folder but the `Applications` folder.
1. Rename the application to something like `Firefox_Old`.
1. Move the application to the `Applications` folder.
1. Open up a terminal and run `/Applications/Firefox_Old.app/Contents/MacOS/firefox-bin -profilemanager` to create a new profile specific to that Firefox version.
1. Once the profile has been created, quit the app, and run it again like usual. You now have a working older Firefox version.
## Snapshots
[Jest snapshot tests](https://jestjs.io/docs/snapshot-testing) are a useful way to prevent unexpected changes to the HTML output of a given component. They should **only** be used when other testing methods (such as asserting elements with `vue-tests-utils`) do not cover the required use case. To use them within GitLab, there are a few guidelines that should be highlighted:
- Treat snapshots as code
- Don't think of a snapshot file as a black box
- Care for the output of the snapshot, otherwise, it's not providing any real value. This will usually involve reading the generated snapshot file as you would read any other piece of code
Think of a snapshot test as a simple way to store a raw `String` representation of what you've put into the item being tested. This can be used to evaluate changes in a component, a store, a complex piece of generated output, etc. You can see more in the list below for some recommended `Do's and Don'ts`.
While snapshot tests can be a very powerful tool, they are meant to supplement, not to replace unit tests.
Jest provides a great set of docs on [best practices](https://jestjs.io/docs/snapshot-testing#best-practices) that we should keep in mind when creating snapshots.
### How does a snapshot work?
A snapshot is purely a stringified version of what you ask to be tested on the left-hand side of the function call. This means any kind of changes you make to the formatting of the string has an impact on the outcome. This process is done by leveraging serializers for an automatic transform step. For Vue this is already taken care of by leveraging the `vue-jest` package, which offers the proper serializer.
Should the outcome of your spec be different from what is in the generated snapshot file, you'll be notified about it by a failing test in your test suite.
Find all the details in Jests official documentation [https://jestjs.io/docs/snapshot-testing](https://jestjs.io/docs/snapshot-testing)
### Pros and Cons
**Pros**
- Provides a good warning against accidental changes of important HTML structures
- Ease of setup
**Cons**
- Lacks the clarity or guard rails that `vue-tests-utils` provides by finding elements and asserting their presence directly
- Creates unnecessary noise when updating components purposefully
- High risk of taking a snapshot of bugs, which then turns the tests against us since the test will now fail when fixing the issue
- No meaningful assertions or expectations within snapshots makes them harder to reason about or replace
- When used with dependencies like [GitLab UI](https://gitlab.com/gitlab-org/gitlab-ui), it creates fragility in tests when the underlying library changes the HTML of a component we are testing
### When to use
**Use snapshots when**
- Protecting critical HTML structures so it doesn't change by accident
- Asserting JS object or JSON outputs of complex utility functions
### When not to use
**Don't use snapshots when**
- Tests could be written using `vue-tests-utils` instead
- Asserting the logic of a component
- Predicting data structure(s) outputs
- There are UI elements outside of the repository (think of GitLab UI version updates)
### Examples
As you can see, the cons of snapshot tests far outweigh the pros in general. To illustrate this better, this section will show a few examples of when you might be tempted to
use snapshot testing and why they are not good patterns.
#### Example #1 - Element visibility
When testing elements visibility, favour using `vue-tests-utils (VTU)` to find a given component and then a basic `.exists()` method call on the VTU wrapper. This provides better readability and more resilient testing. If you look at the examples below, notice how the assertions on the snapshots do not tell you what you are expecting to see. We are relying entirely on `it` description to give us context and on the assumption that the snapshot has captured the desired behavior.
```vue
<template>
<my-component v-if="isVisible" />
</template>
```
Bad:
```javascript
it('hides the component', () => {
createComponent({ props: { isVisible: false }})
expect(wrapper.element).toMatchSnapshot()
})
it('shows the component', () => {
createComponent({ props: { isVisible: true }})
expect(wrapper.element).toMatchSnapshot()
})
```
Good:
```javascript
it('hides the component', () => {
createComponent({ props: { isVisible: false }})
expect(findMyComponent().exists()).toBe(false)
})
it('shows the component', () => {
createComponent({ props: { isVisible: true }})
expect(findMyComponent().exists()).toBe(true)
})
```
Not only that, but imagine having passed the wrong prop to your component and having the wrong visibility: the snapshot test would still pass because you would have captured the HTML **with the issue** and so unless you double-checked the output of the snapshot, you would never know that your test is broken.
#### Example #2 - Presence of text
Finding text within a component is very easy by using the `vue-test-utils` method `wrapper.text()`. However, there are some cases where it might be tempting to use snapshots when the value returned has a lot of inconsistent spacing due to formatting or HTML nesting.
In these instances, it is better to assert each string individually and make multiple assertions than to use a snapshot to ignore the spaces. This is because any change to the DOM layout will fail the snapshot test even if the text is still perfectly formatted.
```vue
<template>
<gl-sprintf :message="my-message">
<template #code="{ content }">
<code>{{ content }}</code>
</template>
</gl-sprintf>
<p> My second message </p>
</template>
```
Bad:
```javascript
it('renders the text as I expect', () => {
expect(wrapper.text()).toMatchSnapshot()
})
```
Good:
```javascript
it('renders the code snippet', () => {
expect(findCodeTag().text()).toContain("myFunction()")
})
it('renders the paragraph text', () => {
expect(findOtherText().text()).toBe("My second message")
})
```
#### Example #3 - Complex HTML
When we have very complex HTML, we should focus on asserting specific sensitive and meaningful points rather than capturing it as a whole. The value in a snapshot test is to **warn developers** that they might have accidentally change an HTML structure that they did not intend to change. If the output of the change is hard to read, which is often the case with complex HTML output, then **is the signal itself that something changed** sufficient? And if it is, can it be accomplished without snapshots?
A good example of a complex HTML output is `GlTable`. Snapshot testing might feel like a good option since you can capture rows and columns structure, but we should instead try to assert text we expect or count the number of rows and columns manually.
```vue
<template>
<gl-table ...all-them-props />
</template>
```
Bad:
```javascript
it('renders GlTable as I expect', () => {
expect(findGlTable().element).toMatchSnapshot()
})
```
Good:
```javascript
it('renders the right number of rows', () => {
expect(findGlTable().findAllRows()).toHaveLength(expectedLength)
})
it('renders the special icon that only appears on a full moon', () => {
expect(findGlTable().findMoonIcon().exists()).toBe(true)
})
it('renders the correct email format', () => {
expect(findGlTable().text()).toContain('my_strange_email@shaddyprovide.com')
})
```
Although more verbose, this now means that our tests are not going to break if `GlTable` changes its internal implementation, we communicate to other developers (or ourselves in 6 months) what is important to preserve when refactoring or adding to our table.
### How to take a snapshot
```javascript
it('makes the name look pretty', () => {
expect(prettifyName('Homer Simpson')).toMatchSnapshot()
})
```
When this test runs the first time a fresh `.snap` file will be created. It will look something like this:
```plaintext
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`makes the name look pretty`] = `
Sir Homer Simpson the Third
`
```
Now, every time you call this test, the new snapshot will be evaluated against the previously created version. This should highlight the fact that it's important to understand the content of your snapshot file and treat it with care. Snapshots will lose their value if the output of the snapshot is too big or complex to read, this means keeping snapshots isolated to human-readable items that can be either evaluated in a merge request review or are guaranteed to never change.
The same can be done for `wrappers` or `elements`
```javascript
it('renders the component correctly', () => {
expect(wrapper).toMatchSnapshot()
expect(wrapper.element).toMatchSnapshot();
})
```
The above test will create two snapshots. It's important to decide which of the snapshots provide more value for codebase safety. That is, if one of these snapshots changes, does that highlight a possible break in the codebase? This can help catch unexpected changes if something in an underlying dependency changes without our knowledge.
## Get started with feature tests
### What is a feature test
A [feature test](testing_levels.md#white-box-tests-at-the-system-level-formerly-known-as-system--feature-tests), also known as `white-box testing`, is a test that spawns a browser and has Capybara helpers. This means the test can:
- Locate an element in the browser.
- Click that element.
- Call the API.
Feature tests are expensive to run. You should make sure that you **really want** this type of test before running one.
All of our feature tests are written in `Ruby` but often end up being written by `JavaScript` engineers, as they implement the user-facing feature. So, the following section assumes no prior knowledge of `Ruby` or `Capybara`, and provide a clear guideline on when and how to use these tests.
### When to use feature tests
You should use a feature test when the test:
- Is across multiple components.
- Requires that a user navigate across pages.
- Is submitting a form and observing results elsewhere.
- Would result in a huge number of mocking and stubbing with fake data and components if done as a unit test.
Feature tests are especially useful when you want to test:
- That multiple components are working together successfully.
- Complex API interactions. Feature tests interact with the API, so they are slower but do not need any level of mocking or fixtures.
### When not to use feature tests
You should use `jest` and `vue-test-utils` unit tests instead of a feature test if you can get the same test results from these methods. Feature tests are quite expensive to run.
You should use a unit test if:
- The behavior you are implementing is all in one component.
- You can simulate other components' behavior to trigger the desired effect.
- You can already select UI elements in the virtual DOM to trigger the desired effects.
Also, if a behavior in your new code needs multiple components to work together, you should consider testing your behavior higher in the component tree. For example, consider a component called `ParentComponent` with the code:
```vue
<script>
export default{
name: ParentComponent,
data(){
return {
internalData: 'oldValue'
}
},
methods:{
changeSomeInternalData(newVal){
this.internalData = newVal
}
}
}
</script>
<template>
<div>
<child-component-1 @child-event="changeSomeInternalData" />
<child-component-2 :parent-data="internalData" />
</div>
</template>
```
In this example:
- `ChildComponent1` emits an event.
- `ParentComponent` changes its `internalData` value.
- `ParentComponent` passes the props down to `ChildComponent2`.
You can use a unit test instead by:
- From inside the `ParentComponent` unit test file, emitting the expected event from `childComponent1`
- Making sure the prop is passed down to `childComponent2`.
Then each child component unit tests what happens when the event is emitted and when the prop changes.
This example also applies at larger scale and with deeper component trees. It is definitely worth using unit tests and avoiding the extra cost of feature tests if you can:
- Confidently mount child components.
- Emit events or select elements in the virtual DOM.
- Get the test behavior that you want.
### Where to create your test
Feature tests live in `spec/features` folder. You should look for existing files that can test the page you are adding a feature to. Within that folder, you can locate your section. For example, if you wanted to add a new feature test for the pipeline page, you would look in `spec/features/projects/pipelines` and see if the test you want to write exists here.
### How to run a feature test
1. Make sure that you have a working GDK environment.
1. Start your `gdk` environment with `gdk start` command.
1. In your terminal, run:
```shell
bundle exec rspec path/to/file:line_of_my_test
```
You can also prefix this command with `WEBDRIVER_HEADLESS=0` which will run the test by opening an actual browser on your computer that you can see, which is very useful for debugging.
To use Firefox, instead of Chrome, prefix the command with `WEBDRIVER=firefox`.
### How to write a test
#### Basic file structure
1. Make all string literals unchangeable
In all feature tests, the very first line should be:
```ruby
# frozen_string_literal: true
```
This is in every `Ruby` file and makes all string literals unchangeable. There are also some performance benefits, but this is beyond the scope of this section.
1. Import dependencies.
You should import the modules you need. You will most likely always need to require `spec_helper`:
```ruby
require 'spec_helper'
```
Import any other relevant module.
1. Create a global scope for RSpec to define our tests, just like what we do in jest with the initial describe block.
Then, you need to create the very first `RSpec` scope.
```ruby
RSpec.describe 'Pipeline', :js do
...
end
```
What is different though, is that just like everything in Ruby, this is actually a `class`. Which means that right at the top, you can `include` modules that you'd need for your test. For example, you could include the `RoutesHelpers` to navigate more easily.
```ruby
RSpec.describe 'Pipeline', :js do
include RoutesHelpers
...
end
```
After all of this implementation, we have a file that looks something like this:
```ruby
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Pipeline', :js do
include RoutesHelpers
end
```
#### Seeding data
Each test is in its own environment and so you must use a factory to seed the required data. For example, to create a test that takes you to the main pipeline page at the route `/namespace/project/-/pipelines/:id/`.
Most feature tests at least require you to create a user, because you want to be signed in. You can skip this step if you don't have to be signed in, but as a general rule, you should **always create a user unless you are specifically testing a feature looked at by an anonymous user**. This makes sure that you explicitly set a level of permission that you can edit in the test as needed to change or test a new level of permission as the section changes. To create a user:
```ruby
let(:user) { create(:user) }
```
This creates a variable that holds the newly created user and we can use `create` because we imported the `spec_helper`.
However, we have not done anything with this user yet because it's just a variable. So, in the `before do` block of the spec, we could sign in with the user so that every spec starts with an authenticated user.
```ruby
let(:user) { create(:user) }
before do
sign_in(user)
end
```
Now that we have a user, we should look at what else we'd need before asserting anything on a pipeline page. If you look at the route `/namespace/project/-/pipelines/:id/` we can determine we need a project and a pipeline.
So we'd create a project and pipeline, and link them together. Usually in factories, the child element requires its parent as an argument. In this case, a pipeline is a child of a project. So we can create the project first, and then when we create the pipeline, we are pass the project as an argument which "binds" the pipeline to the project. A pipeline is also owned by a user, so we need the user as well. For example, this creates a project and a pipeline:
```ruby
let(:user) { create(:user) }
let(:project) { create(:project, :repository) }
let(:pipeline) { create(:ci_pipeline, project: project, ref: 'master', sha: project.commit.id, user: user) }
```
In the same spirit, you could then create a job (build) by using the build factory and passing the parent pipeline:
```ruby
create(:ci_build, pipeline: pipeline, stage_idx: 10, stage: 'publish', name: 'CentOS')
```
There are many factories that already exists, so make sure to look at other existing files to see if what you need is available.
#### Navigation
You can go to a page by using the `visit` method and passing the path as an argument. Rails automatically generates helper paths, so make sure to use these instead of a hardcoded string. They are generated using the route model, so if we want to go to a pipeline, we'd use:
```ruby
visit project_pipeline_path(project, pipeline)
```
Before executing any page interaction when navigating or making asynchronous call through the UI, make sure to use `wait_for_requests` before proceeding with further instructions.
#### Elements interaction
There are a lot of different ways to find and interact with elements.
For best practises, refer to the [UI testing](best_practices.md#ui-testing) section.
To click a button, use `click_button` with the string of text found in the button:
```ruby
click_button 'Text inside the button element'
```
If you want to follow a link, then there is `click_link`:
```ruby
click_link 'Text inside the link tag'
```
You can use `fill_in` to fill input / form elements. The first argument is the selector, the second is `with:` which is the value to pass in.
```ruby
fill_in 'current_password', with: '123devops'
```
Alternatively, you can use the `find` selector paired with `send_keys` to add keys in a field without removing previous text, or `set` which completely replaces the value of the input element.
You can find a more comprehensive list of actions in the [feature tests actions](best_practices.md#actions) documentation.
#### Assertions
To assert anything in a page, you can always access `page` variable, which is automatically defines and actually means the page document. This means you can expect the `page` to have certain components like selectors or content. Here are a few examples:
```ruby
# Finding a button
expect(page).to have_button('Submit review')
```
```ruby
# Finding by text
expect(page).to have_text('build')
```
```ruby
# Finding by `href` value
expect(page).to have_link(pipeline.ref)
```
```ruby
# Find by data-testid
# Like CSS selector, this is acceptable when there isn't a specific matcher available.
expect(page).to have_css('[data-testid="pipeline-multi-actions-dropdown"]')
```
```ruby
# Finding by CSS selector. This is a last resort.
# For example, when you cannot add attributes on the desired element.
expect(page).to have_css('.js-icon-retry')
```
```ruby
# You can combine any of these selectors with `not_to` instead
expect(page).not_to have_button('Submit review')
```
```ruby
# When a test case has back to back expectations,
# it is recommended to group them using `:aggregate_failures`
it 'shows the issue description and design references', :aggregate_failures do
expect(page).to have_text('The designs I mentioned')
expect(page).to have_link(design_tab_ref)
expect(page).to have_link(design_ref_a)
expect(page).to have_link(design_ref_b)
end
```
You can also create a sub-block to look into, to:
- Scope down where you are making your assertions and reduce the risk of finding another element that was not intended.
- Make sure an element is found within the right boundaries.
```ruby
page.within('[data-testid="pipeline-multi-actions-dropdown"]') do
...
end
```
You can find a more comprehensive list of matchers in the [feature tests matchers](best_practices.md#matchers) documentation.
#### Feature flags
By default, every feature flag is enabled **regardless of the YAML definition or the flags you've set manually in your GDK**. To test when a feature flag is disabled, you must manually stub the flag, ideally in a `before do` block.
```ruby
stub_feature_flags(my_feature_flag: false)
```
If you are stubbing an `ee` feature flag, then use:
```ruby
stub_licensed_features(my_feature_flag: false)
```
#### Asserting browser console errors
By default, feature specs won't fail if a browser console error is found. Sometimes we want to cover that there are not
unexpected console errors which could indicate an integration problem.
To set a feature spec to fail if it encounters browser console errors, use `expect_page_to_have_no_console_errors` from
the `BrowserConsoleHelpers` support module:
```ruby
RSpec.describe 'Pipeline', :js do
after do
expect_page_to_have_no_console_errors
end
# ...
end
```
{{< alert type="note" >}}
`expect_page_to_have_no_console_errors` will not work on `WEBDRIVER=firefox`. Logs are only captured when
using the Chrome driver.
{{< /alert >}}
Sometimes, there are known console errors that we want to ignore. To ignore a set of messages, such that the test
**will not** fail if the message is observed, you can pass an `allow:` parameter to
`expect_page_to_have_no_console_errors`:
```ruby
RSpec.describe 'Pipeline', :js do
after do
expect_page_to_have_no_console_errors(allow: [
"Blow up!",
/Foo.*happens/
])
end
# ...
end
```
Update the `BROWSER_CONSOLE_ERROR_FILTER` constant in `spec/support/helpers/browser_console_helpers.rb` to change
the list of console errors that should be globally ignored.
### Debugging
You can run your spec with the prefix `WEBDRIVER_HEADLESS=0` to open an actual browser. However, the specs goes though the commands quickly and leaves you no time to look around.
To avoid this problem, you can write `binding.pry` on the line where you want Capybara to stop execution. You are then inside the browser with standard usage. To understand why you cannot find certain elements, you can:
- Select elements.
- Use the console and network tab.
- Execute selectors inside the browser console.
Inside the terminal, where capybara is running, you can also execute `next` which goes line by line through the test. This way you can check every single interaction one by one to see what might be causing an issue.
### Improving execution time on the GDK
Running the Jest test suite, the number of workers is set to use 60% of the available cores of your machine; this results in faster execution times but higher memory consumption. For more benchmarks on how this works, see [issue 456885](https://gitlab.com/gitlab-org/gitlab/-/issues/456885).
### Updating ChromeDriver
Starting from `Selenium` 4.6, ChromeDriver can be automatically managed by `Selenium Manager` which comes with the `selenium-webdriver` gem.
You are no longer required to manually keeping chromedriver in sync.
---
[Return to Testing documentation](_index.md)
|
---
stage: none
group: unassigned
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: Frontend testing standards and style guidelines
breadcrumbs:
- doc
- development
- testing_guide
---
There are two types of test suites encountered while developing frontend code
at GitLab. We use Jest for JavaScript unit and integration testing,
and RSpec feature tests with Capybara for e2e (end-to-end) integration testing.
Unit and feature tests need to be written for all new features.
Most of the time, you should use [RSpec](https://github.com/rspec/rspec-rails#feature-specs) for your feature tests. For more information on how to get started with feature tests, see [get started with feature tests](#get-started-with-feature-tests)
Regression tests should be written for bug fixes to prevent them from recurring
in the future.
See the [Testing Standards and Style Guidelines](_index.md) page for more
information on general testing practices at GitLab.
## Vue.js testing
If you are looking for a guide on Vue component testing, you can jump right away to this [section](../fe_guide/vue.md#testing-vue-components).
Information on testing Vue 3 is contained in [this page](testing_vue3.md).
## Jest
We use Jest to write frontend unit and integration tests.
Jest tests can be found in `/spec/frontend` and `/ee/spec/frontend` in EE.
### `jsdom`
Jest uses `jsdom` instead of a browser for running tests.
Known issues include:
- [No scrolling support](https://github.com/jsdom/jsdom/blob/15.1.1/lib/jsdom/browser/Window.js#L623-L625)
- [No element sizes or positions](https://github.com/jsdom/jsdom/blob/15.1.1/lib/jsdom/living/nodes/Element-impl.js#L334-L371)
- [No layout engine](https://github.com/jsdom/jsdom/issues/1322) in general
See also the issue for [support running Jest tests in browsers](https://gitlab.com/gitlab-org/gitlab/-/issues/26982).
### Debugging Jest tests
Running `yarn jest-debug` runs Jest in debug mode, allowing you to debug/inspect as described in the [Jest documentation](https://jestjs.io/docs/troubleshooting#tests-are-failing-and-you-don-t-know-why).
### Timeout error
The default timeout for Jest is set in
[`/jest.config.base.js`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/jest.config.base.js).
If your test exceeds that time, it fails.
If you cannot improve the performance of the tests, you can increase the timeout
for the whole suite using [`jest.setTimeout`](https://jestjs.io/docs/next/jest-object#jestsettimeouttimeout)
```javascript
jest.setTimeout(500);
describe('Component', () => {
it('does something amazing', () => {
// ...
});
});
```
or for a specific test by providing a third argument to [`it`](https://jestjs.io/docs/next/api#testname-fn-timeout)
```javascript
describe('Component', () => {
it('does something amazing', () => {
// ...
}, 500)
})
```
Remember that the performance of each test depends on the environment.
### Test-specific stylesheets
To help facilitate RSpec integration tests we have two test-specific stylesheets. These can be used to do things like disable animations to improve test speed, or to make elements visible when they need to be targeted by Capybara click events:
- `app/assets/stylesheets/disable_animations.scss`
- `app/assets/stylesheets/test_environment.scss`
Because the test environment should match the production environment as much as possible, use these minimally and only add to them when necessary.
## What and how to test
Before jumping into more gritty details about Jest-specific workflows like mocks and spies, we should briefly cover what to test with Jest.
### Don't test the library
Libraries are an integral part of any JavaScript developer's life. The general advice would be to not test library internals, but expect that the library knows what it's supposed to do and has test coverage on its own.
A general example could be something like this
```javascript
import { convertToFahrenheit } from 'temperatureLibrary'
function getFahrenheit(celsius) {
return convertToFahrenheit(celsius)
}
```
It does not make sense to test our `getFahrenheit` function because underneath it does nothing else but invoking the library function, and we can expect that one is working as intended.
Let's take a short look into Vue land. Vue is a critical part of the GitLab JavaScript codebase. When writing specs for Vue components, a common gotcha is to actually end up testing Vue provided functionality, because it appears to be the easiest thing to test. Here's an example taken from our codebase.
```javascript
// Component script
{
computed: {
hasMetricTypes() {
return this.metricTypes.length;
},
}
```
```html
<!-- Component template -->
<template>
<gl-dropdown v-if="hasMetricTypes">
<!-- Dropdown content -->
</gl-dropdown>
</template>
```
Testing the `hasMetricTypes` computed prop would seem like a given here. But to test if the computed property is returning the length of `metricTypes`, is testing the Vue library itself. There is no value in this, besides it adding to the test suite. It's better to test a component in the way the user interacts with it: checking the rendered template.
```javascript
// Bad
describe('computed', () => {
describe('hasMetricTypes', () => {
it('returns true if metricTypes exist', () => {
factory({ metricTypes });
expect(wrapper.vm.hasMetricTypes).toBe(2);
});
it('returns true if no metricTypes exist', () => {
factory();
expect(wrapper.vm.hasMetricTypes).toBe(0);
});
});
});
// Good
it('displays a dropdown if metricTypes exist', () => {
factory({ metricTypes });
expect(wrapper.findComponent(GlDropdown).exists()).toBe(true);
});
it('does not display a dropdown if no metricTypes exist', () => {
factory();
expect(wrapper.findComponent(GlDropdown).exists()).toBe(false);
});
```
Keep an eye out for these kinds of tests, as they just make updating logic more fragile and tedious than it needs to be. This is also true for other libraries. A suggestion here is: if you are checking a `wrapper.vm` property, you should probably stop and rethink the test to check the rendered template instead.
Some more examples can be found in the [Frontend unit tests section](testing_levels.md#frontend-unit-tests)
### Don't test your mock
Another common gotcha is that the specs end up verifying the mock is working. If you are using mocks, the mock should support the test, but not be the target of the test.
```javascript
const spy = jest.spyOn(idGenerator, 'create')
spy.mockImplementation = () = '1234'
// Bad
expect(idGenerator.create()).toBe('1234')
// Good: actually focusing on the logic of your component and just leverage the controllable mocks output
expect(wrapper.find('div').html()).toBe('<div id="1234">...</div>')
```
### Don't use imported values in assertions
Prefer literal values in assertions rather than importing constants. This makes tests easier to read, and resilient to changes. This is discussed further in [internationalization recommendations](../i18n/externalization.md#recommendations).
```javascript
// Bad: MY_CONSTANT could accidentally be set to undefined, have a typo etc. and test would still pass
import { MY_CONSTANT } from '../constants';
it('returns the correct value', () => {
expect(ding()).toBe(MY_CONSTANT);
});
// Good: explicit value is asserted
it('returns the correct value', () => {
expect(ding()).toBe('expected literal value');
});
```
### Follow the user
The line between unit and integration tests can be quite blurry in a component heavy world. The most important guideline to give is the following:
- Write clean unit tests if there is actual value in testing a complex piece of logic in isolation to prevent it from breaking in the future
- Otherwise, try to write your specs as close to the user's flow as possible
For example, it's better to use the generated markup to trigger a button click and validate the markup changed accordingly than to call a method manually and verify data structures or computed properties. There's always the chance of accidentally breaking the user flow, while the tests pass and provide a false sense of security.
## Common practices
These some general common practices included as part of our test suite. Should you stumble over something not following this guide, ideally fix it right away. 🎉
### How to query DOM elements
When it comes to querying DOM elements in your tests, it is best to uniquely and semantically target
the element.
Preferentially, this is done by targeting what the user actually sees using [DOM Testing Library](https://testing-library.com/docs/dom-testing-library/intro/).
When selecting by text it is best to use the [`byRole`](https://testing-library.com/docs/queries/byrole/) query
as it helps enforce accessibility best practices. `findByRole` and the other [DOM Testing Library queries](https://testing-library.com/docs/queries/about/) are available when using [`shallowMountExtended` or `mountExtended`](#shallowmountextended-and-mountextended).
When writing Vue component unit tests, it can be wise to query children by component, so that the unit test can focus on comprehensive value coverage
rather than dealing with the complexity of a child component's behavior.
Sometimes, neither of the above are feasible. In these cases, adding test attributes to simplify the selectors might be the best option. A list of
possible selectors include:
- A semantic attribute like `name` (also verifies that `name` was setup properly)
- A `data-testid` attribute ([recommended by maintainers of `@vue/test-utils`](https://github.com/vuejs/vue-test-utils/issues/1498#issuecomment-610133465))
optionally combined with [`shallowMountExtended` or `mountExtended`](#shallowmountextended-and-mountextended)
```javascript
import { shallowMountExtended } from 'helpers/vue_test_utils_helper'
const wrapper = shallowMountExtended(ExampleComponent);
it('exists', () => {
// Best (especially for integration tests)
wrapper.findByRole('link', { name: /Click Me/i })
wrapper.findByRole('link', { name: 'Click Me' })
wrapper.findByText('Click Me')
wrapper.findByText(/Click Me/i)
// Good (especially for unit tests)
wrapper.findComponent(FooComponent);
wrapper.find('input[name=foo]');
wrapper.find('[data-testid="my-foo-id"]');
wrapper.findByTestId('my-foo-id'); // with shallowMountExtended or mountExtended, check below
// Bad
wrapper.find({ ref: 'foo'});
wrapper.find('.js-foo');
wrapper.find('.gl-button');
});
```
You should use `kebab-case` for `data-testid` attribute.
It is not recommended that you add `.js-*` classes just for testing purposes. Only do this if there are no other feasible options available.
Avoid using Vue template refs to query DOM elements in tests because they're an implementation detail of the component, not a public API.
### Querying for child components
When testing Vue components with `@vue/test-utils` another possible approach is querying for child
components instead of querying for DOM nodes. This assumes that implementation details of behavior
under test should be covered by that component's individual unit test. There is no strong preference
in writing DOM or component queries as long as your tests reliably cover expected behavior for the
component under test.
Example:
```javascript
it('exists', () => {
wrapper.findComponent(FooComponent);
});
```
### Naming unit/component tests
Unit/Component tests should be named `${componentName}_spec.js`
If the test name is not specific enough, consider renaming the component.
For Example:
`diff_stats_dropdown.vue` should have a unit/component test named `diff_stats_dropdown_spec.js`
### Describe block naming
When writing describe test blocks to test specific functions/methods,
use the method name as the describe block name.
**Bad**:
```javascript
describe('#methodName', () => {
it('passes', () => {
expect(true).toEqual(true);
});
});
describe('.methodName', () => {
it('passes', () => {
expect(true).toEqual(true);
});
});
```
**Good**:
```javascript
describe('methodName', () => {
it('passes', () => {
expect(true).toEqual(true);
});
});
```
### Testing promises
When testing Promises you should always make sure that the test is asynchronous and rejections are handled. It's now possible to use the `async/await` syntax in the test suite:
```javascript
it('tests a promise', async () => {
const users = await fetchUsers()
expect(users.length).toBe(42)
});
it('tests a promise rejection', async () => {
await expect(user.getUserName(1)).rejects.toThrow('User with 1 not found.');
});
```
You can also return a promise from the test function.
Using the `done` and `done.fail` callbacks is discouraged when working with
promises. They should not be used.
**Bad**:
```javascript
// missing return
it('tests a promise', () => {
promise.then(data => {
expect(data).toBe(asExpected);
});
});
// uses done/done.fail
it('tests a promise', done => {
promise
.then(data => {
expect(data).toBe(asExpected);
})
.then(done)
.catch(done.fail);
});
```
**Good**:
```javascript
// verifying a resolved promise
it('tests a promise', () => {
return promise
.then(data => {
expect(data).toBe(asExpected);
});
});
// verifying a resolved promise using Jest's `resolves` matcher
it('tests a promise', () => {
return expect(promise).resolves.toBe(asExpected);
});
// verifying a rejected promise using Jest's `rejects` matcher
it('tests a promise rejection', () => {
return expect(promise).rejects.toThrow(expectedError);
});
```
### Manipulating Time
Sometimes we have to test time-sensitive code. For example, recurring events that run every X amount of seconds or similar. Here are some strategies to deal with that:
#### `setTimeout()` / `setInterval()` in application
If the application itself is waiting for some time, mock await the waiting. In Jest this is already
[done by default](https://gitlab.com/gitlab-org/gitlab/-/blob/a2128edfee799e49a8732bfa235e2c5e14949c68/jest.config.js#L47)
(see also [Jest Timer Mocks](https://jestjs.io/docs/timer-mocks)).
```javascript
const doSomethingLater = () => {
setTimeout(() => {
// do something
}, 4000);
};
```
**In Jest**:
```javascript
it('does something', () => {
doSomethingLater();
jest.runAllTimers();
expect(something).toBe('done');
});
```
### Mocking the current location in Jest
{{< alert type="note" >}}
The value of `window.location.href` is reset before every test to avoid earlier
tests affecting later ones.
{{< /alert >}}
If your tests require `window.location.href` to take a particular value, use
the `setWindowLocation` helper:
```javascript
import setWindowLocation from 'helpers/set_window_location_helper';
it('passes', () => {
setWindowLocation('https://gitlab.test/foo?bar=true');
expect(window.location).toMatchObject({
hostname: 'gitlab.test',
pathname: '/foo',
search: '?bar=true',
});
});
```
To modify only the hash, use either the `setWindowLocation` helper, or assign
directly to `window.location.hash`, for example:
```javascript
it('passes', () => {
window.location.hash = '#foo';
expect(window.location.href).toBe('http://test.host/#foo');
});
```
If your tests need to assert that certain `window.location` methods were
called, use the `useMockLocationHelper` helper:
```javascript
import { useMockLocationHelper } from 'helpers/mock_window_location_helper';
useMockLocationHelper();
it('passes', () => {
window.location.reload();
expect(window.location.reload).toHaveBeenCalled();
});
```
### Testing clean-up of event listeners and timeouts
Often times in components we create event listeners or timeouts on the `beforeDestroy` (`beforeUnmount` for Vue 3) hooks. It is important to test that both listeners and timeouts are cleared when the component instance is destroyed, as forgetting to clean up these events can cause problems like memory leaks and broken references on event listeners.
Consider the following example:
```javascript
beforeDestroy() {
removeEventListener('keydown', someListener)
clearTimeout(timeoutPointer)
}
```
In the above example, a component is both clearing a `keydown` event listener and a timeout that was created elsewhere.
Let's take a look at the relevant tests.
```javascript
describe('Cleanup before destroy', () => {
beforeEach(() => {
createComponent()
// Destroy the component immediately to invoke the `beforeDestroy` hook
wrapper.destroy()
})
it('removes the event listener', () => {
const spy = jest.spyOn(window, 'removeEventListener')
expect(spy).toHaveBeenCalledTimes(1)
expect(spy).toHaveBeenCalledWith('keydown', expect.any(Function))
})
it('clears the pending timeouts', () => {
const spy = jest.spyOn(window, 'clearTimeout')
expect(spy).toHaveBeenCalledTimes(1)
})
})
```
The above example does not explicitly check for the function that is called on the `keydown` listener as it will usually be an implementation detail. The same happens with the `clearTimeout` call, as the parameter will be a pointer to a timer created internally in the component.
Due to this, it is usually sufficient to check that the spies have been called, with the recommended addition of checking the _times_ that they have been called.
### Waiting in tests
Sometimes a test needs to wait for something to happen in the application before it continues.
You should try to avoid:
- [`setTimeout`](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout) because it makes the reason for waiting unclear. Additionally, it is faked in our tests so its usage is tricky.
- [`setImmediate`](https://developer.mozilla.org/en-US/docs/Web/API/Window/setImmediate) because it is no longer supported in Jest 27 and later. See [this epic](https://gitlab.com/groups/gitlab-org/-/epics/7002) for details.
#### Promises and Ajax calls
Register handler functions to wait for the `Promise` to be resolved.
```javascript
const askTheServer = () => {
return axios
.get('/endpoint')
.then(response => {
// do something
})
.catch(error => {
// do something else
});
};
```
**In Jest**:
```javascript
it('waits for an Ajax call', async () => {
await askTheServer()
expect(something).toBe('done');
});
```
If you cannot register handlers to the `Promise`, for example because it is executed in a synchronous Vue lifecycle hook, take a look at the [`waitFor`](#wait-until-axios-requests-finish) helpers or flush all pending `Promise`s with:
**In Jest**:
```javascript
it('waits for an Ajax call', async () => {
synchronousFunction();
await waitForPromises();
expect(something).toBe('done');
});
```
#### Vue rendering
Use [`nextTick()`](https://v2.vuejs.org/v2/api/#Vue-nextTick) to wait until a Vue component is
re-rendered.
**In Jest**:
```javascript
import { nextTick } from 'vue';
// ...
it('renders something', async () => {
wrapper.setProps({ value: 'new value' });
await nextTick();
expect(wrapper.text()).toBe('new value');
});
```
#### Events
If the application triggers an event that you need to wait for in your test, register an event handler which contains
the assertions:
```javascript
it('waits for an event', () => {
eventHub.$once('someEvent', eventHandler);
someFunction();
return new Promise((resolve) => {
function expectEventHandler() {
expect(something).toBe('done');
resolve();
}
});
});
```
In Jest you can also use a `Promise` for this:
```javascript
it('waits for an event', () => {
const eventTriggered = new Promise(resolve => eventHub.$once('someEvent', resolve));
someFunction();
return eventTriggered.then(() => {
expect(something).toBe('done');
});
});
```
### Manipulate `gon` object
`gon` (or `window.gon`) is a global object used to pass data from the backend. If your test depends
on its value you can directly modify it:
```javascript
describe('when logged in', () => {
beforeEach(() => {
gon.current_user_id = 1;
});
it('shows message', () => {
expect(wrapper.text()).toBe('Logged in!');
});
})
```
`gon` is reset in every test to ensure tests are isolated.
### Ensuring that tests are isolated
Tests are typically architected in a pattern which requires a recurring setup of the component under test. This is often achieved by making use of the `beforeEach` hook.
Example
```javascript
let wrapper;
beforeEach(() => {
wrapper = mount(Component);
});
```
With [enableAutoDestroy](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/100389), it is no longer necessary to manually call `wrapper.destroy()`.
However, some mocks, spies, and fixtures do need to be torn down, and we can leverage the `afterEach` hook.
Example
```javascript
let wrapper;
afterEach(() => {
fakeApollo = null;
store = null;
});
```
### Testing local-only Apollo queries and mutations
To add a new query or mutation before it is added to the backend, we can use the `@client` directive. For example:
```graphql
mutation setActiveBoardItemEE($boardItem: LocalBoardItem, $isIssue: Boolean = true) {
setActiveBoardItem(boardItem: $boardItem) @client {
...Issue @include(if: $isIssue)
...EpicDetailed @skip(if: $isIssue)
}
}
```
When writing test cases for such calls, we can use resolvers to make sure they are called with the correct parameters.
For example, when creating the wrapper, we should make sure the resolver is mapped to the query or mutation.
The mutation we are mocking here is `setActiveBoardItem`:
```javascript
const mockSetActiveBoardItemResolver = jest.fn();
const mockApollo = createMockApollo([], {
Mutation: {
setActiveBoardItem: mockSetActiveBoardItemResolver,
},
});
```
In the following code, we must pass four arguments. The second one must be the collection of input variables of the query or mutation mocked.
To test that the mutation is called with the correct parameters:
```javascript
it('calls setActiveBoardItemMutation on close', async () => {
wrapper.findComponent(GlDrawer).vm.$emit('close');
await waitForPromises();
expect(mockSetActiveBoardItemResolver).toHaveBeenCalledWith(
{},
{
boardItem: null,
},
expect.anything(),
expect.anything(),
);
});
```
### Jest best practices
#### Prefer `toBe` over `toEqual` when comparing primitive values
Jest has [`toBe`](https://jestjs.io/docs/expect#tobevalue) and
[`toEqual`](https://jestjs.io/docs/expect#toequalvalue) matchers.
As [`toBe`](https://jestjs.io/docs/expect#tobevalue) uses
[`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is)
to compare values, it's faster (by default) than using `toEqual`.
While the latter eventually falls back to leverage [`Object.is`](https://github.com/facebook/jest/blob/master/packages/expect/src/jasmineUtils.ts#L91),
for primitive values, it should only be used when complex objects need a comparison.
Examples:
```javascript
const foo = 1;
// Bad
expect(foo).toEqual(1);
// Good
expect(foo).toBe(1);
```
#### Prefer more befitting matchers
Jest provides useful matchers like `toHaveLength` or `toBeUndefined` to make your tests more
readable and to produce more understandable error messages. Check their docs for the
[full list of matchers](https://jestjs.io/docs/expect#methods).
Examples:
```javascript
const arr = [1, 2];
// prints:
// Expected length: 1
// Received length: 2
expect(arr).toHaveLength(1);
// prints:
// Expected: 1
// Received: 2
expect(arr.length).toBe(1);
// prints:
// expect(received).toBe(expected) // Object.is equality
// Expected: undefined
// Received: "bar"
const foo = 'bar';
expect(foo).toBe(undefined);
// prints:
// expect(received).toBeUndefined()
// Received: "bar"
const foo = 'bar';
expect(foo).toBeUndefined();
```
#### Avoid using `toBeTruthy` or `toBeFalsy`
Jest also provides following matchers: `toBeTruthy` and `toBeFalsy`. We should not use them because
they make tests weaker and produce false-positive results.
For example, `expect(someBoolean).toBeFalsy()` passes when `someBoolean === null`, and when
`someBoolean === false`.
#### Tricky `toBeDefined` matcher
Jest has the tricky `toBeDefined` matcher that can produce false positive test. Because it
[validates](https://github.com/facebook/jest/blob/master/packages/expect/src/matchers.ts#L204)
the given value for `undefined` only.
```javascript
// Bad: if finder returns null, the test will pass
expect(wrapper.find('foo')).toBeDefined();
// Good
expect(wrapper.find('foo').exists()).toBe(true);
```
#### Avoid using `setImmediate`
Try to avoid using `setImmediate`. `setImmediate` is an ad-hoc solution to run your callback after
the I/O completes. And it's not part of the Web API, hence, we target NodeJS environments in our
unit tests.
Instead of `setImmediate`, use `jest.runAllTimers` or `jest.runOnlyPendingTimers` to run pending timers.
The latter is useful when you have `setInterval` in the code. **Remember**: our Jest configuration uses fake timers.
## Avoid non-deterministic specs
Non-determinism is the breeding ground for flaky and brittle specs. Such specs end up breaking the CI pipeline, interrupting the work flow of other contributors.
1. Make sure your test subject's collaborators (for example, Axios, Apollo, Lodash helpers) and test environment (for example, Date) behave consistently across systems and over time.
1. Make sure tests are focused and not doing "extra work" (for example, needlessly creating the test subject more than once in an individual test).
### Faking `Date` for determinism
`Date` is faked by default in our Jest environment. This means every call to `Date()` or `Date.now()` returns a fixed deterministic value.
If you really need to change the default fake date, you can call `useFakeDate` within any `describe` block, and
the date will be replaced for that specs within that `describe` context only:
```javascript
import { useFakeDate } from 'helpers/fake_date';
describe('cool/component', () => {
// Default fake `Date`
const TODAY = new Date();
// NOTE: `useFakeDate` cannot be called during test execution (that is, inside `it`, `beforeEach`, `beforeAll`, etc.).
describe("on Ada Lovelace's Birthday", () => {
useFakeDate(1815, 11, 10)
it('Date is no longer default', () => {
expect(new Date()).not.toEqual(TODAY);
});
});
it('Date is still default in this scope', () => {
expect(new Date()).toEqual(TODAY)
});
})
```
Similarly, if you really need to use the real `Date` class, then you can import and call `useRealDate` within any `describe` block:
```javascript
import { useRealDate } from 'helpers/fake_date';
// NOTE: `useRealDate` cannot be called during test execution (that is, inside `it`, `beforeEach`, `beforeAll`, etc.).
describe('with real date', () => {
useRealDate();
});
```
### Faking `Math.random` for determinism
Consider replacing `Math.random` with a fake when the test subject depends on it.
```javascript
beforeEach(() => {
// https://xkcd.com/221/
jest.spyOn(Math, 'random').mockReturnValue(0.4);
});
```
## Console warnings and errors in tests
Unexpected console warnings and errors are indicative of problems in our production code.
We want our test environment to be strict, so your tests should fail when unexpected
`console.error` or `console.warn` calls are made.
### Ignoring console messages from watcher
Since there's a lot of code outside of our control, there are some console messages that
are ignored by default and will **not** fail a test if used. This list of ignored
messages can be maintained where we call `setupConsoleWatcher`. Example:
```javascript
setupConsoleWatcher({
ignores: [
...,
// Any call to `console.error('Foo bar')` or `console.warn('Foo bar')` will be ignored by our console watcher.
'Foo bar',
// Use regex to allow for flexible message matching.
/Lorem ipsum/,
]
});
```
If a specific test needs to ignore a specific message for a `describe` block, use the
`ignoreConsoleMessages` helper near the top of the `describe`. This automatically
calls `beforeAll` and `afterAll` to set up/teardown this set of ignored for the test
context.
Use this sparingly and only if absolutely necessary for test maintainability. Example:
```javascript
import { ignoreConsoleMessages } from 'helpers/console_watcher';
describe('foos/components/foo.vue', () => {
describe('when blooped', () => {
// Will not fail a test if `console.warn('Lorem ipsum')` is called
ignoreConsoleMessages([
/^Lorem ipsum/
]);
});
describe('default', () => {
// Will fail a test if `console.warn('Lorem ipsum')` is called
});
});
```
## Factories
TBU
## Mocking Strategies with Jest
### Stubbing and Mocking
Stubs or spies are often used synonymously. In Jest it's quite easy thanks to the `.spyOn` method.
[Official docs](https://jestjs.io/docs/jest-object#jestspyonobject-methodname)
The more challenging part are mocks, which can be used for functions or even dependencies.
### Manual module mocks
Manual mocks are used to mock modules across the entire Jest environment. This is a very powerful testing tool that helps simplify
unit testing by mocking out modules that cannot be easily consumed in our test environment.
{{< alert type="warning" >}}
Do not use manual mocks if a mock should not be consistently applied in every spec (that is, it's only needed by a few specs).
Instead, consider using [`jest.mock(..)`](https://jestjs.io/docs/jest-object#jestmockmodulename-factory-options)
(or a similar mocking function) in the relevant spec file.
{{< /alert >}}
#### Where should you put manual mocks?
Jest supports [manual module mocks](https://jestjs.io/docs/manual-mocks) by placing a mock in a `__mocks__/` directory next to the source module
(for example, `app/assets/javascripts/ide/__mocks__`). **Don't do this.** We want to keep all of our test-related code in one place (the `spec/` folder).
If a manual mock is needed for a `node_modules` package, use the `spec/frontend/__mocks__` folder. Here's an example of
a [Jest mock for the package `monaco-editor`](https://gitlab.com/gitlab-org/gitlab/-/blob/b7f914cddec9fc5971238cdf12766e79fa1629d7/spec/frontend/__mocks__/monaco-editor/index.js#L1).
If a manual mock is needed for a CE module, place the implementation in
`spec/frontend/__helpers__/mocks` and add a line to the `frontend/test_setup`
(or the `frontend/shared_test_setup`) that looks something like:
```javascript
// "~/lib/utils/axios_utils" is the path to the real module
// "helpers/mocks/axios_utils" is the path to the mocked implementation
jest.mock('~/lib/utils/axios_utils', () => jest.requireActual('helpers/mocks/axios_utils'));
```
#### Manual mock examples
- [`__helpers__/mocks/axios_utils`](https://gitlab.com/gitlab-org/gitlab/-/blob/a50edd12b3b1531389624086b6381a042c8143ef/spec/frontend/__helpers__/mocks/axios_utils.js#L1) -
This mock is helpful because we don't want any unmocked requests to pass any tests. Also, we are able to inject some test helpers such as `axios.waitForAll`.
- [`__mocks__/mousetrap/index.js`](https://gitlab.com/gitlab-org/gitlab/-/blob/cd4c086d894226445be9d18294a060ba46572435/spec/frontend/__mocks__/mousetrap/index.js#L1) -
This mock is helpful because the module itself uses AMD format which webpack understands, but is incompatible with the jest environment. This mock doesn't remove
any behavior, only provides a nice es6 compatible wrapper.
- [`__mocks__/monaco-editor/index.js`](https://gitlab.com/gitlab-org/gitlab/-/blob/b7f914cddec9fc5971238cdf12766e79fa1629d7/spec/frontend/__mocks__/monaco-editor/index.js) -
This mock is helpful because the Monaco package is completely incompatible in a Jest environment. In fact, webpack requires a special loader to make it work. This mock
makes this package consumable by Jest.
### Keep mocks light
Global mocks introduce magic and technically can reduce test coverage. When mocking is deemed profitable:
- Keep the mock short and focused.
- Leave a top-level comment in the mock on why it is necessary.
### Additional mocking techniques
Consult the [official Jest docs](https://jestjs.io/docs/jest-object#mock-modules) for a full overview of the available mocking features.
## Running Frontend Tests
Before generating fixtures, make sure you have a running GDK instance.
For running the frontend tests, you need the following commands:
- `rake frontend:fixtures` (re-)generates [fixtures](#frontend-test-fixtures). Make sure that
fixtures are up-to-date before running tests that require them.
- `yarn jest` runs Jest tests.
### Running CE and EE tests
Whenever you create tests for both CE and EE environments, because your changes have EE features, you need to take some steps to ensure that both tests pass locally and on the pipeline when run.
Check [this section](../ee_features.md#running-ee-vs-ce-tests) to learn more about testing both environments.
### Live testing and focused testing -- Jest
While you work on a test suite, you may want to run these specs in watch mode, so they rerun automatically on every save.
```shell
# Watch and rerun all specs matching the name icon
yarn jest --watch icon
# Watch and rerun one specific file
yarn jest --watch path/to/spec/file.spec.js
```
You can also run some focused tests without the `--watch` flag
```shell
# Run specific jest file
yarn jest ./path/to/local_spec.js
# Run specific jest folder
yarn jest ./path/to/folder/
# Run all jest files which path contain term
yarn jest term
```
## Frontend test fixtures
Frontend fixtures are files containing responses from backend controllers. These responses can be either HTML
generated from HAML templates or JSON payloads. Frontend tests that rely on these responses are
often using fixtures to validate correct integration with the backend code.
### Use fixtures
To import a JSON or HTML fixture, `import` it using the `test_fixtures` alias.
```javascript
import responseBody from 'test_fixtures/some/fixture.json' // loads tmp/tests/frontend/fixtures-ee/some/fixture.json
it('makes a request', () => {
axiosMock.onGet(endpoint).reply(200, responseBody);
myButton.click();
// ...
});
```
### Generate fixtures
You can find code to generate test fixtures in:
- `spec/frontend/fixtures/`, for running tests in CE.
- `ee/spec/frontend/fixtures/`, for running tests in EE.
You can generate fixtures by running:
- `bin/rake frontend:fixtures` to generate all fixtures
- `bin/rspec spec/frontend/fixtures/merge_requests.rb` to generate specific fixtures (in this case for `merge_request.rb`)
You can find generated fixtures are in `tmp/tests/frontend/fixtures-ee`.
To generate a single fixture for a _spec.js file identify the import from `test_fixtures/` directory:
```javascript
// spec/frontend/authentication/webauthn/authenticate_spec.js
import htmlWebauthnAuthenticate from 'test_fixtures/webauthn/authenticate.html';
```
The corresponding fixture file is `spec/frontend/fixtures/webauthn.rb`
To generate the single fixture from the command line run `bin/rspec spec/frontend/fixtures/webauthn.rb`
### Download fixtures
We generate fixtures in GitLab CI, and store them in the package registry.
The `scripts/frontend/download_fixtures.sh` script is meant to download and extract those fixtures for local use:
```shell
# Checks if a frontend fixture package exists in the gitlab-org/gitlab
# package registry by looking at the commits on a local branch.
#
# The package is downloaded and extracted if it exists
$ scripts/frontend/download_fixtures.sh
# Same as above, but only looks at the last 10 commits of the currently checked-out branch
$ scripts/frontend/download_fixtures.sh --max-commits=10
# Looks at the commits on the local master branch instead of the currently checked-out branch
$ scripts/frontend/download_fixtures.sh --branch master
```
#### Creating new fixtures
For each fixture, you can find the content of the `response` variable in the output file.
For example, a test named `"merge_requests/diff_discussion.json"` in `spec/frontend/fixtures/merge_requests.rb`
produces an output file `tmp/tests/frontend/fixtures-ee/merge_requests/diff_discussion.json`.
The `response` variable gets automatically set if the test is marked as `type: :request` or `type: :controller`.
When creating a new fixture, it often makes sense to take a look at the corresponding tests for the
endpoint in `(ee/)spec/controllers/` or `(ee/)spec/requests/`.
##### GraphQL query fixtures
You can create a fixture that represents the result of a GraphQL query using the `get_graphql_query_as_string`
helper method. For example:
```ruby
# spec/frontend/fixtures/releases.rb
describe GraphQL::Query, type: :request do
include GraphqlHelpers
all_releases_query_path = 'releases/graphql/queries/all_releases.query.graphql'
it "graphql/#{all_releases_query_path}.json" do
query = get_graphql_query_as_string(all_releases_query_path)
post_graphql(query, current_user: admin, variables: { fullPath: project.full_path })
expect_graphql_errors_to_be_empty
end
end
```
This will create a new fixture located at
`tmp/tests/frontend/fixtures-ee/graphql/releases/graphql/queries/all_releases.query.graphql.json`.
You can import the JSON fixture in a Jest test using the `test_fixtures` alias
[as described previously](#use-fixtures).
## Data-driven tests
Similar to [RSpec's parameterized tests](best_practices.md#table-based--parameterized-tests),
Jest supports data-driven tests for:
- Individual tests using [`test.each`](https://jestjs.io/docs/api#testeachtable-name-fn-timeout) (aliased to `it.each`).
- Groups of tests using [`describe.each`](https://jestjs.io/docs/api#describeeachtable-name-fn-timeout).
These can be useful for reducing repetition within tests. Each option can take an array of
data values or a tagged template literal.
For example:
```javascript
// function to test
const icon = status => status ? 'pipeline-passed' : 'pipeline-failed'
const message = status => status ? 'pipeline-passed' : 'pipeline-failed'
// test with array block
it.each([
[false, 'pipeline-failed'],
[true, 'pipeline-passed']
])('icon with %s will return %s',
(status, icon) => {
expect(renderPipeline(status)).toEqual(icon)
}
);
```
{{< alert type="note" >}}
Only use template literal block if pretty print is not needed for spec output. For example, empty strings, nested objects etc.
{{< /alert >}}
For example, when testing the difference between an empty search string and a non-empty search string, the use of the array block syntax with the pretty print option would be preferred. That way the differences between an empty string (`''`) and a non-empty string (`'search string'`) would be visible in the spec output. Whereas with a template literal block, the empty string would be shown as a space, which could lead to a confusing developer experience.
```javascript
// bad
it.each`
searchTerm | expected
${''} | ${{ issue: { users: { nodes: [] } } }}
${'search term'} | ${{ issue: { other: { nested: [] } } }}
`('when search term is $searchTerm, it returns $expected', ({ searchTerm, expected }) => {
expect(search(searchTerm)).toEqual(expected)
});
// good
it.each([
['', { issue: { users: { nodes: [] } } }],
['search term', { issue: { other: { nested: [] } } }],
])('when search term is %p, expect to return %p',
(searchTerm, expected) => {
expect(search(searchTerm)).toEqual(expected)
}
);
```
```javascript
// test suite with tagged template literal block
describe.each`
status | icon | message
${false} | ${'pipeline-failed'} | ${'Pipeline failed - boo-urns'}
${true} | ${'pipeline-passed'} | ${'Pipeline succeeded - win!'}
`('pipeline component', ({ status, icon, message }) => {
it(`returns icon ${icon} with status ${status}`, () => {
expect(icon(status)).toEqual(message)
})
it(`returns message ${message} with status ${status}`, () => {
expect(message(status)).toEqual(message)
})
});
```
## Gotchas
### RSpec errors due to JavaScript
By default RSpec unit tests don't run JavaScript in the headless browser
and rely on inspecting the HTML generated by rails.
If an integration test depends on JavaScript to run correctly, you need to make
sure the spec is configured to enable JavaScript when the tests are run. If you
don't do this, the spec runner displays vague error messages.
To enable a JavaScript driver in an `RSpec` test, add `:js` to the
individual spec or the context block containing multiple specs that need
JavaScript enabled:
```ruby
# For one spec
it 'presents information about abuse report', :js do
# assertions...
end
describe "Admin::AbuseReports", :js do
it 'presents information about abuse report' do
# assertions...
end
it 'shows buttons for adding to abuse report' do
# assertions...
end
end
```
### Jest test timeout due to asynchronous imports
If a module asynchronously imports some other modules at runtime, these modules must be
transpiled by the Jest loaders at runtime. It's possible that this can cause [Jest to timeout](https://gitlab.com/gitlab-org/gitlab/-/issues/280809).
If you run into this issue, consider eager importing the module so that Jest compiles
and caches it at compile-time, fixing the runtime timeout.
Consider the following example:
```javascript
// the_subject.js
export default {
components: {
// Async import Thing because it is large and isn't always needed.
Thing: () => import(/* webpackChunkName: 'thing' */ './path/to/thing.vue'),
}
};
```
Jest doesn't automatically transpile the `thing.vue` module, and depending on its size, could
cause Jest to time out. We can force Jest to transpile and cache this module by eagerly importing
it like so:
```javascript
// the_subject_spec.js
import Subject from '~/feature/the_subject.vue';
// Force Jest to transpile and cache
// eslint-disable-next-line no-unused-vars
import _Thing from '~/feature/path/to/thing.vue';
```
{{< alert type="note" >}}
Do not disregard test timeouts. This could be a sign that there's
actually a production problem. Use this opportunity to analyze the production webpack bundles and
chunks and confirm that there is not a production issue with the asynchronous imports.
{{< /alert >}}
## Overview of Frontend Testing Levels
Main information on frontend testing levels can be found in the [Testing Levels page](testing_levels.md).
Tests relevant for frontend development can be found at the following places:
- `spec/frontend/`, for Jest tests
- `spec/features/`, for RSpec tests
RSpec runs complete [feature tests](testing_levels.md#frontend-feature-tests), while the Jest directories contain [frontend unit tests](testing_levels.md#frontend-unit-tests), [frontend component tests](testing_levels.md#frontend-component-tests), and [frontend integration tests](testing_levels.md#frontend-integration-tests).
Before May 2018, `features/` also contained feature tests run by Spinach. These tests were removed from the codebase in May 2018 ([#23036](https://gitlab.com/gitlab-org/gitlab-foss/-/issues/23036)).
See also [Notes on testing Vue components](../fe_guide/vue.md#testing-vue-components).
## Test helpers
Test helpers can be found in [`spec/frontend/__helpers__`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/spec/frontend/__helpers__).
If you introduce new helpers, place them in that directory.
### Vuex Helper: `testAction`
We have a helper available to make testing actions easier, as per [official documentation](https://vuex.vuejs.org/guide/testing.html):
```javascript
// prefer using like this, a single object argument so parameters are obvious from reading the test
await testAction({
action: actions.actionName,
payload: { deleteListId: 1 },
state: { lists: [1, 2, 3] },
expectedMutations: [ { type: types.MUTATION} ],
expectedActions: [],
});
// old way, don't do this for new tests
testAction(
actions.actionName, // action
{ }, // params to be passed to action
state, // state
[
{ type: types.MUTATION},
{ type: types.MUTATION_1, payload: {}},
], // mutations committed
[
{ type: 'actionName', payload: {}},
{ type: 'actionName1', payload: {}},
] // actions dispatched
done,
);
```
### Wait until Axios requests finish
<!-- vale gitlab_base.Spelling = NO -->
The Axios Utils mock module located in `spec/frontend/__helpers__/mocks/axios_utils.js` contains two helper methods for Jest tests that spawn HTTP requests.
These are very useful if you don't have a handle to the request's Promise, for example when a Vue component does a request as part of its lifecycle.
<!-- vale gitlab_base.Spelling = YES -->
- `waitFor(url, callback)`: Runs `callback` after a request to `url` finishes (either successfully or unsuccessfully).
- `waitForAll(callback)`: Runs `callback` once all pending requests have finished. If no requests are pending, runs `callback` on the next tick.
Both functions run `callback` on the next tick after the requests finish (using `setImmediate()`), to allow any `.then()` or `.catch()` handlers to run.
### `shallowMountExtended` and `mountExtended`
The `shallowMountExtended` and `mountExtended` utilities provide you with the ability to perform
any of the available [DOM Testing Library queries](https://testing-library.com/docs/queries/about/)
by prefixing them with `find` or `findAll`.
```javascript
import { shallowMountExtended } from 'helpers/vue_test_utils_helper';
describe('FooComponent', () => {
const wrapper = shallowMountExtended({
template: `
<div data-testid="gitlab-frontend-stack">
<p>GitLab frontend stack</p>
<div role="tablist">
<button role="tab" aria-selected="true">Vue.js</button>
<button role="tab" aria-selected="false">GraphQL</button>
<button role="tab" aria-selected="false">SCSS</button>
</div>
</div>
`,
});
it('finds elements with `findByTestId`', () => {
expect(wrapper.findByTestId('gitlab-frontend-stack').exists()).toBe(true);
});
it('finds elements with `findByText`', () => {
expect(wrapper.findByText('GitLab frontend stack').exists()).toBe(true);
expect(wrapper.findByText('TypeScript').exists()).toBe(false);
});
it('finds elements with `findAllByRole`', () => {
expect(wrapper.findAllByRole('tab').length).toBe(3);
});
});
```
Check an example in [`spec/frontend/alert_management/components/alert_details_spec.js`](https://gitlab.com/gitlab-org/gitlab/-/blob/ac1c9fa4c5b3b45f9566147b1c88fd1339cd7c25/spec/frontend/alert_management/components/alert_details_spec.js#L32).
## Testing with older browsers
Some regressions only affect a specific browser version. We can install and test in particular browsers with either Firefox or BrowserStack using the following steps:
### BrowserStack
[BrowserStack](https://www.browserstack.com/) allows you to test more than 1200 mobile devices and browsers.
You can use it directly through the [live app](https://www.browserstack.com/live) or you can install the [chrome extension](https://chromewebstore.google.com/detail/browserstack/nkihdmlheodkdfojglpcjjmioefjahjb) for easy access.
Sign in to BrowserStack with the credentials saved in the **Engineering** vault of the GitLab
[shared 1Password account](https://handbook.gitlab.com/handbook/security/password-guidelines/#1password-for-teams).
### Firefox
#### macOS
You can download any older version of Firefox from the releases FTP server, <https://ftp.mozilla.org/pub/firefox/releases/>:
1. From the website, select a version, in this case `50.0.1`.
1. Go to the mac folder.
1. Select your preferred language. The DMG package is inside. Download it.
1. Drag and drop the application to any other folder but the `Applications` folder.
1. Rename the application to something like `Firefox_Old`.
1. Move the application to the `Applications` folder.
1. Open up a terminal and run `/Applications/Firefox_Old.app/Contents/MacOS/firefox-bin -profilemanager` to create a new profile specific to that Firefox version.
1. Once the profile has been created, quit the app, and run it again like usual. You now have a working older Firefox version.
## Snapshots
[Jest snapshot tests](https://jestjs.io/docs/snapshot-testing) are a useful way to prevent unexpected changes to the HTML output of a given component. They should **only** be used when other testing methods (such as asserting elements with `vue-tests-utils`) do not cover the required use case. To use them within GitLab, there are a few guidelines that should be highlighted:
- Treat snapshots as code
- Don't think of a snapshot file as a black box
- Care for the output of the snapshot, otherwise, it's not providing any real value. This will usually involve reading the generated snapshot file as you would read any other piece of code
Think of a snapshot test as a simple way to store a raw `String` representation of what you've put into the item being tested. This can be used to evaluate changes in a component, a store, a complex piece of generated output, etc. You can see more in the list below for some recommended `Do's and Don'ts`.
While snapshot tests can be a very powerful tool, they are meant to supplement, not to replace unit tests.
Jest provides a great set of docs on [best practices](https://jestjs.io/docs/snapshot-testing#best-practices) that we should keep in mind when creating snapshots.
### How does a snapshot work?
A snapshot is purely a stringified version of what you ask to be tested on the left-hand side of the function call. This means any kind of changes you make to the formatting of the string has an impact on the outcome. This process is done by leveraging serializers for an automatic transform step. For Vue this is already taken care of by leveraging the `vue-jest` package, which offers the proper serializer.
Should the outcome of your spec be different from what is in the generated snapshot file, you'll be notified about it by a failing test in your test suite.
Find all the details in Jests official documentation [https://jestjs.io/docs/snapshot-testing](https://jestjs.io/docs/snapshot-testing)
### Pros and Cons
**Pros**
- Provides a good warning against accidental changes of important HTML structures
- Ease of setup
**Cons**
- Lacks the clarity or guard rails that `vue-tests-utils` provides by finding elements and asserting their presence directly
- Creates unnecessary noise when updating components purposefully
- High risk of taking a snapshot of bugs, which then turns the tests against us since the test will now fail when fixing the issue
- No meaningful assertions or expectations within snapshots makes them harder to reason about or replace
- When used with dependencies like [GitLab UI](https://gitlab.com/gitlab-org/gitlab-ui), it creates fragility in tests when the underlying library changes the HTML of a component we are testing
### When to use
**Use snapshots when**
- Protecting critical HTML structures so it doesn't change by accident
- Asserting JS object or JSON outputs of complex utility functions
### When not to use
**Don't use snapshots when**
- Tests could be written using `vue-tests-utils` instead
- Asserting the logic of a component
- Predicting data structure(s) outputs
- There are UI elements outside of the repository (think of GitLab UI version updates)
### Examples
As you can see, the cons of snapshot tests far outweigh the pros in general. To illustrate this better, this section will show a few examples of when you might be tempted to
use snapshot testing and why they are not good patterns.
#### Example #1 - Element visibility
When testing elements visibility, favour using `vue-tests-utils (VTU)` to find a given component and then a basic `.exists()` method call on the VTU wrapper. This provides better readability and more resilient testing. If you look at the examples below, notice how the assertions on the snapshots do not tell you what you are expecting to see. We are relying entirely on `it` description to give us context and on the assumption that the snapshot has captured the desired behavior.
```vue
<template>
<my-component v-if="isVisible" />
</template>
```
Bad:
```javascript
it('hides the component', () => {
createComponent({ props: { isVisible: false }})
expect(wrapper.element).toMatchSnapshot()
})
it('shows the component', () => {
createComponent({ props: { isVisible: true }})
expect(wrapper.element).toMatchSnapshot()
})
```
Good:
```javascript
it('hides the component', () => {
createComponent({ props: { isVisible: false }})
expect(findMyComponent().exists()).toBe(false)
})
it('shows the component', () => {
createComponent({ props: { isVisible: true }})
expect(findMyComponent().exists()).toBe(true)
})
```
Not only that, but imagine having passed the wrong prop to your component and having the wrong visibility: the snapshot test would still pass because you would have captured the HTML **with the issue** and so unless you double-checked the output of the snapshot, you would never know that your test is broken.
#### Example #2 - Presence of text
Finding text within a component is very easy by using the `vue-test-utils` method `wrapper.text()`. However, there are some cases where it might be tempting to use snapshots when the value returned has a lot of inconsistent spacing due to formatting or HTML nesting.
In these instances, it is better to assert each string individually and make multiple assertions than to use a snapshot to ignore the spaces. This is because any change to the DOM layout will fail the snapshot test even if the text is still perfectly formatted.
```vue
<template>
<gl-sprintf :message="my-message">
<template #code="{ content }">
<code>{{ content }}</code>
</template>
</gl-sprintf>
<p> My second message </p>
</template>
```
Bad:
```javascript
it('renders the text as I expect', () => {
expect(wrapper.text()).toMatchSnapshot()
})
```
Good:
```javascript
it('renders the code snippet', () => {
expect(findCodeTag().text()).toContain("myFunction()")
})
it('renders the paragraph text', () => {
expect(findOtherText().text()).toBe("My second message")
})
```
#### Example #3 - Complex HTML
When we have very complex HTML, we should focus on asserting specific sensitive and meaningful points rather than capturing it as a whole. The value in a snapshot test is to **warn developers** that they might have accidentally change an HTML structure that they did not intend to change. If the output of the change is hard to read, which is often the case with complex HTML output, then **is the signal itself that something changed** sufficient? And if it is, can it be accomplished without snapshots?
A good example of a complex HTML output is `GlTable`. Snapshot testing might feel like a good option since you can capture rows and columns structure, but we should instead try to assert text we expect or count the number of rows and columns manually.
```vue
<template>
<gl-table ...all-them-props />
</template>
```
Bad:
```javascript
it('renders GlTable as I expect', () => {
expect(findGlTable().element).toMatchSnapshot()
})
```
Good:
```javascript
it('renders the right number of rows', () => {
expect(findGlTable().findAllRows()).toHaveLength(expectedLength)
})
it('renders the special icon that only appears on a full moon', () => {
expect(findGlTable().findMoonIcon().exists()).toBe(true)
})
it('renders the correct email format', () => {
expect(findGlTable().text()).toContain('my_strange_email@shaddyprovide.com')
})
```
Although more verbose, this now means that our tests are not going to break if `GlTable` changes its internal implementation, we communicate to other developers (or ourselves in 6 months) what is important to preserve when refactoring or adding to our table.
### How to take a snapshot
```javascript
it('makes the name look pretty', () => {
expect(prettifyName('Homer Simpson')).toMatchSnapshot()
})
```
When this test runs the first time a fresh `.snap` file will be created. It will look something like this:
```plaintext
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`makes the name look pretty`] = `
Sir Homer Simpson the Third
`
```
Now, every time you call this test, the new snapshot will be evaluated against the previously created version. This should highlight the fact that it's important to understand the content of your snapshot file and treat it with care. Snapshots will lose their value if the output of the snapshot is too big or complex to read, this means keeping snapshots isolated to human-readable items that can be either evaluated in a merge request review or are guaranteed to never change.
The same can be done for `wrappers` or `elements`
```javascript
it('renders the component correctly', () => {
expect(wrapper).toMatchSnapshot()
expect(wrapper.element).toMatchSnapshot();
})
```
The above test will create two snapshots. It's important to decide which of the snapshots provide more value for codebase safety. That is, if one of these snapshots changes, does that highlight a possible break in the codebase? This can help catch unexpected changes if something in an underlying dependency changes without our knowledge.
## Get started with feature tests
### What is a feature test
A [feature test](testing_levels.md#white-box-tests-at-the-system-level-formerly-known-as-system--feature-tests), also known as `white-box testing`, is a test that spawns a browser and has Capybara helpers. This means the test can:
- Locate an element in the browser.
- Click that element.
- Call the API.
Feature tests are expensive to run. You should make sure that you **really want** this type of test before running one.
All of our feature tests are written in `Ruby` but often end up being written by `JavaScript` engineers, as they implement the user-facing feature. So, the following section assumes no prior knowledge of `Ruby` or `Capybara`, and provide a clear guideline on when and how to use these tests.
### When to use feature tests
You should use a feature test when the test:
- Is across multiple components.
- Requires that a user navigate across pages.
- Is submitting a form and observing results elsewhere.
- Would result in a huge number of mocking and stubbing with fake data and components if done as a unit test.
Feature tests are especially useful when you want to test:
- That multiple components are working together successfully.
- Complex API interactions. Feature tests interact with the API, so they are slower but do not need any level of mocking or fixtures.
### When not to use feature tests
You should use `jest` and `vue-test-utils` unit tests instead of a feature test if you can get the same test results from these methods. Feature tests are quite expensive to run.
You should use a unit test if:
- The behavior you are implementing is all in one component.
- You can simulate other components' behavior to trigger the desired effect.
- You can already select UI elements in the virtual DOM to trigger the desired effects.
Also, if a behavior in your new code needs multiple components to work together, you should consider testing your behavior higher in the component tree. For example, consider a component called `ParentComponent` with the code:
```vue
<script>
export default{
name: ParentComponent,
data(){
return {
internalData: 'oldValue'
}
},
methods:{
changeSomeInternalData(newVal){
this.internalData = newVal
}
}
}
</script>
<template>
<div>
<child-component-1 @child-event="changeSomeInternalData" />
<child-component-2 :parent-data="internalData" />
</div>
</template>
```
In this example:
- `ChildComponent1` emits an event.
- `ParentComponent` changes its `internalData` value.
- `ParentComponent` passes the props down to `ChildComponent2`.
You can use a unit test instead by:
- From inside the `ParentComponent` unit test file, emitting the expected event from `childComponent1`
- Making sure the prop is passed down to `childComponent2`.
Then each child component unit tests what happens when the event is emitted and when the prop changes.
This example also applies at larger scale and with deeper component trees. It is definitely worth using unit tests and avoiding the extra cost of feature tests if you can:
- Confidently mount child components.
- Emit events or select elements in the virtual DOM.
- Get the test behavior that you want.
### Where to create your test
Feature tests live in `spec/features` folder. You should look for existing files that can test the page you are adding a feature to. Within that folder, you can locate your section. For example, if you wanted to add a new feature test for the pipeline page, you would look in `spec/features/projects/pipelines` and see if the test you want to write exists here.
### How to run a feature test
1. Make sure that you have a working GDK environment.
1. Start your `gdk` environment with `gdk start` command.
1. In your terminal, run:
```shell
bundle exec rspec path/to/file:line_of_my_test
```
You can also prefix this command with `WEBDRIVER_HEADLESS=0` which will run the test by opening an actual browser on your computer that you can see, which is very useful for debugging.
To use Firefox, instead of Chrome, prefix the command with `WEBDRIVER=firefox`.
### How to write a test
#### Basic file structure
1. Make all string literals unchangeable
In all feature tests, the very first line should be:
```ruby
# frozen_string_literal: true
```
This is in every `Ruby` file and makes all string literals unchangeable. There are also some performance benefits, but this is beyond the scope of this section.
1. Import dependencies.
You should import the modules you need. You will most likely always need to require `spec_helper`:
```ruby
require 'spec_helper'
```
Import any other relevant module.
1. Create a global scope for RSpec to define our tests, just like what we do in jest with the initial describe block.
Then, you need to create the very first `RSpec` scope.
```ruby
RSpec.describe 'Pipeline', :js do
...
end
```
What is different though, is that just like everything in Ruby, this is actually a `class`. Which means that right at the top, you can `include` modules that you'd need for your test. For example, you could include the `RoutesHelpers` to navigate more easily.
```ruby
RSpec.describe 'Pipeline', :js do
include RoutesHelpers
...
end
```
After all of this implementation, we have a file that looks something like this:
```ruby
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Pipeline', :js do
include RoutesHelpers
end
```
#### Seeding data
Each test is in its own environment and so you must use a factory to seed the required data. For example, to create a test that takes you to the main pipeline page at the route `/namespace/project/-/pipelines/:id/`.
Most feature tests at least require you to create a user, because you want to be signed in. You can skip this step if you don't have to be signed in, but as a general rule, you should **always create a user unless you are specifically testing a feature looked at by an anonymous user**. This makes sure that you explicitly set a level of permission that you can edit in the test as needed to change or test a new level of permission as the section changes. To create a user:
```ruby
let(:user) { create(:user) }
```
This creates a variable that holds the newly created user and we can use `create` because we imported the `spec_helper`.
However, we have not done anything with this user yet because it's just a variable. So, in the `before do` block of the spec, we could sign in with the user so that every spec starts with an authenticated user.
```ruby
let(:user) { create(:user) }
before do
sign_in(user)
end
```
Now that we have a user, we should look at what else we'd need before asserting anything on a pipeline page. If you look at the route `/namespace/project/-/pipelines/:id/` we can determine we need a project and a pipeline.
So we'd create a project and pipeline, and link them together. Usually in factories, the child element requires its parent as an argument. In this case, a pipeline is a child of a project. So we can create the project first, and then when we create the pipeline, we are pass the project as an argument which "binds" the pipeline to the project. A pipeline is also owned by a user, so we need the user as well. For example, this creates a project and a pipeline:
```ruby
let(:user) { create(:user) }
let(:project) { create(:project, :repository) }
let(:pipeline) { create(:ci_pipeline, project: project, ref: 'master', sha: project.commit.id, user: user) }
```
In the same spirit, you could then create a job (build) by using the build factory and passing the parent pipeline:
```ruby
create(:ci_build, pipeline: pipeline, stage_idx: 10, stage: 'publish', name: 'CentOS')
```
There are many factories that already exists, so make sure to look at other existing files to see if what you need is available.
#### Navigation
You can go to a page by using the `visit` method and passing the path as an argument. Rails automatically generates helper paths, so make sure to use these instead of a hardcoded string. They are generated using the route model, so if we want to go to a pipeline, we'd use:
```ruby
visit project_pipeline_path(project, pipeline)
```
Before executing any page interaction when navigating or making asynchronous call through the UI, make sure to use `wait_for_requests` before proceeding with further instructions.
#### Elements interaction
There are a lot of different ways to find and interact with elements.
For best practises, refer to the [UI testing](best_practices.md#ui-testing) section.
To click a button, use `click_button` with the string of text found in the button:
```ruby
click_button 'Text inside the button element'
```
If you want to follow a link, then there is `click_link`:
```ruby
click_link 'Text inside the link tag'
```
You can use `fill_in` to fill input / form elements. The first argument is the selector, the second is `with:` which is the value to pass in.
```ruby
fill_in 'current_password', with: '123devops'
```
Alternatively, you can use the `find` selector paired with `send_keys` to add keys in a field without removing previous text, or `set` which completely replaces the value of the input element.
You can find a more comprehensive list of actions in the [feature tests actions](best_practices.md#actions) documentation.
#### Assertions
To assert anything in a page, you can always access `page` variable, which is automatically defines and actually means the page document. This means you can expect the `page` to have certain components like selectors or content. Here are a few examples:
```ruby
# Finding a button
expect(page).to have_button('Submit review')
```
```ruby
# Finding by text
expect(page).to have_text('build')
```
```ruby
# Finding by `href` value
expect(page).to have_link(pipeline.ref)
```
```ruby
# Find by data-testid
# Like CSS selector, this is acceptable when there isn't a specific matcher available.
expect(page).to have_css('[data-testid="pipeline-multi-actions-dropdown"]')
```
```ruby
# Finding by CSS selector. This is a last resort.
# For example, when you cannot add attributes on the desired element.
expect(page).to have_css('.js-icon-retry')
```
```ruby
# You can combine any of these selectors with `not_to` instead
expect(page).not_to have_button('Submit review')
```
```ruby
# When a test case has back to back expectations,
# it is recommended to group them using `:aggregate_failures`
it 'shows the issue description and design references', :aggregate_failures do
expect(page).to have_text('The designs I mentioned')
expect(page).to have_link(design_tab_ref)
expect(page).to have_link(design_ref_a)
expect(page).to have_link(design_ref_b)
end
```
You can also create a sub-block to look into, to:
- Scope down where you are making your assertions and reduce the risk of finding another element that was not intended.
- Make sure an element is found within the right boundaries.
```ruby
page.within('[data-testid="pipeline-multi-actions-dropdown"]') do
...
end
```
You can find a more comprehensive list of matchers in the [feature tests matchers](best_practices.md#matchers) documentation.
#### Feature flags
By default, every feature flag is enabled **regardless of the YAML definition or the flags you've set manually in your GDK**. To test when a feature flag is disabled, you must manually stub the flag, ideally in a `before do` block.
```ruby
stub_feature_flags(my_feature_flag: false)
```
If you are stubbing an `ee` feature flag, then use:
```ruby
stub_licensed_features(my_feature_flag: false)
```
#### Asserting browser console errors
By default, feature specs won't fail if a browser console error is found. Sometimes we want to cover that there are not
unexpected console errors which could indicate an integration problem.
To set a feature spec to fail if it encounters browser console errors, use `expect_page_to_have_no_console_errors` from
the `BrowserConsoleHelpers` support module:
```ruby
RSpec.describe 'Pipeline', :js do
after do
expect_page_to_have_no_console_errors
end
# ...
end
```
{{< alert type="note" >}}
`expect_page_to_have_no_console_errors` will not work on `WEBDRIVER=firefox`. Logs are only captured when
using the Chrome driver.
{{< /alert >}}
Sometimes, there are known console errors that we want to ignore. To ignore a set of messages, such that the test
**will not** fail if the message is observed, you can pass an `allow:` parameter to
`expect_page_to_have_no_console_errors`:
```ruby
RSpec.describe 'Pipeline', :js do
after do
expect_page_to_have_no_console_errors(allow: [
"Blow up!",
/Foo.*happens/
])
end
# ...
end
```
Update the `BROWSER_CONSOLE_ERROR_FILTER` constant in `spec/support/helpers/browser_console_helpers.rb` to change
the list of console errors that should be globally ignored.
### Debugging
You can run your spec with the prefix `WEBDRIVER_HEADLESS=0` to open an actual browser. However, the specs goes though the commands quickly and leaves you no time to look around.
To avoid this problem, you can write `binding.pry` on the line where you want Capybara to stop execution. You are then inside the browser with standard usage. To understand why you cannot find certain elements, you can:
- Select elements.
- Use the console and network tab.
- Execute selectors inside the browser console.
Inside the terminal, where capybara is running, you can also execute `next` which goes line by line through the test. This way you can check every single interaction one by one to see what might be causing an issue.
### Improving execution time on the GDK
Running the Jest test suite, the number of workers is set to use 60% of the available cores of your machine; this results in faster execution times but higher memory consumption. For more benchmarks on how this works, see [issue 456885](https://gitlab.com/gitlab-org/gitlab/-/issues/456885).
### Updating ChromeDriver
Starting from `Selenium` 4.6, ChromeDriver can be automatically managed by `Selenium Manager` which comes with the `selenium-webdriver` gem.
You are no longer required to manually keeping chromedriver in sync.
---
[Return to Testing documentation](_index.md)
|
https://docs.gitlab.com/development/testing_guide/contract
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/testing_guide/_index.md
|
2025-08-13
|
doc/development/testing_guide/contract
|
[
"doc",
"development",
"testing_guide",
"contract"
] |
_index.md
|
none
|
unassigned
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Contract testing
| null |
Contract tests consist of two parts: consumer tests and provider tests. A simple example of a consumer and provider relationship is between the frontend and backend. The frontend would be the consumer and the backend is the provider. The frontend consumes the API that is provided by the backend. The test helps ensure that these two sides follow an agreed upon contract and any divergence from the contract triggers a meaningful conversation to prevent breaking changes from slipping through.
Consumer tests are similar to unit tests, with each spec defining a request and expected mock responses, then creating a contract based on those definitions. Provider tests are similar to integration tests - each spec takes the request defined in the contract, runs it against the actual service, and matches the response against the contract to validate it.
You can check out the existing contract tests at:
- [`spec/contracts/consumer/specs`](https://gitlab.com/gitlab-org/gitlab/-/tree/master/spec/contracts/consumer/specs) for the consumer tests.
- [`spec/contracts/provider/pact_helpers`](https://gitlab.com/gitlab-org/gitlab/-/tree/master/spec/contracts/provider/pact_helpers) for the provider tests.
The contracts themselves are stored in [`/spec/contracts/contracts`](https://gitlab.com/gitlab-org/gitlab/-/tree/master/spec/contracts/contracts) at the moment. The plan is to use [PactBroker](https://docs.pact.io/pact_broker/docker_images) hosted in AWS or another similar service.
## Write the tests
- [Writing consumer tests](consumer_tests.md)
- [Writing provider tests](provider_tests.md)
### Run the consumer tests
Before running the consumer tests, go to `spec/contracts/consumer` and run `npm install`. To run all the consumer tests, you just need to run `npm run jest:contract -- /specs`. Otherwise, to run a specific spec file, replace `/specs` with the specific spec filename. Running the consumer test will create the contract that the provider test uses to verify the actual API behavior.
You can also run tests from the root directory of the project, using the command `yarn jest:contract`.
### Run the provider tests
Before running the provider tests, make sure your GDK (GitLab Development Kit) is fully set up and running. You can follow the setup instructions detailed in the [GDK repository](https://gitlab.com/gitlab-org/gitlab-development-kit/-/tree/main). To run the provider tests, you use Rake tasks that can be found in [`./lib/tasks/contracts`](https://gitlab.com/gitlab-org/gitlab/-/tree/master/lib/tasks/contracts). To get a list of all the Rake tasks related to the provider tests, run `bundle exec rake -T contracts`. For example:
```shell
$ bundle exec rake -T contracts
rake contracts:merge_requests:pact:verify:diffs_batch # Verify provider against the consumer pacts for diffs_batch
rake contracts:merge_requests:pact:verify:diffs_metadata # Verify provider against the consumer pacts for diffs_metadata
rake contracts:merge_requests:pact:verify:discussions # Verify provider against the consumer pacts for discussions
rake contracts:merge_requests:test:merge_requests[contract_merge_requests] # Run all merge request contract tests
```
#### Verify the contracts in Pact Broker
By default, the Rake tasks will verify the locally stored contracts. In order to verify the contracts published in the Pact Broker, we need to set the `PACT_BROKER` environment variable to `true` and the `QA_PACT_BROKER_HOST` to the URL of the Pact Broker. It is important to point out here that the file path and filename of the provider test is what is used to find the contract in the Pact Broker which is why it is important to make sure the [provider test naming conventions](#provider-naming) are followed.
## Publish contracts to Pact Broker
The contracts generated by the consumer test can be published to a hosted Pact Broker by setting the `QA_PACT_BROKER_HOST` environment variable and running the [`publish-contracts.sh`](https://gitlab.com/gitlab-org/gitlab/-/tree/master/spec/contracts/publish-contracts.sh) script.
## Test suite folder structure and naming conventions
To keep the consumer and provider test suite organized and maintainable, it's important that tests are organized, also that consumers and providers are named consistently. Therefore, it's important to adhere to the following conventions.
### Test suite folder structure
Having an organized and sensible folder structure for the test suite makes it easier to find relevant files when reviewing, debugging, or introducing tests.
#### Consumer tests
The consumer tests are grouped according to the different pages in the application. Each file contains various types of requests found in a page. As such, the consumer test files are named using the Rails standards of how pages are referenced. For example, the project pipelines page would be the `Project::Pipelines#index` page so the equivalent consumer test would be located in `consumer/specs/project/pipelines/index.spec.js`.
When defining the location to output the contract generated by the test, we want to follow the same file structure which would be `contracts/project/pipelines/` for this example. This is the structure in `consumer/resources` and `consumer/fixtures` as well.
The naming of the folders must also be pluralized to match how they are called in the Rails naming standard.
#### Provider tests
The provider tests are grouped similarly to our controllers. Each of these tests contains various tests for an API endpoint. For example, the API endpoint to get a list of pipelines for a project would be located in `provider/pact_helpers/project/pipelines/get_list_project_pipelines_helper.rb`. The provider states are grouped according to the different pages in the application similar to the consumer tests.
### Naming conventions
When writing the consumer and provider tests, there are parts where a name is required for the consumer and provider. Since there are no restrictions imposed by Pact on how these should be named, a naming convention is important to keep it easy for us to figure out which consumer and provider tests are involved during debugging. Pact also uses the consumer and provider names to create the locally stored contract filenames in the `#{consumer_name}-#{provider_name}` format.
#### Consumer naming
As mentioned in the [folder structure section](#consumer-tests), consumer tests are grouped according to the different pages in the application. As such, consumer names should follow the same naming format using the Rails standard. For example, the consumer test for `Project::Pipelines#index` would be under the `project` folder and will be called `Pipelines#index` as the consumer name.
#### Provider naming
These are the API endpoints that provide the data to the consumer so they are named according to the API endpoint they pertain to. Be mindful that this begins with the HTTP request method and the rest of the name is as descriptive as possible. For example, if we're writing a test for the `GET /groups/:id/projects` endpoint, we don't want to name it "GET projects endpoint" as there is a `GET /projects` endpoint as well that also fetches a list of projects the user has access to across all of GitLab.
To choose an appropriate name, we can start by checking out our [API documentation](../../../api/api_resources.md) and naming it the same way it is named in there while making sure to keep the name in sentence case. So [`GET /groups/:id/projects`](../../../api/groups.md#list-projects) would be called `GET list a group's projects` and the test filename is `get_list_a_groups_projects_helper.rb`. [`GET /projects`](../../../api/projects.md#list-all-projects) would be called `GET list all projects`, and the test filename `get_list_all_projects_helper.rb`.
There are some cases where the provider being tested may not be documented so, in those cases, fall back to starting with the HTTP request method followed by a name that is as descriptive as possible to ensure it's easy to tell what the provider is for.
#### Conventions summary
| Tests | Folder structure | Naming convention |
| ----- | ---------------- | ----------------- |
| Consumer Test | Follows the Rails reference standards. For example, `Project::Pipelines#index` would be `consumer/specs/project/pipelines/index.spec.js` | Follows the Rails naming standard. For example, `Project::Pipelines#index` would be `Pipelines#index` within the `project` folder. |
| Provider Test | Grouped like the Rails controllers. For example, [`GET list project pipelines` API endpoint](../../../api/pipelines.md#list-project-pipelines) would be `provider/pact_helpers/project/pipelines/get_list_project_pipelines_helper.rb` | Follows the API documentation naming scheme in sentence case. For example, [`GET /projects/:id/pipelines`](../../../api/pipelines.md#list-project-pipelines) would be called `GET list project pipelines`. |
|
---
stage: none
group: unassigned
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: Contract testing
breadcrumbs:
- doc
- development
- testing_guide
- contract
---
Contract tests consist of two parts: consumer tests and provider tests. A simple example of a consumer and provider relationship is between the frontend and backend. The frontend would be the consumer and the backend is the provider. The frontend consumes the API that is provided by the backend. The test helps ensure that these two sides follow an agreed upon contract and any divergence from the contract triggers a meaningful conversation to prevent breaking changes from slipping through.
Consumer tests are similar to unit tests, with each spec defining a request and expected mock responses, then creating a contract based on those definitions. Provider tests are similar to integration tests - each spec takes the request defined in the contract, runs it against the actual service, and matches the response against the contract to validate it.
You can check out the existing contract tests at:
- [`spec/contracts/consumer/specs`](https://gitlab.com/gitlab-org/gitlab/-/tree/master/spec/contracts/consumer/specs) for the consumer tests.
- [`spec/contracts/provider/pact_helpers`](https://gitlab.com/gitlab-org/gitlab/-/tree/master/spec/contracts/provider/pact_helpers) for the provider tests.
The contracts themselves are stored in [`/spec/contracts/contracts`](https://gitlab.com/gitlab-org/gitlab/-/tree/master/spec/contracts/contracts) at the moment. The plan is to use [PactBroker](https://docs.pact.io/pact_broker/docker_images) hosted in AWS or another similar service.
## Write the tests
- [Writing consumer tests](consumer_tests.md)
- [Writing provider tests](provider_tests.md)
### Run the consumer tests
Before running the consumer tests, go to `spec/contracts/consumer` and run `npm install`. To run all the consumer tests, you just need to run `npm run jest:contract -- /specs`. Otherwise, to run a specific spec file, replace `/specs` with the specific spec filename. Running the consumer test will create the contract that the provider test uses to verify the actual API behavior.
You can also run tests from the root directory of the project, using the command `yarn jest:contract`.
### Run the provider tests
Before running the provider tests, make sure your GDK (GitLab Development Kit) is fully set up and running. You can follow the setup instructions detailed in the [GDK repository](https://gitlab.com/gitlab-org/gitlab-development-kit/-/tree/main). To run the provider tests, you use Rake tasks that can be found in [`./lib/tasks/contracts`](https://gitlab.com/gitlab-org/gitlab/-/tree/master/lib/tasks/contracts). To get a list of all the Rake tasks related to the provider tests, run `bundle exec rake -T contracts`. For example:
```shell
$ bundle exec rake -T contracts
rake contracts:merge_requests:pact:verify:diffs_batch # Verify provider against the consumer pacts for diffs_batch
rake contracts:merge_requests:pact:verify:diffs_metadata # Verify provider against the consumer pacts for diffs_metadata
rake contracts:merge_requests:pact:verify:discussions # Verify provider against the consumer pacts for discussions
rake contracts:merge_requests:test:merge_requests[contract_merge_requests] # Run all merge request contract tests
```
#### Verify the contracts in Pact Broker
By default, the Rake tasks will verify the locally stored contracts. In order to verify the contracts published in the Pact Broker, we need to set the `PACT_BROKER` environment variable to `true` and the `QA_PACT_BROKER_HOST` to the URL of the Pact Broker. It is important to point out here that the file path and filename of the provider test is what is used to find the contract in the Pact Broker which is why it is important to make sure the [provider test naming conventions](#provider-naming) are followed.
## Publish contracts to Pact Broker
The contracts generated by the consumer test can be published to a hosted Pact Broker by setting the `QA_PACT_BROKER_HOST` environment variable and running the [`publish-contracts.sh`](https://gitlab.com/gitlab-org/gitlab/-/tree/master/spec/contracts/publish-contracts.sh) script.
## Test suite folder structure and naming conventions
To keep the consumer and provider test suite organized and maintainable, it's important that tests are organized, also that consumers and providers are named consistently. Therefore, it's important to adhere to the following conventions.
### Test suite folder structure
Having an organized and sensible folder structure for the test suite makes it easier to find relevant files when reviewing, debugging, or introducing tests.
#### Consumer tests
The consumer tests are grouped according to the different pages in the application. Each file contains various types of requests found in a page. As such, the consumer test files are named using the Rails standards of how pages are referenced. For example, the project pipelines page would be the `Project::Pipelines#index` page so the equivalent consumer test would be located in `consumer/specs/project/pipelines/index.spec.js`.
When defining the location to output the contract generated by the test, we want to follow the same file structure which would be `contracts/project/pipelines/` for this example. This is the structure in `consumer/resources` and `consumer/fixtures` as well.
The naming of the folders must also be pluralized to match how they are called in the Rails naming standard.
#### Provider tests
The provider tests are grouped similarly to our controllers. Each of these tests contains various tests for an API endpoint. For example, the API endpoint to get a list of pipelines for a project would be located in `provider/pact_helpers/project/pipelines/get_list_project_pipelines_helper.rb`. The provider states are grouped according to the different pages in the application similar to the consumer tests.
### Naming conventions
When writing the consumer and provider tests, there are parts where a name is required for the consumer and provider. Since there are no restrictions imposed by Pact on how these should be named, a naming convention is important to keep it easy for us to figure out which consumer and provider tests are involved during debugging. Pact also uses the consumer and provider names to create the locally stored contract filenames in the `#{consumer_name}-#{provider_name}` format.
#### Consumer naming
As mentioned in the [folder structure section](#consumer-tests), consumer tests are grouped according to the different pages in the application. As such, consumer names should follow the same naming format using the Rails standard. For example, the consumer test for `Project::Pipelines#index` would be under the `project` folder and will be called `Pipelines#index` as the consumer name.
#### Provider naming
These are the API endpoints that provide the data to the consumer so they are named according to the API endpoint they pertain to. Be mindful that this begins with the HTTP request method and the rest of the name is as descriptive as possible. For example, if we're writing a test for the `GET /groups/:id/projects` endpoint, we don't want to name it "GET projects endpoint" as there is a `GET /projects` endpoint as well that also fetches a list of projects the user has access to across all of GitLab.
To choose an appropriate name, we can start by checking out our [API documentation](../../../api/api_resources.md) and naming it the same way it is named in there while making sure to keep the name in sentence case. So [`GET /groups/:id/projects`](../../../api/groups.md#list-projects) would be called `GET list a group's projects` and the test filename is `get_list_a_groups_projects_helper.rb`. [`GET /projects`](../../../api/projects.md#list-all-projects) would be called `GET list all projects`, and the test filename `get_list_all_projects_helper.rb`.
There are some cases where the provider being tested may not be documented so, in those cases, fall back to starting with the HTTP request method followed by a name that is as descriptive as possible to ensure it's easy to tell what the provider is for.
#### Conventions summary
| Tests | Folder structure | Naming convention |
| ----- | ---------------- | ----------------- |
| Consumer Test | Follows the Rails reference standards. For example, `Project::Pipelines#index` would be `consumer/specs/project/pipelines/index.spec.js` | Follows the Rails naming standard. For example, `Project::Pipelines#index` would be `Pipelines#index` within the `project` folder. |
| Provider Test | Grouped like the Rails controllers. For example, [`GET list project pipelines` API endpoint](../../../api/pipelines.md#list-project-pipelines) would be `provider/pact_helpers/project/pipelines/get_list_project_pipelines_helper.rb` | Follows the API documentation naming scheme in sentence case. For example, [`GET /projects/:id/pipelines`](../../../api/pipelines.md#list-project-pipelines) would be called `GET list project pipelines`. |
|
https://docs.gitlab.com/development/testing_guide/consumer_tests
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/testing_guide/consumer_tests.md
|
2025-08-13
|
doc/development/testing_guide/contract
|
[
"doc",
"development",
"testing_guide",
"contract"
] |
consumer_tests.md
|
none
|
unassigned
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Writing consumer tests
| null |
This tutorial guides you through writing a consumer test from scratch. To start, the consumer tests are written using [`jest-pact`](https://github.com/pact-foundation/jest-pact) that builds on top of [`pact-js`](https://github.com/pact-foundation/pact-js). This tutorial shows you how to write a consumer test for the `/discussions.json` REST API endpoint, which is `/:namespace_name/:project_name/-/merge_requests/:id/discussions.json`, that is called in the `MergeRequests#show` page. For an example of a GraphQL consumer test, see [`spec/contracts/consumer/specs/project/pipelines/show.spec.js`](https://gitlab.com/gitlab-org/gitlab/-/tree/master/spec/contracts/consumer/specs/project/pipelines/show.spec.js).
## Create the skeleton
Start by creating the skeleton of a consumer test. Since this is for a request in the `MergeRequests#show` page, under `spec/contracts/consumer/specs/project/merge_requests`, create a file called `show.spec.js`.
Then, populate it with the following function and parameters:
- [`pactWith`](#the-pactwith-function)
- [`PactOptions`](#the-pactoptions-parameter)
- [`PactFn`](#the-pactfn-parameter)
For more information about how the contract test directory is structured, see [Test suite folder structure](_index.md#test-suite-folder-structure).
### The `pactWith` function
The Pact consumer test is defined through the `pactWith` function that takes `PactOptions` and the `PactFn`.
```javascript
import { pactWith } from 'jest-pact';
pactWith(PactOptions, PactFn);
```
### The `PactOptions` parameter
`PactOptions` with `jest-pact` introduces [additional options](https://github.com/pact-foundation/jest-pact/blob/dce370c1ab4b7cb5dff12c4b62246dc229c53d0e/README.md#defaults) that build on top of the ones [provided in `pact-js`](https://github.com/pact-foundation/pact-js#constructor). In most cases, you define the `consumer`, `provider`, `log`, and `dir` options for these tests.
```javascript
import { pactWith } from 'jest-pact';
pactWith(
{
consumer: 'MergeRequests#show',
provider: 'GET discussions',
log: '../logs/consumer.log',
dir: '../contracts/project/merge_requests/show',
},
PactFn
);
```
For more information about how to name consumers and providers, see [Naming conventions](_index.md#naming-conventions).
### The `PactFn` parameter
The `PactFn` is where your tests are defined. This is where you set up the mock provider and where you can use the standard Jest methods like [`Jest.describe`](https://jestjs.io/docs/api#describename-fn), [`Jest.beforeEach`](https://jestjs.io/docs/api#beforeeachfn-timeout), and [`Jest.it`](https://jestjs.io/docs/api#testname-fn-timeout). For more information, see [https://jestjs.io/docs/api](https://jestjs.io/docs/api).
```javascript
import { pactWith } from 'jest-pact';
pactWith(
{
consumer: 'MergeRequests#show',
provider: 'GET discussions',
log: '../logs/consumer.log',
dir: '../contracts/project/merge_requests/show',
},
(provider) => {
describe('GET discussions', () => {
beforeEach(() => {
});
it('return a successful body', async () => {
});
});
},
);
```
## Set up the mock provider
Before you run your test, set up the mock provider that handles the specified requests and returns a specified response. To do that, define the state and the expected request and response in an [`Interaction`](https://github.com/pact-foundation/pact-js/blob/master/src/dsl/interaction.ts).
For this tutorial, define four attributes for the `Interaction`:
1. `state`: A description of what the prerequisite state is before the request is made.
1. `uponReceiving`: A description of what kind of request this `Interaction` is handling.
1. `withRequest`: Where you define the request specifications. It contains the request `method`, `path`, and any `headers`, `body`, or `query`.
1. `willRespondWith`: Where you define the expected response. It contains the response `status`, `headers`, and `body`.
After you define the `Interaction`, add that interaction to the mock provider by calling `addInteraction`.
```javascript
import { pactWith } from 'jest-pact';
import { Matchers } from '@pact-foundation/pact';
pactWith(
{
consumer: 'MergeRequests#show',
provider: 'GET discussions',
log: '../logs/consumer.log',
dir: '../contracts/project/merge_requests/show',
},
(provider) => {
describe('GET discussions', () => {
beforeEach(() => {
const interaction = {
state: 'a merge request with discussions exists',
uponReceiving: 'a request for discussions',
withRequest: {
method: 'GET',
path: '/gitlab-org/gitlab-qa/-/merge_requests/1/discussions.json',
headers: {
Accept: '*/*',
},
},
willRespondWith: {
status: 200,
headers: {
'Content-Type': 'application/json; charset=utf-8',
},
body: Matchers.eachLike({
id: Matchers.string('fd73763cbcbf7b29eb8765d969a38f7d735e222a'),
project_id: Matchers.integer(6954442),
...
resolved: Matchers.boolean(true)
}),
},
};
provider.addInteraction(interaction);
});
it('return a successful body', async () => {
});
});
},
);
```
### Response body `Matchers`
Notice how we use `Matchers` in the `body` of the expected response. This allows us to be flexible enough to accept different values but still be strict enough to distinguish between valid and invalid values. We must ensure that we have a tight definition that is neither too strict nor too lax. Read more about the [different types of `Matchers`](https://github.com/pact-foundation/pact-js/blob/master/docs/matching.md). We are currently using the V2 matching rules.
## Write the test
After the mock provider is set up, you can write the test. For this test, you make a request and expect a particular response.
First, set up the client that makes the API request. To do that, create `spec/contracts/consumer/resources/api/project/merge_requests.js` and add the following API request. If the endpoint is a GraphQL, then we create it under `spec/contracts/consumer/resources/graphql` instead.
```javascript
import axios from 'axios';
export async function getDiscussions(endpoint) {
const { url } = endpoint;
return axios({
method: 'GET',
baseURL: url,
url: '/gitlab-org/gitlab-qa/-/merge_requests/1/discussions.json',
headers: { Accept: '*/*' },
})
}
```
After that's set up, import it to the test file and call it to make the request. Then, you can make the request and define your expectations.
```javascript
import { pactWith } from 'jest-pact';
import { Matchers } from '@pact-foundation/pact';
import { getDiscussions } from '../../../resources/api/project/merge_requests';
pactWith(
{
consumer: 'MergeRequests#show',
provider: 'GET discussions',
log: '../logs/consumer.log',
dir: '../contracts/project/merge_requests/show',
},
(provider) => {
describe('GET discussions', () => {
beforeEach(() => {
const interaction = {
state: 'a merge request with discussions exists',
uponReceiving: 'a request for discussions',
withRequest: {
method: 'GET',
path: '/gitlab-org/gitlab-qa/-/merge_requests/1/discussions.json',
headers: {
Accept: '*/*',
},
},
willRespondWith: {
status: 200,
headers: {
'Content-Type': 'application/json; charset=utf-8',
},
body: Matchers.eachLike({
id: Matchers.string('fd73763cbcbf7b29eb8765d969a38f7d735e222a'),
project_id: Matchers.integer(6954442),
...
resolved: Matchers.boolean(true)
}),
},
};
});
it('return a successful body', async () => {
const discussions = await getDiscussions({
url: provider.mockService.baseUrl,
});
expect(discussions).toEqual(Matchers.eachLike({
id: 'fd73763cbcbf7b29eb8765d969a38f7d735e222a',
project_id: 6954442,
...
resolved: true
}));
});
});
},
);
```
There we have it! The consumer test is now set up. You can now try [running this test](_index.md#run-the-consumer-tests).
## Improve test readability
As you may have noticed, the request and response definitions can get large. This results in the test being difficult to read, with a lot of scrolling to find what you want. You can make the test easier to read by extracting these out to a `fixture`.
Create a file under `spec/contracts/consumer/fixtures/project/merge_requests` called `discussions.fixture.js` where you will place the `request` and `response` definitions.
```javascript
import { Matchers } from '@pact-foundation/pact';
const body = Matchers.eachLike({
id: Matchers.string('fd73763cbcbf7b29eb8765d969a38f7d735e222a'),
project_id: Matchers.integer(6954442),
...
resolved: Matchers.boolean(true)
});
const Discussions = {
body: Matchers.extractPayload(body),
success: {
status: 200,
headers: {
'Content-Type': 'application/json; charset=utf-8',
},
body,
},
scenario: {
state: 'a merge request with discussions exists',
uponReceiving: 'a request for discussions',
},
request: {
withRequest: {
method: 'GET',
path: '/gitlab-org/gitlab-qa/-/merge_requests/1/discussions.json',
headers: {
Accept: '*/*',
},
},
},
};
exports.Discussions = Discussions;
```
With all of that moved to the `fixture`, you can simplify the test to the following:
```javascript
import { pactWith } from 'jest-pact';
import { Discussions } from '../../../fixtures/project/merge_requests/discussions.fixture';
import { getDiscussions } from '../../../resources/api/project/merge_requests';
const CONSUMER_NAME = 'MergeRequests#show';
const PROVIDER_NAME = 'GET discussions';
const CONSUMER_LOG = '../logs/consumer.log';
const CONTRACT_DIR = '../contracts/project/merge_requests/show';
pactWith(
{
consumer: CONSUMER_NAME,
provider: PROVIDER_NAME,
log: CONSUMER_LOG,
dir: CONTRACT_DIR,
},
(provider) => {
describe(PROVIDER_NAME, () => {
beforeEach(() => {
const interaction = {
...Discussions.scenario,
...Discussions.request,
willRespondWith: Discussions.success,
};
provider.addInteraction(interaction);
});
it('return a successful body', async () => {
const discussions = await getDiscussions({
url: provider.mockService.baseUrl,
});
expect(discussions).toEqual(Discussions.body);
});
});
},
);
```
|
---
stage: none
group: unassigned
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: Writing consumer tests
breadcrumbs:
- doc
- development
- testing_guide
- contract
---
This tutorial guides you through writing a consumer test from scratch. To start, the consumer tests are written using [`jest-pact`](https://github.com/pact-foundation/jest-pact) that builds on top of [`pact-js`](https://github.com/pact-foundation/pact-js). This tutorial shows you how to write a consumer test for the `/discussions.json` REST API endpoint, which is `/:namespace_name/:project_name/-/merge_requests/:id/discussions.json`, that is called in the `MergeRequests#show` page. For an example of a GraphQL consumer test, see [`spec/contracts/consumer/specs/project/pipelines/show.spec.js`](https://gitlab.com/gitlab-org/gitlab/-/tree/master/spec/contracts/consumer/specs/project/pipelines/show.spec.js).
## Create the skeleton
Start by creating the skeleton of a consumer test. Since this is for a request in the `MergeRequests#show` page, under `spec/contracts/consumer/specs/project/merge_requests`, create a file called `show.spec.js`.
Then, populate it with the following function and parameters:
- [`pactWith`](#the-pactwith-function)
- [`PactOptions`](#the-pactoptions-parameter)
- [`PactFn`](#the-pactfn-parameter)
For more information about how the contract test directory is structured, see [Test suite folder structure](_index.md#test-suite-folder-structure).
### The `pactWith` function
The Pact consumer test is defined through the `pactWith` function that takes `PactOptions` and the `PactFn`.
```javascript
import { pactWith } from 'jest-pact';
pactWith(PactOptions, PactFn);
```
### The `PactOptions` parameter
`PactOptions` with `jest-pact` introduces [additional options](https://github.com/pact-foundation/jest-pact/blob/dce370c1ab4b7cb5dff12c4b62246dc229c53d0e/README.md#defaults) that build on top of the ones [provided in `pact-js`](https://github.com/pact-foundation/pact-js#constructor). In most cases, you define the `consumer`, `provider`, `log`, and `dir` options for these tests.
```javascript
import { pactWith } from 'jest-pact';
pactWith(
{
consumer: 'MergeRequests#show',
provider: 'GET discussions',
log: '../logs/consumer.log',
dir: '../contracts/project/merge_requests/show',
},
PactFn
);
```
For more information about how to name consumers and providers, see [Naming conventions](_index.md#naming-conventions).
### The `PactFn` parameter
The `PactFn` is where your tests are defined. This is where you set up the mock provider and where you can use the standard Jest methods like [`Jest.describe`](https://jestjs.io/docs/api#describename-fn), [`Jest.beforeEach`](https://jestjs.io/docs/api#beforeeachfn-timeout), and [`Jest.it`](https://jestjs.io/docs/api#testname-fn-timeout). For more information, see [https://jestjs.io/docs/api](https://jestjs.io/docs/api).
```javascript
import { pactWith } from 'jest-pact';
pactWith(
{
consumer: 'MergeRequests#show',
provider: 'GET discussions',
log: '../logs/consumer.log',
dir: '../contracts/project/merge_requests/show',
},
(provider) => {
describe('GET discussions', () => {
beforeEach(() => {
});
it('return a successful body', async () => {
});
});
},
);
```
## Set up the mock provider
Before you run your test, set up the mock provider that handles the specified requests and returns a specified response. To do that, define the state and the expected request and response in an [`Interaction`](https://github.com/pact-foundation/pact-js/blob/master/src/dsl/interaction.ts).
For this tutorial, define four attributes for the `Interaction`:
1. `state`: A description of what the prerequisite state is before the request is made.
1. `uponReceiving`: A description of what kind of request this `Interaction` is handling.
1. `withRequest`: Where you define the request specifications. It contains the request `method`, `path`, and any `headers`, `body`, or `query`.
1. `willRespondWith`: Where you define the expected response. It contains the response `status`, `headers`, and `body`.
After you define the `Interaction`, add that interaction to the mock provider by calling `addInteraction`.
```javascript
import { pactWith } from 'jest-pact';
import { Matchers } from '@pact-foundation/pact';
pactWith(
{
consumer: 'MergeRequests#show',
provider: 'GET discussions',
log: '../logs/consumer.log',
dir: '../contracts/project/merge_requests/show',
},
(provider) => {
describe('GET discussions', () => {
beforeEach(() => {
const interaction = {
state: 'a merge request with discussions exists',
uponReceiving: 'a request for discussions',
withRequest: {
method: 'GET',
path: '/gitlab-org/gitlab-qa/-/merge_requests/1/discussions.json',
headers: {
Accept: '*/*',
},
},
willRespondWith: {
status: 200,
headers: {
'Content-Type': 'application/json; charset=utf-8',
},
body: Matchers.eachLike({
id: Matchers.string('fd73763cbcbf7b29eb8765d969a38f7d735e222a'),
project_id: Matchers.integer(6954442),
...
resolved: Matchers.boolean(true)
}),
},
};
provider.addInteraction(interaction);
});
it('return a successful body', async () => {
});
});
},
);
```
### Response body `Matchers`
Notice how we use `Matchers` in the `body` of the expected response. This allows us to be flexible enough to accept different values but still be strict enough to distinguish between valid and invalid values. We must ensure that we have a tight definition that is neither too strict nor too lax. Read more about the [different types of `Matchers`](https://github.com/pact-foundation/pact-js/blob/master/docs/matching.md). We are currently using the V2 matching rules.
## Write the test
After the mock provider is set up, you can write the test. For this test, you make a request and expect a particular response.
First, set up the client that makes the API request. To do that, create `spec/contracts/consumer/resources/api/project/merge_requests.js` and add the following API request. If the endpoint is a GraphQL, then we create it under `spec/contracts/consumer/resources/graphql` instead.
```javascript
import axios from 'axios';
export async function getDiscussions(endpoint) {
const { url } = endpoint;
return axios({
method: 'GET',
baseURL: url,
url: '/gitlab-org/gitlab-qa/-/merge_requests/1/discussions.json',
headers: { Accept: '*/*' },
})
}
```
After that's set up, import it to the test file and call it to make the request. Then, you can make the request and define your expectations.
```javascript
import { pactWith } from 'jest-pact';
import { Matchers } from '@pact-foundation/pact';
import { getDiscussions } from '../../../resources/api/project/merge_requests';
pactWith(
{
consumer: 'MergeRequests#show',
provider: 'GET discussions',
log: '../logs/consumer.log',
dir: '../contracts/project/merge_requests/show',
},
(provider) => {
describe('GET discussions', () => {
beforeEach(() => {
const interaction = {
state: 'a merge request with discussions exists',
uponReceiving: 'a request for discussions',
withRequest: {
method: 'GET',
path: '/gitlab-org/gitlab-qa/-/merge_requests/1/discussions.json',
headers: {
Accept: '*/*',
},
},
willRespondWith: {
status: 200,
headers: {
'Content-Type': 'application/json; charset=utf-8',
},
body: Matchers.eachLike({
id: Matchers.string('fd73763cbcbf7b29eb8765d969a38f7d735e222a'),
project_id: Matchers.integer(6954442),
...
resolved: Matchers.boolean(true)
}),
},
};
});
it('return a successful body', async () => {
const discussions = await getDiscussions({
url: provider.mockService.baseUrl,
});
expect(discussions).toEqual(Matchers.eachLike({
id: 'fd73763cbcbf7b29eb8765d969a38f7d735e222a',
project_id: 6954442,
...
resolved: true
}));
});
});
},
);
```
There we have it! The consumer test is now set up. You can now try [running this test](_index.md#run-the-consumer-tests).
## Improve test readability
As you may have noticed, the request and response definitions can get large. This results in the test being difficult to read, with a lot of scrolling to find what you want. You can make the test easier to read by extracting these out to a `fixture`.
Create a file under `spec/contracts/consumer/fixtures/project/merge_requests` called `discussions.fixture.js` where you will place the `request` and `response` definitions.
```javascript
import { Matchers } from '@pact-foundation/pact';
const body = Matchers.eachLike({
id: Matchers.string('fd73763cbcbf7b29eb8765d969a38f7d735e222a'),
project_id: Matchers.integer(6954442),
...
resolved: Matchers.boolean(true)
});
const Discussions = {
body: Matchers.extractPayload(body),
success: {
status: 200,
headers: {
'Content-Type': 'application/json; charset=utf-8',
},
body,
},
scenario: {
state: 'a merge request with discussions exists',
uponReceiving: 'a request for discussions',
},
request: {
withRequest: {
method: 'GET',
path: '/gitlab-org/gitlab-qa/-/merge_requests/1/discussions.json',
headers: {
Accept: '*/*',
},
},
},
};
exports.Discussions = Discussions;
```
With all of that moved to the `fixture`, you can simplify the test to the following:
```javascript
import { pactWith } from 'jest-pact';
import { Discussions } from '../../../fixtures/project/merge_requests/discussions.fixture';
import { getDiscussions } from '../../../resources/api/project/merge_requests';
const CONSUMER_NAME = 'MergeRequests#show';
const PROVIDER_NAME = 'GET discussions';
const CONSUMER_LOG = '../logs/consumer.log';
const CONTRACT_DIR = '../contracts/project/merge_requests/show';
pactWith(
{
consumer: CONSUMER_NAME,
provider: PROVIDER_NAME,
log: CONSUMER_LOG,
dir: CONTRACT_DIR,
},
(provider) => {
describe(PROVIDER_NAME, () => {
beforeEach(() => {
const interaction = {
...Discussions.scenario,
...Discussions.request,
willRespondWith: Discussions.success,
};
provider.addInteraction(interaction);
});
it('return a successful body', async () => {
const discussions = await getDiscussions({
url: provider.mockService.baseUrl,
});
expect(discussions).toEqual(Discussions.body);
});
});
},
);
```
|
https://docs.gitlab.com/development/testing_guide/provider_tests
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/testing_guide/provider_tests.md
|
2025-08-13
|
doc/development/testing_guide/contract
|
[
"doc",
"development",
"testing_guide",
"contract"
] |
provider_tests.md
|
none
|
unassigned
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Writing provider tests
| null |
This tutorial guides you through writing a provider test from scratch. It is a continuation of the [consumer test tutorial](consumer_tests.md). To start, the provider tests are written using [`pact-ruby`](https://github.com/pact-foundation/pact-ruby). In this tutorial, you write a provider test that addresses the contract generated by `discussions.spec.js`. As Pact is a consumer-driven testing tool, this tutorial assumes that there is an existing consumer test that had already generated a contract for us to work with.
## Create the skeleton
Provider tests are quite simple. The goal is to set up the test data and then link that with the corresponding contract. Start by creating a file called `get_discussions_helper.rb` under `spec/contracts/provider/pact_helpers/project/merge_request`. The files are called `helpers` to match how they are called by Pact in the Rake tasks, which are set up at the end of this tutorial.
For more information about how the contract test directory is structured, see [Test suite folder structure](_index.md#test-suite-folder-structure).
### The `service_provider` block
The `service_provider` block is where the provider test is defined. For this block, put in a description of the service provider. Name it exactly as it is called in the contracts that are derived from the consumer tests.
```ruby
require_relative '../../../spec_helper'
module Provider
module DiscussionsHelper
Pact.service_provider 'GET discussions' do
end
end
end
```
### The `honours_pact_with` block
The `honours_pact_with` block describes which consumer this provider test is addressing. Similar to the `service_provider` block, name this exactly the same as it's called in the contracts that are derived from the consumer tests.
```ruby
require_relative '../../../spec_helper'
module Provider
module DiscussionsHelper
Pact.service_provider 'GET discussions' do
honours_pact_with 'MergeRequests#show' do
end
end
end
end
```
For more information about how to name consumers and providers, see [Naming conventions](_index.md#naming-conventions).
## Configure the test app
For the provider tests to verify the contracts, you must hook it up to a test app that makes the actual request and return a response to verify against the contract. To do this, configure the `app` the test uses as `Environment::Test.app`, which is defined in [`spec/contracts/provider/environments/test.rb`](https://gitlab.com/gitlab-org/gitlab/-/tree/master/spec/contracts/provider/environments/test.rb).
```ruby
require_relative '../../../spec_helper'
module Provider
module DiscussionsHelper
Pact.service_provider 'GET discussions' do
app { Environment::Test.app }
honours_pact_with 'MergeRequests#show' do
end
end
end
end
```
## Define the contract to verify
Now that the test app is configured, all that is left is to define which contract this provider test is verifying. To do this, set the `pact_uri`.
```ruby
require_relative '../../../spec_helper'
module Provider
module DiscussionsHelper
Pact.service_provider 'GET discussions' do
app { Environment::Test.app }
honours_pact_with 'MergeRequests#show' do
pact_uri '../contracts/project/merge_requests/show/mergerequests#show-merge_request_discussions_endpoint.json'
end
end
end
end
```
## Add / update the Rake tasks
Now that you have a test created, you must create Rake tasks that run this test. The Rake tasks are defined in [`lib/tasks/contracts/merge_requests.rake`](https://gitlab.com/gitlab-org/gitlab/-/tree/master/lib/tasks/contracts/merge_requests.rake) where we have individual Rake tasks to run individual tests, but also Rake tasks that run a group of tests.
Under the `contracts:merge_requests` namespace, introduce the Rake task to run this new test specifically. In it, call `pact.uri` to define the location of the contract and the provider test that tests that contract. Notice here that `pact_uri` has a parameter called `pact_helper`. This is why the provider tests are called `_helper.rb`.
```ruby
Pact::VerificationTask.new(:get_discussions) do |pact|
provider = File.expand_path('../../../spec/contracts/provider', __dir__)
pact_helper_location = "pact_helpers/project/merge_requests/show/get_discussions_helper.rb"
pact.uri(
Provider::ContractSourceHelper.contract_location(:rake, pact_helper_location),
pact_helper: "#{provider}/#{pact_helper_location}"
)
end
```
[`Provider::ContractSourceHelper`](https://gitlab.com/gitlab-org/gitlab/-/tree/master/spec/contracts/provider/helpers/contract_source_helper.rb) is a helper module that has the `#contract_location` method which parses `pact_helper_location` and determines where the contract is stored locally or on the Pact Broker depending on the `requester` passed in.
At the same time, add your new `:get_discussions` Rake task to be included in the `test:merge_requests` Rake task. In that Rake task, there is an array defined (`%w[get_diffs_batch get_diffs_metadata]`). You must add `get_discussions` in that list.
## Create test data
As the last step, create the test data that allows the provider test to return the contract's expected response. You might wonder why you create the test data last. It's really a matter of preference. With the test already configured, you can easily run the test to verify and make sure all the necessary test data are created to produce the expected response.
You can read more about [provider states](https://docs.pact.io/implementation_guides/ruby/provider_states). We can do global provider states but for this tutorial, the provider state is for one specific `state`.
To create the test data, create `show_state.rb` under `spec/contracts/provider/states/project/merge_requests`. Be sure to also import this state file in the `get_discussions_helper.rb` file.
### Default user in `spec/contracts/provider/spec_helper.rb`
Before you create the test data, a default user is created in the [`spec_helper`](https://gitlab.com/gitlab-org/gitlab/-/tree/master/spec/contracts/provider/spec_helper.rb), which is the user being used for the test runs. This user is configured using `RSpec.configure`, as Pact actually is built on top of RSpec. This step allows us to configure the user before any of the test runs.
```ruby
RSpec.configure do |config|
config.include Devise::Test::IntegrationHelpers
config.include FactoryBot::Syntax::Methods
config.before do
user = create(:user, name: Provider::UsersHelper::CONTRACT_USER_NAME).tap do |user|
user.current_sign_in_at = Time.current
end
sign_in user
end
end
```
Any further modifications to the user that's needed can be done through the individual provider state files.
### The `provider_states_for` block
In the state file, you must define which consumer this provider state is for. You can do that with `provider_states_for`. Make sure that the `name` provided matches the name defined for the consumer.
```ruby
Pact.provider_states_for 'MergeRequests#show' do
end
```
### The `provider_state` block
In the `provider_states_for` block, you then define the state the test data is for. These states are also defined in the consumer test. In this case, there is a `'a merge request with discussions exists'` state.
```ruby
Pact.provider_states_for "MergeRequests#show" do
provider_state "a merge request with discussions exists" do
end
end
```
### The `set_up` block
This is where you define the test data creation steps. Use `FactoryBot` to create the data. As you create the test data, you can keep [running the provider test](_index.md#run-the-provider-tests) to check on the status of the test and figure out what else is missing in your data setup.
```ruby
Pact.provider_states_for "MergeRequests#show" do
provider_state "a merge request with discussions exists" do
set_up do
user = User.find_by(name: Provider::UsersHelper::CONTRACT_USER_NAME)
namespace = create(:namespace, name: 'gitlab-org')
project = create(:project, name: 'gitlab-qa', namespace: namespace)
project.add_maintainer(user)
merge_request = create(:merge_request_with_diffs, id: 1, source_project: project, author: user)
create(:discussion_note_on_merge_request, noteable: merge_request, project: project, author: user)
end
end
end
```
## Using the test data
Now that the provider state file is created, you need to import the state file to the provider test.
```ruby
# frozen_string_literal: true
require_relative '../../../spec_helper'
require_relative '../../../states/project/merge_requests/show_state'
module Provider
module DiscussionsHelper
Pact.service_provider "GET discussions" do
app { Environments::Test.app }
honours_pact_with 'Merge Request#show' do
pact_uri '../contracts/project/merge_requests/show/mergerequests#show-merge_request_discussions_endpoint.json'
end
end
end
end
```
And there we have it. The provider test for `get_discussions_helper.rb` should now pass with this.
|
---
stage: none
group: unassigned
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: Writing provider tests
breadcrumbs:
- doc
- development
- testing_guide
- contract
---
This tutorial guides you through writing a provider test from scratch. It is a continuation of the [consumer test tutorial](consumer_tests.md). To start, the provider tests are written using [`pact-ruby`](https://github.com/pact-foundation/pact-ruby). In this tutorial, you write a provider test that addresses the contract generated by `discussions.spec.js`. As Pact is a consumer-driven testing tool, this tutorial assumes that there is an existing consumer test that had already generated a contract for us to work with.
## Create the skeleton
Provider tests are quite simple. The goal is to set up the test data and then link that with the corresponding contract. Start by creating a file called `get_discussions_helper.rb` under `spec/contracts/provider/pact_helpers/project/merge_request`. The files are called `helpers` to match how they are called by Pact in the Rake tasks, which are set up at the end of this tutorial.
For more information about how the contract test directory is structured, see [Test suite folder structure](_index.md#test-suite-folder-structure).
### The `service_provider` block
The `service_provider` block is where the provider test is defined. For this block, put in a description of the service provider. Name it exactly as it is called in the contracts that are derived from the consumer tests.
```ruby
require_relative '../../../spec_helper'
module Provider
module DiscussionsHelper
Pact.service_provider 'GET discussions' do
end
end
end
```
### The `honours_pact_with` block
The `honours_pact_with` block describes which consumer this provider test is addressing. Similar to the `service_provider` block, name this exactly the same as it's called in the contracts that are derived from the consumer tests.
```ruby
require_relative '../../../spec_helper'
module Provider
module DiscussionsHelper
Pact.service_provider 'GET discussions' do
honours_pact_with 'MergeRequests#show' do
end
end
end
end
```
For more information about how to name consumers and providers, see [Naming conventions](_index.md#naming-conventions).
## Configure the test app
For the provider tests to verify the contracts, you must hook it up to a test app that makes the actual request and return a response to verify against the contract. To do this, configure the `app` the test uses as `Environment::Test.app`, which is defined in [`spec/contracts/provider/environments/test.rb`](https://gitlab.com/gitlab-org/gitlab/-/tree/master/spec/contracts/provider/environments/test.rb).
```ruby
require_relative '../../../spec_helper'
module Provider
module DiscussionsHelper
Pact.service_provider 'GET discussions' do
app { Environment::Test.app }
honours_pact_with 'MergeRequests#show' do
end
end
end
end
```
## Define the contract to verify
Now that the test app is configured, all that is left is to define which contract this provider test is verifying. To do this, set the `pact_uri`.
```ruby
require_relative '../../../spec_helper'
module Provider
module DiscussionsHelper
Pact.service_provider 'GET discussions' do
app { Environment::Test.app }
honours_pact_with 'MergeRequests#show' do
pact_uri '../contracts/project/merge_requests/show/mergerequests#show-merge_request_discussions_endpoint.json'
end
end
end
end
```
## Add / update the Rake tasks
Now that you have a test created, you must create Rake tasks that run this test. The Rake tasks are defined in [`lib/tasks/contracts/merge_requests.rake`](https://gitlab.com/gitlab-org/gitlab/-/tree/master/lib/tasks/contracts/merge_requests.rake) where we have individual Rake tasks to run individual tests, but also Rake tasks that run a group of tests.
Under the `contracts:merge_requests` namespace, introduce the Rake task to run this new test specifically. In it, call `pact.uri` to define the location of the contract and the provider test that tests that contract. Notice here that `pact_uri` has a parameter called `pact_helper`. This is why the provider tests are called `_helper.rb`.
```ruby
Pact::VerificationTask.new(:get_discussions) do |pact|
provider = File.expand_path('../../../spec/contracts/provider', __dir__)
pact_helper_location = "pact_helpers/project/merge_requests/show/get_discussions_helper.rb"
pact.uri(
Provider::ContractSourceHelper.contract_location(:rake, pact_helper_location),
pact_helper: "#{provider}/#{pact_helper_location}"
)
end
```
[`Provider::ContractSourceHelper`](https://gitlab.com/gitlab-org/gitlab/-/tree/master/spec/contracts/provider/helpers/contract_source_helper.rb) is a helper module that has the `#contract_location` method which parses `pact_helper_location` and determines where the contract is stored locally or on the Pact Broker depending on the `requester` passed in.
At the same time, add your new `:get_discussions` Rake task to be included in the `test:merge_requests` Rake task. In that Rake task, there is an array defined (`%w[get_diffs_batch get_diffs_metadata]`). You must add `get_discussions` in that list.
## Create test data
As the last step, create the test data that allows the provider test to return the contract's expected response. You might wonder why you create the test data last. It's really a matter of preference. With the test already configured, you can easily run the test to verify and make sure all the necessary test data are created to produce the expected response.
You can read more about [provider states](https://docs.pact.io/implementation_guides/ruby/provider_states). We can do global provider states but for this tutorial, the provider state is for one specific `state`.
To create the test data, create `show_state.rb` under `spec/contracts/provider/states/project/merge_requests`. Be sure to also import this state file in the `get_discussions_helper.rb` file.
### Default user in `spec/contracts/provider/spec_helper.rb`
Before you create the test data, a default user is created in the [`spec_helper`](https://gitlab.com/gitlab-org/gitlab/-/tree/master/spec/contracts/provider/spec_helper.rb), which is the user being used for the test runs. This user is configured using `RSpec.configure`, as Pact actually is built on top of RSpec. This step allows us to configure the user before any of the test runs.
```ruby
RSpec.configure do |config|
config.include Devise::Test::IntegrationHelpers
config.include FactoryBot::Syntax::Methods
config.before do
user = create(:user, name: Provider::UsersHelper::CONTRACT_USER_NAME).tap do |user|
user.current_sign_in_at = Time.current
end
sign_in user
end
end
```
Any further modifications to the user that's needed can be done through the individual provider state files.
### The `provider_states_for` block
In the state file, you must define which consumer this provider state is for. You can do that with `provider_states_for`. Make sure that the `name` provided matches the name defined for the consumer.
```ruby
Pact.provider_states_for 'MergeRequests#show' do
end
```
### The `provider_state` block
In the `provider_states_for` block, you then define the state the test data is for. These states are also defined in the consumer test. In this case, there is a `'a merge request with discussions exists'` state.
```ruby
Pact.provider_states_for "MergeRequests#show" do
provider_state "a merge request with discussions exists" do
end
end
```
### The `set_up` block
This is where you define the test data creation steps. Use `FactoryBot` to create the data. As you create the test data, you can keep [running the provider test](_index.md#run-the-provider-tests) to check on the status of the test and figure out what else is missing in your data setup.
```ruby
Pact.provider_states_for "MergeRequests#show" do
provider_state "a merge request with discussions exists" do
set_up do
user = User.find_by(name: Provider::UsersHelper::CONTRACT_USER_NAME)
namespace = create(:namespace, name: 'gitlab-org')
project = create(:project, name: 'gitlab-qa', namespace: namespace)
project.add_maintainer(user)
merge_request = create(:merge_request_with_diffs, id: 1, source_project: project, author: user)
create(:discussion_note_on_merge_request, noteable: merge_request, project: project, author: user)
end
end
end
```
## Using the test data
Now that the provider state file is created, you need to import the state file to the provider test.
```ruby
# frozen_string_literal: true
require_relative '../../../spec_helper'
require_relative '../../../states/project/merge_requests/show_state'
module Provider
module DiscussionsHelper
Pact.service_provider "GET discussions" do
app { Environments::Test.app }
honours_pact_with 'Merge Request#show' do
pact_uri '../contracts/project/merge_requests/show/mergerequests#show-merge_request_discussions_endpoint.json'
end
end
end
end
```
And there we have it. The provider test for `get_discussions_helper.rb` should now pass with this.
|
https://docs.gitlab.com/development/testing_guide/debugging_end_to_end_test_failures
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/testing_guide/debugging_end_to_end_test_failures.md
|
2025-08-13
|
doc/development/testing_guide/end_to_end
|
[
"doc",
"development",
"testing_guide",
"end_to_end"
] |
debugging_end_to_end_test_failures.md
| null | null | null |
Debugging Failing Tests and Test Pipelines
|
Guidelines for investigating end-to-end test pipeline failures
|
## Overview
This page outlines steps for investigating [end-to-end test](_index.md) failures, deployments, and troubleshooting various GitLab environments. It provides information on how to handle failures, identifying the problematic commit, the logging tools, and ways to reproduce the failure.
## Special considerations for investigating specific environments
### Staging-Canary
`Staging-Canary` is unique when it comes to its blocking `smoke` tests that are triggered by the `deployer` pipeline. `Staging-Canary` executes `smoke` tests for both `Staging-Canary` AND `Staging` environments. This special configuration is designed to help catch issues that occur when incompatibilities arise between the shared and non-shared components of the environments.
`Staging-Canary` and `Staging` both share the same database backend, for example. Should a migration or change to either of the non-shared components during a deployment create an issue, running these tests together helps expose this situation. When the `deployer` pipeline triggers these test runs, they are reported serially in the `#qa_staging` Slack channel and they appear as different runs.
Note when viewing a deployment failure from the `#announcements` Slack channel, you will have to click into the pipeline and look at the `Downstream` results to understand if the deployment failure arose from a failure in `Staging-Canary` or if the failure occurred in `Staging`.
Visit the [announcement issue](https://gitlab.com/gitlab-com/gl-infra/delivery/-/issues/2280) for more context
and to view an uncompressed version of the following image:

Note the diagram has been updated as part of increasing rollback availability by removing the [blocking nature of post-deployment migrations](https://gitlab.com/groups/gitlab-com/gl-infra/-/epics/585).
### Staging Ref
[Staging Ref](https://handbook.gitlab.com/handbook/engineering/infrastructure/environments/staging-ref/) is a Sandbox environment used for pre-production testing of the latest Staging Canary code. It is a shared
environment with wide access permissions and as a result of engineers testing their code, the environment may become unstable and may need to be rebuilt.
The full or smoke E2E test suite can be triggered on an as-needed basis from the `staging-ref` project's [pipeline schedules](https://ops.gitlab.net/gitlab-org/quality/staging-ref/-/pipeline_schedules).
Staging Ref deployment runs parallel to Staging Canary deployment. These two environments share the same GitLab version, if a failure happens
on Staging Ref but not on Staging Canary, it may indicate that the failure is environment specific. See [QA pipeline debugging guide](https://gitlab.com/gitlab-org/quality/gitlab-environment-toolkit-configs/staging-ref/-/blob/main/doc/qa_failure_debug.md) for more information on how to investigate E2E test failures.
### Preprod
[Preprod](https://handbook.gitlab.com/handbook/engineering/infrastructure/environments/#pre) is used to perform validation of release candidates. Every month around the [release date](https://handbook.gitlab.com/handbook/engineering/releases/), and the few days before, it is essential that there are no unexpected failures in the pipeline that will delay the release. There is a pipeline scheduled to run prior to deployment of the release candidate, to give us a chance to identify and resolve any issues with tests or the test environment. This scheduled pipeline should be given equal priority with `Production` and `Staging` pipelines because of the potential impact failures can have on a release.
Tests pipelines are also triggered by the [Kubernetes Workload configuration project](https://gitlab.com/gitlab-com/gl-infra/k8s-workloads/gitlab-com) to ensure that any configuration changes are valid.
### Nightly
[Omnibus nightly builds](https://dev.gitlab.org/gitlab/omnibus-gitlab/-/pipeline_schedules) are paused at the start of a security release and enabled again once the release is complete.
This can cause the nightly tests to either run against an outdated package or fail during the `ce:sanity-version` and `ee:sanity-version` jobs when mirroring is down.
The `#quality` Slack channel should receive two notifications:
1. An announcement from the release team when the security release has started.
1. A notification from GitLab ChatOps when the security release has been published.
For other ways to check if there is an ongoing security release, you can visit the `#releases` Slack channel's `Next Security Release` bookmark, or [search the GitLab project's issues by the `~"upcoming security release"` label](https://gitlab.com/gitlab-org/gitlab/-/issues/?sort=created_date&state=opened&label_name%5B%5D=upcoming%20security%20release&first_page_size=20).
Please note that a security release issue can sometimes be created before a release is in progress.
If you have any questions on the status, you can also reach out to the `@release-managers` in Slack.
### `master` pipelines
GitLab `master` has three QA pipelines generated from scheduled pipeline against the default branch:
- [`test-on-omnibus`](_index.md#using-the-test-on-omnibus-job) runs the `full` suite of end-to-end tests against an omnibus Docker image built from `master`
- [`test-on-gdk`](_index.md#selective-test-execution-based-on-code-path-mappings) runs the full suite of end-to-end tests as part of the `gdk-instance` job against a GDK instance from a Docker image built from `master`
If jobs in `test-on-omnibus` failed due to a GitLab Docker image issue, reach out to the [Distribution team](https://handbook.gitlab.com/handbook/engineering/infrastructure-platforms/gitlab-delivery/distribution/) to see if it's a known problem with the build.
If failures occur only in `test-on-gdk` jobs, it's possible to stop those jobs from being added to new pipelines while the cause is being fixed. See the [runbook](https://gitlab.com/gitlab-org/quality/runbooks/-/tree/97483eafd3db198437faccc40a946fc260c0736a/test_on_gdk#disable-the-e2etest-on-gdk-pipeline) for details.
Note that any failure in `master` QA pipeline will be deployed to Staging, so catching a failure earlier in the pipeline allows us to
find what changes caused it and act on resolving the failure more quickly.
## Verifying current environment version
### Determine the version, revision, branch and package deployed in GitLab environments
To find out the version, revision, branch and package deployed in GitLab.com, staging and canary environments,
run this in the #chat-ops-test Slack channel:
```shell
/chatops run auto_deploy status
```

You will [need access to the https://ops.gitlab.net/gitlab-com/chatops](../../chatops_on_gitlabcom.md#requesting-access) project to run `/chatops` commands.
Ask to be added to this project in the #development Slack channel.
### Determine if a change has been deployed to an environment using revision SHA
If you have a revision SHA that is deployed on an environment, you can find out if a change has made it to that environment.
For example, if the revision SHA deployed on an environment is `c46489109e4` and you want to find out if a change in
`restrict_by_ip_address_spec.rb` has made it there, you can use:
```shell
git show c46489109e4:qa/qa/specs/features/ee/browser_ui/1_manage/group/restrict_by_ip_address_spec.rb
```
You can determine the revision SHA deployed on a GitLab instance by either navigating to <https://www.example.com/help>,
by calling the `https://www.example.com/api/v4/version` API or by running `/chatops run auto_deploy status` in a Slack
channel such as #chat-ops-test.
You can also determine if your commit has been deployed on a GitLab environment using [ChatOps](../../../ci/chatops/_index.md).
For example, if your commit ref is `347e530c5b3dec60c0ce2870bc79ca4c8273604d` you can run this command in a Slack
channel such as #chat-ops-test:
```shell
/chatops run auto_deploy status 347e530c5b3dec60c0ce2870bc79ca4c8273604d
```
### Determine the commit SHA of a nightly image
The commit SHA for a nightly pipeline can be determined in the following ways:
#### By visiting the /help page or calling the `/api/v4/version` API
Run the nightly Docker image
```shell
docker run \
--hostname localhost \
--publish 443:443 --publish 80:80 --publish 22:22 \
gitlab/gitlab-ee:nightly
```
The commit SHA can be determined by visiting the <http://localhost/help> page after sign-in
or by calling the [`/api/v4/version` API](../../../api/version.md) where it is displayed as a value of the `revision` attribute.
#### By inspecting the pipeline that created the nightly image
Nightly images are created by scheduled pipelines here: <https://dev.gitlab.org/gitlab/omnibus-gitlab/pipeline_schedules>
You can look at the last pipeline by clicking the pipeline number for CE nightly or EE nightly under
the "Last pipeline" column.
In the pipeline view click a job under the "GitLab_com:package" column. The SHAs for GitLab Components
are listed towards the end of the logs. The GitLab commit SHA is displayed as a value of `gitlab-rails`.
### Checking Docker images
Sometimes tests may fail due to an outdated Docker image. To check if that's the case, follow the instructions below to see if specific merged code is available in a Docker image.
#### Checking test code (QA image)
If you suspect that certain test is failing due to the `gitlab/gitlab-{ce|ee}-qa` image being outdated, follow these steps:
1. Locally, run `docker run -it --entrypoint /bin/sh gitlab/gitlab-ce-qa:latest` to check for GitLab QA CE code, or `docker run -it --entrypoint /bin/sh gitlab/gitlab-ee-qa:latest` to check for GitLab QA EE code
1. Then, navigate to the `qa` directory (`cd /home/qa/qa`)
1. Finally, use `cat` to see if the code you're looking for is available in certain file (e.g., `cat page/project/issue/show.rb`)
> **Note** if you need to check in another tag (e.g., `nightly`), change it in one of the scripts of step 1 above.
#### Checking application code
1. Locally, run `docker run -it --entrypoint /bin/sh gitlab/gitlab-ce:latest` to check for GitLab CE code, or `docker run -it --entrypoint /bin/sh gitlab/gitlab-ee:latest` to check for GitLab EE code
1. Then, navigate to the `gitlab-rails` directory (`cd /opt/gitlab/embedded/service/gitlab-rails/`)
1. Finally, use `cat` to see if the code you're looking for is available or not in a certain file (e.g., `cat public/assets/issues_analytics/components/issues_analytics-9c3887211ed5aa599c9eea63836486d04605f5dfdd76c49f9b05cc24b103f78a.vue`.)
> **Note** if you want to check another tag (e.g., `nightly`) change it in one of the scripts of step 1 above.
#### Checking application version has the specific MR
1. Find the version which GitLab application is running on. In the failing job logs, search for `docker pull dev.gitlab.org:5005/gitlab/omnibus-gitlab/gitlab-ee-qa` and use the version specified after `gitlab-ee-qa:`.
- For nightly, the approach above won't work. There are two ways for finding the commit version of nightly:
- Run the [nightly image on local](#run-the-test-against-a-gitlab-docker-container), sign-in as admin and navigate to `/help` page or call the `/api/v4/version` API.
- Search for the commit in the [omnibus-GitLab pipeline](https://dev.gitlab.org/gitlab/omnibus-gitlab/-/pipelines) that built the last nightly. Jobs that build nightly have `bundle exec rake docker:push:nightly` command in the `Docker-branch` job of the `Package-and-image` stage. Once you find the latest pipeline, search for `gitlab-rails` under `build-component_shas` in any job under the `Gitlab_com:package` stage. For example, in [this `Ubuntu-16.04-branch` job](https://dev.gitlab.org/gitlab/omnibus-gitlab/-/jobs/9610785#L3373), the commit SHA for `gitlab-rails` is `32e76bc4fb02a615c2bf5a00a8fceaee7812a6bd`.
1. Open commits list for the specific version:
- If version format is like a commit SHA, for example `gitlab-ee-qa:13.10-4b373026c98`, navigate to `https://gitlab.com/gitlab-org/gitlab/-/commits/<commit_SHA>` page, in our example the commit SHA is `4b373026c98`.
- If version format is like a tag, for example `13.10.0-rc20210223090520-ee`, navigate to `https://gitlab.com/gitlab-org/gitlab/-/commits/v<tag>` page, in our example the tag is `13.10.0-rc20210223090520-ee`.
- If page above returns 404 error, check if the version exists in [GitLab Security repo](https://gitlab.com/gitlab-org/security/gitlab) in case there is a security release.
1. Check if the MR that you were searching for is in this version.
- Note the branch name of the MR.
- Search the commits from Step 2 by the branch name.
- If the commit is found, the MR is in this version. For [example](https://gitlab.com/gitlab-org/gitlab/-/commits/v13.10.0-rc20210223090520-ee?utf8=%E2%9C%93&search=add-share-with-group-to-modal).
- If no results, the MR is not in this version. For [example](https://gitlab.com/gitlab-org/gitlab/-/commits/v13.10.0-rc20210223090520-ee?utf8=%E2%9C%93&search=qa-shl-add-requries-admin).
## Test failure logs
The following can help with your investigation:
| Log or artifact | Notes |
|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| [Stack trace](../../../ci/quick_start/_index.md#view-the-status-of-your-pipeline-and-jobs) | Shown in the job's log; the starting point for investigating the test failure |
| [Screenshots and HTML captures](../../../ci/jobs/job_artifacts.md#browse-the-contents-of-the-artifacts-archive) | Available for download in the job's artifact for up to 1 week after the job run |
| [QA Logs](../../../ci/jobs/job_artifacts.md#browse-the-contents-of-the-artifacts-archive) | Included in the job's artifacts; valuable for determining the steps taken by the tests before failing |
| [System Logs](../../../administration/logs/_index.md) (GitLab-rails, Sidekiq, etc.) | Included in the job's artifacts for containerized test runs, such as master and nightly. These are useful for investigating errors originating from the GitLab application itself. <br/><br /> A summary of the system logs related to a test failure can also be found in the description of QA failure issues generated from master and nightly runs containing a correlation ID. |
| Sentry logs ([Staging](https://new-sentry.gitlab.net/organizations/gitlab/issues/?environment=gstg), [Staging Ref](https://new-sentry.gitlab.net/organizations/gitlab/projects/staging-ref), [Preprod](https://new-sentry.gitlab.net/organizations/gitlab/issues/?environment=pre), [Production](https://sentry.gitlab.net/gitlab/gitlabcom/)) | If staging, preprod or production tests fail due to a server error, there should be a record in [Sentry](https://handbook.gitlab.com/handbook/support/workflows/sentry/). For example, you can search for all unresolved staging errors linked to the `gitlab-qa` user with the query [`is:unresolved user:"username:gitlab-qa"`](https://new-sentry.gitlab.net/organizations/gitlab/issues/?environment=gstg&query=is%3Aunresolved+user%3Ausername%3Agitlab-qa). However, note that some actions aren't linked to the `gitlab-qa` user, so they might only appear in the [full unresolved list](https://new-sentry.gitlab.net/organizations/gitlab/issues/?environment=gstg). |
| Kibana logs ([Staging and Preprod](https://nonprod-log.gitlab.net/app/kibana#/discover), [Production](https://log.gprd.gitlab.net/app/kibana#/discover)) | Various system logs from live environments are sent to [Kibana](https://handbook.gitlab.com/handbook/support/workflows/kibana/), including Rails, Postgres, Sidekiq, and Gitaly logs. <br><br>**Note**: Staging and Preprod logs both use the same URL, but the search index pattern will be different. Staging indices contain `gstg` while Preprod contains `pre`. For example, to search within the Staging Rails index, you would change the index pattern dropdown value to `pubsub-rails-inf-gstg*`. More information on how to do this can be found [here](https://handbook.gitlab.com/handbook/support/workflows/kibana/#parameters). |
### Kibana and Sentry Logs
When a request fails in an E2E test that results in an error from the server, the job logs will print a link with the relevant correlation ID to logs in Sentry and Kibana for environments where these are available.
For Kibana, there will be two links available. One directs to a singular search against the Rails index in Kibana Discover, and another directs to the QA Correlation Dashboard, which contain panels of search results from multiple GitLab components.
### Kibana Correlation Dashboards
We have QA Correlation Dashboards in Kibana to help organize logs from various GitLab components (e.g., Rails, Gitaly, Postgres, etc.) that are related to a given correlation ID, all in one place.
- [QA Correlation Dashboard - Staging](https://nonprod-log.gitlab.net/app/dashboards#/view/b74dc030-6f56-11ed-9af2-6131f0ee4ce6?_g=(filters%3A!()%2Cquery%3A(language%3Akuery%2Cquery%3A'')%2CrefreshInterval%3A(pause%3A!t%2Cvalue%3A0)%2Ctime%3A(from%3Anow-1d%2Cto%3Anow)))
- [QA Correlation Dashboard - Preprod](https://nonprod-log.gitlab.net/app/dashboards#/view/15596340-7570-11ed-9af2-6131f0ee4ce6?_g=(filters%3A!()%2CrefreshInterval%3A(pause%3A!t%2Cvalue%3A0)%2Ctime%3A(from%3Anow-1d%2Cto%3Anow)))
- [QA Correlation Dashboard - Prod](https://log.gprd.gitlab.net/app/dashboards#/view/5e6d3440-7597-11ed-9f43-e3784d7fe3ca?_g=(filters%3A!()%2CrefreshInterval%3A(pause%3A!t%2Cvalue%3A0)%2Ctime%3A(from%3Anow-15m%2Cto%3Anow)))
In addition to the dashboard link being automatically generated in E2E test failure logs, you can access these dashboards and use them manually as well. Just replace the correlation ID in the `json.correlation_id` filter with the ID you are interested in and set the appropriate date and time range.
This is similar to the Support team's [Correlation Dashboard](https://handbook.gitlab.com/handbook/support/workflows/kibana/#correlation-dashboard), but can be customized to fit the Quality team's needs.
## Reproducing test failure
### Running tests against GDK running in FIPS mode
GDK can be used in FIPS mode if we wish to debug issues that may be related to FIPS.
Restart GDK using the `FIPS_MODE` variable:
`FIPS_MODE=1 gdk restart`
Tests can then be ran with the `FIPS` variable set:
`FIPS=1 bundle exec bin/qa Test::Instance::All https://gdk.test:3000/ ./qa/specs/features/browser_ui/2_plan/issue/create_issue_spec.rb`
### Run the test against your GDK
You can run the test (or perform the test steps manually) against your local GitLab instance to see if the failure is reproducible. For example:
``` shell
WEBDRIVER_HEADLESS=false bundle exec bin/qa Test::Instance::All http://localhost:3000 qa/specs/features/browser_ui/9_tenant_scale/project/create_project_spec.rb
```
Orchestrated tests are excluded by default. To run them, use `-- --tag orchestrated` before your file name. For example:
``` shell
WEBDRIVER_HEADLESS=false bundle exec bin/qa Test::Instance::All http://localhost:3000 -- --tag orchestrated qa/specs/features/browser_ui/9_tenant_scale/project/create_project_spec.rb
```
### Run the test against a GitLab Docker container
You can also use the same Docker image as the one used in the failing job to run GitLab in a container on your local.
In the logs of the failing job, search for `gitlab-ee` or `gitlab-ce` and use its tag to start the container locally.
Once you have the image tag, [spin up GitLab instance locally](https://gitlab.com/gitlab-org/quality/runbooks/-/blob/main/running_gitlab_locally/index.md)
**Special Considerations**
Note that to be able to pull the Docker image from `registry.gitlab.com` you need to [authenticate with the Container Registry](../../../user/packages/container_registry/authenticate_with_container_registry.md).
To run Nightly images change `registry.gitlab.com/gitlab-org/build/omnibus-gitlab-mirror/gitlab-ee:<tag>` from one of the Docker commands above to `gitlab/gitlab-ee:nightly` or `gitlab/gitlab-ce:nightly`.
**Running the Test**
You can now run the test against this Docker instance. E.g.:
``` shell
WEBDRIVER_HEADLESS=false bundle exec bin/qa Test::Instance::All http://localhost qa/specs/features/browser_ui/9_tenant_scale/project/create_project_spec.rb
```
### Run the tests against CustomersDot staging environment
To run CustomersDot E2E tests locally against staging environment, you will need to clone [CustomersDot](https://gitlab.com/gitlab-org/customers-gitlab-com) project, switch to `qa` directory, and then run
``` shell
STAGING=1 CP_ADMIN_TOKEN=<TOKEN> GL_ADMIN_TOKEN=<TOKEN> bundle exec rspec spec/ui/purchase/purchase_plan_spec.rb
```
**Note** - Token value can be found in GitLab-QA Vault. For details on running tests locally with more options, please refer to [CustomersDot README doc](https://gitlab.com/gitlab-org/customers-gitlab-com/-/blob/staging/README.md)
### Tips for running tests locally
- Use the environment variable `QA_LOG_LEVEL=debug` to enable additional logging output that includes page actions and Git commands.
- Additional information about running tests locally can be found in the [GitLab-qa documentation](https://gitlab.com/gitlab-org/gitlab-qa/-/blob/master/docs/what_tests_can_be_run.md) and in the [instructions for running tests that require special setup](running_tests/running_tests_that_require_special_setup.md#jenkins-tests).
- To determine if the test is [flaky](../unhealthy_tests.md#flaky-tests), check the logs or run the test a few times. If it passes at least once but fails otherwise, it's flaky.
## Identifying commit that introduced a failure
- While triaging failures we often may want to find which specific commit was the one that introduced the failure. While we may sometimes be able to identify this by reviewing the recent commit history, in other cases this may be more obscure. To quickly identify where the failure was introduced [Git bisect](https://git-scm.com/docs/git-bisect) can be quite useful.
- A demo on using Git bisect can be found in [Training Videos](#training-videos).
## Investigating orchestrated test failure
### Verify the reconfigure logs for the GitLab container in the pipeline artefacts
Each orchestrated job has a log file attached as artifacts called
- `<container_name>-reconfigure-logs.txt` - if the container runs successfully on 1st attempt, or
- `<container_name>-retry-<retry_attempt>-reconfigure-logs.txt` - if the test has tried multiple times to spin up the GitLab container due to failure.
If you see any errors in this log file, the issue would be related to `gitlab-ctl reconfigure` command.
Get in touch with the distribution team on `#g_distribution` channel.
### Investigating update-major or update-minor tests locally and common failures
Failures in `update-major` or `update-minor` might indicate that GitLab upgrade fails. Such failures could be caused by migration issues or other changes. To ensure customers won't face such issue during upgrade, investigate the error as priority, especially near the release date.
Follow the document [Investigating update-major or update-minor tests locally and common failures](https://gitlab.com/gitlab-org/quality/runbooks/-/blob/main/debug_orchestrated_test_locally/running_update-major_and_update-minor_locally.md).
## Test Licenses
Please see the [Test Licenses runbook](https://gitlab-org.gitlab.io/quality/runbooks/test_licenses/) for more information on the licenses in use by E2E test pipelines.
## Training videos
- [Quality Engineering: Failure Triage - Using Git bisect to identify commit that introduced a failure](https://www.youtube.com/watch?v=ZvrOF5Bx2Bo)
## Additional references
You can find some [general tips for troubleshooting problems with GitLab end-to-end tests in the development documentation](troubleshooting.md).
|
---
title: Debugging Failing Tests and Test Pipelines
description: Guidelines for investigating end-to-end test pipeline failures
breadcrumbs:
- doc
- development
- testing_guide
- end_to_end
---
## Overview
This page outlines steps for investigating [end-to-end test](_index.md) failures, deployments, and troubleshooting various GitLab environments. It provides information on how to handle failures, identifying the problematic commit, the logging tools, and ways to reproduce the failure.
## Special considerations for investigating specific environments
### Staging-Canary
`Staging-Canary` is unique when it comes to its blocking `smoke` tests that are triggered by the `deployer` pipeline. `Staging-Canary` executes `smoke` tests for both `Staging-Canary` AND `Staging` environments. This special configuration is designed to help catch issues that occur when incompatibilities arise between the shared and non-shared components of the environments.
`Staging-Canary` and `Staging` both share the same database backend, for example. Should a migration or change to either of the non-shared components during a deployment create an issue, running these tests together helps expose this situation. When the `deployer` pipeline triggers these test runs, they are reported serially in the `#qa_staging` Slack channel and they appear as different runs.
Note when viewing a deployment failure from the `#announcements` Slack channel, you will have to click into the pipeline and look at the `Downstream` results to understand if the deployment failure arose from a failure in `Staging-Canary` or if the failure occurred in `Staging`.
Visit the [announcement issue](https://gitlab.com/gitlab-com/gl-infra/delivery/-/issues/2280) for more context
and to view an uncompressed version of the following image:

Note the diagram has been updated as part of increasing rollback availability by removing the [blocking nature of post-deployment migrations](https://gitlab.com/groups/gitlab-com/gl-infra/-/epics/585).
### Staging Ref
[Staging Ref](https://handbook.gitlab.com/handbook/engineering/infrastructure/environments/staging-ref/) is a Sandbox environment used for pre-production testing of the latest Staging Canary code. It is a shared
environment with wide access permissions and as a result of engineers testing their code, the environment may become unstable and may need to be rebuilt.
The full or smoke E2E test suite can be triggered on an as-needed basis from the `staging-ref` project's [pipeline schedules](https://ops.gitlab.net/gitlab-org/quality/staging-ref/-/pipeline_schedules).
Staging Ref deployment runs parallel to Staging Canary deployment. These two environments share the same GitLab version, if a failure happens
on Staging Ref but not on Staging Canary, it may indicate that the failure is environment specific. See [QA pipeline debugging guide](https://gitlab.com/gitlab-org/quality/gitlab-environment-toolkit-configs/staging-ref/-/blob/main/doc/qa_failure_debug.md) for more information on how to investigate E2E test failures.
### Preprod
[Preprod](https://handbook.gitlab.com/handbook/engineering/infrastructure/environments/#pre) is used to perform validation of release candidates. Every month around the [release date](https://handbook.gitlab.com/handbook/engineering/releases/), and the few days before, it is essential that there are no unexpected failures in the pipeline that will delay the release. There is a pipeline scheduled to run prior to deployment of the release candidate, to give us a chance to identify and resolve any issues with tests or the test environment. This scheduled pipeline should be given equal priority with `Production` and `Staging` pipelines because of the potential impact failures can have on a release.
Tests pipelines are also triggered by the [Kubernetes Workload configuration project](https://gitlab.com/gitlab-com/gl-infra/k8s-workloads/gitlab-com) to ensure that any configuration changes are valid.
### Nightly
[Omnibus nightly builds](https://dev.gitlab.org/gitlab/omnibus-gitlab/-/pipeline_schedules) are paused at the start of a security release and enabled again once the release is complete.
This can cause the nightly tests to either run against an outdated package or fail during the `ce:sanity-version` and `ee:sanity-version` jobs when mirroring is down.
The `#quality` Slack channel should receive two notifications:
1. An announcement from the release team when the security release has started.
1. A notification from GitLab ChatOps when the security release has been published.
For other ways to check if there is an ongoing security release, you can visit the `#releases` Slack channel's `Next Security Release` bookmark, or [search the GitLab project's issues by the `~"upcoming security release"` label](https://gitlab.com/gitlab-org/gitlab/-/issues/?sort=created_date&state=opened&label_name%5B%5D=upcoming%20security%20release&first_page_size=20).
Please note that a security release issue can sometimes be created before a release is in progress.
If you have any questions on the status, you can also reach out to the `@release-managers` in Slack.
### `master` pipelines
GitLab `master` has three QA pipelines generated from scheduled pipeline against the default branch:
- [`test-on-omnibus`](_index.md#using-the-test-on-omnibus-job) runs the `full` suite of end-to-end tests against an omnibus Docker image built from `master`
- [`test-on-gdk`](_index.md#selective-test-execution-based-on-code-path-mappings) runs the full suite of end-to-end tests as part of the `gdk-instance` job against a GDK instance from a Docker image built from `master`
If jobs in `test-on-omnibus` failed due to a GitLab Docker image issue, reach out to the [Distribution team](https://handbook.gitlab.com/handbook/engineering/infrastructure-platforms/gitlab-delivery/distribution/) to see if it's a known problem with the build.
If failures occur only in `test-on-gdk` jobs, it's possible to stop those jobs from being added to new pipelines while the cause is being fixed. See the [runbook](https://gitlab.com/gitlab-org/quality/runbooks/-/tree/97483eafd3db198437faccc40a946fc260c0736a/test_on_gdk#disable-the-e2etest-on-gdk-pipeline) for details.
Note that any failure in `master` QA pipeline will be deployed to Staging, so catching a failure earlier in the pipeline allows us to
find what changes caused it and act on resolving the failure more quickly.
## Verifying current environment version
### Determine the version, revision, branch and package deployed in GitLab environments
To find out the version, revision, branch and package deployed in GitLab.com, staging and canary environments,
run this in the #chat-ops-test Slack channel:
```shell
/chatops run auto_deploy status
```

You will [need access to the https://ops.gitlab.net/gitlab-com/chatops](../../chatops_on_gitlabcom.md#requesting-access) project to run `/chatops` commands.
Ask to be added to this project in the #development Slack channel.
### Determine if a change has been deployed to an environment using revision SHA
If you have a revision SHA that is deployed on an environment, you can find out if a change has made it to that environment.
For example, if the revision SHA deployed on an environment is `c46489109e4` and you want to find out if a change in
`restrict_by_ip_address_spec.rb` has made it there, you can use:
```shell
git show c46489109e4:qa/qa/specs/features/ee/browser_ui/1_manage/group/restrict_by_ip_address_spec.rb
```
You can determine the revision SHA deployed on a GitLab instance by either navigating to <https://www.example.com/help>,
by calling the `https://www.example.com/api/v4/version` API or by running `/chatops run auto_deploy status` in a Slack
channel such as #chat-ops-test.
You can also determine if your commit has been deployed on a GitLab environment using [ChatOps](../../../ci/chatops/_index.md).
For example, if your commit ref is `347e530c5b3dec60c0ce2870bc79ca4c8273604d` you can run this command in a Slack
channel such as #chat-ops-test:
```shell
/chatops run auto_deploy status 347e530c5b3dec60c0ce2870bc79ca4c8273604d
```
### Determine the commit SHA of a nightly image
The commit SHA for a nightly pipeline can be determined in the following ways:
#### By visiting the /help page or calling the `/api/v4/version` API
Run the nightly Docker image
```shell
docker run \
--hostname localhost \
--publish 443:443 --publish 80:80 --publish 22:22 \
gitlab/gitlab-ee:nightly
```
The commit SHA can be determined by visiting the <http://localhost/help> page after sign-in
or by calling the [`/api/v4/version` API](../../../api/version.md) where it is displayed as a value of the `revision` attribute.
#### By inspecting the pipeline that created the nightly image
Nightly images are created by scheduled pipelines here: <https://dev.gitlab.org/gitlab/omnibus-gitlab/pipeline_schedules>
You can look at the last pipeline by clicking the pipeline number for CE nightly or EE nightly under
the "Last pipeline" column.
In the pipeline view click a job under the "GitLab_com:package" column. The SHAs for GitLab Components
are listed towards the end of the logs. The GitLab commit SHA is displayed as a value of `gitlab-rails`.
### Checking Docker images
Sometimes tests may fail due to an outdated Docker image. To check if that's the case, follow the instructions below to see if specific merged code is available in a Docker image.
#### Checking test code (QA image)
If you suspect that certain test is failing due to the `gitlab/gitlab-{ce|ee}-qa` image being outdated, follow these steps:
1. Locally, run `docker run -it --entrypoint /bin/sh gitlab/gitlab-ce-qa:latest` to check for GitLab QA CE code, or `docker run -it --entrypoint /bin/sh gitlab/gitlab-ee-qa:latest` to check for GitLab QA EE code
1. Then, navigate to the `qa` directory (`cd /home/qa/qa`)
1. Finally, use `cat` to see if the code you're looking for is available in certain file (e.g., `cat page/project/issue/show.rb`)
> **Note** if you need to check in another tag (e.g., `nightly`), change it in one of the scripts of step 1 above.
#### Checking application code
1. Locally, run `docker run -it --entrypoint /bin/sh gitlab/gitlab-ce:latest` to check for GitLab CE code, or `docker run -it --entrypoint /bin/sh gitlab/gitlab-ee:latest` to check for GitLab EE code
1. Then, navigate to the `gitlab-rails` directory (`cd /opt/gitlab/embedded/service/gitlab-rails/`)
1. Finally, use `cat` to see if the code you're looking for is available or not in a certain file (e.g., `cat public/assets/issues_analytics/components/issues_analytics-9c3887211ed5aa599c9eea63836486d04605f5dfdd76c49f9b05cc24b103f78a.vue`.)
> **Note** if you want to check another tag (e.g., `nightly`) change it in one of the scripts of step 1 above.
#### Checking application version has the specific MR
1. Find the version which GitLab application is running on. In the failing job logs, search for `docker pull dev.gitlab.org:5005/gitlab/omnibus-gitlab/gitlab-ee-qa` and use the version specified after `gitlab-ee-qa:`.
- For nightly, the approach above won't work. There are two ways for finding the commit version of nightly:
- Run the [nightly image on local](#run-the-test-against-a-gitlab-docker-container), sign-in as admin and navigate to `/help` page or call the `/api/v4/version` API.
- Search for the commit in the [omnibus-GitLab pipeline](https://dev.gitlab.org/gitlab/omnibus-gitlab/-/pipelines) that built the last nightly. Jobs that build nightly have `bundle exec rake docker:push:nightly` command in the `Docker-branch` job of the `Package-and-image` stage. Once you find the latest pipeline, search for `gitlab-rails` under `build-component_shas` in any job under the `Gitlab_com:package` stage. For example, in [this `Ubuntu-16.04-branch` job](https://dev.gitlab.org/gitlab/omnibus-gitlab/-/jobs/9610785#L3373), the commit SHA for `gitlab-rails` is `32e76bc4fb02a615c2bf5a00a8fceaee7812a6bd`.
1. Open commits list for the specific version:
- If version format is like a commit SHA, for example `gitlab-ee-qa:13.10-4b373026c98`, navigate to `https://gitlab.com/gitlab-org/gitlab/-/commits/<commit_SHA>` page, in our example the commit SHA is `4b373026c98`.
- If version format is like a tag, for example `13.10.0-rc20210223090520-ee`, navigate to `https://gitlab.com/gitlab-org/gitlab/-/commits/v<tag>` page, in our example the tag is `13.10.0-rc20210223090520-ee`.
- If page above returns 404 error, check if the version exists in [GitLab Security repo](https://gitlab.com/gitlab-org/security/gitlab) in case there is a security release.
1. Check if the MR that you were searching for is in this version.
- Note the branch name of the MR.
- Search the commits from Step 2 by the branch name.
- If the commit is found, the MR is in this version. For [example](https://gitlab.com/gitlab-org/gitlab/-/commits/v13.10.0-rc20210223090520-ee?utf8=%E2%9C%93&search=add-share-with-group-to-modal).
- If no results, the MR is not in this version. For [example](https://gitlab.com/gitlab-org/gitlab/-/commits/v13.10.0-rc20210223090520-ee?utf8=%E2%9C%93&search=qa-shl-add-requries-admin).
## Test failure logs
The following can help with your investigation:
| Log or artifact | Notes |
|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| [Stack trace](../../../ci/quick_start/_index.md#view-the-status-of-your-pipeline-and-jobs) | Shown in the job's log; the starting point for investigating the test failure |
| [Screenshots and HTML captures](../../../ci/jobs/job_artifacts.md#browse-the-contents-of-the-artifacts-archive) | Available for download in the job's artifact for up to 1 week after the job run |
| [QA Logs](../../../ci/jobs/job_artifacts.md#browse-the-contents-of-the-artifacts-archive) | Included in the job's artifacts; valuable for determining the steps taken by the tests before failing |
| [System Logs](../../../administration/logs/_index.md) (GitLab-rails, Sidekiq, etc.) | Included in the job's artifacts for containerized test runs, such as master and nightly. These are useful for investigating errors originating from the GitLab application itself. <br/><br /> A summary of the system logs related to a test failure can also be found in the description of QA failure issues generated from master and nightly runs containing a correlation ID. |
| Sentry logs ([Staging](https://new-sentry.gitlab.net/organizations/gitlab/issues/?environment=gstg), [Staging Ref](https://new-sentry.gitlab.net/organizations/gitlab/projects/staging-ref), [Preprod](https://new-sentry.gitlab.net/organizations/gitlab/issues/?environment=pre), [Production](https://sentry.gitlab.net/gitlab/gitlabcom/)) | If staging, preprod or production tests fail due to a server error, there should be a record in [Sentry](https://handbook.gitlab.com/handbook/support/workflows/sentry/). For example, you can search for all unresolved staging errors linked to the `gitlab-qa` user with the query [`is:unresolved user:"username:gitlab-qa"`](https://new-sentry.gitlab.net/organizations/gitlab/issues/?environment=gstg&query=is%3Aunresolved+user%3Ausername%3Agitlab-qa). However, note that some actions aren't linked to the `gitlab-qa` user, so they might only appear in the [full unresolved list](https://new-sentry.gitlab.net/organizations/gitlab/issues/?environment=gstg). |
| Kibana logs ([Staging and Preprod](https://nonprod-log.gitlab.net/app/kibana#/discover), [Production](https://log.gprd.gitlab.net/app/kibana#/discover)) | Various system logs from live environments are sent to [Kibana](https://handbook.gitlab.com/handbook/support/workflows/kibana/), including Rails, Postgres, Sidekiq, and Gitaly logs. <br><br>**Note**: Staging and Preprod logs both use the same URL, but the search index pattern will be different. Staging indices contain `gstg` while Preprod contains `pre`. For example, to search within the Staging Rails index, you would change the index pattern dropdown value to `pubsub-rails-inf-gstg*`. More information on how to do this can be found [here](https://handbook.gitlab.com/handbook/support/workflows/kibana/#parameters). |
### Kibana and Sentry Logs
When a request fails in an E2E test that results in an error from the server, the job logs will print a link with the relevant correlation ID to logs in Sentry and Kibana for environments where these are available.
For Kibana, there will be two links available. One directs to a singular search against the Rails index in Kibana Discover, and another directs to the QA Correlation Dashboard, which contain panels of search results from multiple GitLab components.
### Kibana Correlation Dashboards
We have QA Correlation Dashboards in Kibana to help organize logs from various GitLab components (e.g., Rails, Gitaly, Postgres, etc.) that are related to a given correlation ID, all in one place.
- [QA Correlation Dashboard - Staging](https://nonprod-log.gitlab.net/app/dashboards#/view/b74dc030-6f56-11ed-9af2-6131f0ee4ce6?_g=(filters%3A!()%2Cquery%3A(language%3Akuery%2Cquery%3A'')%2CrefreshInterval%3A(pause%3A!t%2Cvalue%3A0)%2Ctime%3A(from%3Anow-1d%2Cto%3Anow)))
- [QA Correlation Dashboard - Preprod](https://nonprod-log.gitlab.net/app/dashboards#/view/15596340-7570-11ed-9af2-6131f0ee4ce6?_g=(filters%3A!()%2CrefreshInterval%3A(pause%3A!t%2Cvalue%3A0)%2Ctime%3A(from%3Anow-1d%2Cto%3Anow)))
- [QA Correlation Dashboard - Prod](https://log.gprd.gitlab.net/app/dashboards#/view/5e6d3440-7597-11ed-9f43-e3784d7fe3ca?_g=(filters%3A!()%2CrefreshInterval%3A(pause%3A!t%2Cvalue%3A0)%2Ctime%3A(from%3Anow-15m%2Cto%3Anow)))
In addition to the dashboard link being automatically generated in E2E test failure logs, you can access these dashboards and use them manually as well. Just replace the correlation ID in the `json.correlation_id` filter with the ID you are interested in and set the appropriate date and time range.
This is similar to the Support team's [Correlation Dashboard](https://handbook.gitlab.com/handbook/support/workflows/kibana/#correlation-dashboard), but can be customized to fit the Quality team's needs.
## Reproducing test failure
### Running tests against GDK running in FIPS mode
GDK can be used in FIPS mode if we wish to debug issues that may be related to FIPS.
Restart GDK using the `FIPS_MODE` variable:
`FIPS_MODE=1 gdk restart`
Tests can then be ran with the `FIPS` variable set:
`FIPS=1 bundle exec bin/qa Test::Instance::All https://gdk.test:3000/ ./qa/specs/features/browser_ui/2_plan/issue/create_issue_spec.rb`
### Run the test against your GDK
You can run the test (or perform the test steps manually) against your local GitLab instance to see if the failure is reproducible. For example:
``` shell
WEBDRIVER_HEADLESS=false bundle exec bin/qa Test::Instance::All http://localhost:3000 qa/specs/features/browser_ui/9_tenant_scale/project/create_project_spec.rb
```
Orchestrated tests are excluded by default. To run them, use `-- --tag orchestrated` before your file name. For example:
``` shell
WEBDRIVER_HEADLESS=false bundle exec bin/qa Test::Instance::All http://localhost:3000 -- --tag orchestrated qa/specs/features/browser_ui/9_tenant_scale/project/create_project_spec.rb
```
### Run the test against a GitLab Docker container
You can also use the same Docker image as the one used in the failing job to run GitLab in a container on your local.
In the logs of the failing job, search for `gitlab-ee` or `gitlab-ce` and use its tag to start the container locally.
Once you have the image tag, [spin up GitLab instance locally](https://gitlab.com/gitlab-org/quality/runbooks/-/blob/main/running_gitlab_locally/index.md)
**Special Considerations**
Note that to be able to pull the Docker image from `registry.gitlab.com` you need to [authenticate with the Container Registry](../../../user/packages/container_registry/authenticate_with_container_registry.md).
To run Nightly images change `registry.gitlab.com/gitlab-org/build/omnibus-gitlab-mirror/gitlab-ee:<tag>` from one of the Docker commands above to `gitlab/gitlab-ee:nightly` or `gitlab/gitlab-ce:nightly`.
**Running the Test**
You can now run the test against this Docker instance. E.g.:
``` shell
WEBDRIVER_HEADLESS=false bundle exec bin/qa Test::Instance::All http://localhost qa/specs/features/browser_ui/9_tenant_scale/project/create_project_spec.rb
```
### Run the tests against CustomersDot staging environment
To run CustomersDot E2E tests locally against staging environment, you will need to clone [CustomersDot](https://gitlab.com/gitlab-org/customers-gitlab-com) project, switch to `qa` directory, and then run
``` shell
STAGING=1 CP_ADMIN_TOKEN=<TOKEN> GL_ADMIN_TOKEN=<TOKEN> bundle exec rspec spec/ui/purchase/purchase_plan_spec.rb
```
**Note** - Token value can be found in GitLab-QA Vault. For details on running tests locally with more options, please refer to [CustomersDot README doc](https://gitlab.com/gitlab-org/customers-gitlab-com/-/blob/staging/README.md)
### Tips for running tests locally
- Use the environment variable `QA_LOG_LEVEL=debug` to enable additional logging output that includes page actions and Git commands.
- Additional information about running tests locally can be found in the [GitLab-qa documentation](https://gitlab.com/gitlab-org/gitlab-qa/-/blob/master/docs/what_tests_can_be_run.md) and in the [instructions for running tests that require special setup](running_tests/running_tests_that_require_special_setup.md#jenkins-tests).
- To determine if the test is [flaky](../unhealthy_tests.md#flaky-tests), check the logs or run the test a few times. If it passes at least once but fails otherwise, it's flaky.
## Identifying commit that introduced a failure
- While triaging failures we often may want to find which specific commit was the one that introduced the failure. While we may sometimes be able to identify this by reviewing the recent commit history, in other cases this may be more obscure. To quickly identify where the failure was introduced [Git bisect](https://git-scm.com/docs/git-bisect) can be quite useful.
- A demo on using Git bisect can be found in [Training Videos](#training-videos).
## Investigating orchestrated test failure
### Verify the reconfigure logs for the GitLab container in the pipeline artefacts
Each orchestrated job has a log file attached as artifacts called
- `<container_name>-reconfigure-logs.txt` - if the container runs successfully on 1st attempt, or
- `<container_name>-retry-<retry_attempt>-reconfigure-logs.txt` - if the test has tried multiple times to spin up the GitLab container due to failure.
If you see any errors in this log file, the issue would be related to `gitlab-ctl reconfigure` command.
Get in touch with the distribution team on `#g_distribution` channel.
### Investigating update-major or update-minor tests locally and common failures
Failures in `update-major` or `update-minor` might indicate that GitLab upgrade fails. Such failures could be caused by migration issues or other changes. To ensure customers won't face such issue during upgrade, investigate the error as priority, especially near the release date.
Follow the document [Investigating update-major or update-minor tests locally and common failures](https://gitlab.com/gitlab-org/quality/runbooks/-/blob/main/debug_orchestrated_test_locally/running_update-major_and_update-minor_locally.md).
## Test Licenses
Please see the [Test Licenses runbook](https://gitlab-org.gitlab.io/quality/runbooks/test_licenses/) for more information on the licenses in use by E2E test pipelines.
## Training videos
- [Quality Engineering: Failure Triage - Using Git bisect to identify commit that introduced a failure](https://www.youtube.com/watch?v=ZvrOF5Bx2Bo)
## Additional references
You can find some [general tips for troubleshooting problems with GitLab end-to-end tests in the development documentation](troubleshooting.md).
|
https://docs.gitlab.com/development/testing_guide/style_guide
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/testing_guide/style_guide.md
|
2025-08-13
|
doc/development/testing_guide/end_to_end
|
[
"doc",
"development",
"testing_guide",
"end_to_end"
] |
style_guide.md
|
none
|
unassigned
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Style guide for writing end-to-end tests
| null |
This document describes the conventions used at GitLab for writing End-to-end (E2E) tests using the GitLab QA project.
This guide is an extension of the primary [testing standards and style guidelines](../_index.md). If this guide defines a rule that contradicts the primary guide, this guide takes precedence.
## `click_` versus `go_to_`
### When to use `click_`?
When selecting a single link to navigate, use `click_`.
For example:
```ruby
def click_add_badge_button
click_element 'add-badge-button'
end
```
From a testing perspective, if we want to check that selecting a link, or a button (a single interaction) is working as intended, we would want the test to read as:
- Select a certain element
- Verify the action took place
### When to use `go_to_`?
When interacting with multiple elements to go to a page, use `go_to_`.
For example:
```ruby
def go_to_applications
click_element('nav-item-link', submenu_item: 'Applications')
end
```
`go_to_` fits the definition of interacting with multiple elements very well given it's more of a meta-navigation action that includes multiple interactions.
Notice that in the above example, before selecting the `'nav-item-link'`, another element is hovered over.
> We can create these methods as helpers to abstract multi-step navigation.
## Element naming convention
When adding new elements to a page, it's important that we have a uniform element naming convention.
We follow a simple formula roughly based on Hungarian notation.
*Formula*: `element :<descriptor>_<type>`
- `descriptor`: The natural-language description of what the element is. On the login page, this could be `username`, or `password`.
- `type`: A generic control on the page that can be seen by a user.
- `-button`
- `-checkbox`
- `-container`: an element that includes other elements, but doesn't present visible content itself. For example, an element that has a third-party editor inside it, but which isn't the editor itself and so doesn't include the editor's content.
- `-content`: any element that contains text, images, or any other content displayed to the user.
- `-dropdown`
- `-field`: a text input element.
- `-link`
- `-modal`: a popup modal dialog, for example, a confirmation prompt.
- `-placeholder`: a temporary element that appears while content is loading. For example, the elements that are displayed instead of discussions while the discussions are being fetched.
- `-radio`
- `-tab`
- `-menu_item`
{{< alert type="note" >}}
If none of the listed types are suitable, open a merge request to add an appropriate type to the list.
{{< /alert >}}
### Examples
**Good**
```ruby
view '...' do
element 'edit-button'
element 'notes-tab'
element 'squash-checkbox'
element 'username-field'
element 'issue-title-content'
end
```
**Bad**
```ruby
view '...' do
# `'-confirmation'` should be `'-field'`. what sort of confirmation? a checkbox confirmation? no real way to disambiguate.
# an appropriate replacement would be `element 'password-confirmation-field'`
element 'password-confirmation'
# `'clone-options'` is too vague. If it's a dropdown menu, it should be `'clone-dropdown'`.
# If it's a checkbox, it should be `'clone-checkbox'`
element 'clone-options'
# how is this url being displayed? is it a textbox? a simple span?
# If it is content on the page, it should be `'ssh-clone-url-content'`
element 'ssh-clone-url'
end
```
## Block argument naming
To have a standard on what we call pages and resources when using the `.perform` method,
we use the name of the page object in [snake_case](https://en.wikipedia.org/wiki/Snake_case)
(all lowercase, with words separated by an underscore). See good and bad examples below.
While we prefer to follow the standard in most cases, it is also acceptable to
use common abbreviations (for example, `mr`) or other alternatives, as long as
the name is not ambiguous. This can include appending `_page` if it helps to
avoid confusion or make the code more readable. For example, if a page object is
named `New`, it could be confusing to name the block argument `new` because that
is used to instantiate objects, so `new_page` would be acceptable.
We chose not to use `page` because that would shadow the
Capybara DSL, potentially leading to confusion and bugs.
### Examples
**Good**
```ruby
Page::Project::Members.perform do |members|
members.do_something
end
```
```ruby
Resource::MergeRequest.fabricate! do |merge_request|
merge_request.do_something_else
end
```
```ruby
Resource::MergeRequest.fabricate! do |mr|
mr.do_something_else
end
```
```ruby
Page::Project::New.perform do |new_page|
new_page.do_something
end
```
**Bad**
```ruby
Page::Project::Members.perform do |project_settings_members_page|
project_settings_members_page.do_something
end
```
```ruby
Page::Project::New.perform do |page|
page.do_something
end
```
> Besides the advantage of having a standard in place, by following this standard we also write shorter lines of code.
|
---
stage: none
group: unassigned
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: Style guide for writing end-to-end tests
breadcrumbs:
- doc
- development
- testing_guide
- end_to_end
---
This document describes the conventions used at GitLab for writing End-to-end (E2E) tests using the GitLab QA project.
This guide is an extension of the primary [testing standards and style guidelines](../_index.md). If this guide defines a rule that contradicts the primary guide, this guide takes precedence.
## `click_` versus `go_to_`
### When to use `click_`?
When selecting a single link to navigate, use `click_`.
For example:
```ruby
def click_add_badge_button
click_element 'add-badge-button'
end
```
From a testing perspective, if we want to check that selecting a link, or a button (a single interaction) is working as intended, we would want the test to read as:
- Select a certain element
- Verify the action took place
### When to use `go_to_`?
When interacting with multiple elements to go to a page, use `go_to_`.
For example:
```ruby
def go_to_applications
click_element('nav-item-link', submenu_item: 'Applications')
end
```
`go_to_` fits the definition of interacting with multiple elements very well given it's more of a meta-navigation action that includes multiple interactions.
Notice that in the above example, before selecting the `'nav-item-link'`, another element is hovered over.
> We can create these methods as helpers to abstract multi-step navigation.
## Element naming convention
When adding new elements to a page, it's important that we have a uniform element naming convention.
We follow a simple formula roughly based on Hungarian notation.
*Formula*: `element :<descriptor>_<type>`
- `descriptor`: The natural-language description of what the element is. On the login page, this could be `username`, or `password`.
- `type`: A generic control on the page that can be seen by a user.
- `-button`
- `-checkbox`
- `-container`: an element that includes other elements, but doesn't present visible content itself. For example, an element that has a third-party editor inside it, but which isn't the editor itself and so doesn't include the editor's content.
- `-content`: any element that contains text, images, or any other content displayed to the user.
- `-dropdown`
- `-field`: a text input element.
- `-link`
- `-modal`: a popup modal dialog, for example, a confirmation prompt.
- `-placeholder`: a temporary element that appears while content is loading. For example, the elements that are displayed instead of discussions while the discussions are being fetched.
- `-radio`
- `-tab`
- `-menu_item`
{{< alert type="note" >}}
If none of the listed types are suitable, open a merge request to add an appropriate type to the list.
{{< /alert >}}
### Examples
**Good**
```ruby
view '...' do
element 'edit-button'
element 'notes-tab'
element 'squash-checkbox'
element 'username-field'
element 'issue-title-content'
end
```
**Bad**
```ruby
view '...' do
# `'-confirmation'` should be `'-field'`. what sort of confirmation? a checkbox confirmation? no real way to disambiguate.
# an appropriate replacement would be `element 'password-confirmation-field'`
element 'password-confirmation'
# `'clone-options'` is too vague. If it's a dropdown menu, it should be `'clone-dropdown'`.
# If it's a checkbox, it should be `'clone-checkbox'`
element 'clone-options'
# how is this url being displayed? is it a textbox? a simple span?
# If it is content on the page, it should be `'ssh-clone-url-content'`
element 'ssh-clone-url'
end
```
## Block argument naming
To have a standard on what we call pages and resources when using the `.perform` method,
we use the name of the page object in [snake_case](https://en.wikipedia.org/wiki/Snake_case)
(all lowercase, with words separated by an underscore). See good and bad examples below.
While we prefer to follow the standard in most cases, it is also acceptable to
use common abbreviations (for example, `mr`) or other alternatives, as long as
the name is not ambiguous. This can include appending `_page` if it helps to
avoid confusion or make the code more readable. For example, if a page object is
named `New`, it could be confusing to name the block argument `new` because that
is used to instantiate objects, so `new_page` would be acceptable.
We chose not to use `page` because that would shadow the
Capybara DSL, potentially leading to confusion and bugs.
### Examples
**Good**
```ruby
Page::Project::Members.perform do |members|
members.do_something
end
```
```ruby
Resource::MergeRequest.fabricate! do |merge_request|
merge_request.do_something_else
end
```
```ruby
Resource::MergeRequest.fabricate! do |mr|
mr.do_something_else
end
```
```ruby
Page::Project::New.perform do |new_page|
new_page.do_something
end
```
**Bad**
```ruby
Page::Project::Members.perform do |project_settings_members_page|
project_settings_members_page.do_something
end
```
```ruby
Page::Project::New.perform do |page|
page.do_something
end
```
> Besides the advantage of having a standard in place, by following this standard we also write shorter lines of code.
|
https://docs.gitlab.com/development/testing_guide/end_to_end
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/testing_guide/_index.md
|
2025-08-13
|
doc/development/testing_guide/end_to_end
|
[
"doc",
"development",
"testing_guide",
"end_to_end"
] |
_index.md
|
none
|
unassigned
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
End-to-end Testing
| null |
## What is end-to-end testing?
End-to-end (e2e) testing is a strategy used to check whether your application works as expected across the entire software stack and architecture, including integration of all micro-services and components that are supposed to work together.
## How do we test GitLab?
To test GitLab, we:
1. Use [CNG](https://gitlab.com/gitlab-org/build/CNG) to build GitLab Cloud Native packages.
1. Deploy these packages using the [orchestrator](https://gitlab.com/gitlab-org/gitlab/-/tree/master/qa/gems/gitlab-orchestrator?ref_type=heads) CLI tool to create
a running instance of GitLab to run E2E tests against.
Additionally, we use the [GitLab Development Kit](https://gitlab.com/gitlab-org/gitlab-development-kit) (GDK) as a test environment that can be deployed quickly for faster test feedback.
### Testing nightly builds
We run scheduled pipelines each night to test nightly builds created by Omnibus. You can find these pipelines at <https://gitlab.com/gitlab-org/gitlab/-/pipeline_schedules> (requires the Developer role). Results are reported in the `#e2e-run-master` Slack channel.
### Testing staging
We run scheduled pipelines each night to test staging. You can find these pipelines at <https://gitlab.com/gitlab-org/quality/staging/pipelines> (requires the Developer role). Results are reported in the `#e2e-run-staging` Slack channel.
### Testing code in merge requests
[End-to-end test pipelines](test_pipelines.md) describes pipeline setup responsible for running E2E testing within merge requests.
#### Using the test-on-omnibus job
It is possible to run end-to-end tests for a merge request by triggering the `e2e:test-on-omnibus-ee` manual action in the `qa` stage (not available for forks).
**This runs end-to-end tests against a custom EE (with an Ultimate license) Docker image built from your merge request's changes.**
Manual action that starts end-to-end tests is also available in [`gitlab-org/omnibus-gitlab` merge requests](https://docs.gitlab.com/omnibus/build/team_member_docs.html#i-have-an-mr-in-the-omnibus-gitlab-project-and-want-a-package-or-docker-image-to-test-it).
#### With merged results pipelines
In a merged results pipeline, the pipeline runs on a new ref that contains the merge result of the source and target branch.
The end-to-end tests on a merged results pipeline would use the new ref instead of the head of the merge request source branch.
```mermaid
graph LR
A["x1y1z1 - master HEAD"]
B["d1e1f1 - merged results (CI_COMMIT_SHA)"]
A --> B
B --> C["Merged results pipeline"]
C --> D["E2E tests"]
```
##### Running custom tests
The [existing scenarios](https://gitlab.com/gitlab-org/gitlab-qa/blob/master/docs/what_tests_can_be_run.md)
that run in the downstream `gitlab-qa-mirror` pipeline include many tests, but there are times when you might want to run a
test or a group of tests that are different than the groups in any of the existing scenarios.
For example, when we [dequarantine](https://handbook.gitlab.com/handbook/engineering/infrastructure-platforms/developer-experience/pipeline-triage/#dequarantining-tests) a flaky test we first want to make sure that it's no longer flaky. We can do that by running `_ee:quarantine` manual job. When selecting the name (not the play icon) of manual job, you are prompted to enter variables. You can use any of [the variables that can be used with `gitlab-qa`](https://gitlab.com/gitlab-org/gitlab-qa/blob/master/docs/what_tests_can_be_run.md#supported-gitlab-environment-variables) as well as these:
| Variable | Description |
| --------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `QA_SCENARIO` | The scenario to run (default `Test::Instance::Image`) |
| `QA_TESTS` | The tests to run (no default, which means run all the tests in the scenario). Use file paths as you would when running tests by using RSpec, for example, `qa/specs/features/ee/browser_ui` would include all the `EE` UI tests. |
| `QA_RSPEC_TAGS` | The RSpec tags to add (default `--tag quarantine`) |
For now,
[manual jobs with custom variables don't use the same variable when retried](https://gitlab.com/gitlab-org/gitlab/-/issues/31367),
so if you want to run the same tests multiple times,
specify the same variables in each `custom-parallel` job (up to as
many of the 10 available jobs that you want to run).
#### Selective test execution
In order to limit amount of tests executed in a merge request, dynamic selection of which tests to execute is present. Algorithm of which tests to run is based on changed files and merge request labels. Following criteria determine which tests will run:
1. Changes in `qa` framework code would execute the full suite
1. Changes in particular `_spec.rb` file in `qa` folder would execute only that particular test. In this case knapsack will not be used to run jobs in parallel.
##### Selective test execution based on code path mappings
- `coverband` [gem](https://github.com/danmayer/coverband) is used in a non-standard way for E2E selective test execution in `backend` MRs.
- `coverband` is enabled in the GitLab application only when `COVERBAND_ENABLED` [ENV variable is set](https://gitlab.com/gitlab-org/gitlab/-/blob/master/config/initializers/coverband.rb#L4). This is set only in the scheduled `e2e:test-on-gdk` pipeline on `master` and not in MR pipelines.
- Source code paths are mapped [before each E2E example starts](https://gitlab.com/gitlab-org/gitlab/-/blob/master/qa/qa/support/formatters/coverband_formatter.rb#L44) and after [each E2E example finishes](https://gitlab.com/gitlab-org/gitlab/-/blob/master/qa/qa/support/formatters/coverband_formatter.rb#L62) by using [internal API](https://gitlab.com/gitlab-org/gitlab/-/blob/master/lib/api/internal/coverage.rb).
- Full consolidated mapping is uploaded to GCS in [code-path-mappings bucket](https://console.cloud.google.com/storage/browser/code-path-mappings)
- This mapping is used for selecting tests in `backend` MRs.
Mapping based selective test execution is currently in use for `test-on-gdk` pipeline. For more information, see
[epic 47](https://gitlab.com/groups/gitlab-org/quality/quality-engineering/-/epics/47).
#### Overriding selective test execution
To override selective test execution and trigger the full suite, label `pipeline:run-all-e2e` should be added to particular merge request.
#### Skipping end-to-end tests
In some cases, it may not be necessary to run the end-to-end test suite.
Examples could include:
- ~"Stuff that should Just Work"
- Small refactors
- A small requested change during review, that doesn't warrant running the entire suite a second time
Skip running end-to-end tests by applying the `pipeline:skip-e2e` label to the merge request.
{{< alert type="warning" >}}
There is a risk in skipping end-to-end tests. Use caution and discretion when applying this label. The end-to-end test suite is the last line of defense before changes are merged into the default branch. Skipping these tests increases the risk of introducing regressions into the codebase.
{{< /alert >}}
#### Dynamic parallel job scaling
To maintain consistent pipeline run times, the CI/CD job count for each particular E2E test suite is scaled dynamically based on total run time of tests in the suite.
The [`generate_e2e_pipelines`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/qa/tasks/ci.rake?ref_type=heads) Rake task creates CI/CD YAML files that:
- Create the correct number of parallel jobs.
- Skip particular jobs entirely if no tests would be executed.
This functionality works in tandem with [selective test execution](#selective-test-execution) to optimize pipeline run time and costs as much as possible based on
particular changes within merge request.
##### Design outline
Dynamic job scaling relies on [Test Scenario](https://gitlab.com/gitlab-org/gitlab/-/tree/master/qa/qa/scenario/test?ref_type=heads) classes. This abstraction encapsulates the following:
- The RSpec tags a particular scenario should execute.
- An optional spec file pattern that can limit the scenario to particular spec files.
- A pipeline mapping which defines the pipeline types and jobs a particular scenario would run in merge request pipelines.
The [PipelineCreator](https://gitlab.com/gitlab-org/gitlab/-/blob/master/qa/qa/tools/ci/pipeline_creator.rb?ref_type=heads) class generates pipeline YAML files with
dynamically adjusted parallel job counts. Before pipeline YAML generation, `PipelineCreator` iterates over all defined `Test Scenario` classes and creates a mapping
which contains a total of calculated test run time for each CI/CD job. Based on this information, the pipeline YAML file is generated with correctly adjusted parallel job count.
`PipelineCreator` additionally takes input from [selective test execution](#selective-test-execution) to further reduce the total number of tests that
would be executed.
For an example of how to create a new scenario that would run this scenario in merge request pipelines and scale parallel jobs dynamically, see
[Adding new jobs to E2E test pipelines](test_pipelines.md#adding-new-jobs-to-e2e-test-pipelines).
## Test pipeline tools and configuration
### Test parallelization
Our CI setup uses the [`knapsack`](https://github.com/KnapsackPro/knapsack) gem to enable test parallelization. Knapsack reports are automatically generated and stored in the `knapsack-reports` GCS bucket within the `gitlab-qa-resources` project. The [`KnapsackReport`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/qa/qa/support/knapsack_report.rb) helper manages the report generation and upload process.
### Test metrics
To enhance test health visibility, a custom setup exports the pipeline's test execution results to an [InfluxDB](https://influxdb.quality.gitlab.net/) instance, with results visualized on [Grafana](https://dashboards.quality.gitlab.net/) dashboards.
### Test reports
#### Allure report
For additional test results visibility, tests that run on pipelines generate and host [Allure](https://github.com/allure-framework/allure2) test reports.
The `QA` framework is using the [Allure RSpec](https://github.com/allure-framework/allure-ruby/blob/master/allure-rspec/README.md) gem to generate source files for the `Allure` test report. An additional job in the pipeline:
- Fetches these source files from all test jobs.
- Generates and uploads the report to the `S3` bucket `gitlab-qa-allure-report` located in `AWS` group project `eng-quality-ops-ci-cd-shared-infra`.
A common CI template for report uploading is stored in [`allure-report.yml`](https://gitlab.com/gitlab-org/quality/pipeline-common/-/blob/master/ci/allure-report.yml).
##### Merge requests
When these tests are executed in the scope of merge requests, the `Allure` report is uploaded to the `GCS` bucket and a bot comment is added linking to their respective reports.
##### Scheduled pipelines
Scheduled pipelines for these tests contain a `generate-allure-report` job under the `Report` stage. They also output a link to the current test report. Each type of scheduled pipeline generates a static link for the latest test report according to its stage. You can find a list of this in the [GitLab handbook](https://handbook.gitlab.com/handbook/engineering/infrastructure-platforms/developer-experience/end-to-end-pipeline-monitoring/#allure-report).
### Provisioning
Provisioning of all components is performed by the [`engineering-productivity-infrastructure`](https://gitlab.com/gitlab-org/quality/engineering-productivity-infrastructure) project.
### Exporting metrics in CI
Use these environment variables to configure metrics export:
| Variable | Required | Information |
| ------------------------ | -------- |------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `QA_INFLUXDB_URL` | `true` | Should be set to `https://influxdb.quality.gitlab.net`. No default value. |
| `QA_INFLUXDB_TOKEN` | `true` | InfluxDB write token that can be found under `Influxdb auth tokens` document in `Gitlab-QA` `1Password` vault. No default value. |
| `QA_RUN_TYPE` | `false` | Arbitrary name for test execution, like `e2e:test-on-omnibus-ee`. Automatically inferred from the project name for live environment test executions. No default value. |
| `QA_EXPORT_TEST_METRICS` | `false` | Flag to enable or disable metrics export to InfluxDB. Defaults to `false`. |
| `QA_SAVE_TEST_METRICS` | `false` | Flag to enable or disable saving metrics as JSON file. Defaults to `false`. |
## How do you run the tests?
If you are not [testing code in a merge request](#testing-code-in-merge-requests), there are two main options for running the tests. If you want to run the existing tests against a live GitLab instance or against a pre-built Docker image, use the [GitLab QA orchestrator](https://gitlab.com/gitlab-org/gitlab-qa/tree/master/README.md). See also [examples of the test scenarios you can run by using the orchestrator](https://gitlab.com/gitlab-org/gitlab-qa/blob/master/docs/what_tests_can_be_run.md#examples).
On the other hand, if you would like to run against a local development GitLab environment, you can use the [GitLab Development Kit (GDK)](https://gitlab.com/gitlab-org/gitlab-development-kit/). Refer to the instructions in the [QA README](https://gitlab.com/gitlab-org/gitlab/-/tree/master/qa/README.md#how-can-i-use-it) and the section below.
### Running tests that require special setup
Learn how to perform [tests that require special setup or consideration to run on your local environment](running_tests/running_tests_that_require_special_setup.md).
## How do you write tests?
Before you write new tests, review the [GitLab QA architecture](https://gitlab.com/gitlab-org/gitlab-qa/blob/master/docs/architecture.md).
After you've decided where to put [test environment orchestration scenarios](https://gitlab.com/gitlab-org/gitlab-qa/tree/master/lib/gitlab/qa/scenario) and [instance-level scenarios](https://gitlab.com/gitlab-org/gitlab-foss/tree/master/qa/qa/specs/features), take a look at the [GitLab QA README](https://gitlab.com/gitlab-org/gitlab/-/tree/master/qa/README.md), the [GitLab QA orchestrator README](https://gitlab.com/gitlab-org/gitlab-qa/tree/master/README.md), and [the already existing instance-level scenarios](https://gitlab.com/gitlab-org/gitlab-foss/tree/master/qa/qa/specs/features).
### Consider **not** writing an end-to-end test
We should follow these best practices for end-to-end tests:
- Do not write an end-to-end test if a lower-level feature test exists. End-to-end tests require more work and resources.
- Troubleshooting for end-to-end tests can be more complex as connections to the application under test are not known.
## Continued reading
### Getting started with E2E testing
- [Beginner's Guide](beginners_guide/_index.md): An introductory guide to help new contributors get started with E2E testing
- [Flows](beginners_guide/flows.md): Overview of `Flows` used to capture reusable sequences of actions in tests
- [Page objects](beginners_guide/page_objects.md): Explanation of page objects and their role in test design
- [Resources](beginners_guide/resources.md): Overview of `Resources` class that used for creating test data
### Best practices
- [Best practices when writing end-to-end tests](best_practices/_index.md): Guidelines for efficient and reliable E2E testing
- [Dynamic element validation](best_practices/dynamic_element_validation.md): Techniques for handling dynamic elements in tests
- [Execution context selection](best_practices/execution_context_selection.md): Tips for choosing the right execution context for tests to run on
- [Testing with feature flags](best_practices/feature_flags.md): Managing feature flags during tests
- [RSpec metadata for end-to-end tests](best_practices/rspec_metadata_tests.md): Using metadata to organize and categorize tests
- [Test users](best_practices/users.md): Guidelines for creating and managing test users
- [Waits](best_practices/waits.md): Best practices for using waits to handle asynchronous elements
- [Style guide for writing end-to-end tests](style_guide.md): Standards and conventions to ensure consistency in E2E tests
### Testing infrastructure
- [Test pipelines](test_pipelines.md): Overview of the pipeline setup for E2E tests, including parallelization and CI configuration
- [Test infrastructure for cloud integrations](test_infrastructure.md): Describes cloud-specific setups
### Running and troubleshooting tests
- [Running tests](running_tests/_index.md): Instructions for executing tests
- [Running tests that require special setup](running_tests/running_tests_that_require_special_setup.md): Specific setup requirements for certain tests
- [Troubleshooting](troubleshooting.md): Common issues encountered during E2E testing and solutions
### Miscellaneous
- [Developer Experience Sub-Department handbook](https://handbook.gitlab.com/handbook/engineering/infrastructure-platforms/developer-experience/): Topics related to our vision, monitoring practices, failure triage processes, etc
- [`gitlab-qa`](https://gitlab.com/gitlab-org/gitlab-qa/-/tree/master/docs): For information regarding the use of the GitLab QA orchestrator
- [`customers-gitlab-com`](https://gitlab.com/gitlab-org/customers-gitlab-com/-/tree/main/qa/doc) (internal only): For guides that are specific to the CustomersDot platform
## Where can you ask for help?
You can ask question in the `#s_developer_experience` channel on Slack (GitLab internal) or you can find an issue you would like to work on in [the `gitlab` issue tracker](https://gitlab.com/gitlab-org/gitlab/-/issues?label_name%5B%5D=QA&label_name%5B%5D=test).
|
---
stage: none
group: unassigned
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: End-to-end Testing
breadcrumbs:
- doc
- development
- testing_guide
- end_to_end
---
## What is end-to-end testing?
End-to-end (e2e) testing is a strategy used to check whether your application works as expected across the entire software stack and architecture, including integration of all micro-services and components that are supposed to work together.
## How do we test GitLab?
To test GitLab, we:
1. Use [CNG](https://gitlab.com/gitlab-org/build/CNG) to build GitLab Cloud Native packages.
1. Deploy these packages using the [orchestrator](https://gitlab.com/gitlab-org/gitlab/-/tree/master/qa/gems/gitlab-orchestrator?ref_type=heads) CLI tool to create
a running instance of GitLab to run E2E tests against.
Additionally, we use the [GitLab Development Kit](https://gitlab.com/gitlab-org/gitlab-development-kit) (GDK) as a test environment that can be deployed quickly for faster test feedback.
### Testing nightly builds
We run scheduled pipelines each night to test nightly builds created by Omnibus. You can find these pipelines at <https://gitlab.com/gitlab-org/gitlab/-/pipeline_schedules> (requires the Developer role). Results are reported in the `#e2e-run-master` Slack channel.
### Testing staging
We run scheduled pipelines each night to test staging. You can find these pipelines at <https://gitlab.com/gitlab-org/quality/staging/pipelines> (requires the Developer role). Results are reported in the `#e2e-run-staging` Slack channel.
### Testing code in merge requests
[End-to-end test pipelines](test_pipelines.md) describes pipeline setup responsible for running E2E testing within merge requests.
#### Using the test-on-omnibus job
It is possible to run end-to-end tests for a merge request by triggering the `e2e:test-on-omnibus-ee` manual action in the `qa` stage (not available for forks).
**This runs end-to-end tests against a custom EE (with an Ultimate license) Docker image built from your merge request's changes.**
Manual action that starts end-to-end tests is also available in [`gitlab-org/omnibus-gitlab` merge requests](https://docs.gitlab.com/omnibus/build/team_member_docs.html#i-have-an-mr-in-the-omnibus-gitlab-project-and-want-a-package-or-docker-image-to-test-it).
#### With merged results pipelines
In a merged results pipeline, the pipeline runs on a new ref that contains the merge result of the source and target branch.
The end-to-end tests on a merged results pipeline would use the new ref instead of the head of the merge request source branch.
```mermaid
graph LR
A["x1y1z1 - master HEAD"]
B["d1e1f1 - merged results (CI_COMMIT_SHA)"]
A --> B
B --> C["Merged results pipeline"]
C --> D["E2E tests"]
```
##### Running custom tests
The [existing scenarios](https://gitlab.com/gitlab-org/gitlab-qa/blob/master/docs/what_tests_can_be_run.md)
that run in the downstream `gitlab-qa-mirror` pipeline include many tests, but there are times when you might want to run a
test or a group of tests that are different than the groups in any of the existing scenarios.
For example, when we [dequarantine](https://handbook.gitlab.com/handbook/engineering/infrastructure-platforms/developer-experience/pipeline-triage/#dequarantining-tests) a flaky test we first want to make sure that it's no longer flaky. We can do that by running `_ee:quarantine` manual job. When selecting the name (not the play icon) of manual job, you are prompted to enter variables. You can use any of [the variables that can be used with `gitlab-qa`](https://gitlab.com/gitlab-org/gitlab-qa/blob/master/docs/what_tests_can_be_run.md#supported-gitlab-environment-variables) as well as these:
| Variable | Description |
| --------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `QA_SCENARIO` | The scenario to run (default `Test::Instance::Image`) |
| `QA_TESTS` | The tests to run (no default, which means run all the tests in the scenario). Use file paths as you would when running tests by using RSpec, for example, `qa/specs/features/ee/browser_ui` would include all the `EE` UI tests. |
| `QA_RSPEC_TAGS` | The RSpec tags to add (default `--tag quarantine`) |
For now,
[manual jobs with custom variables don't use the same variable when retried](https://gitlab.com/gitlab-org/gitlab/-/issues/31367),
so if you want to run the same tests multiple times,
specify the same variables in each `custom-parallel` job (up to as
many of the 10 available jobs that you want to run).
#### Selective test execution
In order to limit amount of tests executed in a merge request, dynamic selection of which tests to execute is present. Algorithm of which tests to run is based on changed files and merge request labels. Following criteria determine which tests will run:
1. Changes in `qa` framework code would execute the full suite
1. Changes in particular `_spec.rb` file in `qa` folder would execute only that particular test. In this case knapsack will not be used to run jobs in parallel.
##### Selective test execution based on code path mappings
- `coverband` [gem](https://github.com/danmayer/coverband) is used in a non-standard way for E2E selective test execution in `backend` MRs.
- `coverband` is enabled in the GitLab application only when `COVERBAND_ENABLED` [ENV variable is set](https://gitlab.com/gitlab-org/gitlab/-/blob/master/config/initializers/coverband.rb#L4). This is set only in the scheduled `e2e:test-on-gdk` pipeline on `master` and not in MR pipelines.
- Source code paths are mapped [before each E2E example starts](https://gitlab.com/gitlab-org/gitlab/-/blob/master/qa/qa/support/formatters/coverband_formatter.rb#L44) and after [each E2E example finishes](https://gitlab.com/gitlab-org/gitlab/-/blob/master/qa/qa/support/formatters/coverband_formatter.rb#L62) by using [internal API](https://gitlab.com/gitlab-org/gitlab/-/blob/master/lib/api/internal/coverage.rb).
- Full consolidated mapping is uploaded to GCS in [code-path-mappings bucket](https://console.cloud.google.com/storage/browser/code-path-mappings)
- This mapping is used for selecting tests in `backend` MRs.
Mapping based selective test execution is currently in use for `test-on-gdk` pipeline. For more information, see
[epic 47](https://gitlab.com/groups/gitlab-org/quality/quality-engineering/-/epics/47).
#### Overriding selective test execution
To override selective test execution and trigger the full suite, label `pipeline:run-all-e2e` should be added to particular merge request.
#### Skipping end-to-end tests
In some cases, it may not be necessary to run the end-to-end test suite.
Examples could include:
- ~"Stuff that should Just Work"
- Small refactors
- A small requested change during review, that doesn't warrant running the entire suite a second time
Skip running end-to-end tests by applying the `pipeline:skip-e2e` label to the merge request.
{{< alert type="warning" >}}
There is a risk in skipping end-to-end tests. Use caution and discretion when applying this label. The end-to-end test suite is the last line of defense before changes are merged into the default branch. Skipping these tests increases the risk of introducing regressions into the codebase.
{{< /alert >}}
#### Dynamic parallel job scaling
To maintain consistent pipeline run times, the CI/CD job count for each particular E2E test suite is scaled dynamically based on total run time of tests in the suite.
The [`generate_e2e_pipelines`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/qa/tasks/ci.rake?ref_type=heads) Rake task creates CI/CD YAML files that:
- Create the correct number of parallel jobs.
- Skip particular jobs entirely if no tests would be executed.
This functionality works in tandem with [selective test execution](#selective-test-execution) to optimize pipeline run time and costs as much as possible based on
particular changes within merge request.
##### Design outline
Dynamic job scaling relies on [Test Scenario](https://gitlab.com/gitlab-org/gitlab/-/tree/master/qa/qa/scenario/test?ref_type=heads) classes. This abstraction encapsulates the following:
- The RSpec tags a particular scenario should execute.
- An optional spec file pattern that can limit the scenario to particular spec files.
- A pipeline mapping which defines the pipeline types and jobs a particular scenario would run in merge request pipelines.
The [PipelineCreator](https://gitlab.com/gitlab-org/gitlab/-/blob/master/qa/qa/tools/ci/pipeline_creator.rb?ref_type=heads) class generates pipeline YAML files with
dynamically adjusted parallel job counts. Before pipeline YAML generation, `PipelineCreator` iterates over all defined `Test Scenario` classes and creates a mapping
which contains a total of calculated test run time for each CI/CD job. Based on this information, the pipeline YAML file is generated with correctly adjusted parallel job count.
`PipelineCreator` additionally takes input from [selective test execution](#selective-test-execution) to further reduce the total number of tests that
would be executed.
For an example of how to create a new scenario that would run this scenario in merge request pipelines and scale parallel jobs dynamically, see
[Adding new jobs to E2E test pipelines](test_pipelines.md#adding-new-jobs-to-e2e-test-pipelines).
## Test pipeline tools and configuration
### Test parallelization
Our CI setup uses the [`knapsack`](https://github.com/KnapsackPro/knapsack) gem to enable test parallelization. Knapsack reports are automatically generated and stored in the `knapsack-reports` GCS bucket within the `gitlab-qa-resources` project. The [`KnapsackReport`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/qa/qa/support/knapsack_report.rb) helper manages the report generation and upload process.
### Test metrics
To enhance test health visibility, a custom setup exports the pipeline's test execution results to an [InfluxDB](https://influxdb.quality.gitlab.net/) instance, with results visualized on [Grafana](https://dashboards.quality.gitlab.net/) dashboards.
### Test reports
#### Allure report
For additional test results visibility, tests that run on pipelines generate and host [Allure](https://github.com/allure-framework/allure2) test reports.
The `QA` framework is using the [Allure RSpec](https://github.com/allure-framework/allure-ruby/blob/master/allure-rspec/README.md) gem to generate source files for the `Allure` test report. An additional job in the pipeline:
- Fetches these source files from all test jobs.
- Generates and uploads the report to the `S3` bucket `gitlab-qa-allure-report` located in `AWS` group project `eng-quality-ops-ci-cd-shared-infra`.
A common CI template for report uploading is stored in [`allure-report.yml`](https://gitlab.com/gitlab-org/quality/pipeline-common/-/blob/master/ci/allure-report.yml).
##### Merge requests
When these tests are executed in the scope of merge requests, the `Allure` report is uploaded to the `GCS` bucket and a bot comment is added linking to their respective reports.
##### Scheduled pipelines
Scheduled pipelines for these tests contain a `generate-allure-report` job under the `Report` stage. They also output a link to the current test report. Each type of scheduled pipeline generates a static link for the latest test report according to its stage. You can find a list of this in the [GitLab handbook](https://handbook.gitlab.com/handbook/engineering/infrastructure-platforms/developer-experience/end-to-end-pipeline-monitoring/#allure-report).
### Provisioning
Provisioning of all components is performed by the [`engineering-productivity-infrastructure`](https://gitlab.com/gitlab-org/quality/engineering-productivity-infrastructure) project.
### Exporting metrics in CI
Use these environment variables to configure metrics export:
| Variable | Required | Information |
| ------------------------ | -------- |------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `QA_INFLUXDB_URL` | `true` | Should be set to `https://influxdb.quality.gitlab.net`. No default value. |
| `QA_INFLUXDB_TOKEN` | `true` | InfluxDB write token that can be found under `Influxdb auth tokens` document in `Gitlab-QA` `1Password` vault. No default value. |
| `QA_RUN_TYPE` | `false` | Arbitrary name for test execution, like `e2e:test-on-omnibus-ee`. Automatically inferred from the project name for live environment test executions. No default value. |
| `QA_EXPORT_TEST_METRICS` | `false` | Flag to enable or disable metrics export to InfluxDB. Defaults to `false`. |
| `QA_SAVE_TEST_METRICS` | `false` | Flag to enable or disable saving metrics as JSON file. Defaults to `false`. |
## How do you run the tests?
If you are not [testing code in a merge request](#testing-code-in-merge-requests), there are two main options for running the tests. If you want to run the existing tests against a live GitLab instance or against a pre-built Docker image, use the [GitLab QA orchestrator](https://gitlab.com/gitlab-org/gitlab-qa/tree/master/README.md). See also [examples of the test scenarios you can run by using the orchestrator](https://gitlab.com/gitlab-org/gitlab-qa/blob/master/docs/what_tests_can_be_run.md#examples).
On the other hand, if you would like to run against a local development GitLab environment, you can use the [GitLab Development Kit (GDK)](https://gitlab.com/gitlab-org/gitlab-development-kit/). Refer to the instructions in the [QA README](https://gitlab.com/gitlab-org/gitlab/-/tree/master/qa/README.md#how-can-i-use-it) and the section below.
### Running tests that require special setup
Learn how to perform [tests that require special setup or consideration to run on your local environment](running_tests/running_tests_that_require_special_setup.md).
## How do you write tests?
Before you write new tests, review the [GitLab QA architecture](https://gitlab.com/gitlab-org/gitlab-qa/blob/master/docs/architecture.md).
After you've decided where to put [test environment orchestration scenarios](https://gitlab.com/gitlab-org/gitlab-qa/tree/master/lib/gitlab/qa/scenario) and [instance-level scenarios](https://gitlab.com/gitlab-org/gitlab-foss/tree/master/qa/qa/specs/features), take a look at the [GitLab QA README](https://gitlab.com/gitlab-org/gitlab/-/tree/master/qa/README.md), the [GitLab QA orchestrator README](https://gitlab.com/gitlab-org/gitlab-qa/tree/master/README.md), and [the already existing instance-level scenarios](https://gitlab.com/gitlab-org/gitlab-foss/tree/master/qa/qa/specs/features).
### Consider **not** writing an end-to-end test
We should follow these best practices for end-to-end tests:
- Do not write an end-to-end test if a lower-level feature test exists. End-to-end tests require more work and resources.
- Troubleshooting for end-to-end tests can be more complex as connections to the application under test are not known.
## Continued reading
### Getting started with E2E testing
- [Beginner's Guide](beginners_guide/_index.md): An introductory guide to help new contributors get started with E2E testing
- [Flows](beginners_guide/flows.md): Overview of `Flows` used to capture reusable sequences of actions in tests
- [Page objects](beginners_guide/page_objects.md): Explanation of page objects and their role in test design
- [Resources](beginners_guide/resources.md): Overview of `Resources` class that used for creating test data
### Best practices
- [Best practices when writing end-to-end tests](best_practices/_index.md): Guidelines for efficient and reliable E2E testing
- [Dynamic element validation](best_practices/dynamic_element_validation.md): Techniques for handling dynamic elements in tests
- [Execution context selection](best_practices/execution_context_selection.md): Tips for choosing the right execution context for tests to run on
- [Testing with feature flags](best_practices/feature_flags.md): Managing feature flags during tests
- [RSpec metadata for end-to-end tests](best_practices/rspec_metadata_tests.md): Using metadata to organize and categorize tests
- [Test users](best_practices/users.md): Guidelines for creating and managing test users
- [Waits](best_practices/waits.md): Best practices for using waits to handle asynchronous elements
- [Style guide for writing end-to-end tests](style_guide.md): Standards and conventions to ensure consistency in E2E tests
### Testing infrastructure
- [Test pipelines](test_pipelines.md): Overview of the pipeline setup for E2E tests, including parallelization and CI configuration
- [Test infrastructure for cloud integrations](test_infrastructure.md): Describes cloud-specific setups
### Running and troubleshooting tests
- [Running tests](running_tests/_index.md): Instructions for executing tests
- [Running tests that require special setup](running_tests/running_tests_that_require_special_setup.md): Specific setup requirements for certain tests
- [Troubleshooting](troubleshooting.md): Common issues encountered during E2E testing and solutions
### Miscellaneous
- [Developer Experience Sub-Department handbook](https://handbook.gitlab.com/handbook/engineering/infrastructure-platforms/developer-experience/): Topics related to our vision, monitoring practices, failure triage processes, etc
- [`gitlab-qa`](https://gitlab.com/gitlab-org/gitlab-qa/-/tree/master/docs): For information regarding the use of the GitLab QA orchestrator
- [`customers-gitlab-com`](https://gitlab.com/gitlab-org/customers-gitlab-com/-/tree/main/qa/doc) (internal only): For guides that are specific to the CustomersDot platform
## Where can you ask for help?
You can ask question in the `#s_developer_experience` channel on Slack (GitLab internal) or you can find an issue you would like to work on in [the `gitlab` issue tracker](https://gitlab.com/gitlab-org/gitlab/-/issues?label_name%5B%5D=QA&label_name%5B%5D=test).
|
https://docs.gitlab.com/development/testing_guide/test_pipelines
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/testing_guide/test_pipelines.md
|
2025-08-13
|
doc/development/testing_guide/end_to_end
|
[
"doc",
"development",
"testing_guide",
"end_to_end"
] |
test_pipelines.md
|
none
|
unassigned
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
End-to-end test pipelines
| null |
## Common architecture
All E2E tests are executed within separate child pipelines. To support different dynamic features of E2E testing pipelines, all child pipeline YAML files are generated by `e2e-test-pipeline-generate` CI/CD job and triggered by respective trigger job.
### e2e-test-pipeline-generate
The `e2e-test-pipeline-generate` job generates CI/CD YAML file definitions which are used to trigger child pipelines that run E2E tests.
The [`generate_e2e_pipelines`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/qa/tasks/ci.rake) Rake task:
1. Determines which e2e specs should be executed in a particular merge request pipeline.
1. Generates a CI/CD YAML file definition for each E2E test pipeline type.
This Rake task:
1. Analyzes changes in a particular merge request and determines which specs must be executed using selective test execution with
[these criteria](_index.md#selective-test-execution). Based on that, a `dry-run` of every
[scenario](https://gitlab.com/gitlab-org/gitlab/-/tree/master/qa/qa/scenario/test) executes and determines if a scenario contains any executable tests.
1. The total run time for each scenario is calculated.
1. Based on the run time value, [dynamic job scaling](_index.md#dynamic-parallel-job-scaling) calculates the necessary number of parallel CI/CD jobs for each scenario type
and generates pipeline YAML file with appropriate values.
## `e2e:perf-on-cng`
The `e2e:perf-on-cng` child pipeline runs tests against a [Cloud Native GitLab](https://gitlab.com/gitlab-org/build/CNG) installation.
Deployment is managed by the [`orchestrator`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/qa/gems/gitlab-orchestrator/README.md)
CLI tool, which you can also use to locally recreate CI/CD deployments.
The `e2e:perf-on-cng` child pipeline is executed in merge requests and is a non blocking job. If any test fails, it won't block your merge requests from being merged.
### Setup
This E2E test child pipeline is triggered by the `e2e:perf-on-cng` job using dynamically generated CI/CD YAML file stored as artifacts in the `e2e-test-pipeline-generate`
CI/CD job. CI/CD YAML files are generated using a [template](https://gitlab.com/gitlab-org/gitlab/-/blob/master/.gitlab/ci/test-on-cng/main.gitlab-ci.yml).
### child pipeline jobs
The child pipeline consists of several stages that support E2E test execution.
#### .pre
- `build-cng-env` job is responsible for setting up all environment variables for [CNG](https://gitlab.com/gitlab-org/build/CNG-mirror) downstream pipeline
- `build-cng` job triggers `CNG` downstream pipeline which is responsible for building all necessary images
#### prepare
- `dotenv-vars` job is responsible to create an artifact out of the `qa/performance_test` folder which consists of all the k6 performance test. This artifact will be downloaded by downstream pipeline jobs to run the tests. It also stores some env vars like `CI_JOB_NAME`, `CI_JOB_ID` and `GITLAB_HELM_CHART_REF` as can be seen in the [job definition](https://gitlab.com/gitlab-org/gitlab/-/blob/andywh/perf_testing_in_mr/.gitlab/ci/performance-on-cng/main.gitlab-ci.yml#L52-54), which will be used by `run-performance-tests` job
#### test
##### `run-performance-test` job
This job triggers a downstream multi-project pipeline in [Component Performance testing](https://gitlab.com/gitlab-org/quality/component-performance-testing) project. This pipeline performs the following actions
1. Creates two gpc instances in the same region and zone.
1. server instance: where CNG instance of GitLab is created using `orchestrator`
1. local k8s cluster setup using [`kind`](https://github.com/kubernetes-sigs/kind)
1. GitLab installation using official [`helm` chart](https://gitlab.com/gitlab-org/charts/gitlab)
1. test runner instance: which runs the k6 tests download as an artifact from `dotenv-vars` job and runs it against the CNG GitLab instance created on the server instance.
### Troubleshooting
Sometimes the multi-project job under `run-performance-test` job may fail during data seeding with gem incompatibility error.
An example of the error is
```shell
/usr/lib/ruby/gems/3.3.0/gems/bundler-2.6.9/lib/bundler/vendor/pub_grub/lib/pub_grub/version_solver.rb:225:in `resolve_conflict': Could not find compatible versions (Bundler::PubGrub::SolveFailure)
Because every version of gitlab-backup-cli depends on grpc ~> 1.74.0
and Gemfile depends on gitlab-backup-cli >= 0,
grpc ~> 1.74.0 is required.
```
This happens because there might have been an update on the Gemfile which your merge request doesn't contain. Rebasing the merge request branch with the master branch should fix this issue.
## `e2e:test-on-cng`
The `e2e:test-on-cng` child pipeline runs tests against a [Cloud Native GitLab](https://gitlab.com/gitlab-org/build/CNG) installation.
Deployment is managed by the [`orchestrator`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/qa/gems/gitlab-orchestrator/README.md)
CLI tool, which you can also use to locally recreate CI/CD deployments.
The `e2e:test-on-cng` child pipeline is executed in merge requests and is part of pre-merge validation lifecycle. If any test fails, you can't merge introduced
code changes.
### Setup
This E2E test child pipeline is triggered by the `e2e:test-on-cng` job using dynamically generated CI/CD YAML file stored as artifacts in the `e2e-test-pipeline-generate`
CI/CD job. CI/CD YAML files are generated using a [template](https://gitlab.com/gitlab-org/gitlab/-/blob/master/.gitlab/ci/test-on-cng/main.gitlab-ci.yml).
### child pipeline jobs
The child pipeline consists of several stages that support E2E test execution.
#### .pre
- `build-cng-env` job is responsible for setting up all environment variables for [CNG](https://gitlab.com/gitlab-org/build/CNG-mirror) downstream pipeline
- `build-cng` job triggers `CNG` downstream pipeline which is responsible for building all necessary images
#### test
Jobs in `test` stage perform following actions:
1. local k8s cluster setup using [`kind`](https://github.com/kubernetes-sigs/kind)
1. GitLab installation using official [`helm` chart](https://gitlab.com/gitlab-org/charts/gitlab)
1. E2E test execution against performed deployment
##### report
This stage is responsible for [allure test report](_index.md#allure-report) generation.
### Debugging
To help with debugging:
- Each test job prints a list of arguments that you can pass to the [`orchestrator`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/qa/gems/gitlab-orchestrator/README.md) to exactly recreate the same deployment for local debugging.
- Cluster events log and all pod logs are saved in E2E test job artifacts.
- `orchestrator` automatically outputs all cluster events with errors in the case of failed deployment.
## `e2e:test-on-omnibus-ee`
The `e2e:test-on-omnibus-ee` child pipeline runs tests against an [Omnibus](https://gitlab.com/gitlab-org/omnibus-gitlab) installation. This pipeline type is not executed
in merge request pipelines by default and can be triggered manually by triggering the `e2e:test-on-omnibus-ee` job.
This pipeline type is allowed to fail and even in the case of a manual trigger inside of a merge request pipeline, failing tests will not block the ability to merge.
Linux package deployment is managed by [`gitlab-qa`](https://gitlab.com/gitlab-org/gitlab-qa).
### Setup
This E2E test child pipeline is triggered by the `e2e:test-on-omnibus-ee` job using dynamically generated CI/CD YAML file stored as artifacts in
`e2e-test-pipeline-generate` CI/CD jobs. The CI/CD YAML file is generated using a
[template](https://gitlab.com/gitlab-org/gitlab/-/blob/master/.gitlab/ci/test-on-omnibus/main.gitlab-ci.yml).
### child pipeline jobs
E2E test execution pipeline consists of several stages which all support execution of E2E tests.
#### .pre
This stage is responsible for the following tasks:
- Triggering downstream pipeline which builds the [`omnibus-gitlab`](https://gitlab.com/gitlab-org/omnibus-gitlab) Docker image.
#### test
Jobs in `test` stage perform following actions:
1. Installs GitLab by using a built Linux package.
1. Executes E2E tests against the Linux package installation.
#### report
This stage is responsible for [allure test report](_index.md#allure-report) generation.
## `e2e:test-on-gdk`
The `e2e:test-on-gdk` child pipeline supports development of the GitLab platform by providing feedback to engineers on
end-to-end test execution faster than via `e2e:test-on-omnibus-ee`.
This is achieved by running tests against the [GitLab Development Kit](https://gitlab.com/gitlab-org/gitlab-development-kit) (GDK),
which can be built and installed in less time than when testing against [Omnibus GitLab](https://gitlab.com/gitlab-org/omnibus-gitlab).
The trade-off is that Omnibus GitLab can be used to deploy a production installation, whereas the GDK is a development
environment. Tests that run against the GDK might not catch bugs that depend on part of the process of preparing GitLab
to run in a production environment, including pre-compiling assets, assigning configuration defaults as part of an official
installation package, deploying GitLab services to multiple servers, and more. On the other hand, engineers who use the
GDK day-to-day can benefit from automated tests catching bugs that only appear on the GDK.
### Setup
This E2E test child pipeline is triggered by the `e2e:test-on-gdk` job using dynamically generated CI/CD YAML file stored as artifacts in the `e2e-test-pipeline-generate`
CI/CD job. The CI/CD YAML file is generated by using a [template](https://gitlab.com/gitlab-org/gitlab/-/blob/master/.gitlab/ci/test-on-gdk/main.gitlab-ci.yml).
#### `build-gdk-image`
[The `build-gdk-image` job](https://gitlab.com/gitlab-org/gitlab/-/blob/07504c34b28ac656537cd60810992aa15e9e91b8/.gitlab/ci/build-images.gitlab-ci.yml#L32)
uses the code from the merge request to build a Docker image that can be used in test jobs to launch a GDK instance in a container. The image is pushed to the container registry.
The job also runs in pipelines on the default branch to build a base image that includes the GDK and GitLab components.
This avoids building the entire image from scratch in merge requests. However, if the merge request includes changes to
[certain GitLab components or code](https://gitlab.com/gitlab-org/gitlab/-/blob/24109c1a7ae1f29d4f6f1aeba3a13cbd8ea0e8e6/.gitlab/ci/rules.gitlab-ci.yml#L911)
the job will rebuild the base image before building the image that will be used in the test jobs.
#### child pipeline jobs
The child pipeline consists of several stages that support E2E test execution.
##### test
Jobs in the `test` stage perform following actions:
1. Start an instance of GDK by using the Docker image built by the [`build-gdk-image`](#build-gdk-image) job.
1. Run E2E tests against the running instance of GDK.
#### report
This stage is responsible for [allure test report](_index.md#allure-report) generation.
## Test Licenses
For more information on the licenses these pipelines use, see [test licenses](https://gitlab-org.gitlab.io/quality/runbooks/test_licenses/).
## Adding new jobs to E2E test pipelines
E2E test pipelines use dynamic scaling of jobs based on their runtime. To create a mapping between job definitions in pipeline definition YAML files and
a particular test scenario, `scenario` classes are used. These classes are located in `qa/qa/scenario` folder.
A typical job definition in one of the e2e test pipeline definition YAML files would look like:
```yaml
my-new-test-job:
# ...
variables:
QA_SCENARIO: Test::Integration::MyNewTestScenario
```
In this example:
- `QA_SCENARIO: Test::Integration::MyNewTestScenario`: name of the scenario class that is passed to the `qa/bin/qa` test execution script. While the full class
name would be `QA::Scenario::Test:Integration::MyNewTestScenario`, `QA::Scenario` is omitted to have shorted definitions.
Considering example above, perform the following steps to create a new job:
1. Create a new scenario `my_new_job.rb` in the [`integration`](https://gitlab.com/gitlab-org/gitlab/-/tree/master/qa/qa/scenario/test/integration) directory
of the [`e2e`](https://gitlab.com/gitlab-org/gitlab/-/tree/master/qa) test framework. The scenario class should define a pipeline mapping that couples the
scenario to a specific job in a specific pipeline type. If job was added to the [test-on-cng](#e2etest-on-cng) pipeline, this scenario would define RSpec
tags that should be executed and pipeline mapping:
```ruby
module QA
module Scenario
module Test
module Integration
class MyNewJob < Test::Instance::All
tags :some_special_tag
pipeline_mappings test_on_cng: %w[my-new-test-job]
end
end
end
end
end
```
1. Add the new job definition in the [`main.gitlab-ci.yml`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/.gitlab/ci/test-on-cng/main.gitlab-ci.yml)
pipeline definition:
```yaml
my-new-test-job:
extends:
- .cng-test
variables:
QA_SCENARIO: Test::Integration::MyNewTestScenario
```
Such a definition ensures that `my-new-test-job` has automatic parallel job scaling based on predefined runtime threshold.
|
---
stage: none
group: unassigned
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: End-to-end test pipelines
breadcrumbs:
- doc
- development
- testing_guide
- end_to_end
---
## Common architecture
All E2E tests are executed within separate child pipelines. To support different dynamic features of E2E testing pipelines, all child pipeline YAML files are generated by `e2e-test-pipeline-generate` CI/CD job and triggered by respective trigger job.
### e2e-test-pipeline-generate
The `e2e-test-pipeline-generate` job generates CI/CD YAML file definitions which are used to trigger child pipelines that run E2E tests.
The [`generate_e2e_pipelines`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/qa/tasks/ci.rake) Rake task:
1. Determines which e2e specs should be executed in a particular merge request pipeline.
1. Generates a CI/CD YAML file definition for each E2E test pipeline type.
This Rake task:
1. Analyzes changes in a particular merge request and determines which specs must be executed using selective test execution with
[these criteria](_index.md#selective-test-execution). Based on that, a `dry-run` of every
[scenario](https://gitlab.com/gitlab-org/gitlab/-/tree/master/qa/qa/scenario/test) executes and determines if a scenario contains any executable tests.
1. The total run time for each scenario is calculated.
1. Based on the run time value, [dynamic job scaling](_index.md#dynamic-parallel-job-scaling) calculates the necessary number of parallel CI/CD jobs for each scenario type
and generates pipeline YAML file with appropriate values.
## `e2e:perf-on-cng`
The `e2e:perf-on-cng` child pipeline runs tests against a [Cloud Native GitLab](https://gitlab.com/gitlab-org/build/CNG) installation.
Deployment is managed by the [`orchestrator`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/qa/gems/gitlab-orchestrator/README.md)
CLI tool, which you can also use to locally recreate CI/CD deployments.
The `e2e:perf-on-cng` child pipeline is executed in merge requests and is a non blocking job. If any test fails, it won't block your merge requests from being merged.
### Setup
This E2E test child pipeline is triggered by the `e2e:perf-on-cng` job using dynamically generated CI/CD YAML file stored as artifacts in the `e2e-test-pipeline-generate`
CI/CD job. CI/CD YAML files are generated using a [template](https://gitlab.com/gitlab-org/gitlab/-/blob/master/.gitlab/ci/test-on-cng/main.gitlab-ci.yml).
### child pipeline jobs
The child pipeline consists of several stages that support E2E test execution.
#### .pre
- `build-cng-env` job is responsible for setting up all environment variables for [CNG](https://gitlab.com/gitlab-org/build/CNG-mirror) downstream pipeline
- `build-cng` job triggers `CNG` downstream pipeline which is responsible for building all necessary images
#### prepare
- `dotenv-vars` job is responsible to create an artifact out of the `qa/performance_test` folder which consists of all the k6 performance test. This artifact will be downloaded by downstream pipeline jobs to run the tests. It also stores some env vars like `CI_JOB_NAME`, `CI_JOB_ID` and `GITLAB_HELM_CHART_REF` as can be seen in the [job definition](https://gitlab.com/gitlab-org/gitlab/-/blob/andywh/perf_testing_in_mr/.gitlab/ci/performance-on-cng/main.gitlab-ci.yml#L52-54), which will be used by `run-performance-tests` job
#### test
##### `run-performance-test` job
This job triggers a downstream multi-project pipeline in [Component Performance testing](https://gitlab.com/gitlab-org/quality/component-performance-testing) project. This pipeline performs the following actions
1. Creates two gpc instances in the same region and zone.
1. server instance: where CNG instance of GitLab is created using `orchestrator`
1. local k8s cluster setup using [`kind`](https://github.com/kubernetes-sigs/kind)
1. GitLab installation using official [`helm` chart](https://gitlab.com/gitlab-org/charts/gitlab)
1. test runner instance: which runs the k6 tests download as an artifact from `dotenv-vars` job and runs it against the CNG GitLab instance created on the server instance.
### Troubleshooting
Sometimes the multi-project job under `run-performance-test` job may fail during data seeding with gem incompatibility error.
An example of the error is
```shell
/usr/lib/ruby/gems/3.3.0/gems/bundler-2.6.9/lib/bundler/vendor/pub_grub/lib/pub_grub/version_solver.rb:225:in `resolve_conflict': Could not find compatible versions (Bundler::PubGrub::SolveFailure)
Because every version of gitlab-backup-cli depends on grpc ~> 1.74.0
and Gemfile depends on gitlab-backup-cli >= 0,
grpc ~> 1.74.0 is required.
```
This happens because there might have been an update on the Gemfile which your merge request doesn't contain. Rebasing the merge request branch with the master branch should fix this issue.
## `e2e:test-on-cng`
The `e2e:test-on-cng` child pipeline runs tests against a [Cloud Native GitLab](https://gitlab.com/gitlab-org/build/CNG) installation.
Deployment is managed by the [`orchestrator`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/qa/gems/gitlab-orchestrator/README.md)
CLI tool, which you can also use to locally recreate CI/CD deployments.
The `e2e:test-on-cng` child pipeline is executed in merge requests and is part of pre-merge validation lifecycle. If any test fails, you can't merge introduced
code changes.
### Setup
This E2E test child pipeline is triggered by the `e2e:test-on-cng` job using dynamically generated CI/CD YAML file stored as artifacts in the `e2e-test-pipeline-generate`
CI/CD job. CI/CD YAML files are generated using a [template](https://gitlab.com/gitlab-org/gitlab/-/blob/master/.gitlab/ci/test-on-cng/main.gitlab-ci.yml).
### child pipeline jobs
The child pipeline consists of several stages that support E2E test execution.
#### .pre
- `build-cng-env` job is responsible for setting up all environment variables for [CNG](https://gitlab.com/gitlab-org/build/CNG-mirror) downstream pipeline
- `build-cng` job triggers `CNG` downstream pipeline which is responsible for building all necessary images
#### test
Jobs in `test` stage perform following actions:
1. local k8s cluster setup using [`kind`](https://github.com/kubernetes-sigs/kind)
1. GitLab installation using official [`helm` chart](https://gitlab.com/gitlab-org/charts/gitlab)
1. E2E test execution against performed deployment
##### report
This stage is responsible for [allure test report](_index.md#allure-report) generation.
### Debugging
To help with debugging:
- Each test job prints a list of arguments that you can pass to the [`orchestrator`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/qa/gems/gitlab-orchestrator/README.md) to exactly recreate the same deployment for local debugging.
- Cluster events log and all pod logs are saved in E2E test job artifacts.
- `orchestrator` automatically outputs all cluster events with errors in the case of failed deployment.
## `e2e:test-on-omnibus-ee`
The `e2e:test-on-omnibus-ee` child pipeline runs tests against an [Omnibus](https://gitlab.com/gitlab-org/omnibus-gitlab) installation. This pipeline type is not executed
in merge request pipelines by default and can be triggered manually by triggering the `e2e:test-on-omnibus-ee` job.
This pipeline type is allowed to fail and even in the case of a manual trigger inside of a merge request pipeline, failing tests will not block the ability to merge.
Linux package deployment is managed by [`gitlab-qa`](https://gitlab.com/gitlab-org/gitlab-qa).
### Setup
This E2E test child pipeline is triggered by the `e2e:test-on-omnibus-ee` job using dynamically generated CI/CD YAML file stored as artifacts in
`e2e-test-pipeline-generate` CI/CD jobs. The CI/CD YAML file is generated using a
[template](https://gitlab.com/gitlab-org/gitlab/-/blob/master/.gitlab/ci/test-on-omnibus/main.gitlab-ci.yml).
### child pipeline jobs
E2E test execution pipeline consists of several stages which all support execution of E2E tests.
#### .pre
This stage is responsible for the following tasks:
- Triggering downstream pipeline which builds the [`omnibus-gitlab`](https://gitlab.com/gitlab-org/omnibus-gitlab) Docker image.
#### test
Jobs in `test` stage perform following actions:
1. Installs GitLab by using a built Linux package.
1. Executes E2E tests against the Linux package installation.
#### report
This stage is responsible for [allure test report](_index.md#allure-report) generation.
## `e2e:test-on-gdk`
The `e2e:test-on-gdk` child pipeline supports development of the GitLab platform by providing feedback to engineers on
end-to-end test execution faster than via `e2e:test-on-omnibus-ee`.
This is achieved by running tests against the [GitLab Development Kit](https://gitlab.com/gitlab-org/gitlab-development-kit) (GDK),
which can be built and installed in less time than when testing against [Omnibus GitLab](https://gitlab.com/gitlab-org/omnibus-gitlab).
The trade-off is that Omnibus GitLab can be used to deploy a production installation, whereas the GDK is a development
environment. Tests that run against the GDK might not catch bugs that depend on part of the process of preparing GitLab
to run in a production environment, including pre-compiling assets, assigning configuration defaults as part of an official
installation package, deploying GitLab services to multiple servers, and more. On the other hand, engineers who use the
GDK day-to-day can benefit from automated tests catching bugs that only appear on the GDK.
### Setup
This E2E test child pipeline is triggered by the `e2e:test-on-gdk` job using dynamically generated CI/CD YAML file stored as artifacts in the `e2e-test-pipeline-generate`
CI/CD job. The CI/CD YAML file is generated by using a [template](https://gitlab.com/gitlab-org/gitlab/-/blob/master/.gitlab/ci/test-on-gdk/main.gitlab-ci.yml).
#### `build-gdk-image`
[The `build-gdk-image` job](https://gitlab.com/gitlab-org/gitlab/-/blob/07504c34b28ac656537cd60810992aa15e9e91b8/.gitlab/ci/build-images.gitlab-ci.yml#L32)
uses the code from the merge request to build a Docker image that can be used in test jobs to launch a GDK instance in a container. The image is pushed to the container registry.
The job also runs in pipelines on the default branch to build a base image that includes the GDK and GitLab components.
This avoids building the entire image from scratch in merge requests. However, if the merge request includes changes to
[certain GitLab components or code](https://gitlab.com/gitlab-org/gitlab/-/blob/24109c1a7ae1f29d4f6f1aeba3a13cbd8ea0e8e6/.gitlab/ci/rules.gitlab-ci.yml#L911)
the job will rebuild the base image before building the image that will be used in the test jobs.
#### child pipeline jobs
The child pipeline consists of several stages that support E2E test execution.
##### test
Jobs in the `test` stage perform following actions:
1. Start an instance of GDK by using the Docker image built by the [`build-gdk-image`](#build-gdk-image) job.
1. Run E2E tests against the running instance of GDK.
#### report
This stage is responsible for [allure test report](_index.md#allure-report) generation.
## Test Licenses
For more information on the licenses these pipelines use, see [test licenses](https://gitlab-org.gitlab.io/quality/runbooks/test_licenses/).
## Adding new jobs to E2E test pipelines
E2E test pipelines use dynamic scaling of jobs based on their runtime. To create a mapping between job definitions in pipeline definition YAML files and
a particular test scenario, `scenario` classes are used. These classes are located in `qa/qa/scenario` folder.
A typical job definition in one of the e2e test pipeline definition YAML files would look like:
```yaml
my-new-test-job:
# ...
variables:
QA_SCENARIO: Test::Integration::MyNewTestScenario
```
In this example:
- `QA_SCENARIO: Test::Integration::MyNewTestScenario`: name of the scenario class that is passed to the `qa/bin/qa` test execution script. While the full class
name would be `QA::Scenario::Test:Integration::MyNewTestScenario`, `QA::Scenario` is omitted to have shorted definitions.
Considering example above, perform the following steps to create a new job:
1. Create a new scenario `my_new_job.rb` in the [`integration`](https://gitlab.com/gitlab-org/gitlab/-/tree/master/qa/qa/scenario/test/integration) directory
of the [`e2e`](https://gitlab.com/gitlab-org/gitlab/-/tree/master/qa) test framework. The scenario class should define a pipeline mapping that couples the
scenario to a specific job in a specific pipeline type. If job was added to the [test-on-cng](#e2etest-on-cng) pipeline, this scenario would define RSpec
tags that should be executed and pipeline mapping:
```ruby
module QA
module Scenario
module Test
module Integration
class MyNewJob < Test::Instance::All
tags :some_special_tag
pipeline_mappings test_on_cng: %w[my-new-test-job]
end
end
end
end
end
```
1. Add the new job definition in the [`main.gitlab-ci.yml`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/.gitlab/ci/test-on-cng/main.gitlab-ci.yml)
pipeline definition:
```yaml
my-new-test-job:
extends:
- .cng-test
variables:
QA_SCENARIO: Test::Integration::MyNewTestScenario
```
Such a definition ensures that `my-new-test-job` has automatic parallel job scaling based on predefined runtime threshold.
|
https://docs.gitlab.com/development/testing_guide/tips_and_tricks
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/testing_guide/tips_and_tricks.md
|
2025-08-13
|
doc/development/testing_guide/end_to_end
|
[
"doc",
"development",
"testing_guide",
"end_to_end"
] |
tips_and_tricks.md
| null | null | null |
Test Governance Tips and Tricks
|
This page lists a number of tips and tricks we have found useful in day to day end-to-end test level related tasks.
|
## Overview
This page lists a number of tips and tricks we have found useful in day to day Quality Engineering related
tasks.
## Running GitLab-QA pipeline against a specific GitLab release
While working on the [GitLab-QA codebase](https://gitlab.com/gitlab-org/gitlab-qa), it is sometimes helpful to run the GitLab-QA pipeline
against a specific release of the [GitLab project](https://gitlab.com/gitlab-org/gitlab). This could be
due reasons such as that particular GitLab release containing specific code needed for validating the changes made
in GitLab-QA. To run a [GitLab-QA pipeline](https://gitlab.com/gitlab-org/gitlab-qa/pipelines) against
a specific GitLab release, we need to know the GitLab release version created and tagged by the omnibus pipeline.
This can be found by either observing the `RELEASE` variable in any of the `test-on-omnibus` test jobs or
in the last output line of the `Trigger:gitlab-docker` job triggered by the `test-on-omnibus` job. Here is an example of what the `RELEASE` string
looks like:
```shell
registry.gitlab.com/gitlab-org/omnibus-gitlab/gitlab-ee:41b42271ff37bf79066ef3089432ee28cfd81d8c
```
Copy this string and create a new [GitLab-QA pipeline](https://gitlab.com/gitlab-org/gitlab-qa/pipelines)
with a `RELEASE` variable and use the copied string as its value. Create another variable called `QA_IMAGE` and set it to the value
that can be found in the `test-on-omnibus` upstream job. Here is an example of what the `QA_IMAGE` string looks like:
```shell
registry.gitlab.com/gitlab-org/gitlab/gitlab-ee-qa:qa-shl-use-unique-group-for-access-termination-specs
```
Note that the string is the same as `RELEASE` except for the `-qa` suffix on the image name and the tag which is the branch name on the GitLab project.
Now run the pipeline against the branch that has your changes.
It's also possible to trigger a manual GitLab-QA pipeline against a specific [GitLab environment](https://handbook.gitlab.com/handbook/engineering/testing/end-to-end-pipeline-monitoring/) using the `RELEASE` and `QA_IMAGE` variable from the `test-on-omnibus` job of GitLab Merge Request.
For example, here is the link to run a manual GitLab QA pipeline [against Staging](https://ops.gitlab.net/gitlab-org/quality/staging/-/pipelines/new?var[RELEASE]=%27insert_docker_release_image_name_from_the_MR%27&var[QA_IMAGE]=%27insert_docker_qa_image_name_from_the_MR%27&var[GITLAB_QA_CONTAINER_REGISTRY_ACCESS_TOKEN]=%27insert_gitlab_qa_user_production_access_token%27).
- Note: If `registry.gitlab.com` is used, you will also need to include the `GITLAB_QA_CONTAINER_REGISTRY_ACCESS_TOKEN` variable with the value set to the production `gitlab-qa` user's access token to avoid authentication errors.
## Running end-to-end test pipelines using code from a specific GitLab-QA branch
### Running from a specific GitLab-QA branch against a live environment
It is often needed to test the impact of changes in the [GitLab-QA codebase](https://gitlab.com/gitlab-org/gitlab-qa) on
[`gitlab-org/gitlab` nightly schedule pipeline](https://gitlab.com/gitlab-org/gitlab/-/pipeline_schedules), [Staging](https://ops.gitlab.net/gitlab-org/quality/staging/-/pipelines),
[Pre-Prod](https://ops.gitlab.net/gitlab-org/quality/preprod/-/pipelines), [Canary](https://ops.gitlab.net/gitlab-org/quality/canary/-/pipelines)
or [Production](https://ops.gitlab.net/gitlab-org/quality/production/-/pipelines) pipelines.
This can be achieved by manually triggering a pipeline in any of these projects and setting the `QA_BRANCH` variable to the branch name you are working on in the [GitLab-QA project](https://gitlab.com/gitlab-org/gitlab-qa).
As a result, the pipeline will checkout the specified branch and build the `gitlab-qa` gem instead of using the latest published gem.
### Running from a specific GitLab-QA branch against a GitLab branch MR
You can checkout a test branch and edit the `Gemfile` to change the `gitlab-qa` line to install via the GitLab-QA branch.
For example in the `qa/gemfile`:
```console
gem 'gitlab-qa', git: 'https://gitlab.com/gitlab-org/gitlab-qa.git', branch: '<GitLab-QA-branch>'
```
Make sure to also `bundle install` and commit the `Gemfile.lock` as well.
Doing so successfully will allow the `gitlab-qa` gem to be built from a custom branch.
## Configure VS Code for GitLab-qa debugging
The [Ruby LSP VS Code extension](https://marketplace.visualstudio.com/items?itemName=Shopify.ruby-lsp) adds a few Ruby-related capabilities to VS Code, including the ability to debug Ruby code.
After you install the extension you can use VS Code to debug end-to-end specs running against your local GDK. You will need to add a Run configuration to `launch.json`. For example, the following `launch.json` will add a configuration named `Debug Test::Instance::All current file` to the list in the Run view of your Sidebar. Then, with a spec file open in the editor you can start debugging (F5) and VS Code will run the tests in the spec file.
```json
{
"version": "0.2.0",
"configurations": [
{
"name": "Debug Test::Instance::All current file",
"type": "ruby_lsp",
"request": "launch",
"useBundler": true,
"pathToBundler": "<path_to_bundler>",
"cwd": "${workspaceRoot}/qa",
"program": "${workspaceRoot}/qa/bin/qa",
"env": {
"CHROME_HEADLESS": "false",
"QA_DEBUG": "true"
},
"args": [
"Test::Instance::All",
"http://localhost:3000",
"--",
"${file}"
]
}
]
}
```
You can include multiple configurations, and any environment variables or command line options can be included. For example, here's one that will debug smoke tests while running them on Staging:
```json
{
"name": "Debug Staging Smoke tests",
"type": "Ruby",
"request": "launch",
"useBundler": true,
"pathToBundler": "<path_to_bundler>",
"cwd": "${workspaceRoot}/qa",
"program": "${workspaceRoot}/qa/bin/qa",
"env": {
"CHROME_HEADLESS": "false",
"QA_DEBUG": "true",
"GITLAB_USERNAME": "gitlab-qa",
"GITLAB_PASSWORD": "from 1Password",
"GITLAB_QA_ACCESS_TOKEN": "from 1Password"
},
"args": [
"Test::Instance::All",
"https://staging.gitlab.com",
"--",
"--tag", "smoke"
]
}
```
## Set up experimental auto-scaled runners
Sometimes, it's useful to [deploy auto-scaled runners to try out and compare different machine types](https://gitlab.com/gitlab-com/www-gitlab-com/-/issues/10623).
To do so, follow these steps:
1. Create a service account to access shared cache in [the `gitlab-qa-resources` GCP project](https://console.cloud.google.com/iam-admin/serviceaccounts?project=gitlab-qa-resources).
1. Download the service account credentials JSON file.
1. Create a VM instance to host the auto-scaled runners manager in [the `gitlab-qa-resources` GCP project](https://console.cloud.google.com/compute/instances?project=gitlab-qa-resources).
1. Add the service account to the VM instance.
1. Add you SSH key to the VM instance.
1. Upload the service account credentials JSON file to the VM instance (e.g. `scp ~/Downloads/gitlab-qa-resources-abc123.json <your-username>@VM-IP:/home/<your-username>`).
1. Create a storage bucket for the shared cache in [the `gitlab-qa-resources` GCP project](https://console.cloud.google.com/storage/browser?project=gitlab-qa-resources).
1. SSH into the VM instance (using GCP's Web interface).
1. Follow [the installation steps for auto-scaled runners manager](https://docs.gitlab.com/runner/executors/docker_machine.html#preparing-the-environment):
1. [Install `gitlab-runner`](https://docs.gitlab.com/runner/install/linux-repository.html#installing-gitlab-runner).
1. [Install Docker Machine](https://web.archive.org/web/20210619101324/https://docs.docker.com/machine/install-machine/).
1. [Register the runner](https://docs.gitlab.com/runner/register/#linux)
1. Make sure to set a specific tag for the runner.
1. Set `docker+machine` as the runner executor.
1. Move the service account credentials JSON file to its final destination (using `sudo`): `sudo mv home/<your-username>/gitlab-qa-resources-abc123.json /etc/gitlab-runner/service-account.json`
1. Edit the runner manager with something like the following configuration (make sure to check the [`[runners.machine]`](https://docs.gitlab.com/runner/configuration/advanced-configuration.html#the-runnersmachine-section) documentation):
```toml
concurrent = 500
check_interval = 0
[session_server]
session_timeout = 1800
[[runners]]
name = "n2d-highcpu-4 Relevant description of the runner manager"
url = "https://gitlab.com/"
token = "[REDACTED]"
executor = "docker+machine"
limit = 500
pre_clone_script = "eval \"$CI_PRE_CLONE_SCRIPT\""
request_concurrency = 500
environment = [
"DOCKER_TLS_CERTDIR=",
"DOCKER_DRIVER=overlay2",
"FF_USE_DIRECT_DOWNLOAD=true",
"FF_GITLAB_REGISTRY_HELPER_IMAGE=true"
]
[runners.custom_build_dir]
enabled = true
[runners.cache]
Type = "gcs"
Shared = true
[runners.cache.gcs]
BucketName = "BUCKET-NAME-FOR-THE-SHARED-CACHE"
CredentialsFile = "/etc/gitlab-runner/service-account.json"
[runners.docker]
tls_verify = false
image = "ruby:2.7"
privileged = true
disable_entrypoint_overwrite = false
oom_kill_disable = false
disable_cache = false
shm_size = 0
volumes = [
"/cache",
"/certs/client"
]
[runners.machine]
IdleCount = 0
IdleTime = 600
MachineDriver = "google"
MachineName = "rymai-n2d-hc-4-%s"
MachineOptions = [
# Additional machine options can be added using the Google Compute Engine driver.
# If you experience problems with an unreachable host (ex. "Waiting for SSH"),
# you should remove optional parameters to help with debugging.
# https://docs.docker.com/machine/drivers/gce/
"google-project=gitlab-qa-resources",
"google-zone=us-central1-a", # e.g. 'us-central1-a', full list in https://cloud.google.com/compute/docs/regions-zones/
"google-machine-type=n2d-highcpu-4", # e.g. 'n1-standard-8'
"google-disk-size=50",
"google-disk-type=pd-ssd",
"google-label=gl_resource_type:ci_ephemeral",
"google-username=cos",
"google-operation-backoff-initial-interval=2",
"google-use-internal-ip",
"engine-registry-mirror=https://mirror.gcr.io",
]
OffPeakTimezone = ""
OffPeakIdleCount = 0
OffPeakIdleTime = 0
MaxBuilds = 20
[[runners.machine.autoscaling]]
Periods = ["* * 8-18 * * mon-fri *"] # During the weekends
IdleCount = 0
IdleTime = 600
Timezone = "UTC"
```
## Scripts and tools for automating tasks
### Toolbox
The [Quality Toolbox](https://gitlab.com/gitlab-org/quality/toolbox) contains several scripts that can be useful when working with GitLab end-to-end tests, such as one to [generate a report of flaky tests](https://gitlab.com/gitlab-org/quality/toolbox#generate-a-flaky-examples-report), or one to [report job success rates](https://gitlab.com/gitlab-org/quality/toolbox#pipeline-job-report).
### Rake tasks
The [`qa/tools` directory](https://gitlab.com/gitlab-org/gitlab/blob/master/qa/qa/tools/) contains Rake tasks that perform automated tasks on a schedule (such as [deleting subgroups](https://gitlab.com/gitlab-org/gitlab/-/blob/master/qa/qa/tools/delete_subgroups.rb) after a test run), or that can be run as needed (such as [revoking personal access tokens](https://gitlab.com/gitlab-org/gitlab/-/blob/master/qa/qa/tools/revoke_all_personal_access_tokens.rb)).
#### Delete Test SSH Keys
This script deletes SSH keys for a specific user. It can be executed via the `delete_test_ssh_keys` Rake task in the `qa` directory.
The Rake task accepts three arguments that can be used to limit the keys that are deleted, and to perform a dry run.
- The first argument, `title_portion`, limits keys to be deleted to those that include the string provided.
- The second argument, `delete_before`, limits keys to be deleted to those that were created before the given date.
- The third optional argument, `dry_run`, determines if the command will be executed as a dry run, summarizing the keys to be deleted. Set to `true` to execute as a dry run.
Two environment variables are also required:
- `GITLAB_ADDRESS` is the address of the target GitLab instance.
- `GITLAB_QA_ACCESS_TOKEN` should be a personal access token with API access and should belong to the user whose keys will be deleted.
For example, the following command will delete all SSH keys with a title that includes `E2E test key:` and that were created before `2020-08-02` on `https://staging.gitlab.com` for the user with the provided personal access token:
```shell
GITLAB_QA_ACCESS_TOKEN=secret GITLAB_ADDRESS=https://staging.gitlab.com bundle exec rake "delete_test_ssh_keys[E2E test key:, 2020-08-02]"
```
#### Set default password and create a personal access token
There is a Rake task to set the default password (from `Runtime::User.default_password`) if it's not set already, and it creates a personal access token.
This is useful when testing on a fresh GitLab instance (e.g., an omnibus-GitLab Docker image) and you don't want to have to log in and create an access token manually.
Usage example (run from the `gitlab/qa` directory):
```shell
$ bundle exec rake 'initialize_gitlab_auth[https://gitlab.test]'
Signing in and creating the default password for the root user if it's not set already...
Creating an API scoped access token for the root user...
Token: <some_token_value>
```
|
---
title: Test Governance Tips and Tricks
description: This page lists a number of tips and tricks we have found useful in day
to day end-to-end test level related tasks.
breadcrumbs:
- doc
- development
- testing_guide
- end_to_end
---
## Overview
This page lists a number of tips and tricks we have found useful in day to day Quality Engineering related
tasks.
## Running GitLab-QA pipeline against a specific GitLab release
While working on the [GitLab-QA codebase](https://gitlab.com/gitlab-org/gitlab-qa), it is sometimes helpful to run the GitLab-QA pipeline
against a specific release of the [GitLab project](https://gitlab.com/gitlab-org/gitlab). This could be
due reasons such as that particular GitLab release containing specific code needed for validating the changes made
in GitLab-QA. To run a [GitLab-QA pipeline](https://gitlab.com/gitlab-org/gitlab-qa/pipelines) against
a specific GitLab release, we need to know the GitLab release version created and tagged by the omnibus pipeline.
This can be found by either observing the `RELEASE` variable in any of the `test-on-omnibus` test jobs or
in the last output line of the `Trigger:gitlab-docker` job triggered by the `test-on-omnibus` job. Here is an example of what the `RELEASE` string
looks like:
```shell
registry.gitlab.com/gitlab-org/omnibus-gitlab/gitlab-ee:41b42271ff37bf79066ef3089432ee28cfd81d8c
```
Copy this string and create a new [GitLab-QA pipeline](https://gitlab.com/gitlab-org/gitlab-qa/pipelines)
with a `RELEASE` variable and use the copied string as its value. Create another variable called `QA_IMAGE` and set it to the value
that can be found in the `test-on-omnibus` upstream job. Here is an example of what the `QA_IMAGE` string looks like:
```shell
registry.gitlab.com/gitlab-org/gitlab/gitlab-ee-qa:qa-shl-use-unique-group-for-access-termination-specs
```
Note that the string is the same as `RELEASE` except for the `-qa` suffix on the image name and the tag which is the branch name on the GitLab project.
Now run the pipeline against the branch that has your changes.
It's also possible to trigger a manual GitLab-QA pipeline against a specific [GitLab environment](https://handbook.gitlab.com/handbook/engineering/testing/end-to-end-pipeline-monitoring/) using the `RELEASE` and `QA_IMAGE` variable from the `test-on-omnibus` job of GitLab Merge Request.
For example, here is the link to run a manual GitLab QA pipeline [against Staging](https://ops.gitlab.net/gitlab-org/quality/staging/-/pipelines/new?var[RELEASE]=%27insert_docker_release_image_name_from_the_MR%27&var[QA_IMAGE]=%27insert_docker_qa_image_name_from_the_MR%27&var[GITLAB_QA_CONTAINER_REGISTRY_ACCESS_TOKEN]=%27insert_gitlab_qa_user_production_access_token%27).
- Note: If `registry.gitlab.com` is used, you will also need to include the `GITLAB_QA_CONTAINER_REGISTRY_ACCESS_TOKEN` variable with the value set to the production `gitlab-qa` user's access token to avoid authentication errors.
## Running end-to-end test pipelines using code from a specific GitLab-QA branch
### Running from a specific GitLab-QA branch against a live environment
It is often needed to test the impact of changes in the [GitLab-QA codebase](https://gitlab.com/gitlab-org/gitlab-qa) on
[`gitlab-org/gitlab` nightly schedule pipeline](https://gitlab.com/gitlab-org/gitlab/-/pipeline_schedules), [Staging](https://ops.gitlab.net/gitlab-org/quality/staging/-/pipelines),
[Pre-Prod](https://ops.gitlab.net/gitlab-org/quality/preprod/-/pipelines), [Canary](https://ops.gitlab.net/gitlab-org/quality/canary/-/pipelines)
or [Production](https://ops.gitlab.net/gitlab-org/quality/production/-/pipelines) pipelines.
This can be achieved by manually triggering a pipeline in any of these projects and setting the `QA_BRANCH` variable to the branch name you are working on in the [GitLab-QA project](https://gitlab.com/gitlab-org/gitlab-qa).
As a result, the pipeline will checkout the specified branch and build the `gitlab-qa` gem instead of using the latest published gem.
### Running from a specific GitLab-QA branch against a GitLab branch MR
You can checkout a test branch and edit the `Gemfile` to change the `gitlab-qa` line to install via the GitLab-QA branch.
For example in the `qa/gemfile`:
```console
gem 'gitlab-qa', git: 'https://gitlab.com/gitlab-org/gitlab-qa.git', branch: '<GitLab-QA-branch>'
```
Make sure to also `bundle install` and commit the `Gemfile.lock` as well.
Doing so successfully will allow the `gitlab-qa` gem to be built from a custom branch.
## Configure VS Code for GitLab-qa debugging
The [Ruby LSP VS Code extension](https://marketplace.visualstudio.com/items?itemName=Shopify.ruby-lsp) adds a few Ruby-related capabilities to VS Code, including the ability to debug Ruby code.
After you install the extension you can use VS Code to debug end-to-end specs running against your local GDK. You will need to add a Run configuration to `launch.json`. For example, the following `launch.json` will add a configuration named `Debug Test::Instance::All current file` to the list in the Run view of your Sidebar. Then, with a spec file open in the editor you can start debugging (F5) and VS Code will run the tests in the spec file.
```json
{
"version": "0.2.0",
"configurations": [
{
"name": "Debug Test::Instance::All current file",
"type": "ruby_lsp",
"request": "launch",
"useBundler": true,
"pathToBundler": "<path_to_bundler>",
"cwd": "${workspaceRoot}/qa",
"program": "${workspaceRoot}/qa/bin/qa",
"env": {
"CHROME_HEADLESS": "false",
"QA_DEBUG": "true"
},
"args": [
"Test::Instance::All",
"http://localhost:3000",
"--",
"${file}"
]
}
]
}
```
You can include multiple configurations, and any environment variables or command line options can be included. For example, here's one that will debug smoke tests while running them on Staging:
```json
{
"name": "Debug Staging Smoke tests",
"type": "Ruby",
"request": "launch",
"useBundler": true,
"pathToBundler": "<path_to_bundler>",
"cwd": "${workspaceRoot}/qa",
"program": "${workspaceRoot}/qa/bin/qa",
"env": {
"CHROME_HEADLESS": "false",
"QA_DEBUG": "true",
"GITLAB_USERNAME": "gitlab-qa",
"GITLAB_PASSWORD": "from 1Password",
"GITLAB_QA_ACCESS_TOKEN": "from 1Password"
},
"args": [
"Test::Instance::All",
"https://staging.gitlab.com",
"--",
"--tag", "smoke"
]
}
```
## Set up experimental auto-scaled runners
Sometimes, it's useful to [deploy auto-scaled runners to try out and compare different machine types](https://gitlab.com/gitlab-com/www-gitlab-com/-/issues/10623).
To do so, follow these steps:
1. Create a service account to access shared cache in [the `gitlab-qa-resources` GCP project](https://console.cloud.google.com/iam-admin/serviceaccounts?project=gitlab-qa-resources).
1. Download the service account credentials JSON file.
1. Create a VM instance to host the auto-scaled runners manager in [the `gitlab-qa-resources` GCP project](https://console.cloud.google.com/compute/instances?project=gitlab-qa-resources).
1. Add the service account to the VM instance.
1. Add you SSH key to the VM instance.
1. Upload the service account credentials JSON file to the VM instance (e.g. `scp ~/Downloads/gitlab-qa-resources-abc123.json <your-username>@VM-IP:/home/<your-username>`).
1. Create a storage bucket for the shared cache in [the `gitlab-qa-resources` GCP project](https://console.cloud.google.com/storage/browser?project=gitlab-qa-resources).
1. SSH into the VM instance (using GCP's Web interface).
1. Follow [the installation steps for auto-scaled runners manager](https://docs.gitlab.com/runner/executors/docker_machine.html#preparing-the-environment):
1. [Install `gitlab-runner`](https://docs.gitlab.com/runner/install/linux-repository.html#installing-gitlab-runner).
1. [Install Docker Machine](https://web.archive.org/web/20210619101324/https://docs.docker.com/machine/install-machine/).
1. [Register the runner](https://docs.gitlab.com/runner/register/#linux)
1. Make sure to set a specific tag for the runner.
1. Set `docker+machine` as the runner executor.
1. Move the service account credentials JSON file to its final destination (using `sudo`): `sudo mv home/<your-username>/gitlab-qa-resources-abc123.json /etc/gitlab-runner/service-account.json`
1. Edit the runner manager with something like the following configuration (make sure to check the [`[runners.machine]`](https://docs.gitlab.com/runner/configuration/advanced-configuration.html#the-runnersmachine-section) documentation):
```toml
concurrent = 500
check_interval = 0
[session_server]
session_timeout = 1800
[[runners]]
name = "n2d-highcpu-4 Relevant description of the runner manager"
url = "https://gitlab.com/"
token = "[REDACTED]"
executor = "docker+machine"
limit = 500
pre_clone_script = "eval \"$CI_PRE_CLONE_SCRIPT\""
request_concurrency = 500
environment = [
"DOCKER_TLS_CERTDIR=",
"DOCKER_DRIVER=overlay2",
"FF_USE_DIRECT_DOWNLOAD=true",
"FF_GITLAB_REGISTRY_HELPER_IMAGE=true"
]
[runners.custom_build_dir]
enabled = true
[runners.cache]
Type = "gcs"
Shared = true
[runners.cache.gcs]
BucketName = "BUCKET-NAME-FOR-THE-SHARED-CACHE"
CredentialsFile = "/etc/gitlab-runner/service-account.json"
[runners.docker]
tls_verify = false
image = "ruby:2.7"
privileged = true
disable_entrypoint_overwrite = false
oom_kill_disable = false
disable_cache = false
shm_size = 0
volumes = [
"/cache",
"/certs/client"
]
[runners.machine]
IdleCount = 0
IdleTime = 600
MachineDriver = "google"
MachineName = "rymai-n2d-hc-4-%s"
MachineOptions = [
# Additional machine options can be added using the Google Compute Engine driver.
# If you experience problems with an unreachable host (ex. "Waiting for SSH"),
# you should remove optional parameters to help with debugging.
# https://docs.docker.com/machine/drivers/gce/
"google-project=gitlab-qa-resources",
"google-zone=us-central1-a", # e.g. 'us-central1-a', full list in https://cloud.google.com/compute/docs/regions-zones/
"google-machine-type=n2d-highcpu-4", # e.g. 'n1-standard-8'
"google-disk-size=50",
"google-disk-type=pd-ssd",
"google-label=gl_resource_type:ci_ephemeral",
"google-username=cos",
"google-operation-backoff-initial-interval=2",
"google-use-internal-ip",
"engine-registry-mirror=https://mirror.gcr.io",
]
OffPeakTimezone = ""
OffPeakIdleCount = 0
OffPeakIdleTime = 0
MaxBuilds = 20
[[runners.machine.autoscaling]]
Periods = ["* * 8-18 * * mon-fri *"] # During the weekends
IdleCount = 0
IdleTime = 600
Timezone = "UTC"
```
## Scripts and tools for automating tasks
### Toolbox
The [Quality Toolbox](https://gitlab.com/gitlab-org/quality/toolbox) contains several scripts that can be useful when working with GitLab end-to-end tests, such as one to [generate a report of flaky tests](https://gitlab.com/gitlab-org/quality/toolbox#generate-a-flaky-examples-report), or one to [report job success rates](https://gitlab.com/gitlab-org/quality/toolbox#pipeline-job-report).
### Rake tasks
The [`qa/tools` directory](https://gitlab.com/gitlab-org/gitlab/blob/master/qa/qa/tools/) contains Rake tasks that perform automated tasks on a schedule (such as [deleting subgroups](https://gitlab.com/gitlab-org/gitlab/-/blob/master/qa/qa/tools/delete_subgroups.rb) after a test run), or that can be run as needed (such as [revoking personal access tokens](https://gitlab.com/gitlab-org/gitlab/-/blob/master/qa/qa/tools/revoke_all_personal_access_tokens.rb)).
#### Delete Test SSH Keys
This script deletes SSH keys for a specific user. It can be executed via the `delete_test_ssh_keys` Rake task in the `qa` directory.
The Rake task accepts three arguments that can be used to limit the keys that are deleted, and to perform a dry run.
- The first argument, `title_portion`, limits keys to be deleted to those that include the string provided.
- The second argument, `delete_before`, limits keys to be deleted to those that were created before the given date.
- The third optional argument, `dry_run`, determines if the command will be executed as a dry run, summarizing the keys to be deleted. Set to `true` to execute as a dry run.
Two environment variables are also required:
- `GITLAB_ADDRESS` is the address of the target GitLab instance.
- `GITLAB_QA_ACCESS_TOKEN` should be a personal access token with API access and should belong to the user whose keys will be deleted.
For example, the following command will delete all SSH keys with a title that includes `E2E test key:` and that were created before `2020-08-02` on `https://staging.gitlab.com` for the user with the provided personal access token:
```shell
GITLAB_QA_ACCESS_TOKEN=secret GITLAB_ADDRESS=https://staging.gitlab.com bundle exec rake "delete_test_ssh_keys[E2E test key:, 2020-08-02]"
```
#### Set default password and create a personal access token
There is a Rake task to set the default password (from `Runtime::User.default_password`) if it's not set already, and it creates a personal access token.
This is useful when testing on a fresh GitLab instance (e.g., an omnibus-GitLab Docker image) and you don't want to have to log in and create an access token manually.
Usage example (run from the `gitlab/qa` directory):
```shell
$ bundle exec rake 'initialize_gitlab_auth[https://gitlab.test]'
Signing in and creating the default password for the root user if it's not set already...
Creating an API scoped access token for the root user...
Token: <some_token_value>
```
|
https://docs.gitlab.com/development/testing_guide/troubleshooting
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/testing_guide/troubleshooting.md
|
2025-08-13
|
doc/development/testing_guide/end_to_end
|
[
"doc",
"development",
"testing_guide",
"end_to_end"
] |
troubleshooting.md
|
none
|
unassigned
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Troubleshooting end-to-end tests
| null |
## See what the browser is doing
If end-to-end tests fail, it can be very helpful to see what is happening in your
browser when it fails. For example, if tests don't run at all, the test framework
might be trying to open a URL that isn't valid on your machine. This problem becomes
clearer if you see the page fail in the browser.
To make the test framework show the browser as it runs the tests,
set `WEBDRIVER_HEADLESS=false`. For example:
```shell
cd gitlab/qa
WEBDRIVER_HEADLESS=false bundle exec bin/qa Test::Instance::All http://localhost:3000
```
## Enable logging
Sometimes a test might fail and the failure stack trace doesn't provide enough
information to determine what went wrong. You can get more information by enabling
debug logs by setting `QA_LOG_LEVEL=debug`, to see what the test framework is attempting.
For example:
```shell
cd gitlab/qa
QA_LOG_LEVEL=debug bundle exec bin/qa Test::Instance::All http://localhost:3000
```
The test framework then outputs many logs showing the actions taken during
the tests:
```plaintext
[date=2022-03-31 23:19:47 from=QA Tests] INFO -- Starting test: Create Merge request creation from fork can merge feature branch fork to mainline
[date=2022-03-31 23:19:49 from=QA Tests] DEBUG -- has_element? :login_page (wait: 0) returned: true
[date=2022-03-31 23:19:52 from=QA Tests] DEBUG -- filling :login_field with "root"
[date=2022-03-31 23:19:52 from=QA Tests] DEBUG -- filling :password_field with "*****"
[date=2022-03-31 23:19:52 from=QA Tests] DEBUG -- clicking :sign_in_button
```
## Tests don't run at all
This section assumes you're running the tests locally (such as the GDK) and you're doing
so from the `gitlab/qa/` folder, not from `gitlab-qa`. For example, if you receive a
`Net::ReadTimeout` error, the browser might be unable to load the specified URL:
```shell
cd gitlab/qa
bundle exec bin/qa Test::Instance::All http://localhost:3000
bundler: failed to load command: bin/qa (bin/qa)
Net::ReadTimeout: Net::ReadTimeout with #<TCPSocket:(closed)>
```
This error can happen if GitLab runs on an address that does not resolve from
`localhost`. For example, if you set the GDK `hostname`
[to a specific local IP address](https://gitlab.com/gitlab-org/gitlab-qa/-/blob/master/docs/run_qa_against_gdk.md#run-qa-tests-against-your-gdk-setup),
you must use that IP address instead of `localhost` in the command.
For example, if your IP is `192.168.0.12`:
```shell
bundle exec bin/qa Test::Instance::All http://192.168.0.12:3000
```
## Tests sign out when visiting a page
If the tests sign in successfully as a test user, but then unexpectedly sign out, you might be using an
incorrect URL to execute the test. By default, tests use the URL `http://127.0.0.1:3000`, but if a hostname
has been configured for the instance, you must explicitly pass that hostname to the tests. The tests use
the `web_url` returned by the API to go to different pages. They go to the configured hostname, rather than
`http://127.0.0.1:3000`, so the test user appears signed out.
This example runs the tests against `http://127.0.0.1:3000`, and signs out if a hostname has been configured:
```shell
bundle exec rspec qa/specs/features/ee/browser_ui/3_create/repository/code_owners_spec.rb
```
To avoid this, explicitly set `QA_GITLAB_URL` to the configured hostname, for example:
```shell
QA_GITLAB_URL=http://gdk.test:3000 bundle exec rspec qa/specs/features/ee/browser_ui/3_create/repository/code_owners_spec.rb
```
|
---
stage: none
group: unassigned
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: Troubleshooting end-to-end tests
breadcrumbs:
- doc
- development
- testing_guide
- end_to_end
---
## See what the browser is doing
If end-to-end tests fail, it can be very helpful to see what is happening in your
browser when it fails. For example, if tests don't run at all, the test framework
might be trying to open a URL that isn't valid on your machine. This problem becomes
clearer if you see the page fail in the browser.
To make the test framework show the browser as it runs the tests,
set `WEBDRIVER_HEADLESS=false`. For example:
```shell
cd gitlab/qa
WEBDRIVER_HEADLESS=false bundle exec bin/qa Test::Instance::All http://localhost:3000
```
## Enable logging
Sometimes a test might fail and the failure stack trace doesn't provide enough
information to determine what went wrong. You can get more information by enabling
debug logs by setting `QA_LOG_LEVEL=debug`, to see what the test framework is attempting.
For example:
```shell
cd gitlab/qa
QA_LOG_LEVEL=debug bundle exec bin/qa Test::Instance::All http://localhost:3000
```
The test framework then outputs many logs showing the actions taken during
the tests:
```plaintext
[date=2022-03-31 23:19:47 from=QA Tests] INFO -- Starting test: Create Merge request creation from fork can merge feature branch fork to mainline
[date=2022-03-31 23:19:49 from=QA Tests] DEBUG -- has_element? :login_page (wait: 0) returned: true
[date=2022-03-31 23:19:52 from=QA Tests] DEBUG -- filling :login_field with "root"
[date=2022-03-31 23:19:52 from=QA Tests] DEBUG -- filling :password_field with "*****"
[date=2022-03-31 23:19:52 from=QA Tests] DEBUG -- clicking :sign_in_button
```
## Tests don't run at all
This section assumes you're running the tests locally (such as the GDK) and you're doing
so from the `gitlab/qa/` folder, not from `gitlab-qa`. For example, if you receive a
`Net::ReadTimeout` error, the browser might be unable to load the specified URL:
```shell
cd gitlab/qa
bundle exec bin/qa Test::Instance::All http://localhost:3000
bundler: failed to load command: bin/qa (bin/qa)
Net::ReadTimeout: Net::ReadTimeout with #<TCPSocket:(closed)>
```
This error can happen if GitLab runs on an address that does not resolve from
`localhost`. For example, if you set the GDK `hostname`
[to a specific local IP address](https://gitlab.com/gitlab-org/gitlab-qa/-/blob/master/docs/run_qa_against_gdk.md#run-qa-tests-against-your-gdk-setup),
you must use that IP address instead of `localhost` in the command.
For example, if your IP is `192.168.0.12`:
```shell
bundle exec bin/qa Test::Instance::All http://192.168.0.12:3000
```
## Tests sign out when visiting a page
If the tests sign in successfully as a test user, but then unexpectedly sign out, you might be using an
incorrect URL to execute the test. By default, tests use the URL `http://127.0.0.1:3000`, but if a hostname
has been configured for the instance, you must explicitly pass that hostname to the tests. The tests use
the `web_url` returned by the API to go to different pages. They go to the configured hostname, rather than
`http://127.0.0.1:3000`, so the test user appears signed out.
This example runs the tests against `http://127.0.0.1:3000`, and signs out if a hostname has been configured:
```shell
bundle exec rspec qa/specs/features/ee/browser_ui/3_create/repository/code_owners_spec.rb
```
To avoid this, explicitly set `QA_GITLAB_URL` to the configured hostname, for example:
```shell
QA_GITLAB_URL=http://gdk.test:3000 bundle exec rspec qa/specs/features/ee/browser_ui/3_create/repository/code_owners_spec.rb
```
|
https://docs.gitlab.com/development/testing_guide/feature_flag_testing
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/testing_guide/feature_flag_testing.md
|
2025-08-13
|
doc/development/testing_guide/end_to_end
|
[
"doc",
"development",
"testing_guide",
"end_to_end"
] |
feature_flag_testing.md
|
none
|
unassigned
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Testing feature flags with end-to-end tests
| null |
## Feature Flag E2E (end-to-end) Testing
### Workflow of E2E runs on Staging and Production
#### Scheduled Runs
We run scheduled E2E tests on both staging and production environments every 4 hours. These tests help ensure that recent deployments haven't introduced regressions.
We can monitor test results in the following Slack channels:
- [#e2e-run-staging](https://gitlab.enterprise.slack.com/archives/CBS3YKMGD)
- [#e2e-run-production](https://gitlab.enterprise.slack.com/archives/CCNNKFP8B)
### E2E Flow When Changing a Feature Flag With a Merge Request
#### When changes include a feature flag definition file
When a feature flag definition file has been added or changed in a merge request, 2 pipelines are triggered in the downstream `E2E GDK` job:
- `gdk-instance` has the feature flag set to the default value in the feature flag definition file.
- `gdk-instance-ff-inverse` has the feature flag set to the opposite of the default value.
- The job `e2e:test-on-omnibus-ee` needs to be triggered manually to ensure orchestrated tests also pass.
##### When the MR is approved (but not yet merged)
- The `pipeline:tier-3` label is automatically added.
- E2E tests run through downstream pipelines that are named `e2e:test-on-cng` and `e2e:test-on-gdk`.
- If any of these E2E jobs fail, they block the pipeline from moving forward. Test results are posted as a comment by the E2E bot on the merge request, review them carefully before proceeding.
##### When the MR is merged
Once the MR is merged and the commit has been picked for auto-deploy to environments such as staging-canary, staging, production-canary, and production:
- If a feature flag default is changed in an MR, no ChatOps message is posted in the `#e2e-run-staging` or `#e2e-run-production` channels. ChatOps messages only appear when toggling a flag using the [/chatops commands](https://handbook.gitlab.com/handbook/support/workflows/chatops/).
- Head to `#e2e-run-staging` and `#e2e-run-production` and wait for the next scheduled `full run` to complete. A passing run confirms the deployment is safe. If it fails, investigate before continuing further rollouts.

#### When changes do not include a feature flag definition file
If work has been done behind the feature flag but the definition file has not been changed, open a draft MR with the original changes and also edit the definition file to trigger `gdk-instance` and `gdk-instance-ff-inverse` and manually run `e2e:test-on-omnibus-ee` as well to ensure the changes in the original MR do not break any E2E tests.
### Feature flag value changes on staging or production
If a feature flag value is changed on staging or production through a ChatOps command, a `GitLab ChatOps` message is sent in Slack to the corresponding E2E run channel, either [#e2e-run-staging](https://gitlab.enterprise.slack.com/archives/CBS3YKMGD) or [#e2e-run-production](https://gitlab.enterprise.slack.com/archives/CCNNKFP8B).

Once the pipeline completes, a followup message with the results is sent to the same Slack channel. If the pipeline failed, it includes a link to the debugging instructions below.

Note that if the message has a 🚒 emoji, it has already been reviewed by a pipeline triage DRI and deemed to be a known failure unrelated to the feature flag changes. If it has a 💥 emoji, this indicates a new failure which could be related to the feature flag changes.
### Debugging test failures from a feature flag toggle pipeline
To view the individual test errors, click the `Pipeline` link and view the failing job directly (must be logged into `ops.gitlab.net`), or click the `Allure Report` and open the failing test. There you can see the stacktrace and any available artifacts including screenshots.
#### Determine if the failures are known
1. Check the previous full runs in the [#e2e-run-staging](https://gitlab.enterprise.slack.com/archives/CBS3YKMGD) or [#e2e-run-production](https://gitlab.enterprise.slack.com/archives/CCNNKFP8B) Slack channels that were triggered before your feature flag toggle. If the same tests failed with the same error messages, it's likely the failures aren't related to your toggle.
1. In case the test hasn't failed recently but is flaky, search for a failure issue for the test:
- From the [GitLab project](https://gitlab.com/gitlab-org/gitlab/-/issues), search the path of the test, for example `browser_ui/2_plan/issue/create_issue_spec.rb`, and exclude test case issue types.

- Look for an issue with the correct test title. There can be multiple tests in the same spec file.
- Open all issues that match the title and look for one that has the same error as the one in the failing feature flag pipeline.
- If there is a failure issue with a matching error, check that the first failure under the `Reports` section is a pipeline created BEFORE the feature flag value was changed as the failure issue may be from the feature flag pipeline itself. If the first failure was before the changes, it was probably not caused by the feature flag toggle.
1. Rerun the failing job. If the test still fails, try to debug locally with [Running E2E tests against GDK](#running-e2e-tests-against-gdk) or against staging with [Running E2E tests against staging](#running-e2e-tests-against-staging)
#### Running E2E tests against GDK
If not already done, follow the instructions to [install GDK](https://gitlab.com/gitlab-org/gitlab-development-kit/-/blob/main/doc/_index.md) as your local GitLab development environment.
After GDK is up and running, change the feature flag value in the rails console if needed.
To enable a feature flag:
``` shell
bundle exec rails console
Feature.enable(:feature_flag_name)
```
To disable a feature flag:
``` shell
bundle exec rails console
Feature.disable(:feature_flag_name)
```
Visit the GDK URL and ensure that the feature flag has changed to the correct state.
To run an EE test, a license needs to be set with
``` shell
export QA_EE_LICENSE=$(cat /path/to/gitlab_license)
```
From the `gitlab/qa` directory run:
``` shell
WEBDRIVER_HEADLESS=false \ # Optional, to see the tests running
QA_LOG_LEVEL=DEBUG \ # Optional, to see more detailed logging
QA_GITLAB_URL="http://{GDK IP ADDRESS}:{GDK PORT}" \ # Needed if GDK url is not the default http://localhost:3000
bundle exec rspec qa/specs/features/<path/to/spec.rb>
```
#### Running E2E tests against staging
The `GITLAB_QA_USER_AGENT` environment variable is needed to bypass captcha. The value can be found in GSM. The tests may also need `GITLAB_ADMIN_USERNAME`, and `GITLAB_ADMIN_PASSWORD` if the tests require admin access.
From the `gitlab/qa` directory run:
``` shell
GITLAB_QA_USER_AGENT=<GSM> \
GITLAB_USERNAME="gitlab-qa" \
GITLAB_PASSWORD=<GSM> \
bundle exec bin/qa Test::Instance::All https://staging.gitlab.com -- qa/specs/features/<path/to/spec.rb>
```
### Additional links
- [E2E tests against GDK](running_tests/_index.md)
- [E2E troubleshooting](troubleshooting.md)
- [What E2E tests can be run](https://gitlab.com/gitlab-org/gitlab-qa/-/blob/master/docs/what_tests_can_be_run.md)
|
---
stage: none
group: unassigned
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: Testing feature flags with end-to-end tests
breadcrumbs:
- doc
- development
- testing_guide
- end_to_end
---
## Feature Flag E2E (end-to-end) Testing
### Workflow of E2E runs on Staging and Production
#### Scheduled Runs
We run scheduled E2E tests on both staging and production environments every 4 hours. These tests help ensure that recent deployments haven't introduced regressions.
We can monitor test results in the following Slack channels:
- [#e2e-run-staging](https://gitlab.enterprise.slack.com/archives/CBS3YKMGD)
- [#e2e-run-production](https://gitlab.enterprise.slack.com/archives/CCNNKFP8B)
### E2E Flow When Changing a Feature Flag With a Merge Request
#### When changes include a feature flag definition file
When a feature flag definition file has been added or changed in a merge request, 2 pipelines are triggered in the downstream `E2E GDK` job:
- `gdk-instance` has the feature flag set to the default value in the feature flag definition file.
- `gdk-instance-ff-inverse` has the feature flag set to the opposite of the default value.
- The job `e2e:test-on-omnibus-ee` needs to be triggered manually to ensure orchestrated tests also pass.
##### When the MR is approved (but not yet merged)
- The `pipeline:tier-3` label is automatically added.
- E2E tests run through downstream pipelines that are named `e2e:test-on-cng` and `e2e:test-on-gdk`.
- If any of these E2E jobs fail, they block the pipeline from moving forward. Test results are posted as a comment by the E2E bot on the merge request, review them carefully before proceeding.
##### When the MR is merged
Once the MR is merged and the commit has been picked for auto-deploy to environments such as staging-canary, staging, production-canary, and production:
- If a feature flag default is changed in an MR, no ChatOps message is posted in the `#e2e-run-staging` or `#e2e-run-production` channels. ChatOps messages only appear when toggling a flag using the [/chatops commands](https://handbook.gitlab.com/handbook/support/workflows/chatops/).
- Head to `#e2e-run-staging` and `#e2e-run-production` and wait for the next scheduled `full run` to complete. A passing run confirms the deployment is safe. If it fails, investigate before continuing further rollouts.

#### When changes do not include a feature flag definition file
If work has been done behind the feature flag but the definition file has not been changed, open a draft MR with the original changes and also edit the definition file to trigger `gdk-instance` and `gdk-instance-ff-inverse` and manually run `e2e:test-on-omnibus-ee` as well to ensure the changes in the original MR do not break any E2E tests.
### Feature flag value changes on staging or production
If a feature flag value is changed on staging or production through a ChatOps command, a `GitLab ChatOps` message is sent in Slack to the corresponding E2E run channel, either [#e2e-run-staging](https://gitlab.enterprise.slack.com/archives/CBS3YKMGD) or [#e2e-run-production](https://gitlab.enterprise.slack.com/archives/CCNNKFP8B).

Once the pipeline completes, a followup message with the results is sent to the same Slack channel. If the pipeline failed, it includes a link to the debugging instructions below.

Note that if the message has a 🚒 emoji, it has already been reviewed by a pipeline triage DRI and deemed to be a known failure unrelated to the feature flag changes. If it has a 💥 emoji, this indicates a new failure which could be related to the feature flag changes.
### Debugging test failures from a feature flag toggle pipeline
To view the individual test errors, click the `Pipeline` link and view the failing job directly (must be logged into `ops.gitlab.net`), or click the `Allure Report` and open the failing test. There you can see the stacktrace and any available artifacts including screenshots.
#### Determine if the failures are known
1. Check the previous full runs in the [#e2e-run-staging](https://gitlab.enterprise.slack.com/archives/CBS3YKMGD) or [#e2e-run-production](https://gitlab.enterprise.slack.com/archives/CCNNKFP8B) Slack channels that were triggered before your feature flag toggle. If the same tests failed with the same error messages, it's likely the failures aren't related to your toggle.
1. In case the test hasn't failed recently but is flaky, search for a failure issue for the test:
- From the [GitLab project](https://gitlab.com/gitlab-org/gitlab/-/issues), search the path of the test, for example `browser_ui/2_plan/issue/create_issue_spec.rb`, and exclude test case issue types.

- Look for an issue with the correct test title. There can be multiple tests in the same spec file.
- Open all issues that match the title and look for one that has the same error as the one in the failing feature flag pipeline.
- If there is a failure issue with a matching error, check that the first failure under the `Reports` section is a pipeline created BEFORE the feature flag value was changed as the failure issue may be from the feature flag pipeline itself. If the first failure was before the changes, it was probably not caused by the feature flag toggle.
1. Rerun the failing job. If the test still fails, try to debug locally with [Running E2E tests against GDK](#running-e2e-tests-against-gdk) or against staging with [Running E2E tests against staging](#running-e2e-tests-against-staging)
#### Running E2E tests against GDK
If not already done, follow the instructions to [install GDK](https://gitlab.com/gitlab-org/gitlab-development-kit/-/blob/main/doc/_index.md) as your local GitLab development environment.
After GDK is up and running, change the feature flag value in the rails console if needed.
To enable a feature flag:
``` shell
bundle exec rails console
Feature.enable(:feature_flag_name)
```
To disable a feature flag:
``` shell
bundle exec rails console
Feature.disable(:feature_flag_name)
```
Visit the GDK URL and ensure that the feature flag has changed to the correct state.
To run an EE test, a license needs to be set with
``` shell
export QA_EE_LICENSE=$(cat /path/to/gitlab_license)
```
From the `gitlab/qa` directory run:
``` shell
WEBDRIVER_HEADLESS=false \ # Optional, to see the tests running
QA_LOG_LEVEL=DEBUG \ # Optional, to see more detailed logging
QA_GITLAB_URL="http://{GDK IP ADDRESS}:{GDK PORT}" \ # Needed if GDK url is not the default http://localhost:3000
bundle exec rspec qa/specs/features/<path/to/spec.rb>
```
#### Running E2E tests against staging
The `GITLAB_QA_USER_AGENT` environment variable is needed to bypass captcha. The value can be found in GSM. The tests may also need `GITLAB_ADMIN_USERNAME`, and `GITLAB_ADMIN_PASSWORD` if the tests require admin access.
From the `gitlab/qa` directory run:
``` shell
GITLAB_QA_USER_AGENT=<GSM> \
GITLAB_USERNAME="gitlab-qa" \
GITLAB_PASSWORD=<GSM> \
bundle exec bin/qa Test::Instance::All https://staging.gitlab.com -- qa/specs/features/<path/to/spec.rb>
```
### Additional links
- [E2E tests against GDK](running_tests/_index.md)
- [E2E troubleshooting](troubleshooting.md)
- [What E2E tests can be run](https://gitlab.com/gitlab-org/gitlab-qa/-/blob/master/docs/what_tests_can_be_run.md)
|
https://docs.gitlab.com/development/testing_guide/test_infrastructure
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/testing_guide/test_infrastructure.md
|
2025-08-13
|
doc/development/testing_guide/end_to_end
|
[
"doc",
"development",
"testing_guide",
"end_to_end"
] |
test_infrastructure.md
|
none
|
unassigned
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
End-to-end Testing Infrastructure for Cloud Integrations
| null |
This content is about infrastructure we integrate with GitLab QA test scenarios, at the end-to-end level.
## What infrastructure do we have in place?
We currently use GCP and AWS platforms to test a few end-to-end scenarios. These are separated from other
sandbox projects to prevent accidental deletion of resources that run beyond automated test runs. If you do not have
access to these accounts already, you can create an access request. In GCP, we use `group-qa-tests-566cc6`
and in AWS, the cloud account `eng-quality-ops-ci-cd-shared-infra-498dbd5a`.
If you have test scenarios that require these platforms, we encourage you to use the existing infrastructure and
accounts so we can efficiently consolidate and maintain our end-to-end test suite.
## Why do we have this infrastructure?
GitLab has several features that integrate well with known Cloud Providers. To fully test this integration,
we have infrastructure in place that connects GitLab QA with these providers.
We currently use GCP for its Cloud Storage resources to test Object Storage (GCS) and to create Kubernetes clusters. We also use AWS to test Object Storage (S3).
## How do we maintain this infrastructure?
We have an active [Janitor](https://gitlab.com/gitlab-com/gl-infra/gitlab-gcp-janitor) project that ensures resources in GCP are cleaned up if a test fails to remove it. The Janitor jobs run daily on a scheduled pipeline and target exclusively GCP `group-qa-tests-566cc6`.
AWS uses lifecycle management rules to delete objects after 1 day. We have an established [process](https://gitlab.com/gitlab-org/quality/engineering-productivity/team/-/blob/main/runbooks/rotating-credentials.md) that enables anyone with access to these environments to rotate credentials.
|
---
stage: none
group: unassigned
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: End-to-end Testing Infrastructure for Cloud Integrations
breadcrumbs:
- doc
- development
- testing_guide
- end_to_end
---
This content is about infrastructure we integrate with GitLab QA test scenarios, at the end-to-end level.
## What infrastructure do we have in place?
We currently use GCP and AWS platforms to test a few end-to-end scenarios. These are separated from other
sandbox projects to prevent accidental deletion of resources that run beyond automated test runs. If you do not have
access to these accounts already, you can create an access request. In GCP, we use `group-qa-tests-566cc6`
and in AWS, the cloud account `eng-quality-ops-ci-cd-shared-infra-498dbd5a`.
If you have test scenarios that require these platforms, we encourage you to use the existing infrastructure and
accounts so we can efficiently consolidate and maintain our end-to-end test suite.
## Why do we have this infrastructure?
GitLab has several features that integrate well with known Cloud Providers. To fully test this integration,
we have infrastructure in place that connects GitLab QA with these providers.
We currently use GCP for its Cloud Storage resources to test Object Storage (GCS) and to create Kubernetes clusters. We also use AWS to test Object Storage (S3).
## How do we maintain this infrastructure?
We have an active [Janitor](https://gitlab.com/gitlab-com/gl-infra/gitlab-gcp-janitor) project that ensures resources in GCP are cleaned up if a test fails to remove it. The Janitor jobs run daily on a scheduled pipeline and target exclusively GCP `group-qa-tests-566cc6`.
AWS uses lifecycle management rules to delete objects after 1 day. We have an established [process](https://gitlab.com/gitlab-org/quality/engineering-productivity/team/-/blob/main/runbooks/rotating-credentials.md) that enables anyone with access to these environments to rotate credentials.
|
https://docs.gitlab.com/development/testing_guide/end_to_end/resources
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/testing_guide/end_to_end/resources.md
|
2025-08-13
|
doc/development/testing_guide/end_to_end/beginners_guide
|
[
"doc",
"development",
"testing_guide",
"end_to_end",
"beginners_guide"
] |
resources.md
|
none
|
unassigned
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Resource classes in GitLab QA
| null |
Resources are primarily created using Browser UI steps, but can also be created via the API or the CLI.
## How to properly implement a resource class?
All resource classes should inherit from `Resource::Base`.
There is only one mandatory method to implement to define a resource class.
This is the `#fabricate!` method, which is used to build the resource via the
browser UI. Note that you should only use [Page objects](page_objects.md) to
interact with a Web page in this method.
Here is an imaginary example:
```ruby
module QA
module Resource
class Shirt < Base
attr_accessor :name
def fabricate!
Page::Dashboard::Index.perform do |dashboard_index|
dashboard_index.go_to_new_shirt
end
Page::Shirt::New.perform do |shirt_new|
shirt_new.set_name(name)
shirt_new.create_shirt!
end
end
end
end
end
```
### Define API implementation
A resource class may also implement the three following methods to be able to
create the resource via the public GitLab API:
- `#api_get_path`: The `GET` path to fetch an existing resource.
- `#api_post_path`: The `POST` path to create a new resource.
- `#api_post_body`: The `POST` body (as a Ruby hash) to create a new resource.
> Be aware that many API resources are [paginated](../../../../api/rest/_index.md#pagination).
> If you don't find the results you expect, check if there is more that one page of results.
Let's take the `Shirt` resource class, and add these three API methods:
```ruby
module QA
module Resource
class Shirt < Base
attr_accessor :name
def fabricate!
# ... same as before
end
def api_get_path
"/shirt/#{name}"
end
def api_post_path
"/shirts"
end
def api_post_body
{
name: name
}
end
end
end
end
```
The `Project` resource is a good real example of Browser
UI and API implementations.
#### Resource attributes
A resource may need another resource to exist first. For instance, a project
needs a group to be created in.
To define a resource attribute, you can use the `attribute` method with a
block using the other resource class to fabricate the resource.
That allows access to the other resource from your resource object's
methods. You would usually use it in `#fabricate!`, `#api_get_path`,
`#api_post_path`, `#api_post_body`.
Let's take the `Shirt` resource class, and add a `project` attribute to it:
```ruby
module QA
module Resource
class Shirt < Base
attr_accessor :name
attribute :project do
Project.fabricate! do |resource|
resource.name = 'project-to-create-a-shirt'
end
end
def fabricate!
project.visit!
Page::Project::Show.perform do |project_show|
project_show.go_to_new_shirt
end
Page::Shirt::New.perform do |shirt_new|
shirt_new.set_name(name)
shirt_new.create_shirt!
end
end
def api_get_path
"/project/#{project.path}/shirt/#{name}"
end
def api_post_path
"/project/#{project.path}/shirts"
end
def api_post_body
{
name: name
}
end
end
end
end
```
**Note that all the attributes are lazily constructed. This means if you want
a specific attribute to be fabricated first, you must call the
attribute method first even if you're not using it.**
#### Product data attributes
Once created, you may want to populate a resource with attributes that can be
found in the Web page, or in the API response.
For instance, once you create a project, you may want to store its repository
SSH URL as an attribute.
Again we could use the `attribute` method with a block, using a page object
to retrieve the data on the page.
Let's take the `Shirt` resource class, and define a `:brand` attribute:
```ruby
module QA
module Resource
class Shirt < Base
attr_accessor :name
attribute :project do
Project.fabricate! do |resource|
resource.name = 'project-to-create-a-shirt'
end
end
# Attribute populated from the Browser UI (using the block)
attribute :brand do
Page::Shirt::Show.perform do |shirt_show|
shirt_show.fetch_brand_from_page
end
end
# ... same as before
end
end
end
```
**Note again that all the attributes are lazily constructed. This means if
you call `shirt.brand` after moving to the other page, it doesn't properly
retrieve the data because we're no longer on the expected page.**
Consider this:
```ruby
shirt =
QA::Resource::Shirt.fabricate! do |resource|
resource.name = "GitLab QA"
end
shirt.project.visit!
shirt.brand # => FAIL!
```
The above example fails because now we're on the project page, trying to
construct the brand data from the shirt page, however we moved to the project
page already. There are two ways to solve this, one is that we could try to
retrieve the brand before visiting the project again:
```ruby
shirt =
QA::Resource::Shirt.fabricate! do |resource|
resource.name = "GitLab QA"
end
shirt.brand # => OK!
shirt.project.visit!
shirt.brand # => OK!
```
The attribute is stored in the instance, therefore all the following calls
are fine, using the data previously constructed. If we think that this
might be too brittle, we could eagerly construct the data right before
ending fabrication:
```ruby
module QA
module Resource
class Shirt < Base
# ... same as before
def fabricate!
project.visit!
Page::Project::Show.perform do |project_show|
project_show.go_to_new_shirt
end
Page::Shirt::New.perform do |shirt_new|
shirt_new.set_name(name)
shirt_new.create_shirt!
end
populate(:brand) # Eagerly construct the data
end
end
end
end
```
The `populate` method iterates through its arguments and call each
attribute. Here `populate(:brand)` has the same effect as
just `brand`. Using the populate method makes the intention clearer.
With this, it ensures we construct the data right after we create the
shirt. The drawback is that this always constructs the data when the
resource is fabricated even if we don't need to use the data.
Alternatively, we could just make sure we're on the right page before
constructing the brand data:
```ruby
module QA
module Resource
class Shirt < Base
attr_accessor :name
attribute :project do
Project.fabricate! do |resource|
resource.name = 'project-to-create-a-shirt'
end
end
# Attribute populated from the Browser UI (using the block)
attribute :brand do
back_url = current_url
visit!
Page::Shirt::Show.perform do |shirt_show|
shirt_show.fetch_brand_from_page
end
visit(back_url)
end
# ... same as before
end
end
end
```
This ensures it's on the shirt page before constructing brand, and
move back to the previous page to avoid breaking the state.
#### Define an attribute based on an API response
Sometimes, you want to define a resource attribute based on the API response
from its `GET` or `POST` request. For instance, if the creation of a shirt via
the API returns
```ruby
{
brand: 'a-brand-new-brand',
style: 't-shirt',
materials: [[:cotton, 80], [:polyamide, 20]]
}
```
you may want to store `style` as-is in the resource, and fetch the first value
of the first `materials` item in a `main_fabric` attribute.
Let's take the `Shirt` resource class, and define a `:style` and a
`:main_fabric` attributes:
```ruby
module QA
module Resource
class Shirt < Base
# ... same as before
# @style from the instance if present,
# or fetched from the API response if present,
# or a QA::Resource::Base::NoValueError is raised otherwise
attribute :style
# If @main_fabric is not present,
# and if the API does not contain this field, this block will be
# used to construct the value based on the API response, and
# store the result in @main_fabric
attribute :main_fabric do
api_response.&dig(:materials, 0, 0)
end
# ... same as before
end
end
end
```
**Notes on attributes precedence**:
- resource instance variables have the highest precedence
- attributes from the API response take precedence over attributes from the
block (usually from Browser UI)
- attributes without a value raises a `QA::Resource::Base::NoValueError` error
## Creating resources in your tests
To create a resource in your tests, you can call the `.fabricate!` method on
the resource class, or use the [factory](#factories) to create it.
Note that if the resource class supports API fabrication, this uses this
fabrication by default.
Here is an example that uses the API fabrication method under the hood
since it's supported by the `Shirt` resource class:
```ruby
my_shirt = Resource::Shirt.fabricate! do |shirt|
shirt.name = 'my-shirt'
end
expect(page).to have_text(my_shirt.name) # => "my-shirt" from the resource's instance variable
expect(page).to have_text(my_shirt.brand) # => "a-brand-new-brand" from the API response
expect(page).to have_text(my_shirt.style) # => "t-shirt" from the API response
expect(page).to have_text(my_shirt.main_fabric) # => "cotton" from the API response via the block
```
If you explicitly want to use the Browser UI fabrication method, you can call
the `.fabricate_via_browser_ui!` method instead:
```ruby
my_shirt = Resource::Shirt.fabricate_via_browser_ui! do |shirt|
shirt.name = 'my-shirt'
end
expect(page).to have_text(my_shirt.name) # => "my-shirt" from the resource's instance variable
expect(page).to have_text(my_shirt.brand) # => the brand name fetched from the `Page::Shirt::Show` page via the block
expect(page).to have_text(my_shirt.style) # => QA::Resource::Base::NoValueError will be raised because no API response nor a block is provided
expect(page).to have_text(my_shirt.main_fabric) # => QA::Resource::Base::NoValueError will be raised because no API response and the block didn't provide a value (because it's also based on the API response)
```
You can also explicitly use the API fabrication method, by calling the
`.fabricate_via_api!` method:
```ruby
my_shirt = Resource::Shirt.fabricate_via_api! do |shirt|
shirt.name = 'my-shirt'
end
```
In this case, the result is similar to calling `Resource::Shirt.fabricate!`.
### Factories
You may also use [FactoryBot](https://github.com/thoughtbot/factory_bot/) invocations to create, build, and fetch resources within your tests.
```ruby
# create a project via the API to use in the test
let(:project) { create(:project) }
# create an issue belonging to a project via the API to use in the test
let(:issue) { create(:issue, project: project) }
# create a private project via the API with a specific name
let(:project) { create(:project, :private, name: 'my-project-name', add_name_uuid: false) }
# create one commit in a project that performs three actions
let(:commit) do
create(:commit, commit_message: 'my message', project: project, actions: [
{ action: 'create', file_path: 'README.md', content: '# Welcome!' },
{ action: 'update', file_path: 'README.md', content: '# Updated' },
{ action: 'delete', file_path: 'README.md' }
])
end
###
# instantiate an Issue but don't create it via API yet
let(:issue) { build(:issue) }
# instantiate a Project and perform some actions before creating
let(:project) do
build(:project) do |p|
p.name = 'Test'
p.add_name_uuid = false
end
end
# fetch an existing issue via the API with attributes
let(:existing_issue) { build(:issue, project: project, iid: issue.iid).reload! }
```
All factories are defined in [`qa/qa/factories`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/qa/qa/factories/) and are representative of
their respective `QA::Resource::Base` class.
For example, a factory `:issue` can be found in `qa/resource/issue.rb`. A factory `:project` can be found in `qa/resource/project.rb`.
#### Create a new Factory
Given a resource:
```ruby
# qa/resource/shirt.rb
module QA
module Resource
class Shirt < Base
attr_accessor :name
attr_reader :read_only
attribute :brand
def api_post_body
{ name: name, brand: brand }
end
end
end
end
```
Define a factory with defaults and overrides:
```ruby
# qa/factories/shirts.rb
module QA
FactoryBot.define do
factory :shirt, class: 'QA::Resource::Shirt' do
brand { 'BrandName' }
trait :with_name do
name { 'Shirt Name' }
end
end
end
end
```
In the test, create the resource via the API:
```ruby
let(:my_shirt) { create(:shirt, brand: 'AnotherBrand') } #<Resource::Shirt @brand="AnotherBrand" @name=nil>
let(:named_shirt) { create(:shirt, :with_name) } #<Resource::Shirt @brand="Brand Name" @name="Shirt Name">
let(:invalid_shirt) { create(:shirt, read_only: true) } # NoMethodError
it 'creates a shirt' do
expect(my_shirt.brand).to eq('AnotherBrand')
expect(named_shirt.name).to eq('Shirt Name')
expect(invalid_shirt).to raise_error(NoMethodError) # tries to call Resource::Shirt#read_only=
end
```
### Resources cleanup
We have a mechanism to [collect](https://gitlab.com/gitlab-org/gitlab/-/blob/44345381e89d6bbd440f7b4c680d03e8b75b86de/qa/qa/tools/test_resource_data_processor.rb#L32)
all resources created during test executions, and another to [handle](https://gitlab.com/gitlab-org/gitlab/-/blob/44345381e89d6bbd440f7b4c680d03e8b75b86de/qa/qa/tools/test_resources_handler.rb#L44)
these resources. On [dotcom environments](https://handbook.gitlab.com/handbook/engineering/infrastructure/environments/#environments), after a test suite finishes in the [E2E pipelines](https://handbook.gitlab.com/handbook/engineering/infrastructure-platforms/developer-experience/debugging-end-to-end-test-failures/), resources from all passing test are
automatically deleted in the same pipeline run. Resources from all failed tests are reserved for investigation,
and won't be deleted until the following Saturday by a scheduled pipeline. When introducing new resources,
also make sure to add any resource that cannot be deleted to the [IGNORED_RESOURCES](https://gitlab.com/gitlab-org/gitlab/-/blob/44345381e89d6bbd440f7b4c680d03e8b75b86de/qa/qa/tools/test_resources_handler.rb#L29)
list.
## Where to ask for help?
If you need more information, ask for help on `#s_developer_experience` channel on Slack
(internal, GitLab Team only).
If you are not a Team Member, and you still need help to contribute,
open an issue in GitLab issue tracker with the `~QA` label.
|
---
stage: none
group: unassigned
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: Resource classes in GitLab QA
breadcrumbs:
- doc
- development
- testing_guide
- end_to_end
- beginners_guide
---
Resources are primarily created using Browser UI steps, but can also be created via the API or the CLI.
## How to properly implement a resource class?
All resource classes should inherit from `Resource::Base`.
There is only one mandatory method to implement to define a resource class.
This is the `#fabricate!` method, which is used to build the resource via the
browser UI. Note that you should only use [Page objects](page_objects.md) to
interact with a Web page in this method.
Here is an imaginary example:
```ruby
module QA
module Resource
class Shirt < Base
attr_accessor :name
def fabricate!
Page::Dashboard::Index.perform do |dashboard_index|
dashboard_index.go_to_new_shirt
end
Page::Shirt::New.perform do |shirt_new|
shirt_new.set_name(name)
shirt_new.create_shirt!
end
end
end
end
end
```
### Define API implementation
A resource class may also implement the three following methods to be able to
create the resource via the public GitLab API:
- `#api_get_path`: The `GET` path to fetch an existing resource.
- `#api_post_path`: The `POST` path to create a new resource.
- `#api_post_body`: The `POST` body (as a Ruby hash) to create a new resource.
> Be aware that many API resources are [paginated](../../../../api/rest/_index.md#pagination).
> If you don't find the results you expect, check if there is more that one page of results.
Let's take the `Shirt` resource class, and add these three API methods:
```ruby
module QA
module Resource
class Shirt < Base
attr_accessor :name
def fabricate!
# ... same as before
end
def api_get_path
"/shirt/#{name}"
end
def api_post_path
"/shirts"
end
def api_post_body
{
name: name
}
end
end
end
end
```
The `Project` resource is a good real example of Browser
UI and API implementations.
#### Resource attributes
A resource may need another resource to exist first. For instance, a project
needs a group to be created in.
To define a resource attribute, you can use the `attribute` method with a
block using the other resource class to fabricate the resource.
That allows access to the other resource from your resource object's
methods. You would usually use it in `#fabricate!`, `#api_get_path`,
`#api_post_path`, `#api_post_body`.
Let's take the `Shirt` resource class, and add a `project` attribute to it:
```ruby
module QA
module Resource
class Shirt < Base
attr_accessor :name
attribute :project do
Project.fabricate! do |resource|
resource.name = 'project-to-create-a-shirt'
end
end
def fabricate!
project.visit!
Page::Project::Show.perform do |project_show|
project_show.go_to_new_shirt
end
Page::Shirt::New.perform do |shirt_new|
shirt_new.set_name(name)
shirt_new.create_shirt!
end
end
def api_get_path
"/project/#{project.path}/shirt/#{name}"
end
def api_post_path
"/project/#{project.path}/shirts"
end
def api_post_body
{
name: name
}
end
end
end
end
```
**Note that all the attributes are lazily constructed. This means if you want
a specific attribute to be fabricated first, you must call the
attribute method first even if you're not using it.**
#### Product data attributes
Once created, you may want to populate a resource with attributes that can be
found in the Web page, or in the API response.
For instance, once you create a project, you may want to store its repository
SSH URL as an attribute.
Again we could use the `attribute` method with a block, using a page object
to retrieve the data on the page.
Let's take the `Shirt` resource class, and define a `:brand` attribute:
```ruby
module QA
module Resource
class Shirt < Base
attr_accessor :name
attribute :project do
Project.fabricate! do |resource|
resource.name = 'project-to-create-a-shirt'
end
end
# Attribute populated from the Browser UI (using the block)
attribute :brand do
Page::Shirt::Show.perform do |shirt_show|
shirt_show.fetch_brand_from_page
end
end
# ... same as before
end
end
end
```
**Note again that all the attributes are lazily constructed. This means if
you call `shirt.brand` after moving to the other page, it doesn't properly
retrieve the data because we're no longer on the expected page.**
Consider this:
```ruby
shirt =
QA::Resource::Shirt.fabricate! do |resource|
resource.name = "GitLab QA"
end
shirt.project.visit!
shirt.brand # => FAIL!
```
The above example fails because now we're on the project page, trying to
construct the brand data from the shirt page, however we moved to the project
page already. There are two ways to solve this, one is that we could try to
retrieve the brand before visiting the project again:
```ruby
shirt =
QA::Resource::Shirt.fabricate! do |resource|
resource.name = "GitLab QA"
end
shirt.brand # => OK!
shirt.project.visit!
shirt.brand # => OK!
```
The attribute is stored in the instance, therefore all the following calls
are fine, using the data previously constructed. If we think that this
might be too brittle, we could eagerly construct the data right before
ending fabrication:
```ruby
module QA
module Resource
class Shirt < Base
# ... same as before
def fabricate!
project.visit!
Page::Project::Show.perform do |project_show|
project_show.go_to_new_shirt
end
Page::Shirt::New.perform do |shirt_new|
shirt_new.set_name(name)
shirt_new.create_shirt!
end
populate(:brand) # Eagerly construct the data
end
end
end
end
```
The `populate` method iterates through its arguments and call each
attribute. Here `populate(:brand)` has the same effect as
just `brand`. Using the populate method makes the intention clearer.
With this, it ensures we construct the data right after we create the
shirt. The drawback is that this always constructs the data when the
resource is fabricated even if we don't need to use the data.
Alternatively, we could just make sure we're on the right page before
constructing the brand data:
```ruby
module QA
module Resource
class Shirt < Base
attr_accessor :name
attribute :project do
Project.fabricate! do |resource|
resource.name = 'project-to-create-a-shirt'
end
end
# Attribute populated from the Browser UI (using the block)
attribute :brand do
back_url = current_url
visit!
Page::Shirt::Show.perform do |shirt_show|
shirt_show.fetch_brand_from_page
end
visit(back_url)
end
# ... same as before
end
end
end
```
This ensures it's on the shirt page before constructing brand, and
move back to the previous page to avoid breaking the state.
#### Define an attribute based on an API response
Sometimes, you want to define a resource attribute based on the API response
from its `GET` or `POST` request. For instance, if the creation of a shirt via
the API returns
```ruby
{
brand: 'a-brand-new-brand',
style: 't-shirt',
materials: [[:cotton, 80], [:polyamide, 20]]
}
```
you may want to store `style` as-is in the resource, and fetch the first value
of the first `materials` item in a `main_fabric` attribute.
Let's take the `Shirt` resource class, and define a `:style` and a
`:main_fabric` attributes:
```ruby
module QA
module Resource
class Shirt < Base
# ... same as before
# @style from the instance if present,
# or fetched from the API response if present,
# or a QA::Resource::Base::NoValueError is raised otherwise
attribute :style
# If @main_fabric is not present,
# and if the API does not contain this field, this block will be
# used to construct the value based on the API response, and
# store the result in @main_fabric
attribute :main_fabric do
api_response.&dig(:materials, 0, 0)
end
# ... same as before
end
end
end
```
**Notes on attributes precedence**:
- resource instance variables have the highest precedence
- attributes from the API response take precedence over attributes from the
block (usually from Browser UI)
- attributes without a value raises a `QA::Resource::Base::NoValueError` error
## Creating resources in your tests
To create a resource in your tests, you can call the `.fabricate!` method on
the resource class, or use the [factory](#factories) to create it.
Note that if the resource class supports API fabrication, this uses this
fabrication by default.
Here is an example that uses the API fabrication method under the hood
since it's supported by the `Shirt` resource class:
```ruby
my_shirt = Resource::Shirt.fabricate! do |shirt|
shirt.name = 'my-shirt'
end
expect(page).to have_text(my_shirt.name) # => "my-shirt" from the resource's instance variable
expect(page).to have_text(my_shirt.brand) # => "a-brand-new-brand" from the API response
expect(page).to have_text(my_shirt.style) # => "t-shirt" from the API response
expect(page).to have_text(my_shirt.main_fabric) # => "cotton" from the API response via the block
```
If you explicitly want to use the Browser UI fabrication method, you can call
the `.fabricate_via_browser_ui!` method instead:
```ruby
my_shirt = Resource::Shirt.fabricate_via_browser_ui! do |shirt|
shirt.name = 'my-shirt'
end
expect(page).to have_text(my_shirt.name) # => "my-shirt" from the resource's instance variable
expect(page).to have_text(my_shirt.brand) # => the brand name fetched from the `Page::Shirt::Show` page via the block
expect(page).to have_text(my_shirt.style) # => QA::Resource::Base::NoValueError will be raised because no API response nor a block is provided
expect(page).to have_text(my_shirt.main_fabric) # => QA::Resource::Base::NoValueError will be raised because no API response and the block didn't provide a value (because it's also based on the API response)
```
You can also explicitly use the API fabrication method, by calling the
`.fabricate_via_api!` method:
```ruby
my_shirt = Resource::Shirt.fabricate_via_api! do |shirt|
shirt.name = 'my-shirt'
end
```
In this case, the result is similar to calling `Resource::Shirt.fabricate!`.
### Factories
You may also use [FactoryBot](https://github.com/thoughtbot/factory_bot/) invocations to create, build, and fetch resources within your tests.
```ruby
# create a project via the API to use in the test
let(:project) { create(:project) }
# create an issue belonging to a project via the API to use in the test
let(:issue) { create(:issue, project: project) }
# create a private project via the API with a specific name
let(:project) { create(:project, :private, name: 'my-project-name', add_name_uuid: false) }
# create one commit in a project that performs three actions
let(:commit) do
create(:commit, commit_message: 'my message', project: project, actions: [
{ action: 'create', file_path: 'README.md', content: '# Welcome!' },
{ action: 'update', file_path: 'README.md', content: '# Updated' },
{ action: 'delete', file_path: 'README.md' }
])
end
###
# instantiate an Issue but don't create it via API yet
let(:issue) { build(:issue) }
# instantiate a Project and perform some actions before creating
let(:project) do
build(:project) do |p|
p.name = 'Test'
p.add_name_uuid = false
end
end
# fetch an existing issue via the API with attributes
let(:existing_issue) { build(:issue, project: project, iid: issue.iid).reload! }
```
All factories are defined in [`qa/qa/factories`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/qa/qa/factories/) and are representative of
their respective `QA::Resource::Base` class.
For example, a factory `:issue` can be found in `qa/resource/issue.rb`. A factory `:project` can be found in `qa/resource/project.rb`.
#### Create a new Factory
Given a resource:
```ruby
# qa/resource/shirt.rb
module QA
module Resource
class Shirt < Base
attr_accessor :name
attr_reader :read_only
attribute :brand
def api_post_body
{ name: name, brand: brand }
end
end
end
end
```
Define a factory with defaults and overrides:
```ruby
# qa/factories/shirts.rb
module QA
FactoryBot.define do
factory :shirt, class: 'QA::Resource::Shirt' do
brand { 'BrandName' }
trait :with_name do
name { 'Shirt Name' }
end
end
end
end
```
In the test, create the resource via the API:
```ruby
let(:my_shirt) { create(:shirt, brand: 'AnotherBrand') } #<Resource::Shirt @brand="AnotherBrand" @name=nil>
let(:named_shirt) { create(:shirt, :with_name) } #<Resource::Shirt @brand="Brand Name" @name="Shirt Name">
let(:invalid_shirt) { create(:shirt, read_only: true) } # NoMethodError
it 'creates a shirt' do
expect(my_shirt.brand).to eq('AnotherBrand')
expect(named_shirt.name).to eq('Shirt Name')
expect(invalid_shirt).to raise_error(NoMethodError) # tries to call Resource::Shirt#read_only=
end
```
### Resources cleanup
We have a mechanism to [collect](https://gitlab.com/gitlab-org/gitlab/-/blob/44345381e89d6bbd440f7b4c680d03e8b75b86de/qa/qa/tools/test_resource_data_processor.rb#L32)
all resources created during test executions, and another to [handle](https://gitlab.com/gitlab-org/gitlab/-/blob/44345381e89d6bbd440f7b4c680d03e8b75b86de/qa/qa/tools/test_resources_handler.rb#L44)
these resources. On [dotcom environments](https://handbook.gitlab.com/handbook/engineering/infrastructure/environments/#environments), after a test suite finishes in the [E2E pipelines](https://handbook.gitlab.com/handbook/engineering/infrastructure-platforms/developer-experience/debugging-end-to-end-test-failures/), resources from all passing test are
automatically deleted in the same pipeline run. Resources from all failed tests are reserved for investigation,
and won't be deleted until the following Saturday by a scheduled pipeline. When introducing new resources,
also make sure to add any resource that cannot be deleted to the [IGNORED_RESOURCES](https://gitlab.com/gitlab-org/gitlab/-/blob/44345381e89d6bbd440f7b4c680d03e8b75b86de/qa/qa/tools/test_resources_handler.rb#L29)
list.
## Where to ask for help?
If you need more information, ask for help on `#s_developer_experience` channel on Slack
(internal, GitLab Team only).
If you are not a Team Member, and you still need help to contribute,
open an issue in GitLab issue tracker with the `~QA` label.
|
https://docs.gitlab.com/development/testing_guide/end_to_end/beginners_guide
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/testing_guide/end_to_end/_index.md
|
2025-08-13
|
doc/development/testing_guide/end_to_end/beginners_guide
|
[
"doc",
"development",
"testing_guide",
"end_to_end",
"beginners_guide"
] |
_index.md
|
none
|
unassigned
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Beginner's guide to writing end-to-end tests
| null |
This tutorial walks you through the creation of end-to-end (_e2e_) tests for [GitLab Community Edition](https://about.gitlab.com/install/?version=ce) and [GitLab Enterprise Edition](https://about.gitlab.com/install/).
By the end of this tutorial, you can:
- Determine whether an end-to-end test is needed.
- Understand the directory structure within `qa/`.
- Write a basic end-to-end test that validates login features.
- Develop any missing [page object](page_objects.md) libraries.
## Before you write a test
Before you write tests, your [GitLab Development Kit (GDK)](https://gitlab.com/gitlab-org/gitlab-development-kit) must be configured to run the specs. The end-to-end tests:
- Are contained within the `qa/` directory.
- Should be independent and [idempotent](https://en.wikipedia.org/wiki/Idempotence#Computer_science_meaning).
- Create [resources](resources.md) (such as project, issue, user) on an ad-hoc basis.
- Test the UI and API interfaces, and use the API to efficiently set up the UI tests.
## Determine if end-to-end tests are needed
Check the code coverage of a specific feature before writing end-to-end tests for the [GitLab](https://gitlab-org.gitlab.io/gitlab/coverage-ruby/#_AllFiles) project. Does sufficient test coverage exist at the unit, feature, or integration levels? If you answered *yes*, then you *don't* need an end-to-end test.
For information about the distribution of tests per level in GitLab, see [Testing Levels](https://gitlab.com/gitlab-org/gitlab/-/blob/master/doc/development/testing_guide/testing_levels.md).
- See the [How to test at the correct level?](https://gitlab.com/gitlab-org/gitlab/-/blob/master/doc/development/testing_guide/testing_levels.md#how-to-test-at-the-correct-level) section of the [Testing levels](https://gitlab.com/gitlab-org/gitlab/-/blob/master/doc/development/testing_guide/testing_levels.md) document.
- Review how often the feature changes. Stable features that don't change very often might not be worth covering with end-to-end tests if they are already covered in lower level tests.
- Finally, discuss the proposed test with the developers involved in implementing the feature and the lower-level tests.
{{< alert type="warning" >}}
Check the [GitLab](https://gitlab-org.gitlab.io/gitlab/coverage-ruby/#_AllFiles) coverage project for previously written tests for this feature. To analyze code coverage, you must understand which application files implement specific features.
{{< /alert >}}
In this tutorial we're writing a login end-to-end test, even though it has been sufficiently covered by lower-level testing, because it's the first step for most end-to-end flows, and is easiest to understand.
## Identify the DevOps stage
The GitLab QA end-to-end tests are organized by the different [stages in the DevOps lifecycle](https://gitlab.com/gitlab-org/gitlab-foss/tree/master/qa/qa/specs/features/browser_ui). Determine where the test should be placed by [stage](https://handbook.gitlab.com/handbook/product/categories/#devops-stages), determine which feature the test belongs to, and then place it in a subdirectory under the stage.

If the test is Enterprise Edition only, the test is created in the `features/ee` directory, but follow the same DevOps lifecycle format.
## Create a skeleton test
In the first part of this tutorial we are testing login, which is owned by the Manage stage. Inside `qa/specs/features/browser_ui/1_manage/login`, create a file `basic_login_spec.rb`.
### The outer `context` block
See the [`RSpec.describe` outer block](#the-outer-rspecdescribe-block)
{{< alert type="warning" >}}
The outer `context` [was deprecated](https://gitlab.com/gitlab-org/quality/quality-engineering/team-tasks/-/issues/550) in `13.2` in adherence to RSpec 4.0 specifications. Use `RSpec.describe` instead.
{{< /alert >}}
### The outer `RSpec.describe` block
Specs have an outer `RSpec.describe` indicating the DevOps stage.
```ruby
# frozen_string_literal: true
module QA
RSpec.describe 'Manage' do
end
end
```
### The `describe` block
Inside of our outer `RSpec.describe`, describe the feature to test. In this case, `Login`.
```ruby
# frozen_string_literal: true
module QA
RSpec.describe 'Manage' do
describe 'Login' do
end
end
end
```
### The `product_group` metadata
Assign `product_group` metadata and specify what product group this test belongs to. In this case, `authentication_and_authorization`.
```ruby
# frozen_string_literal: true
module QA
RSpec.describe 'Manage' do
describe 'Login', product_group: :authentication do
end
end
end
```
### The `it` blocks (examples)
Every test suite contains at least one `it` block (example). A good way to start writing end-to-end tests is to write test case descriptions as `it` blocks:
```ruby
module QA
RSpec.describe 'Manage' do
describe 'Login', product_group: :authentication do
it 'can login' do
end
it 'can logout' do
end
end
end
end
```
## Write the test
An important question is "What do we test?" and even more importantly, "How do we test?"
Begin by logging in.
```ruby
# frozen_string_literal: true
module QA
RSpec.describe 'Manage' do
describe 'Login', product_group: :authentication do
it 'can login' do
Flow::Login.sign_in
end
it 'can logout' do
Flow::Login.sign_in
end
end
end
end
```
{{< alert type="note" >}}
For more information on Flows, see [Flows](flows.md)
{{< /alert >}}
After [running the spec](#run-the-spec), our test should login and end; then we should answer the question "What do we test?"
```ruby
# frozen_string_literal: true
module QA
RSpec.describe 'Manage' do
describe 'Login', product_group: :authentication do
it 'can login' do
Flow::Login.sign_in
Page::Main::Menu.perform do |menu|
expect(menu).to be_signed_in
end
end
it 'can logout' do
Flow::Login.sign_in
Page::Main::Menu.perform do |menu|
menu.sign_out
expect(menu).not_to be_signed_in
end
end
end
end
end
```
**What do we test?**
1. Can we sign in?
1. Can we sign out?
**How do we test?**
1. Check if the user avatar appears in the left sidebar.
1. Check if the user avatar *does not* appear in the left sidebar.
Behind the scenes, `be_signed_in` is a [predicate matcher](https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/predicates/) that [implements checking the user avatar](https://gitlab.com/gitlab-org/gitlab/-/blob/master/qa/qa/page/main/menu.rb#L92).
## De-duplicate your code
Refactor your test to use a `before` block for test setup, since it's duplicating a call to `sign_in`.
```ruby
# frozen_string_literal: true
module QA
RSpec.describe 'Manage' do
describe 'Login', product_group: :authentication do
before do
Flow::Login.sign_in
end
it 'can login' do
Page::Main::Menu.perform do |menu|
expect(menu).to be_signed_in
end
end
it 'can logout' do
Page::Main::Menu.perform do |menu|
menu.sign_out
expect(menu).not_to be_signed_in
end
end
end
end
end
```
The `before` block is essentially a `before(:each)` and is run before each example, ensuring we now sign in at the beginning of each test.
## Test setup using resources and page objects
Next, let's test something other than Login. Let's test Issues, which are owned by the Plan stage and the Project Management Group, so [create a file](#identify-the-devops-stage) in `qa/specs/features/browser_ui/2_plan/issue` called `issues_spec.rb`.
```ruby
# frozen_string_literal: true
module QA
RSpec.describe 'Plan' do
describe 'Issues', product_group: :project_management do
let(:issue) { create(:issue) }
before do
Flow::Login.sign_in
issue.visit!
end
it 'can close an issue' do
Page::Project::Issue::Show.perform do |show|
show.click_close_issue_button
expect(show).to be_closed
end
end
end
end
end
```
Note the following important points:
- At the start of our example, we are at the `page/issue/show.rb` [page](page_objects.md).
- Our test fabricates only what it needs, when it needs it.
- The issue is fabricated through the API to save time.
- GitLab prefers `let()` over instance variables. See [best practices](../../best_practices.md#subject-and-let-variables).
- `be_closed` is not implemented in `page/project/issue/show.rb` yet, but is implemented in the next step.
The issue is fabricated as a [Resource](resources.md), which is a GitLab entity you can create through the UI or API. Other examples include:
- A [Merge Request](https://gitlab.com/gitlab-org/gitlab/-/blob/master/qa/qa/resource/merge_request.rb).
- A [User](https://gitlab.com/gitlab-org/gitlab/-/blob/master/qa/qa/resource/user.rb).
- A [Project](https://gitlab.com/gitlab-org/gitlab/-/blob/master/qa/qa/resource/project.rb).
- A [Group](https://gitlab.com/gitlab-org/gitlab/-/blob/master/qa/qa/resource/group.rb).
## Write the page object
A [Page Object](page_objects.md) is a class in our suite that represents a page within GitLab. The **Login** page would be one example. Since our page object for the **Issue Show** page already exists, add the `closed?` method.
```ruby
module Page::Project::Issue
class Show
view 'app/views/projects/issues/show.html.haml' do
element 'closed-status-box'
end
def closed?
has_element?('closed-status-box')
end
end
end
```
Next, define the element `closed-status-box` within your view, so your Page Object can see it.
```ruby
-#=> app/views/projects/issues/show.html.haml
.issuable-status-box.status-box.status-box-issue-closed{ ..., data: { testid: 'closed-status-box' } }
```
## Run the spec
Before running the spec, make sure that:
- GDK is installed.
- GDK is running locally on port 3000.
- No additional [RSpec metadata tags](../best_practices/rspec_metadata_tests.md) have been applied.
- Your working directory is `qa/` within your GDK GitLab installation.
- Your GitLab instance-level settings are default. If you changed the default settings, some tests might have unexpected results.
- Because the GDK requires a password change on first login, you must include the GDK password for `root` user
To run the spec, run the following command:
```shell
GITLAB_PASSWORD=<GDK root password> bundle exec rspec <test_file>
```
Where `<test_file>` is:
- `qa/specs/features/browser_ui/1_manage/login/log_in_spec.rb` when running the Login example.
- `qa/specs/features/browser_ui/2_plan/issue/create_issue_spec.rb` when running the Issue example.
Additional information on test execution and possible options are described in ["QA framework README"](https://gitlab.com/gitlab-org/gitlab/-/blob/master/qa/README.md#run-the-end-to-end-tests-in-a-local-development-environment)
## Preparing test for code review
Before submitting the test for code review, there are a few housecleaning tasks to do:
1. Ensure that the test name follows the recommended [naming convention](../best_practices/_index.md#test-naming).
1. Ensure that the spec is [linked to a test case](../best_practices/_index.md#link-a-test-to-its-test-case).
1. Ensure that the spec has the correct `product_group` metadata. See [Product sections, stages, groups, and categories](https://handbook.gitlab.com/handbook/product/categories/) for the comprehensive list of groups.
1. Ensure that the relevant [RSpec metadata](../best_practices/rspec_metadata_tests.md) are added to the spec.
1. Ensure the page object elements are named according to the [recommended naming convention](../style_guide.md#element-naming-convention).
{{< alert type="note" >}}
For more information, see [End-to-end testing best practices](../best_practices/_index.md) and [End-to-end testing style guide](../style_guide.md).
{{< /alert >}}
## End-to-end test merge request template
When submitting a new end-to-end test, use the ["New End to End Test"](https://gitlab.com/gitlab-org/gitlab/-/blob/master/.gitlab/merge_request_templates/New%20End%20To%20End%20Test.md) merge request description template for additional steps that are required prior a successful merge.
|
---
stage: none
group: unassigned
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: Beginner's guide to writing end-to-end tests
breadcrumbs:
- doc
- development
- testing_guide
- end_to_end
- beginners_guide
---
This tutorial walks you through the creation of end-to-end (_e2e_) tests for [GitLab Community Edition](https://about.gitlab.com/install/?version=ce) and [GitLab Enterprise Edition](https://about.gitlab.com/install/).
By the end of this tutorial, you can:
- Determine whether an end-to-end test is needed.
- Understand the directory structure within `qa/`.
- Write a basic end-to-end test that validates login features.
- Develop any missing [page object](page_objects.md) libraries.
## Before you write a test
Before you write tests, your [GitLab Development Kit (GDK)](https://gitlab.com/gitlab-org/gitlab-development-kit) must be configured to run the specs. The end-to-end tests:
- Are contained within the `qa/` directory.
- Should be independent and [idempotent](https://en.wikipedia.org/wiki/Idempotence#Computer_science_meaning).
- Create [resources](resources.md) (such as project, issue, user) on an ad-hoc basis.
- Test the UI and API interfaces, and use the API to efficiently set up the UI tests.
## Determine if end-to-end tests are needed
Check the code coverage of a specific feature before writing end-to-end tests for the [GitLab](https://gitlab-org.gitlab.io/gitlab/coverage-ruby/#_AllFiles) project. Does sufficient test coverage exist at the unit, feature, or integration levels? If you answered *yes*, then you *don't* need an end-to-end test.
For information about the distribution of tests per level in GitLab, see [Testing Levels](https://gitlab.com/gitlab-org/gitlab/-/blob/master/doc/development/testing_guide/testing_levels.md).
- See the [How to test at the correct level?](https://gitlab.com/gitlab-org/gitlab/-/blob/master/doc/development/testing_guide/testing_levels.md#how-to-test-at-the-correct-level) section of the [Testing levels](https://gitlab.com/gitlab-org/gitlab/-/blob/master/doc/development/testing_guide/testing_levels.md) document.
- Review how often the feature changes. Stable features that don't change very often might not be worth covering with end-to-end tests if they are already covered in lower level tests.
- Finally, discuss the proposed test with the developers involved in implementing the feature and the lower-level tests.
{{< alert type="warning" >}}
Check the [GitLab](https://gitlab-org.gitlab.io/gitlab/coverage-ruby/#_AllFiles) coverage project for previously written tests for this feature. To analyze code coverage, you must understand which application files implement specific features.
{{< /alert >}}
In this tutorial we're writing a login end-to-end test, even though it has been sufficiently covered by lower-level testing, because it's the first step for most end-to-end flows, and is easiest to understand.
## Identify the DevOps stage
The GitLab QA end-to-end tests are organized by the different [stages in the DevOps lifecycle](https://gitlab.com/gitlab-org/gitlab-foss/tree/master/qa/qa/specs/features/browser_ui). Determine where the test should be placed by [stage](https://handbook.gitlab.com/handbook/product/categories/#devops-stages), determine which feature the test belongs to, and then place it in a subdirectory under the stage.

If the test is Enterprise Edition only, the test is created in the `features/ee` directory, but follow the same DevOps lifecycle format.
## Create a skeleton test
In the first part of this tutorial we are testing login, which is owned by the Manage stage. Inside `qa/specs/features/browser_ui/1_manage/login`, create a file `basic_login_spec.rb`.
### The outer `context` block
See the [`RSpec.describe` outer block](#the-outer-rspecdescribe-block)
{{< alert type="warning" >}}
The outer `context` [was deprecated](https://gitlab.com/gitlab-org/quality/quality-engineering/team-tasks/-/issues/550) in `13.2` in adherence to RSpec 4.0 specifications. Use `RSpec.describe` instead.
{{< /alert >}}
### The outer `RSpec.describe` block
Specs have an outer `RSpec.describe` indicating the DevOps stage.
```ruby
# frozen_string_literal: true
module QA
RSpec.describe 'Manage' do
end
end
```
### The `describe` block
Inside of our outer `RSpec.describe`, describe the feature to test. In this case, `Login`.
```ruby
# frozen_string_literal: true
module QA
RSpec.describe 'Manage' do
describe 'Login' do
end
end
end
```
### The `product_group` metadata
Assign `product_group` metadata and specify what product group this test belongs to. In this case, `authentication_and_authorization`.
```ruby
# frozen_string_literal: true
module QA
RSpec.describe 'Manage' do
describe 'Login', product_group: :authentication do
end
end
end
```
### The `it` blocks (examples)
Every test suite contains at least one `it` block (example). A good way to start writing end-to-end tests is to write test case descriptions as `it` blocks:
```ruby
module QA
RSpec.describe 'Manage' do
describe 'Login', product_group: :authentication do
it 'can login' do
end
it 'can logout' do
end
end
end
end
```
## Write the test
An important question is "What do we test?" and even more importantly, "How do we test?"
Begin by logging in.
```ruby
# frozen_string_literal: true
module QA
RSpec.describe 'Manage' do
describe 'Login', product_group: :authentication do
it 'can login' do
Flow::Login.sign_in
end
it 'can logout' do
Flow::Login.sign_in
end
end
end
end
```
{{< alert type="note" >}}
For more information on Flows, see [Flows](flows.md)
{{< /alert >}}
After [running the spec](#run-the-spec), our test should login and end; then we should answer the question "What do we test?"
```ruby
# frozen_string_literal: true
module QA
RSpec.describe 'Manage' do
describe 'Login', product_group: :authentication do
it 'can login' do
Flow::Login.sign_in
Page::Main::Menu.perform do |menu|
expect(menu).to be_signed_in
end
end
it 'can logout' do
Flow::Login.sign_in
Page::Main::Menu.perform do |menu|
menu.sign_out
expect(menu).not_to be_signed_in
end
end
end
end
end
```
**What do we test?**
1. Can we sign in?
1. Can we sign out?
**How do we test?**
1. Check if the user avatar appears in the left sidebar.
1. Check if the user avatar *does not* appear in the left sidebar.
Behind the scenes, `be_signed_in` is a [predicate matcher](https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/predicates/) that [implements checking the user avatar](https://gitlab.com/gitlab-org/gitlab/-/blob/master/qa/qa/page/main/menu.rb#L92).
## De-duplicate your code
Refactor your test to use a `before` block for test setup, since it's duplicating a call to `sign_in`.
```ruby
# frozen_string_literal: true
module QA
RSpec.describe 'Manage' do
describe 'Login', product_group: :authentication do
before do
Flow::Login.sign_in
end
it 'can login' do
Page::Main::Menu.perform do |menu|
expect(menu).to be_signed_in
end
end
it 'can logout' do
Page::Main::Menu.perform do |menu|
menu.sign_out
expect(menu).not_to be_signed_in
end
end
end
end
end
```
The `before` block is essentially a `before(:each)` and is run before each example, ensuring we now sign in at the beginning of each test.
## Test setup using resources and page objects
Next, let's test something other than Login. Let's test Issues, which are owned by the Plan stage and the Project Management Group, so [create a file](#identify-the-devops-stage) in `qa/specs/features/browser_ui/2_plan/issue` called `issues_spec.rb`.
```ruby
# frozen_string_literal: true
module QA
RSpec.describe 'Plan' do
describe 'Issues', product_group: :project_management do
let(:issue) { create(:issue) }
before do
Flow::Login.sign_in
issue.visit!
end
it 'can close an issue' do
Page::Project::Issue::Show.perform do |show|
show.click_close_issue_button
expect(show).to be_closed
end
end
end
end
end
```
Note the following important points:
- At the start of our example, we are at the `page/issue/show.rb` [page](page_objects.md).
- Our test fabricates only what it needs, when it needs it.
- The issue is fabricated through the API to save time.
- GitLab prefers `let()` over instance variables. See [best practices](../../best_practices.md#subject-and-let-variables).
- `be_closed` is not implemented in `page/project/issue/show.rb` yet, but is implemented in the next step.
The issue is fabricated as a [Resource](resources.md), which is a GitLab entity you can create through the UI or API. Other examples include:
- A [Merge Request](https://gitlab.com/gitlab-org/gitlab/-/blob/master/qa/qa/resource/merge_request.rb).
- A [User](https://gitlab.com/gitlab-org/gitlab/-/blob/master/qa/qa/resource/user.rb).
- A [Project](https://gitlab.com/gitlab-org/gitlab/-/blob/master/qa/qa/resource/project.rb).
- A [Group](https://gitlab.com/gitlab-org/gitlab/-/blob/master/qa/qa/resource/group.rb).
## Write the page object
A [Page Object](page_objects.md) is a class in our suite that represents a page within GitLab. The **Login** page would be one example. Since our page object for the **Issue Show** page already exists, add the `closed?` method.
```ruby
module Page::Project::Issue
class Show
view 'app/views/projects/issues/show.html.haml' do
element 'closed-status-box'
end
def closed?
has_element?('closed-status-box')
end
end
end
```
Next, define the element `closed-status-box` within your view, so your Page Object can see it.
```ruby
-#=> app/views/projects/issues/show.html.haml
.issuable-status-box.status-box.status-box-issue-closed{ ..., data: { testid: 'closed-status-box' } }
```
## Run the spec
Before running the spec, make sure that:
- GDK is installed.
- GDK is running locally on port 3000.
- No additional [RSpec metadata tags](../best_practices/rspec_metadata_tests.md) have been applied.
- Your working directory is `qa/` within your GDK GitLab installation.
- Your GitLab instance-level settings are default. If you changed the default settings, some tests might have unexpected results.
- Because the GDK requires a password change on first login, you must include the GDK password for `root` user
To run the spec, run the following command:
```shell
GITLAB_PASSWORD=<GDK root password> bundle exec rspec <test_file>
```
Where `<test_file>` is:
- `qa/specs/features/browser_ui/1_manage/login/log_in_spec.rb` when running the Login example.
- `qa/specs/features/browser_ui/2_plan/issue/create_issue_spec.rb` when running the Issue example.
Additional information on test execution and possible options are described in ["QA framework README"](https://gitlab.com/gitlab-org/gitlab/-/blob/master/qa/README.md#run-the-end-to-end-tests-in-a-local-development-environment)
## Preparing test for code review
Before submitting the test for code review, there are a few housecleaning tasks to do:
1. Ensure that the test name follows the recommended [naming convention](../best_practices/_index.md#test-naming).
1. Ensure that the spec is [linked to a test case](../best_practices/_index.md#link-a-test-to-its-test-case).
1. Ensure that the spec has the correct `product_group` metadata. See [Product sections, stages, groups, and categories](https://handbook.gitlab.com/handbook/product/categories/) for the comprehensive list of groups.
1. Ensure that the relevant [RSpec metadata](../best_practices/rspec_metadata_tests.md) are added to the spec.
1. Ensure the page object elements are named according to the [recommended naming convention](../style_guide.md#element-naming-convention).
{{< alert type="note" >}}
For more information, see [End-to-end testing best practices](../best_practices/_index.md) and [End-to-end testing style guide](../style_guide.md).
{{< /alert >}}
## End-to-end test merge request template
When submitting a new end-to-end test, use the ["New End to End Test"](https://gitlab.com/gitlab-org/gitlab/-/blob/master/.gitlab/merge_request_templates/New%20End%20To%20End%20Test.md) merge request description template for additional steps that are required prior a successful merge.
|
https://docs.gitlab.com/development/testing_guide/end_to_end/page_objects
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/testing_guide/end_to_end/page_objects.md
|
2025-08-13
|
doc/development/testing_guide/end_to_end/beginners_guide
|
[
"doc",
"development",
"testing_guide",
"end_to_end",
"beginners_guide"
] |
page_objects.md
|
none
|
unassigned
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Page objects in GitLab QA
| null |
In GitLab QA we are using a known pattern, called _Page Objects_.
This means that we have built an abstraction for all pages in GitLab that we use
to drive GitLab QA scenarios. Whenever we do something on a page, like filling
in a form or selecting a button, we do that only through a page object
associated with this area of GitLab.
For example, when GitLab QA test harness signs in into GitLab, it needs to fill
in user login and user password. To do that, we have a class, called
`Page::Main::Login` and `sign_in_using_credentials` methods, that is the only
piece of the code, that reads the `user-login` and `user-password`
fields.
## Why do we need that?
We need page objects because we need to reduce duplication and avoid problems
whenever someone changes some selectors in the GitLab source code.
Imagine that we have a hundred specs in GitLab QA, and we need to sign in to
GitLab each time, before we make assertions. Without a page object, one would
need to rely on volatile helpers or invoke Capybara methods directly. Imagine
invoking `fill_in 'user-login'` in every `*_spec.rb` file / test example.
When someone later changes `t.text_field 'login'` in the view associated with
this page to `t.text_field 'username'` it generates a different field
identifier, what would effectively break all tests.
Because we are using `Page::Main::Login.perform(&:sign_in_using_credentials)`
everywhere, when we want to sign in to GitLab, the page object is the single
source of truth, and we must update `fill_in 'user-login'`
to `fill_in 'user-username'` only in one place.
## What problems did we have in the past?
We do not run QA tests for every commit, because of performance reasons, and
the time it would take to build packages and test everything.
That is why when someone changes `t.text_field 'login'` to
`t.text_field 'username'` in the _new session_ view we don't know about this
change until our GitLab QA nightly pipeline fails, or until someone triggers
`package-and-qa` action in their merge request.
Such a change would break all tests. We call this problem a _fragile
tests problem_.
To make GitLab QA more reliable and robust, we had to solve this
problem by introducing coupling between GitLab CE / EE views and GitLab QA.
## How did we solve fragile tests problem?
Currently, when you add a new `Page::Base` derived class, you must also
define all selectors that your page objects depend on.
Whenever you push your code to CE / EE repository, `qa:selectors` sanity test
job runs as a part of a CI pipeline.
This test validates all page objects that we have implemented in
`qa/page` directory. When it fails, it notifies you about missing
or invalid views/selectors definition.
## How to properly implement a page object?
We have built a DSL to define coupling between a page object and GitLab views
it is actually implemented by. See an example below.
```ruby
module Page
module Main
class Login < Page::Base
view 'app/views/devise/passwords/edit.html.haml' do
element 'password-field'
element 'password-confirmation'
element 'change-password-button'
end
view 'app/views/devise/sessions/_new_base.html.haml' do
element 'login-field'
element 'password-field'
element 'sign-in-button'
end
# ...
end
end
end
```
### Defining Elements
The `view` DSL method corresponds to the Rails view, partial, or Vue component that renders the elements.
The `element` DSL method in turn declares an element for which a corresponding
`testid=element-name` data attribute must be added, if not already, to the view file.
You can also define a value (String or Regexp) to match to the actual view
code but **this is deprecated** in favor of the above method for two reasons:
- Consistency: there is only one way to define an element
- Separation of concerns: Tests use dedicated `data-testid` attributes instead of reusing code
or classes used by other components (for example, `js-*` classes etc.)
```ruby
view 'app/views/my/view.html.haml' do
### Good ###
# Implicitly require the CSS selector `[data-testid="logout-button"]` to be present in the view
element 'logout-button'
### Bad ###
## This is deprecated and forbidden by the `QA/ElementWithPattern` RuboCop cop.
# Require `f.submit "Sign in"` to be present in `my/view.html.haml
element :my_button, 'f.submit "Sign in"' # rubocop:disable QA/ElementWithPattern
## This is deprecated and forbidden by the `QA/ElementWithPattern` RuboCop cop.
# Match every line in `my/view.html.haml` against
# `/link_to .* "My Profile"/` regexp.
element :profile_link, /link_to .* "My Profile"/ # rubocop:disable QA/ElementWithPattern
end
```
### Adding Elements to a View
Given the following elements...
```ruby
view 'app/views/my/view.html.haml' do
element 'login-field'
element 'password-field'
element 'sign-in-button'
end
```
To add these elements to the view, you must change the Rails view, partial, or Vue component by adding a `data-testid` attribute
for each element defined.
In our case, `data-testid="login-field"`, `data-testid="password-field"` and `data-testid="sign-in-button"`
`app/views/my/view.html.haml`
```ruby
= f.text_field :login, class: "form-control top", autofocus: "autofocus", autocapitalize: "off", autocorrect: "off", required: true, title: "This field is required.", data: { testid: 'login_field' }
= f.password_field :password, class: "form-control bottom", required: true, title: "This field is required.", data: { testid: 'password_field' }
= f.submit "Sign in", class: "btn btn-confirm", data: { testid: 'sign_in_button' }
```
Things to note:
- The name of the element and the `data-testid` must match and be kebab cased
- If the element appears on the page unconditionally, add `required: true` to the element. See
[Dynamic element validation](../best_practices/dynamic_element_validation.md)
- You should not see `data-qa-selector` classes in Page Objects.
We should use the [`data-testid`](#data-testid-vs-data-qa-selector)
method of definition
### `data-testid` vs `data-qa-selector`
{{< history >}}
- Introduced in GitLab 16.1
{{< /history >}}
Any existing `data-qa-selector` class should be considered deprecated
and we should use the `data-testid` method of definition.
### Dynamic element selection
A common occurrence in automated testing is selecting a single "one-of-many" element.
In a list of several items, how do you differentiate what you are selecting on?
The most common workaround for this is via text matching. Instead, a better practice is
by matching on that specific element by a unique identifier, rather than by text.
We got around this by adding the `data-qa-*` extensible selection mechanism.
#### Examples
**Example 1**
Given the following Rails view (using GitLab Issues as an example):
```ruby
%ul.issues-list
- @issues.each do |issue|
%li.issue{data: { testid: 'issue', qa_issue_title: issue.title } }= link_to issue
```
We can select on that specific issue by matching on the Rails model.
```ruby
class Page::Project::Issues::Index < Page::Base
def has_issue?(issue)
has_element?(:issue, issue_title: issue)
end
end
```
In our test, we can validate that this particular issue exists.
```ruby
describe 'Issue' do
it 'has an issue titled "hello"' do
Page::Project::Issues::Index.perform do |index|
expect(index).to have_issue('hello')
end
end
end
```
**Example 2**
*By an index...*
```ruby
%ol
- @some_model.each_with_index do |model, idx|
%li.model{ data: { testid: 'model', qa_index: idx } }
```
```ruby
expect(the_page).to have_element(:model, index: 1) #=> select on the first model that appears in the list
```
### Exceptions
In some cases, it might not be possible or worthwhile to add a selector.
Some UI components use external libraries, including some maintained by third parties.
Even if a library is maintained by GitLab, the selector sanity test only runs
on code within the GitLab project, so it's not possible to specify the path for
the view for code in a library.
In such rare cases it's reasonable to use CSS selectors in page object methods,
with a comment explaining why an `element` can't be added.
### Define Page concerns
Some pages share common behaviors, and/or are prepended with EE-specific modules that adds EE-specific methods.
These modules must:
1. Extend from the `QA::Page::PageConcern` module, with `extend QA::Page::PageConcern`.
1. Override the `self.prepended` method if they need to `include`/`prepend` other modules themselves, and/or define
`view` or `elements`.
1. Call `super` as the first thing in `self.prepended`.
1. Include/prepend other modules and define their `view`/`elements` in a `base.class_eval` block to ensure they're
defined in the class that prepends the module.
These steps ensure the sanity selectors check detect problems properly.
For example, `qa/qa/ee/page/merge_request/show.rb` adds EE-specific methods to `qa/qa/page/merge_request/show.rb` (with
`QA::Page::MergeRequest::Show.prepend_mod_with('Page::MergeRequest::Show', namespace: QA)`) and following is how it's implemented
(only showing the relevant part and referring to the 4 steps described above with inline comments):
```ruby
module QA
module EE
module Page
module MergeRequest
module Show
extend QA::Page::PageConcern # 1.
def self.prepended(base) # 2.
super # 3.
base.class_eval do # 4.
prepend Page::Component::LicenseManagement
view 'app/assets/javascripts/vue_merge_request_widget/components/states/sha_mismatch.vue' do
element 'head-mismatch', "The source branch HEAD has recently changed."
end
[...]
end
end
end
end
end
end
end
```
## Running the test locally
During development, you can run the `qa:selectors` test by running
```shell
bin/qa Test::Sanity::Selectors
```
from within the `qa` directory.
## Where to ask for help?
If you need more information, ask for help on `#s_developer_experience` channel on Slack
(internal, GitLab Team only).
If you are not a Team Member, and you still need help to contribute,
open an issue in GitLab issue tracker with the `~QA` label.
|
---
stage: none
group: unassigned
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: Page objects in GitLab QA
breadcrumbs:
- doc
- development
- testing_guide
- end_to_end
- beginners_guide
---
In GitLab QA we are using a known pattern, called _Page Objects_.
This means that we have built an abstraction for all pages in GitLab that we use
to drive GitLab QA scenarios. Whenever we do something on a page, like filling
in a form or selecting a button, we do that only through a page object
associated with this area of GitLab.
For example, when GitLab QA test harness signs in into GitLab, it needs to fill
in user login and user password. To do that, we have a class, called
`Page::Main::Login` and `sign_in_using_credentials` methods, that is the only
piece of the code, that reads the `user-login` and `user-password`
fields.
## Why do we need that?
We need page objects because we need to reduce duplication and avoid problems
whenever someone changes some selectors in the GitLab source code.
Imagine that we have a hundred specs in GitLab QA, and we need to sign in to
GitLab each time, before we make assertions. Without a page object, one would
need to rely on volatile helpers or invoke Capybara methods directly. Imagine
invoking `fill_in 'user-login'` in every `*_spec.rb` file / test example.
When someone later changes `t.text_field 'login'` in the view associated with
this page to `t.text_field 'username'` it generates a different field
identifier, what would effectively break all tests.
Because we are using `Page::Main::Login.perform(&:sign_in_using_credentials)`
everywhere, when we want to sign in to GitLab, the page object is the single
source of truth, and we must update `fill_in 'user-login'`
to `fill_in 'user-username'` only in one place.
## What problems did we have in the past?
We do not run QA tests for every commit, because of performance reasons, and
the time it would take to build packages and test everything.
That is why when someone changes `t.text_field 'login'` to
`t.text_field 'username'` in the _new session_ view we don't know about this
change until our GitLab QA nightly pipeline fails, or until someone triggers
`package-and-qa` action in their merge request.
Such a change would break all tests. We call this problem a _fragile
tests problem_.
To make GitLab QA more reliable and robust, we had to solve this
problem by introducing coupling between GitLab CE / EE views and GitLab QA.
## How did we solve fragile tests problem?
Currently, when you add a new `Page::Base` derived class, you must also
define all selectors that your page objects depend on.
Whenever you push your code to CE / EE repository, `qa:selectors` sanity test
job runs as a part of a CI pipeline.
This test validates all page objects that we have implemented in
`qa/page` directory. When it fails, it notifies you about missing
or invalid views/selectors definition.
## How to properly implement a page object?
We have built a DSL to define coupling between a page object and GitLab views
it is actually implemented by. See an example below.
```ruby
module Page
module Main
class Login < Page::Base
view 'app/views/devise/passwords/edit.html.haml' do
element 'password-field'
element 'password-confirmation'
element 'change-password-button'
end
view 'app/views/devise/sessions/_new_base.html.haml' do
element 'login-field'
element 'password-field'
element 'sign-in-button'
end
# ...
end
end
end
```
### Defining Elements
The `view` DSL method corresponds to the Rails view, partial, or Vue component that renders the elements.
The `element` DSL method in turn declares an element for which a corresponding
`testid=element-name` data attribute must be added, if not already, to the view file.
You can also define a value (String or Regexp) to match to the actual view
code but **this is deprecated** in favor of the above method for two reasons:
- Consistency: there is only one way to define an element
- Separation of concerns: Tests use dedicated `data-testid` attributes instead of reusing code
or classes used by other components (for example, `js-*` classes etc.)
```ruby
view 'app/views/my/view.html.haml' do
### Good ###
# Implicitly require the CSS selector `[data-testid="logout-button"]` to be present in the view
element 'logout-button'
### Bad ###
## This is deprecated and forbidden by the `QA/ElementWithPattern` RuboCop cop.
# Require `f.submit "Sign in"` to be present in `my/view.html.haml
element :my_button, 'f.submit "Sign in"' # rubocop:disable QA/ElementWithPattern
## This is deprecated and forbidden by the `QA/ElementWithPattern` RuboCop cop.
# Match every line in `my/view.html.haml` against
# `/link_to .* "My Profile"/` regexp.
element :profile_link, /link_to .* "My Profile"/ # rubocop:disable QA/ElementWithPattern
end
```
### Adding Elements to a View
Given the following elements...
```ruby
view 'app/views/my/view.html.haml' do
element 'login-field'
element 'password-field'
element 'sign-in-button'
end
```
To add these elements to the view, you must change the Rails view, partial, or Vue component by adding a `data-testid` attribute
for each element defined.
In our case, `data-testid="login-field"`, `data-testid="password-field"` and `data-testid="sign-in-button"`
`app/views/my/view.html.haml`
```ruby
= f.text_field :login, class: "form-control top", autofocus: "autofocus", autocapitalize: "off", autocorrect: "off", required: true, title: "This field is required.", data: { testid: 'login_field' }
= f.password_field :password, class: "form-control bottom", required: true, title: "This field is required.", data: { testid: 'password_field' }
= f.submit "Sign in", class: "btn btn-confirm", data: { testid: 'sign_in_button' }
```
Things to note:
- The name of the element and the `data-testid` must match and be kebab cased
- If the element appears on the page unconditionally, add `required: true` to the element. See
[Dynamic element validation](../best_practices/dynamic_element_validation.md)
- You should not see `data-qa-selector` classes in Page Objects.
We should use the [`data-testid`](#data-testid-vs-data-qa-selector)
method of definition
### `data-testid` vs `data-qa-selector`
{{< history >}}
- Introduced in GitLab 16.1
{{< /history >}}
Any existing `data-qa-selector` class should be considered deprecated
and we should use the `data-testid` method of definition.
### Dynamic element selection
A common occurrence in automated testing is selecting a single "one-of-many" element.
In a list of several items, how do you differentiate what you are selecting on?
The most common workaround for this is via text matching. Instead, a better practice is
by matching on that specific element by a unique identifier, rather than by text.
We got around this by adding the `data-qa-*` extensible selection mechanism.
#### Examples
**Example 1**
Given the following Rails view (using GitLab Issues as an example):
```ruby
%ul.issues-list
- @issues.each do |issue|
%li.issue{data: { testid: 'issue', qa_issue_title: issue.title } }= link_to issue
```
We can select on that specific issue by matching on the Rails model.
```ruby
class Page::Project::Issues::Index < Page::Base
def has_issue?(issue)
has_element?(:issue, issue_title: issue)
end
end
```
In our test, we can validate that this particular issue exists.
```ruby
describe 'Issue' do
it 'has an issue titled "hello"' do
Page::Project::Issues::Index.perform do |index|
expect(index).to have_issue('hello')
end
end
end
```
**Example 2**
*By an index...*
```ruby
%ol
- @some_model.each_with_index do |model, idx|
%li.model{ data: { testid: 'model', qa_index: idx } }
```
```ruby
expect(the_page).to have_element(:model, index: 1) #=> select on the first model that appears in the list
```
### Exceptions
In some cases, it might not be possible or worthwhile to add a selector.
Some UI components use external libraries, including some maintained by third parties.
Even if a library is maintained by GitLab, the selector sanity test only runs
on code within the GitLab project, so it's not possible to specify the path for
the view for code in a library.
In such rare cases it's reasonable to use CSS selectors in page object methods,
with a comment explaining why an `element` can't be added.
### Define Page concerns
Some pages share common behaviors, and/or are prepended with EE-specific modules that adds EE-specific methods.
These modules must:
1. Extend from the `QA::Page::PageConcern` module, with `extend QA::Page::PageConcern`.
1. Override the `self.prepended` method if they need to `include`/`prepend` other modules themselves, and/or define
`view` or `elements`.
1. Call `super` as the first thing in `self.prepended`.
1. Include/prepend other modules and define their `view`/`elements` in a `base.class_eval` block to ensure they're
defined in the class that prepends the module.
These steps ensure the sanity selectors check detect problems properly.
For example, `qa/qa/ee/page/merge_request/show.rb` adds EE-specific methods to `qa/qa/page/merge_request/show.rb` (with
`QA::Page::MergeRequest::Show.prepend_mod_with('Page::MergeRequest::Show', namespace: QA)`) and following is how it's implemented
(only showing the relevant part and referring to the 4 steps described above with inline comments):
```ruby
module QA
module EE
module Page
module MergeRequest
module Show
extend QA::Page::PageConcern # 1.
def self.prepended(base) # 2.
super # 3.
base.class_eval do # 4.
prepend Page::Component::LicenseManagement
view 'app/assets/javascripts/vue_merge_request_widget/components/states/sha_mismatch.vue' do
element 'head-mismatch', "The source branch HEAD has recently changed."
end
[...]
end
end
end
end
end
end
end
```
## Running the test locally
During development, you can run the `qa:selectors` test by running
```shell
bin/qa Test::Sanity::Selectors
```
from within the `qa` directory.
## Where to ask for help?
If you need more information, ask for help on `#s_developer_experience` channel on Slack
(internal, GitLab Team only).
If you are not a Team Member, and you still need help to contribute,
open an issue in GitLab issue tracker with the `~QA` label.
|
https://docs.gitlab.com/development/testing_guide/end_to_end/flows
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/testing_guide/end_to_end/flows.md
|
2025-08-13
|
doc/development/testing_guide/end_to_end/beginners_guide
|
[
"doc",
"development",
"testing_guide",
"end_to_end",
"beginners_guide"
] |
flows.md
|
none
|
unassigned
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Flows in GitLab QA
| null |
Flows are frequently used sequences of actions. They are a higher level
of abstraction than page objects. Flows can include multiple page objects,
or any other relevant code.
For example, the sign in flow encapsulates two steps that are included
in every browser UI test.
```ruby
# QA::Flow::Login
def sign_in(as: nil)
Runtime::Browser.visit(:gitlab, Page::Main::Login)
Page::Main::Login.perform { |login| login.sign_in_using_credentials(user: as) }
end
# When used in a test
it 'performs a test after signing in as the default user' do
Flow::Login.sign_in
# Perform the test
end
```
`QA::Flow::Login` provides an even more useful flow, allowing a test to easily switch users.
```ruby
# QA::Flow::Login
def while_signed_in(as: nil)
Page::Main::Menu.perform(&:sign_out_if_signed_in)
sign_in(as: as)
yield
Page::Main::Menu.perform(&:sign_out)
end
# When used in a test
it 'performs a test as one user and verifies as another' do
user1 = create(:user)
user2 = create(:user)
Flow::Login.while_signed_in(as: user1) do
# Perform some setup as user1
end
Flow::Login.sign_in(as: user2)
# Perform the rest of the test as user2
end
```
|
---
stage: none
group: unassigned
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: Flows in GitLab QA
breadcrumbs:
- doc
- development
- testing_guide
- end_to_end
- beginners_guide
---
Flows are frequently used sequences of actions. They are a higher level
of abstraction than page objects. Flows can include multiple page objects,
or any other relevant code.
For example, the sign in flow encapsulates two steps that are included
in every browser UI test.
```ruby
# QA::Flow::Login
def sign_in(as: nil)
Runtime::Browser.visit(:gitlab, Page::Main::Login)
Page::Main::Login.perform { |login| login.sign_in_using_credentials(user: as) }
end
# When used in a test
it 'performs a test after signing in as the default user' do
Flow::Login.sign_in
# Perform the test
end
```
`QA::Flow::Login` provides an even more useful flow, allowing a test to easily switch users.
```ruby
# QA::Flow::Login
def while_signed_in(as: nil)
Page::Main::Menu.perform(&:sign_out_if_signed_in)
sign_in(as: as)
yield
Page::Main::Menu.perform(&:sign_out)
end
# When used in a test
it 'performs a test as one user and verifies as another' do
user1 = create(:user)
user2 = create(:user)
Flow::Login.while_signed_in(as: user1) do
# Perform some setup as user1
end
Flow::Login.sign_in(as: user2)
# Perform the rest of the test as user2
end
```
|
https://docs.gitlab.com/development/testing_guide/end_to_end/feature_flags
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/testing_guide/end_to_end/feature_flags.md
|
2025-08-13
|
doc/development/testing_guide/end_to_end/best_practices
|
[
"doc",
"development",
"testing_guide",
"end_to_end",
"best_practices"
] |
feature_flags.md
|
none
|
unassigned
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Testing with feature flags
| null |
To run a specific test with a feature flag enabled you can use the `QA::Runtime::Feature` class to
enable and disable feature flags ([via the API](../../../../api/features.md)).
Note that administrator authorization is required to change feature flags. `QA::Runtime::Feature`
automatically authenticates as an administrator as long as you provide an appropriate access
token via `GITLAB_QA_ADMIN_ACCESS_TOKEN` (recommended), or provide `GITLAB_ADMIN_USERNAME`
and `GITLAB_ADMIN_PASSWORD`.
## `feature_flag` RSpec tag
Be sure to include the `feature_flag` tag so that the test can be skipped on the appropriate environments.
**Required metadata**:
`name`
- Format: `feature_flag: { name: 'feature_flag_name' }`
- Used for informational purposes. It shall be included to determine which
feature flag is under test.
**Optional metadata**:
`scope`
- Format: `feature_flag: { name: 'feature_flag_name', scope: :project }`
- When `scope` is set to `:global`, the test will be **skipped on all live .com environments**. This is to avoid issues with feature flag changes affecting other tests or users on that environment.
- When `scope` is set to any other value (such as `:project`, `:group` or `:user`), or if no `scope` is specified, the test will only be **skipped on canary, production, and pre-production**.
This is due to the fact that administrator access is not available there.
{{< alert type="warning" >}}
You are strongly advised to first try and [enable feature flags only for a group, project, user](../../../feature_flags/_index.md#feature-actors),
or [feature group](../../../feature_flags/_index.md#feature-groups).
{{< /alert >}}
- If a global feature flag must be used, it is strongly recommended to apply `scope: :global` to the `feature_flag` metadata. This is, however, left up to the SET's discretion to determine the level of risk.
- For example, a test uses a global feature flag that only affects a small area of the application and is also needed to check for critical issues on live environments.
In such a scenario, it would be riskier to skip running the test. For cases like this, `scope` can be left out of the metadata so that it can still run in live environments
with administrator access, such as staging.
**Note on `requires_admin`**: This tag should still be applied if there are other actions within the test that require administrator access that are unrelated to updating a
feature flag (like creating a user via the API).
The code below would enable a feature flag named `:feature_flag_name` for the project
created by the test:
```ruby
RSpec.describe "with feature flag enabled", feature_flag: {
name: 'feature_flag_name',
scope: :project
} do
let(:project) { Resource::Project.fabricate_via_api! }
around do |example|
Runtime::Feature.enable(:feature_flag_name, project: project)
example.run
Runtime::Feature.disable(:feature_flag_name, project: project)
end
it "feature flag test" do
# Execute the test with the feature flag enabled.
# It will only affect the project created in this test.
end
end
```
Note that the `enable` and `disable` methods first set the flag and then check that the updated
value is returned by the API.
Similarly, you can enable a feature for a group, user, or feature group:
```ruby
group = Resource::Group.fabricate_via_api!
Runtime::Feature.enable(:feature_flag_name, group: group)
user = Resource::User.fabricate_via_api!
Runtime::Feature.enable(:feature_flag_name, user: user)
feature_group = "a_feature_group"
Runtime::Feature.enable(:feature_flag_name, feature_group: feature_group)
```
If no scope is provided, the feature flag is set instance-wide:
```ruby
# This will affect all users!
Runtime::Feature.enable(:feature_flag_name)
```
## Working with selectors
A new feature often replaces a `vue` component or a `haml` file with a new one.
In most cases, the new file or component is accessible only with a feature flag.
This approach becomes problematic when tests must pass both with, and without,
the feature flag enabled. To ensure tests pass in both scenarios:
1. Create another selector inside the new component or file.
1. Give it the same name as the old one.
Selectors are connected to a specific frontend file in the [page object](../beginners_guide/page_objects.md),
and checked for availability inside our `qa:selectors` test. If the mentioned selector
is missing inside that frontend file, the test fails. To ensure selectors are
available when a feature flag is enabled or disabled, add the new selector to the
[page object](../beginners_guide/page_objects.md), leaving the old selector in place.
The test uses the correct selector and still detects missing selectors.
If a new feature changes an existing frontend file that already has a selector,
you can add a new selector with the same name. However, only one of the selectors
displays on the page. You should:
1. Disable the other with the feature flag.
1. Add a comment in the frontend file to delete the old selector from the frontend
file and from the page object file when the feature flag is removed.
### Example before
```ruby
# This is the link to the old file
view 'app/views/devise/passwords/edit.html.haml' do
# The new selector should have the same name
element 'password-field'
...
end
```
### Example after
```ruby
view 'app/views/devise/passwords/edit.html.haml' do
element 'password-field'
...
end
# Now it can verify the selector is available
view 'app/views/devise/passwords/new_edit_behind_ff.html.haml' do
# The selector has the same name
element 'password-field'
end
```
## Working with resource classes
If a resource class must behave differently when a feature flag is active, toggle a
variable with the name of the feature flag inside the class. This variable and condition
ensure all actions are handled appropriately.
You can set this variable inside the `fabricate_via_api` call. For a consistent approach:
- Use an `activated` check, not a deactivated one.
- Add the word `activated` to the end of a variable's name.
- Inside the `initialize` method, set the variable's default value.
For example:
```ruby
def initialize
name_of_the_feature_flag_activated = false
...
end
```
### Cleanup
After the feature flag is removed, clean up the resource class and delete the variable.
All methods should use the condition procedures of the now-default state.
## Managing flakiness due to caching
All application settings, and all feature flags, are cached inside GitLab for one minute.
All caching is disabled during testing, except on static environments.
When a test changes a feature flag, it can cause flaky behavior if elements are visible only with an
active feature flag. To circumvent this behavior, add a wait for elements behind a feature flag.
## Running a scenario with a feature flag enabled
It's also possible to run an entire scenario with a feature flag enabled, without having to edit
existing tests or write new ones.
See the [QA README](https://gitlab.com/gitlab-org/gitlab/-/tree/master/qa#running-tests-with-a-feature-flag-enabled)
for details.
## Confirming that end-to-end tests pass with a feature flag enabled
End-to-end tests should pass with a feature flag enabled before it is enabled on Staging or on GitLab.com. Tests that need to be updated should be identified as part of [quad-planning](https://handbook.gitlab.com/handbook/engineering/infrastructure/test-platform/quad-planning/). The relevant [counterpart Software Engineer in Test](https://handbook.gitlab.com/handbook/engineering/quality/#individual-contributors) is responsible for updating the tests or assisting another engineer to do so. However, if a change does not go through quad-planning and a required test update is not made, test failures could block deployment.
### Automatic test execution when a feature flag definition changes
There are two ways to confirm that end-to-end tests pass:
- If a merge request adds or edits a [feature flag definition file](../../../feature_flags/_index.md#feature-flag-definition-and-validation),
two `e2e:test-on-gdk` jobs (`gdk-instance` and `gdk-instance-ff-inverse`) are included automatically in the merge request pipeline.
One job runs the application with default feature flag state and another sets it to inverse value. The jobs execute the same suite of tests to confirm that they pass with the feature flag either enabled or disabled.
- In some cases, if end-to-end test jobs didn't trigger automatically, or if it has run the tests with the default feature flag values (which might not be desired),
you can create a Draft MR that enables the feature flag to ensure that all E2E tests pass with the feature flag enabled and disabled.
### Troubleshooting end-to-end test failures with feature flag enabled
If enabling the feature flag results in E2E test failures, you can browse the artifacts in the failed pipeline to see screenshots of the failed tests. After which, you can either:
- Identify tests that need to be updated and contact the relevant [counterpart Software Engineer in Test](https://handbook.gitlab.com/handbook/engineering/quality/#individual-contributors) responsible for updating the tests or assisting another engineer to do so. However, if a change does not go through [quad-planning](https://handbook.gitlab.com/handbook/engineering/infrastructure/test-platform/quad-planning/) and a required test update is not made, test failures could block deployment.
- Run the failed tests [locally](https://gitlab.com/gitlab-org/gitlab/-/tree/master/qa#run-the-end-to-end-tests-in-a-local-development-environment)
with the [feature flag enabled](https://gitlab.com/gitlab-org/gitlab/-/tree/master/qa#running-tests-with-a-feature-flag-enabled-or-disabled).
This option requires considerable amount of setup, but you'll be able to see what the browser is doing as it's running the failed
tests, which can help debug the problem faster. You can also refer to the [Troubleshooting Guide for E2E tests](../troubleshooting.md) for
support for common blockers.
### Test execution during feature development
If an end-to-end test enables a feature flag, the end-to-end test suite can be used to test changes in a merge request
by running the `e2e:test-on-omnibus-ee` job in the merge request pipeline. If the feature flag and relevant changes have already been merged, you can confirm that the tests
pass on the default branch. The end-to-end tests run on the default branch every two hours, and the results are posted to a
[Test Session Report, which is available in the testcase-sessions project](https://gitlab.com/gitlab-org/quality/testcase-sessions/-/issues?label_name%5B%5D=found%3Amain).
If the relevant tests do not enable the feature flag themselves, you can check if the tests will need to be updated by opening
a draft merge request that enables the flag by default via a [feature flag definition file](../../../feature_flags/_index.md#feature-flag-definition-and-validation).
That will [automatically execute the end-to-end test suite](#automatic-test-execution-when-a-feature-flag-definition-changes).
The merge request can be closed once the tests pass. If you need assistance to update the tests, contact the relevant [stable counterpart in the Quality department](https://handbook.gitlab.com/handbook/engineering/quality/#individual-contributors), or any Software Engineer in Test if there is no stable counterpart for your group.
|
---
stage: none
group: unassigned
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: Testing with feature flags
breadcrumbs:
- doc
- development
- testing_guide
- end_to_end
- best_practices
---
To run a specific test with a feature flag enabled you can use the `QA::Runtime::Feature` class to
enable and disable feature flags ([via the API](../../../../api/features.md)).
Note that administrator authorization is required to change feature flags. `QA::Runtime::Feature`
automatically authenticates as an administrator as long as you provide an appropriate access
token via `GITLAB_QA_ADMIN_ACCESS_TOKEN` (recommended), or provide `GITLAB_ADMIN_USERNAME`
and `GITLAB_ADMIN_PASSWORD`.
## `feature_flag` RSpec tag
Be sure to include the `feature_flag` tag so that the test can be skipped on the appropriate environments.
**Required metadata**:
`name`
- Format: `feature_flag: { name: 'feature_flag_name' }`
- Used for informational purposes. It shall be included to determine which
feature flag is under test.
**Optional metadata**:
`scope`
- Format: `feature_flag: { name: 'feature_flag_name', scope: :project }`
- When `scope` is set to `:global`, the test will be **skipped on all live .com environments**. This is to avoid issues with feature flag changes affecting other tests or users on that environment.
- When `scope` is set to any other value (such as `:project`, `:group` or `:user`), or if no `scope` is specified, the test will only be **skipped on canary, production, and pre-production**.
This is due to the fact that administrator access is not available there.
{{< alert type="warning" >}}
You are strongly advised to first try and [enable feature flags only for a group, project, user](../../../feature_flags/_index.md#feature-actors),
or [feature group](../../../feature_flags/_index.md#feature-groups).
{{< /alert >}}
- If a global feature flag must be used, it is strongly recommended to apply `scope: :global` to the `feature_flag` metadata. This is, however, left up to the SET's discretion to determine the level of risk.
- For example, a test uses a global feature flag that only affects a small area of the application and is also needed to check for critical issues on live environments.
In such a scenario, it would be riskier to skip running the test. For cases like this, `scope` can be left out of the metadata so that it can still run in live environments
with administrator access, such as staging.
**Note on `requires_admin`**: This tag should still be applied if there are other actions within the test that require administrator access that are unrelated to updating a
feature flag (like creating a user via the API).
The code below would enable a feature flag named `:feature_flag_name` for the project
created by the test:
```ruby
RSpec.describe "with feature flag enabled", feature_flag: {
name: 'feature_flag_name',
scope: :project
} do
let(:project) { Resource::Project.fabricate_via_api! }
around do |example|
Runtime::Feature.enable(:feature_flag_name, project: project)
example.run
Runtime::Feature.disable(:feature_flag_name, project: project)
end
it "feature flag test" do
# Execute the test with the feature flag enabled.
# It will only affect the project created in this test.
end
end
```
Note that the `enable` and `disable` methods first set the flag and then check that the updated
value is returned by the API.
Similarly, you can enable a feature for a group, user, or feature group:
```ruby
group = Resource::Group.fabricate_via_api!
Runtime::Feature.enable(:feature_flag_name, group: group)
user = Resource::User.fabricate_via_api!
Runtime::Feature.enable(:feature_flag_name, user: user)
feature_group = "a_feature_group"
Runtime::Feature.enable(:feature_flag_name, feature_group: feature_group)
```
If no scope is provided, the feature flag is set instance-wide:
```ruby
# This will affect all users!
Runtime::Feature.enable(:feature_flag_name)
```
## Working with selectors
A new feature often replaces a `vue` component or a `haml` file with a new one.
In most cases, the new file or component is accessible only with a feature flag.
This approach becomes problematic when tests must pass both with, and without,
the feature flag enabled. To ensure tests pass in both scenarios:
1. Create another selector inside the new component or file.
1. Give it the same name as the old one.
Selectors are connected to a specific frontend file in the [page object](../beginners_guide/page_objects.md),
and checked for availability inside our `qa:selectors` test. If the mentioned selector
is missing inside that frontend file, the test fails. To ensure selectors are
available when a feature flag is enabled or disabled, add the new selector to the
[page object](../beginners_guide/page_objects.md), leaving the old selector in place.
The test uses the correct selector and still detects missing selectors.
If a new feature changes an existing frontend file that already has a selector,
you can add a new selector with the same name. However, only one of the selectors
displays on the page. You should:
1. Disable the other with the feature flag.
1. Add a comment in the frontend file to delete the old selector from the frontend
file and from the page object file when the feature flag is removed.
### Example before
```ruby
# This is the link to the old file
view 'app/views/devise/passwords/edit.html.haml' do
# The new selector should have the same name
element 'password-field'
...
end
```
### Example after
```ruby
view 'app/views/devise/passwords/edit.html.haml' do
element 'password-field'
...
end
# Now it can verify the selector is available
view 'app/views/devise/passwords/new_edit_behind_ff.html.haml' do
# The selector has the same name
element 'password-field'
end
```
## Working with resource classes
If a resource class must behave differently when a feature flag is active, toggle a
variable with the name of the feature flag inside the class. This variable and condition
ensure all actions are handled appropriately.
You can set this variable inside the `fabricate_via_api` call. For a consistent approach:
- Use an `activated` check, not a deactivated one.
- Add the word `activated` to the end of a variable's name.
- Inside the `initialize` method, set the variable's default value.
For example:
```ruby
def initialize
name_of_the_feature_flag_activated = false
...
end
```
### Cleanup
After the feature flag is removed, clean up the resource class and delete the variable.
All methods should use the condition procedures of the now-default state.
## Managing flakiness due to caching
All application settings, and all feature flags, are cached inside GitLab for one minute.
All caching is disabled during testing, except on static environments.
When a test changes a feature flag, it can cause flaky behavior if elements are visible only with an
active feature flag. To circumvent this behavior, add a wait for elements behind a feature flag.
## Running a scenario with a feature flag enabled
It's also possible to run an entire scenario with a feature flag enabled, without having to edit
existing tests or write new ones.
See the [QA README](https://gitlab.com/gitlab-org/gitlab/-/tree/master/qa#running-tests-with-a-feature-flag-enabled)
for details.
## Confirming that end-to-end tests pass with a feature flag enabled
End-to-end tests should pass with a feature flag enabled before it is enabled on Staging or on GitLab.com. Tests that need to be updated should be identified as part of [quad-planning](https://handbook.gitlab.com/handbook/engineering/infrastructure/test-platform/quad-planning/). The relevant [counterpart Software Engineer in Test](https://handbook.gitlab.com/handbook/engineering/quality/#individual-contributors) is responsible for updating the tests or assisting another engineer to do so. However, if a change does not go through quad-planning and a required test update is not made, test failures could block deployment.
### Automatic test execution when a feature flag definition changes
There are two ways to confirm that end-to-end tests pass:
- If a merge request adds or edits a [feature flag definition file](../../../feature_flags/_index.md#feature-flag-definition-and-validation),
two `e2e:test-on-gdk` jobs (`gdk-instance` and `gdk-instance-ff-inverse`) are included automatically in the merge request pipeline.
One job runs the application with default feature flag state and another sets it to inverse value. The jobs execute the same suite of tests to confirm that they pass with the feature flag either enabled or disabled.
- In some cases, if end-to-end test jobs didn't trigger automatically, or if it has run the tests with the default feature flag values (which might not be desired),
you can create a Draft MR that enables the feature flag to ensure that all E2E tests pass with the feature flag enabled and disabled.
### Troubleshooting end-to-end test failures with feature flag enabled
If enabling the feature flag results in E2E test failures, you can browse the artifacts in the failed pipeline to see screenshots of the failed tests. After which, you can either:
- Identify tests that need to be updated and contact the relevant [counterpart Software Engineer in Test](https://handbook.gitlab.com/handbook/engineering/quality/#individual-contributors) responsible for updating the tests or assisting another engineer to do so. However, if a change does not go through [quad-planning](https://handbook.gitlab.com/handbook/engineering/infrastructure/test-platform/quad-planning/) and a required test update is not made, test failures could block deployment.
- Run the failed tests [locally](https://gitlab.com/gitlab-org/gitlab/-/tree/master/qa#run-the-end-to-end-tests-in-a-local-development-environment)
with the [feature flag enabled](https://gitlab.com/gitlab-org/gitlab/-/tree/master/qa#running-tests-with-a-feature-flag-enabled-or-disabled).
This option requires considerable amount of setup, but you'll be able to see what the browser is doing as it's running the failed
tests, which can help debug the problem faster. You can also refer to the [Troubleshooting Guide for E2E tests](../troubleshooting.md) for
support for common blockers.
### Test execution during feature development
If an end-to-end test enables a feature flag, the end-to-end test suite can be used to test changes in a merge request
by running the `e2e:test-on-omnibus-ee` job in the merge request pipeline. If the feature flag and relevant changes have already been merged, you can confirm that the tests
pass on the default branch. The end-to-end tests run on the default branch every two hours, and the results are posted to a
[Test Session Report, which is available in the testcase-sessions project](https://gitlab.com/gitlab-org/quality/testcase-sessions/-/issues?label_name%5B%5D=found%3Amain).
If the relevant tests do not enable the feature flag themselves, you can check if the tests will need to be updated by opening
a draft merge request that enables the flag by default via a [feature flag definition file](../../../feature_flags/_index.md#feature-flag-definition-and-validation).
That will [automatically execute the end-to-end test suite](#automatic-test-execution-when-a-feature-flag-definition-changes).
The merge request can be closed once the tests pass. If you need assistance to update the tests, contact the relevant [stable counterpart in the Quality department](https://handbook.gitlab.com/handbook/engineering/quality/#individual-contributors), or any Software Engineer in Test if there is no stable counterpart for your group.
|
https://docs.gitlab.com/development/testing_guide/end_to_end/users
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/testing_guide/end_to_end/users.md
|
2025-08-13
|
doc/development/testing_guide/end_to_end/best_practices
|
[
"doc",
"development",
"testing_guide",
"end_to_end",
"best_practices"
] |
users.md
|
none
|
unassigned
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Environment Setup | Users
| null |
## Administrator user
E2E test framework utilizes administrator user for certain resource creation, like `user` or for changing certain instance level settings. It is not necessary to explicitly configure administrator user for environments used in [test-pipelines](../test_pipelines.md) because these environments automatically create administrator user with known default credentials and personal access token. If administrator user requires different credentials, these can be configured through following environment variables:
- `GITLAB_ADMIN_USERNAME`
- `GITLAB_ADMIN_PASSWORD`
- `GITLAB_QA_ADMIN_ACCESS_TOKEN`: this variable is optional and would be created via UI using administrator credentials when not set.
Administrator user can be accessed via global accessor method `QA::Runtime::User::Store.admin_user`.
## Test user
All tests running against one of the [test-pipelines](../test_pipelines.md) automatically create a new test user for each test. Resource instance of this user is then made globally available via `QA::Runtime::User::Store.test_user` accessor method. All user related actions like signing in or creating other objects via API by default will use this user's credentials or personal access token. Automatic user creation is performed by using administrator user personal access token which is pre-seeded automatically on all ephemeral environments used in [test-pipelines](../test_pipelines.md).
### Using single user
It is advised to not run all tests using single user but certain environments impose limitations for generating new user for each test. In order to forcefully disable unique test user creation, environment variable `QA_CREATE_UNIQUE_TEST_USERS` should be set to false. Example reason why unique user creation might be disabled:
- environment does have administrator user available and can create new users but it has only one top level group with ultimate license. In such case, a single user which is a member of this group has to be used due to new unique users not having access to the common group with ultimate license.
In such case, `test user` is initialized using credentials from environments variables - `GITLAB_USERNAME` and `GITLAB_PASSWORD`. Additionally, to provide a pre-configured personal access token for test user, `GITLAB_QA_ACCESS_TOKEN` variable can be set.
### No admin environments
Certain environments might not have administrator user and have no ability to create one. For tests to work when running against such environment, test user must be configured via environment variables mentioned in [Using single user](#using-single-user) section. Additionally, to prevent test framework from trying to initialize administrator user, environment variable `QA_NO_ADMIN_ENV` must be set to `true`.
#### Additional test user
In case the test is running on an environment with no admin environment or an environment that doesn't allow user creation, it is possible to use a second pre-configured user in the test.
Credentials for this user must be configured using `GITLAB_QA_USERNAME_1` and `GITLAB_QA_PASSWORD_1` environment variables.
The instance of the user can be accessed using the method `QA::Runtime::User::Store.additional_test_user`.
This method also ensures that on environments that allow for user fabrication, the test will create a new unique user rather than relying on a pre-configured one.
## Disable email verification
[Account email verification](../../../../security/email_verification.md) locks a user account if suspicious activity is detected. After an account is locked, the user must verify their identity or reset their password to sign in to GitLab.
This feature is disabled by default, you can use the [Application settings API](../../../../api/settings.md) to enable the `require_email_verification_on_account_locked` attribute.
Disabling email verification turns off email verification for all users in the instance.
|
---
stage: none
group: unassigned
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: Environment Setup | Users
breadcrumbs:
- doc
- development
- testing_guide
- end_to_end
- best_practices
---
## Administrator user
E2E test framework utilizes administrator user for certain resource creation, like `user` or for changing certain instance level settings. It is not necessary to explicitly configure administrator user for environments used in [test-pipelines](../test_pipelines.md) because these environments automatically create administrator user with known default credentials and personal access token. If administrator user requires different credentials, these can be configured through following environment variables:
- `GITLAB_ADMIN_USERNAME`
- `GITLAB_ADMIN_PASSWORD`
- `GITLAB_QA_ADMIN_ACCESS_TOKEN`: this variable is optional and would be created via UI using administrator credentials when not set.
Administrator user can be accessed via global accessor method `QA::Runtime::User::Store.admin_user`.
## Test user
All tests running against one of the [test-pipelines](../test_pipelines.md) automatically create a new test user for each test. Resource instance of this user is then made globally available via `QA::Runtime::User::Store.test_user` accessor method. All user related actions like signing in or creating other objects via API by default will use this user's credentials or personal access token. Automatic user creation is performed by using administrator user personal access token which is pre-seeded automatically on all ephemeral environments used in [test-pipelines](../test_pipelines.md).
### Using single user
It is advised to not run all tests using single user but certain environments impose limitations for generating new user for each test. In order to forcefully disable unique test user creation, environment variable `QA_CREATE_UNIQUE_TEST_USERS` should be set to false. Example reason why unique user creation might be disabled:
- environment does have administrator user available and can create new users but it has only one top level group with ultimate license. In such case, a single user which is a member of this group has to be used due to new unique users not having access to the common group with ultimate license.
In such case, `test user` is initialized using credentials from environments variables - `GITLAB_USERNAME` and `GITLAB_PASSWORD`. Additionally, to provide a pre-configured personal access token for test user, `GITLAB_QA_ACCESS_TOKEN` variable can be set.
### No admin environments
Certain environments might not have administrator user and have no ability to create one. For tests to work when running against such environment, test user must be configured via environment variables mentioned in [Using single user](#using-single-user) section. Additionally, to prevent test framework from trying to initialize administrator user, environment variable `QA_NO_ADMIN_ENV` must be set to `true`.
#### Additional test user
In case the test is running on an environment with no admin environment or an environment that doesn't allow user creation, it is possible to use a second pre-configured user in the test.
Credentials for this user must be configured using `GITLAB_QA_USERNAME_1` and `GITLAB_QA_PASSWORD_1` environment variables.
The instance of the user can be accessed using the method `QA::Runtime::User::Store.additional_test_user`.
This method also ensures that on environments that allow for user fabrication, the test will create a new unique user rather than relying on a pre-configured one.
## Disable email verification
[Account email verification](../../../../security/email_verification.md) locks a user account if suspicious activity is detected. After an account is locked, the user must verify their identity or reset their password to sign in to GitLab.
This feature is disabled by default, you can use the [Application settings API](../../../../api/settings.md) to enable the `require_email_verification_on_account_locked` attribute.
Disabling email verification turns off email verification for all users in the instance.
|
https://docs.gitlab.com/development/testing_guide/end_to_end/execution_context_selection
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/testing_guide/end_to_end/execution_context_selection.md
|
2025-08-13
|
doc/development/testing_guide/end_to_end/best_practices
|
[
"doc",
"development",
"testing_guide",
"end_to_end",
"best_practices"
] |
execution_context_selection.md
|
none
|
unassigned
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Execution context selection
| null |
Some tests are designed to be run against specific environments, or in specific [pipelines](https://handbook.gitlab.com/handbook/engineering/testing/end-to-end-pipeline-monitoring) or jobs. We can specify the test execution context using the `only` and `except` metadata.
## Available switches
| Switch | Function | Type |
| ------------ | -------------------------------- | ------------------- |
| `tld` | Set the top-level domain matcher | `String` |
| `subdomain` | Set the subdomain matcher | `Array` or `String` |
| `domain` | Set the domain matcher | `String` |
| `production` | Match the production environment | `Static` |
| `pipeline` | Match a pipeline | `Array` or `Static` |
| `job` | Match a job | `Array` or `Static` |
{{< alert type="warning" >}}
You cannot specify `:production` and `{ <switch>: 'value' }` simultaneously.
These options are mutually exclusive. If you want to specify production, you
can control the `tld` and `domain` independently.
{{< /alert >}}
## Examples
### Only
Run tests in only the specified context.
Matches use:
- Regex for environments.
- String matching for pipelines.
- Regex or string matching for jobs
- Lambda or truthy/falsey value for generic condition
| Test execution context | Key | Matches |
| --------------------------------------------------- | ----------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `gitlab.com` | `only: :production` | `gitlab.com` |
| `staging.gitlab.com` | `only: { subdomain: :staging }` | `(staging).+.com` |
| `gitlab.com and staging.gitlab.com` | `only: { subdomain: /(staging.)?/, domain: 'gitlab' }` | `(staging.)?gitlab.com` |
| `dev.gitlab.org` | `only: { tld: '.org', domain: 'gitlab', subdomain: 'dev' }` | `(dev).gitlab.org` |
| `staging.gitlab.com and domain.gitlab.com` | `only: { subdomain: %i[staging domain] }` | `(staging\|domain).+.com` |
| The `nightly` pipeline | `only: { pipeline: :nightly }` | ["nightly scheduled pipeline"](https://gitlab.com/gitlab-org/gitlab/-/pipeline_schedules) |
| The `nightly` and `canary` pipelines | `only: { pipeline: [:nightly, :canary] }` | ["nightly scheduled pipeline"](https://gitlab.com/gitlab-org/gitlab/-/pipeline_schedules) and ["canary"](https://gitlab.com/gitlab-org/quality/canary) |
| The `ee:instance` job | `only: { job: 'ee:instance' }` | The `ee:instance` job in any pipeline |
| Any `quarantine` job | `only: { job: '.*quarantine' }` | Any job ending in `quarantine` in any pipeline |
| Local development environment | `only: :local` | Any environment where `Runtime::Env.running_in_ci?` is false |
| Any run where condition evaluates to a truthy value | `only: { condition: -> { ENV['TEST_ENV'] == 'true' } }` | Any run where `TEST_ENV` is set to true |
```ruby
RSpec.describe 'Area' do
it 'runs in any environment or pipeline' do; end
it 'runs only in production environment', only: :production do; end
it 'runs only in staging environment', only: { subdomain: :staging } do; end
it 'runs in dev environment', only: { tld: '.org', domain: 'gitlab', subdomain: 'dev' } do; end
it 'runs in prod and staging environments', only: { subdomain: /(staging.)?/, domain: 'gitlab' } {}
it 'runs only in nightly pipeline', only: { pipeline: :nightly } do; end
it 'runs in nightly and canary pipelines', only: { pipeline: [:nightly, :canary] } do; end
it 'runs in specific environment matching condition', only: { condition: -> { ENV['TEST_ENV'] == 'true' } } do; end
end
```
### Except
Run tests in their typical contexts except as specified.
Matches use:
- Regex for environments.
- String matching for pipelines.
- Regex or string matching for jobs
- Lambda or truthy/falsey value for generic condition
| Test execution context | Key | Matches |
| ---------------------------------------------------------- | ------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `gitlab.com` | `except: :production` | `gitlab.com` |
| `staging.gitlab.com` | `except: { subdomain: :staging }` | `(staging).+.com` |
| `gitlab.com and staging.gitlab.com` | `except: { subdomain: /(staging.)?/, domain: 'gitlab' }` | `(staging.)?gitlab.com` |
| `dev.gitlab.org` | `except: { tld: '.org', domain: 'gitlab', subdomain: 'dev' }` | `(dev).gitlab.org` |
| `staging.gitlab.com and domain.gitlab.com` | `except: { subdomain: %i[staging domain] }` | `(staging\|domain).+.com` |
| The `nightly` pipeline | `only: { pipeline: :nightly }` | ["nightly scheduled pipeline"](https://gitlab.com/gitlab-org/gitlab/-/pipeline_schedules) |
| The `nightly` and `canary` pipelines | `only: { pipeline: [:nightly, :canary] }` | ["nightly scheduled pipeline"](https://gitlab.com/gitlab-org/gitlab/-/pipeline_schedules) and ["canary"](https://gitlab.com/gitlab-org/quality/canary) |
| The `ee:instance` job | `except: { job: 'ee:instance' }` | The `ee:instance` job in any pipeline |
| Any `quarantine` job | `except: { job: '.*quarantine' }` | Any job ending in `quarantine` in any pipeline |
| Any run except where condition evaluates to a truthy value | `except: { condition: -> { ENV['TEST_ENV'] == 'true' } }` | Any run where `TEST_ENV` is not set to true |
```ruby
RSpec.describe 'Area' do
it 'runs in any execution context except the production environment', except: :production do; end
it 'runs in any execution context except the staging environment', except: { subdomain: :staging } do; end
it 'runs in any execution context except the nightly pipeline', except: { pipeline: :nightly } do; end
it 'runs in any execution context except the ee:instance job', except: { job: 'ee:instance' } do; end
it 'runs in specific environment not matching condition', except: { condition: -> { ENV['TEST_ENV'] == 'true' } } do; end
end
```
## Usage notes
If the test has a `before` or `after` block, you must add the `only` or `except` metadata to the outer `RSpec.describe` block.
To run a test tagged with `only` on your local GitLab instance, you can do one of the following:
- Make sure you **do not** have the `CI_PROJECT_NAME` or `CI_JOB_NAME` environment variables set.
- Set the appropriate variable to match the metadata. For example, if the metadata is `only: { pipeline: :nightly }` then set `CI_PROJECT_NAME=nightly`. If the metadata is `only: { job: 'ee:instance' }` then set `CI_JOB_NAME=ee:instance`.
- Temporarily remove the metadata.
To run a test tagged with `except` locally, you can either:
- Make sure you **do not** have the `CI_PROJECT_NAME` or `CI_JOB_NAME` environment variables set.
- Temporarily remove the metadata.
## Quarantine a test for a specific environment
Similarly to specifying that a test should only run against a specific environment, it's also possible to quarantine a
test only when it runs against a specific environment. The syntax is exactly the same, except that the `only: { ... }`
hash is nested in the [`quarantine: { ... }`](https://handbook.gitlab.com/handbook/engineering/testing/pipeline-triage/#quarantining-tests) hash.
For example, `quarantine: { only: { subdomain: :staging } }` only quarantines the test when run against `staging`.
The quarantine feature can be explicitly disabled with the `DISABLE_QUARANTINE` environment variable. This can be useful when running tests locally.
|
---
stage: none
group: unassigned
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: Execution context selection
breadcrumbs:
- doc
- development
- testing_guide
- end_to_end
- best_practices
---
Some tests are designed to be run against specific environments, or in specific [pipelines](https://handbook.gitlab.com/handbook/engineering/testing/end-to-end-pipeline-monitoring) or jobs. We can specify the test execution context using the `only` and `except` metadata.
## Available switches
| Switch | Function | Type |
| ------------ | -------------------------------- | ------------------- |
| `tld` | Set the top-level domain matcher | `String` |
| `subdomain` | Set the subdomain matcher | `Array` or `String` |
| `domain` | Set the domain matcher | `String` |
| `production` | Match the production environment | `Static` |
| `pipeline` | Match a pipeline | `Array` or `Static` |
| `job` | Match a job | `Array` or `Static` |
{{< alert type="warning" >}}
You cannot specify `:production` and `{ <switch>: 'value' }` simultaneously.
These options are mutually exclusive. If you want to specify production, you
can control the `tld` and `domain` independently.
{{< /alert >}}
## Examples
### Only
Run tests in only the specified context.
Matches use:
- Regex for environments.
- String matching for pipelines.
- Regex or string matching for jobs
- Lambda or truthy/falsey value for generic condition
| Test execution context | Key | Matches |
| --------------------------------------------------- | ----------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `gitlab.com` | `only: :production` | `gitlab.com` |
| `staging.gitlab.com` | `only: { subdomain: :staging }` | `(staging).+.com` |
| `gitlab.com and staging.gitlab.com` | `only: { subdomain: /(staging.)?/, domain: 'gitlab' }` | `(staging.)?gitlab.com` |
| `dev.gitlab.org` | `only: { tld: '.org', domain: 'gitlab', subdomain: 'dev' }` | `(dev).gitlab.org` |
| `staging.gitlab.com and domain.gitlab.com` | `only: { subdomain: %i[staging domain] }` | `(staging\|domain).+.com` |
| The `nightly` pipeline | `only: { pipeline: :nightly }` | ["nightly scheduled pipeline"](https://gitlab.com/gitlab-org/gitlab/-/pipeline_schedules) |
| The `nightly` and `canary` pipelines | `only: { pipeline: [:nightly, :canary] }` | ["nightly scheduled pipeline"](https://gitlab.com/gitlab-org/gitlab/-/pipeline_schedules) and ["canary"](https://gitlab.com/gitlab-org/quality/canary) |
| The `ee:instance` job | `only: { job: 'ee:instance' }` | The `ee:instance` job in any pipeline |
| Any `quarantine` job | `only: { job: '.*quarantine' }` | Any job ending in `quarantine` in any pipeline |
| Local development environment | `only: :local` | Any environment where `Runtime::Env.running_in_ci?` is false |
| Any run where condition evaluates to a truthy value | `only: { condition: -> { ENV['TEST_ENV'] == 'true' } }` | Any run where `TEST_ENV` is set to true |
```ruby
RSpec.describe 'Area' do
it 'runs in any environment or pipeline' do; end
it 'runs only in production environment', only: :production do; end
it 'runs only in staging environment', only: { subdomain: :staging } do; end
it 'runs in dev environment', only: { tld: '.org', domain: 'gitlab', subdomain: 'dev' } do; end
it 'runs in prod and staging environments', only: { subdomain: /(staging.)?/, domain: 'gitlab' } {}
it 'runs only in nightly pipeline', only: { pipeline: :nightly } do; end
it 'runs in nightly and canary pipelines', only: { pipeline: [:nightly, :canary] } do; end
it 'runs in specific environment matching condition', only: { condition: -> { ENV['TEST_ENV'] == 'true' } } do; end
end
```
### Except
Run tests in their typical contexts except as specified.
Matches use:
- Regex for environments.
- String matching for pipelines.
- Regex or string matching for jobs
- Lambda or truthy/falsey value for generic condition
| Test execution context | Key | Matches |
| ---------------------------------------------------------- | ------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `gitlab.com` | `except: :production` | `gitlab.com` |
| `staging.gitlab.com` | `except: { subdomain: :staging }` | `(staging).+.com` |
| `gitlab.com and staging.gitlab.com` | `except: { subdomain: /(staging.)?/, domain: 'gitlab' }` | `(staging.)?gitlab.com` |
| `dev.gitlab.org` | `except: { tld: '.org', domain: 'gitlab', subdomain: 'dev' }` | `(dev).gitlab.org` |
| `staging.gitlab.com and domain.gitlab.com` | `except: { subdomain: %i[staging domain] }` | `(staging\|domain).+.com` |
| The `nightly` pipeline | `only: { pipeline: :nightly }` | ["nightly scheduled pipeline"](https://gitlab.com/gitlab-org/gitlab/-/pipeline_schedules) |
| The `nightly` and `canary` pipelines | `only: { pipeline: [:nightly, :canary] }` | ["nightly scheduled pipeline"](https://gitlab.com/gitlab-org/gitlab/-/pipeline_schedules) and ["canary"](https://gitlab.com/gitlab-org/quality/canary) |
| The `ee:instance` job | `except: { job: 'ee:instance' }` | The `ee:instance` job in any pipeline |
| Any `quarantine` job | `except: { job: '.*quarantine' }` | Any job ending in `quarantine` in any pipeline |
| Any run except where condition evaluates to a truthy value | `except: { condition: -> { ENV['TEST_ENV'] == 'true' } }` | Any run where `TEST_ENV` is not set to true |
```ruby
RSpec.describe 'Area' do
it 'runs in any execution context except the production environment', except: :production do; end
it 'runs in any execution context except the staging environment', except: { subdomain: :staging } do; end
it 'runs in any execution context except the nightly pipeline', except: { pipeline: :nightly } do; end
it 'runs in any execution context except the ee:instance job', except: { job: 'ee:instance' } do; end
it 'runs in specific environment not matching condition', except: { condition: -> { ENV['TEST_ENV'] == 'true' } } do; end
end
```
## Usage notes
If the test has a `before` or `after` block, you must add the `only` or `except` metadata to the outer `RSpec.describe` block.
To run a test tagged with `only` on your local GitLab instance, you can do one of the following:
- Make sure you **do not** have the `CI_PROJECT_NAME` or `CI_JOB_NAME` environment variables set.
- Set the appropriate variable to match the metadata. For example, if the metadata is `only: { pipeline: :nightly }` then set `CI_PROJECT_NAME=nightly`. If the metadata is `only: { job: 'ee:instance' }` then set `CI_JOB_NAME=ee:instance`.
- Temporarily remove the metadata.
To run a test tagged with `except` locally, you can either:
- Make sure you **do not** have the `CI_PROJECT_NAME` or `CI_JOB_NAME` environment variables set.
- Temporarily remove the metadata.
## Quarantine a test for a specific environment
Similarly to specifying that a test should only run against a specific environment, it's also possible to quarantine a
test only when it runs against a specific environment. The syntax is exactly the same, except that the `only: { ... }`
hash is nested in the [`quarantine: { ... }`](https://handbook.gitlab.com/handbook/engineering/testing/pipeline-triage/#quarantining-tests) hash.
For example, `quarantine: { only: { subdomain: :staging } }` only quarantines the test when run against `staging`.
The quarantine feature can be explicitly disabled with the `DISABLE_QUARANTINE` environment variable. This can be useful when running tests locally.
|
https://docs.gitlab.com/development/testing_guide/end_to_end/best_practices
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/testing_guide/end_to_end/_index.md
|
2025-08-13
|
doc/development/testing_guide/end_to_end/best_practices
|
[
"doc",
"development",
"testing_guide",
"end_to_end",
"best_practices"
] |
_index.md
|
none
|
unassigned
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
End-to-end testing Best Practices
| null |
This is a tailored extension of the Best Practices [found in the testing guide](../../best_practices.md).
## Class and module naming
The QA framework uses [Zeitwerk](https://github.com/fxn/zeitwerk) for class and module autoloading. The default Zeitwerk [inflector](https://github.com/fxn/zeitwerk#zeitwerkinflector) converts snake_cased filenames to PascalCased module or class names. It is advised to stick to this pattern to avoid manual maintenance of inflections.
In case custom inflection logic is needed, custom inflectors are added in the [qa.rb](https://gitlab.com/gitlab-org/gitlab/-/blob/master/qa/qa.rb) file in the `loader.inflector.inflect` method invocation.
## Link a test to its test case
Every test should have a corresponding test case in the [GitLab project test cases](https://gitlab.com/gitlab-org/gitlab/-/quality/test_cases) as well as a results issue in the [Quality Test Cases project](https://gitlab.com/gitlab-org/quality/testcases/-/issues).
If a test case issue does not yet exist, any GitLab team member can create a new test case in
the **[CI/CD > Test cases](https://gitlab.com/gitlab-org/gitlab/-/quality/test_cases)** page of the GitLab project
with a placeholder title. After the test case URL is linked to a test in the code, when the test is
run in a pipeline that has reporting enabled, the `report-results` script automatically updates the
test case and the results issue.
If a results issue does not yet exist, the `report-results` script automatically creates one and
links it to its corresponding test case.
To link a test case to a test in the code, you must manually add a `testcase` RSpec metadata tag.
In most cases, a single test is associated with a single test case.
For example:
```ruby
RSpec.describe 'Stage' do
describe 'General description of the feature under test' do
it 'test name', testcase: 'https://gitlab.com/gitlab-org/gitlab/-/quality/test_cases/:test_case_id' do
...
end
it 'another test', testcase: 'https://gitlab.com/gitlab-org/gitlab/-/quality/test_cases/:another_test_case_id' do
...
end
end
end
```
### For shared tests
Most tests are defined by a single line of a `spec` file, which is why those tests can be linked to a
single test case via the `testcase` tag.
However, some tests don't have a one-to-one relationship between a line of a `spec` file and a test case.
This is because some tests are defined in a way that means a single line is associated with
multiple tests, including:
- Parallelized tests.
- Templated tests.
- Tests in shared examples that include more than one example.
In those and similar cases we need to include the test case link by other means.
To illustrate, there are two tests in the shared examples in [`qa/specs/features/ee/browser_ui/3_create/repository/restrict_push_protected_branch_spec.rb`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/qa/qa/specs/features/ee/browser_ui/3_create/repository/restrict_push_protected_branch_spec.rb):
```ruby
RSpec.shared_examples 'unselected maintainer' do |testcase|
it 'user fails to push', testcase: testcase do
...
end
end
RSpec.shared_examples 'selected developer' do |testcase|
it 'user pushes and merges', testcase: testcase do
...
end
end
```
Consider the following test that includes the shared examples:
```ruby
RSpec.describe 'Create' do
describe 'Restricted protected branch push and merge' do
context 'when only one user is allowed to merge and push to a protected branch' do
...
it_behaves_like 'unselected maintainer', 'https://gitlab.com/gitlab-org/gitlab/-/quality/test_cases/347775'
it_behaves_like 'selected developer', 'https://gitlab.com/gitlab-org/gitlab/-/quality/test_cases/347774'
end
context 'when only one group is allowed to merge and push to a protected branch' do
...
it_behaves_like 'unselected maintainer', 'https://gitlab.com/gitlab-org/gitlab/-/quality/test_cases/347772'
it_behaves_like 'selected developer', 'https://gitlab.com/gitlab-org/gitlab/-/quality/test_cases/347773'
end
end
end
```
We recommend creating four associated test cases, two for each shared example.
## Test naming
Test names should form a readable sentence defining the purpose of the test. Our [testing guide](_index.md) extends the [Thoughtbot testing style guide](https://github.com/thoughtbot/guides/tree/master/testing-rspec). This page clarifies the guidelines, along with input from [https://www.betterspecs.org/](https://www.betterspecs.org/) and [the RSpec naming guide](https://rspec.rubystyle.guide/#naming.)
### Recommended approach
The following block generates a test named `Plan wiki content creation in a project adds a home page`
``` ruby
# `RSpec.describe` is the DevOps Stage being covered
RSpec.describe 'Plan', product_group: :knowledge do
# `describe` is the feature being tested
describe 'wiki content creation' do
# `context` provides the condition being covered
context 'in a project'
# `it` defines the expected result of the test
it 'adds a home page'
...
end
...
end
...
end
end
```
1. Every `describe`, `context`, and `it` blocks should have a short description attached
1. Keep descriptions as concise as possible.
1. Long descriptions or multiple conditionals could be a sign it should be split up (additional `context` blocks).
1. The [Documentation Style Guide](../../../documentation/styleguide/_index.md) gives recommendations on how to write concisely and with [active voice](../../../documentation/styleguide/_index.md#active-voice).
1. The outermost `Rspec.describe` block should be [the DevOps stage name](https://handbook.gitlab.com/handbook/product/categories/#devops-stages)
1. Inside the `Rspec.describe` block is a `describe` block with the name of the feature being tested
1. Optional `context` blocks define what the conditions being tested are
1. `context` blocks descriptions should begin with `when`, `with`, `without`, `for`, `and`, `on`, `in`, `as`, or `if` to match the [RuboCop rule](https://www.rubydoc.info/gems/rubocop-rspec/RuboCop/Cop/RSpec/ContextWording)
1. The `it` block describes the pass/fail criteria for the test
1. In `shared_examples` with a single example a `specify` block can be used instead of a named `it` block
## Prefer API over UI
The end-to-end testing framework has the ability to fabricate its resources on a case-by-case basis.
Resources should be fabricated via the API wherever possible.
We can save both time and money by fabricating resources that our test will need via the API.
[Learn more](../beginners_guide/resources.md) about resources.
## Avoid superfluous expectations
To keep tests lean, it is important that we only test what we need to test.
Ensure that you do not add any `expect()` statements that are unrelated to what needs to be tested.
For example:
```ruby
#=> Good
Flow::Login.sign_in
Page::Main::Menu.perform do |menu|
expect(menu).to be_signed_in
end
#=> Bad
Flow::Login.sign_in(as: user)
Page::Main::Menu.perform do |menu|
expect(menu).to be_signed_in
expect(page).to have_content(user.name) #=> we already validated being signed in. redundant.
expect(menu).to have_element(:nav_bar) #=> likely unnecessary. already validated in lower-level. test doesn't call for validating this.
end
#=> Good
issue = create(:issue, name: 'issue-name')
Project::Issues::Index.perform do |index|
expect(index).to have_issue(issue)
end
#=> Bad
issue = create(:issue, name: 'issue-name')
Project::Issues::Index.perform do |index|
expect(index).to have_issue(issue)
expect(page).to have_content(issue.name) #=> page content check is redundant as the issue was already validated in the line above.
end
```
## Prefer `aggregate_failures` when there are back-to-back expectations
See [Prefer aggregate failures when there are multiple expectations](#prefer-aggregate_failures-when-there-are-multiple-expectations)
## Prefer `aggregate_failures` when there are multiple expectations
In cases where there must be multiple expectations within a test case, it is preferable to use `aggregate_failures`.
This allows you to group a set of expectations and see all the failures altogether, rather than having the test being aborted on the first failure.
For example:
```ruby
#=> Good
Page::Search::Results.perform do |search|
search.switch_to_code
aggregate_failures 'testing search results' do
expect(search).to have_file_in_project(template[:file_name], project.name)
expect(search).to have_file_with_content(template[:file_name], content[0..33])
end
end
#=> Bad
Page::Search::Results.perform do |search|
search.switch_to_code
expect(search).to have_file_in_project(template[:file_name], project.name)
expect(search).to have_file_with_content(template[:file_name], content[0..33])
end
```
Attach the `:aggregate_failures` metadata to the example if multiple expectations are separated by statements.
```ruby
#=> Good
it 'searches', :aggregate_failures do
Page::Search::Results.perform do |search|
expect(search).to have_file_in_project(template[:file_name], project.name)
search.switch_to_code
expect(search).to have_file_with_content(template[:file_name], content[0..33])
end
end
#=> Bad
it 'searches' do
Page::Search::Results.perform do |search|
expect(search).to have_file_in_project(template[:file_name], project.name)
search.switch_to_code
expect(search).to have_file_with_content(template[:file_name], content[0..33])
end
end
```
## Avoid multiple actions in `expect do ... raise_error` blocks
When you wrap multiple actions in a single `expect do ... end.not_to raise_error` or `expect do ... end.to raise_error` block,
it can be hard to debug the actual cause of the failure, because of how the logs are printed. Important information can be truncated
or missing altogether.
For example, if you encapsulate some actions and expectations in a private method in the test, like `expect_owner_permissions_allow_delete_issue`:
```ruby
it "has Owner role with Owner permissions" do
Page::Dashboard::Projects.perform do |projects|
projects.filter_by_name(project.name)
expect(projects).to have_project_with_access_role(project.name, 'Owner')
end
expect_owner_permissions_allow_delete_issue
end
```
Then, in the method itself:
```ruby
#=> Good
def expect_owner_permissions_allow_delete_issue
issue.visit!
Page::Project::Issue::Show.perform(&:delete_issue)
Page::Project::Issue::Index.perform do |index|
expect(index).not_to have_issue(issue)
end
end
#=> Bad
def expect_owner_permissions_allow_delete_issue
expect do
issue.visit!
Page::Project::Issue::Show.perform(&:delete_issue)
Page::Project::Issue::Index.perform do |index|
expect(index).not_to have_issue(issue)
end
end.not_to raise_error
end
```
## Prefer to split tests across multiple files
Our framework includes a couple of parallelization mechanisms that work by executing spec files in parallel.
However, because tests are parallelized by spec file and not by test/example, we can't achieve greater parallelization if a new test is added to an existing file.
Nonetheless, there could be other reasons to add a new test to an existing file.
For example, if tests share state that is expensive to set up it might be more efficient to perform that setup once even if it means the tests that use the setup can't be parallelized.
In summary:
- **Do**: Split tests across separate files, unless the tests share expensive setup.
- **Don't**: Put new tests in an existing file without considering the impact on parallelization.
## `let` variables vs instance variables
By default, follow the [testing best practices](../../best_practices.md#subject-and-let-variables) when using `let`
or instance variables. However, in end-to-end tests, set-ups such as creating resources are expensive.
If you use `let` to store a resource, it will be created for each example separately.
If the resource can be shared among multiple examples, use an instance variable in the `before(:all)`
block instead of `let` to save run time.
When the variable cannot be shared by multiple examples, use `let`.
## Limit the use of the UI in `before(:context)` and `after` hooks
Limit the use of `before(:context)` hooks to perform setup tasks with only API calls,
non-UI operations, or basic UI operations such as login.
We use [`capybara-screenshot`](https://github.com/mattheworiordan/capybara-screenshot) library to automatically save a screenshot on
failure.
`capybara-screenshot` [saves the screenshot in the RSpec's `after` hook](https://github.com/mattheworiordan/capybara-screenshot/blob/master/lib/capybara-screenshot/rspec.rb#L97).
[If there is a failure in `before(:context)`, the `after` hook is not called](https://github.com/rspec/rspec-core/pull/2652/files#diff-5e04af96d5156e787f28d519a8c99615R148) and so the screenshot is not saved.
Given this fact, we should limit the use of `before(:context)` to only those operations where a screenshot is not needed.
Similarly, the `after` hook should only be used for non-UI operations. Any UI operations in `after` hook in a test file
would execute before the `after` hook that takes the screenshot. This would result in moving the UI status away from the
point of failure and so the screenshot would not be captured at the right moment.
## Ensure tests do not leave the browser logged in
All tests expect to be able to sign in at the start of the test.
For an example see [issue #34736](https://gitlab.com/gitlab-org/gitlab/-/issues/34736).
Ideally, actions performed in an `after(:context)` (or
[`before(:context)`](#limit-the-use-of-the-ui-in-beforecontext-and-after-hooks))
block are performed using the API. If it's necessary to do so with the user
interface (for example, if API functionality doesn't exist), be sure to sign
out at the end of the block.
```ruby
after(:all) do
login unless Page::Main::Menu.perform(&:signed_in?)
# Do something while logged in
Page::Main::Menu.perform(&:sign_out)
end
```
## Tag tests that require administrator access
We don't run tests that require administrator access against our Production environments.
When you add a new test that requires administrator access, apply the RSpec metadata `:requires_admin` so that the test will not be included in the test suites executed against Production and other environments on which we don't want to run those tests.
When running tests locally or configuring a pipeline, the environment variable `QA_CAN_TEST_ADMIN_FEATURES` can be set to `false` to skip tests that have the `:requires_admin` tag.
{{< alert type="note" >}}
If the only action in the test that requires administrator access is to toggle a feature flag, use the `feature_flag` tag instead. More details can be found in [testing with feature flags](feature_flags.md).
{{< /alert >}}
## Prefer `Commit` resource over `ProjectPush`
In line with [using the API](#prefer-api-over-ui), use a `Commit` resource whenever possible.
`ProjectPush` uses raw shell commands from the Git command-line interface (CLI), and the `Commit` resource makes an HTTP request.
```ruby
# Using a commit resource
Resource::Repository::Commit.fabricate_via_api! do |commit|
commit.commit_message = 'Initial commit'
commit.add_files([
{ file_path: 'README.md', content: 'Hello, GitLab' }
])
end
# Using a ProjectPush
Resource::Repository::ProjectPush.fabricate! do |push|
push.commit_message = 'Initial commit'
push.file_name = 'README.md'
push.file_content = 'Hello, GitLab'
end
```
A few exceptions for using a `ProjectPush` would be when your test calls for testing SSH integration or
using the Git CLI.
## Preferred method to blur elements
To blur an element, the preferred method is to select another element that does not alter the test state.
If there's a mask that blocks the page elements, such as may occur with some dropdowns,
use WebDriver's native mouse events to simulate a click event on the coordinates of an element. Use the following method: `click_element_coordinates`.
Avoid clicking the `body` for blurring elements such as inputs and dropdowns because it clicks the center of the viewport.
This action can also unintentionally click other elements, altering the test state and causing it to fail.
```ruby
# Clicking another element to blur an input
def add_issue_to_epic(issue_url)
find_element(:issue_actions_split_button).find('button', text: 'Add an issue').click
fill_element(:add_issue_input, issue_url)
# Clicking the title blurs the input
click_element(:title)
click_element(:add_issue_button)
end
# Using native mouse click events in the case of a mask/overlay
click_element_coordinates(:title)
```
## Ensure `expect` statements wait efficiently
In general, we use an `expect` statement to check that something is as we expect it. For example:
```ruby
Page::Project::Pipeline::Show.perform do |pipeline|
expect(pipeline).to have_job('a_job')
end
```
### Use `eventually_` matchers for expectations that require waiting
When something requires waiting to be matched, use `eventually_` matchers with clear wait duration definition.
`Eventually` matchers use the following naming pattern: `eventually_${rspec_matcher_name}`. They are defined in [eventually_matcher.rb](https://gitlab.com/gitlab-org/gitlab/-/blob/master/qa/qa/support/matchers/eventually_matcher.rb).
```ruby
expect { async_value }.to eventually_eq(value).within(max_duration: 120, max_attempts: 60, reload_page: page)
```
### Create negatable matchers to speed `expect` checks
However, sometimes we want to check that something is not as we don't want it to be. In other
words, we want to make sure something is absent. For unit tests and feature specs,
we commonly use `not_to`
because RSpec's built-in matchers are negatable, as are Capybara's, which means the following two statements are
equivalent.
```ruby
except(page).not_to have_text('hidden')
except(page).to have_no_text('hidden')
```
Unfortunately, that's not automatically the case for the predicate methods that we add to our
[page objects](../beginners_guide/page_objects.md). We need to [create our own negatable matchers](https://rspec.info/features/3-12/rspec-expectations/custom-matchers/define-matcher/).
The initial example uses the `have_job` matcher which is derived from the
[`has_job?` predicate method of the `Page::Project::Pipeline::Show` page object](https://gitlab.com/gitlab-org/gitlab/-/blob/87864b3047c23b4308f59c27a3757045944af447/qa/qa/page/project/pipeline/show.rb#L53).
To create a negatable matcher, we use `has_no_job?` for the negative case:
```ruby
RSpec::Matchers.define :have_job do |job_name|
match do |page_object|
page_object.has_job?(job_name)
end
match_when_negated do |page_object|
page_object.has_no_job?(job_name)
end
end
```
And then the two `expect` statements in the following example are equivalent:
```ruby
Page::Project::Pipeline::Show.perform do |pipeline|
expect(pipeline).not_to have_job('a_job')
expect(pipeline).to have_no_job('a_job')
end
```
[See this merge request for a real example of adding a custom matcher](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/46302).
We are creating custom negatable matchers in `qa/spec/support/matchers`.
{{< alert type="note" >}}
We need to create custom negatable matchers only for the predicate methods we've added to the test framework, and only if we're using `not_to`. If we use `to have_no_*` a negatable matcher is not necessary but it increases code readability.
{{< /alert >}}
### Why we need negatable matchers
Consider the following code, but assume that we don't have a custom negatable matcher for `have_job`.
```ruby
# Bad
Page::Project::Pipeline::Show.perform do |pipeline|
expect(pipeline).not_to have_job('a_job')
end
```
For this statement to pass, `have_job('a_job')` has to return `false` so that `not_to` can negate it.
The problem is that `have_job('a_job')` waits up to ten seconds for `'a job'` to appear before
returning `false`. Under the expected condition this test will take ten seconds longer than it needs to.
Instead, we could force no wait:
```ruby
# Not as bad but potentially flaky
Page::Project::Pipeline::Show.perform do |pipeline|
expect(pipeline).not_to have_job('a_job', wait: 0)
end
```
The problem is that if `'a_job'` is present and we're waiting for it to disappear, this statement will fail.
Neither problem is present if we create a custom negatable matcher because the `has_no_job?` predicate method
would be used, which would wait only as long as necessary for the job to disappear.
Lastly, negatable matchers are preferred over using matchers of the form `have_no_*` because it's a common and familiar practice to negate matchers using `not_to`. If we facilitate that practice by adding negatable matchers, we make it easier for subsequent test authors to write efficient tests.
## Use logger over puts
We currently use Rails `logger` to handle logs in both GitLab QA application and end-to-end tests.
This provides additional functionalities when compared with `puts`, such as:
- Ability to specify the logging level.
- Ability to tag similar logs.
- Auto-formatting log messages.
|
---
stage: none
group: unassigned
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: End-to-end testing Best Practices
breadcrumbs:
- doc
- development
- testing_guide
- end_to_end
- best_practices
---
This is a tailored extension of the Best Practices [found in the testing guide](../../best_practices.md).
## Class and module naming
The QA framework uses [Zeitwerk](https://github.com/fxn/zeitwerk) for class and module autoloading. The default Zeitwerk [inflector](https://github.com/fxn/zeitwerk#zeitwerkinflector) converts snake_cased filenames to PascalCased module or class names. It is advised to stick to this pattern to avoid manual maintenance of inflections.
In case custom inflection logic is needed, custom inflectors are added in the [qa.rb](https://gitlab.com/gitlab-org/gitlab/-/blob/master/qa/qa.rb) file in the `loader.inflector.inflect` method invocation.
## Link a test to its test case
Every test should have a corresponding test case in the [GitLab project test cases](https://gitlab.com/gitlab-org/gitlab/-/quality/test_cases) as well as a results issue in the [Quality Test Cases project](https://gitlab.com/gitlab-org/quality/testcases/-/issues).
If a test case issue does not yet exist, any GitLab team member can create a new test case in
the **[CI/CD > Test cases](https://gitlab.com/gitlab-org/gitlab/-/quality/test_cases)** page of the GitLab project
with a placeholder title. After the test case URL is linked to a test in the code, when the test is
run in a pipeline that has reporting enabled, the `report-results` script automatically updates the
test case and the results issue.
If a results issue does not yet exist, the `report-results` script automatically creates one and
links it to its corresponding test case.
To link a test case to a test in the code, you must manually add a `testcase` RSpec metadata tag.
In most cases, a single test is associated with a single test case.
For example:
```ruby
RSpec.describe 'Stage' do
describe 'General description of the feature under test' do
it 'test name', testcase: 'https://gitlab.com/gitlab-org/gitlab/-/quality/test_cases/:test_case_id' do
...
end
it 'another test', testcase: 'https://gitlab.com/gitlab-org/gitlab/-/quality/test_cases/:another_test_case_id' do
...
end
end
end
```
### For shared tests
Most tests are defined by a single line of a `spec` file, which is why those tests can be linked to a
single test case via the `testcase` tag.
However, some tests don't have a one-to-one relationship between a line of a `spec` file and a test case.
This is because some tests are defined in a way that means a single line is associated with
multiple tests, including:
- Parallelized tests.
- Templated tests.
- Tests in shared examples that include more than one example.
In those and similar cases we need to include the test case link by other means.
To illustrate, there are two tests in the shared examples in [`qa/specs/features/ee/browser_ui/3_create/repository/restrict_push_protected_branch_spec.rb`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/qa/qa/specs/features/ee/browser_ui/3_create/repository/restrict_push_protected_branch_spec.rb):
```ruby
RSpec.shared_examples 'unselected maintainer' do |testcase|
it 'user fails to push', testcase: testcase do
...
end
end
RSpec.shared_examples 'selected developer' do |testcase|
it 'user pushes and merges', testcase: testcase do
...
end
end
```
Consider the following test that includes the shared examples:
```ruby
RSpec.describe 'Create' do
describe 'Restricted protected branch push and merge' do
context 'when only one user is allowed to merge and push to a protected branch' do
...
it_behaves_like 'unselected maintainer', 'https://gitlab.com/gitlab-org/gitlab/-/quality/test_cases/347775'
it_behaves_like 'selected developer', 'https://gitlab.com/gitlab-org/gitlab/-/quality/test_cases/347774'
end
context 'when only one group is allowed to merge and push to a protected branch' do
...
it_behaves_like 'unselected maintainer', 'https://gitlab.com/gitlab-org/gitlab/-/quality/test_cases/347772'
it_behaves_like 'selected developer', 'https://gitlab.com/gitlab-org/gitlab/-/quality/test_cases/347773'
end
end
end
```
We recommend creating four associated test cases, two for each shared example.
## Test naming
Test names should form a readable sentence defining the purpose of the test. Our [testing guide](_index.md) extends the [Thoughtbot testing style guide](https://github.com/thoughtbot/guides/tree/master/testing-rspec). This page clarifies the guidelines, along with input from [https://www.betterspecs.org/](https://www.betterspecs.org/) and [the RSpec naming guide](https://rspec.rubystyle.guide/#naming.)
### Recommended approach
The following block generates a test named `Plan wiki content creation in a project adds a home page`
``` ruby
# `RSpec.describe` is the DevOps Stage being covered
RSpec.describe 'Plan', product_group: :knowledge do
# `describe` is the feature being tested
describe 'wiki content creation' do
# `context` provides the condition being covered
context 'in a project'
# `it` defines the expected result of the test
it 'adds a home page'
...
end
...
end
...
end
end
```
1. Every `describe`, `context`, and `it` blocks should have a short description attached
1. Keep descriptions as concise as possible.
1. Long descriptions or multiple conditionals could be a sign it should be split up (additional `context` blocks).
1. The [Documentation Style Guide](../../../documentation/styleguide/_index.md) gives recommendations on how to write concisely and with [active voice](../../../documentation/styleguide/_index.md#active-voice).
1. The outermost `Rspec.describe` block should be [the DevOps stage name](https://handbook.gitlab.com/handbook/product/categories/#devops-stages)
1. Inside the `Rspec.describe` block is a `describe` block with the name of the feature being tested
1. Optional `context` blocks define what the conditions being tested are
1. `context` blocks descriptions should begin with `when`, `with`, `without`, `for`, `and`, `on`, `in`, `as`, or `if` to match the [RuboCop rule](https://www.rubydoc.info/gems/rubocop-rspec/RuboCop/Cop/RSpec/ContextWording)
1. The `it` block describes the pass/fail criteria for the test
1. In `shared_examples` with a single example a `specify` block can be used instead of a named `it` block
## Prefer API over UI
The end-to-end testing framework has the ability to fabricate its resources on a case-by-case basis.
Resources should be fabricated via the API wherever possible.
We can save both time and money by fabricating resources that our test will need via the API.
[Learn more](../beginners_guide/resources.md) about resources.
## Avoid superfluous expectations
To keep tests lean, it is important that we only test what we need to test.
Ensure that you do not add any `expect()` statements that are unrelated to what needs to be tested.
For example:
```ruby
#=> Good
Flow::Login.sign_in
Page::Main::Menu.perform do |menu|
expect(menu).to be_signed_in
end
#=> Bad
Flow::Login.sign_in(as: user)
Page::Main::Menu.perform do |menu|
expect(menu).to be_signed_in
expect(page).to have_content(user.name) #=> we already validated being signed in. redundant.
expect(menu).to have_element(:nav_bar) #=> likely unnecessary. already validated in lower-level. test doesn't call for validating this.
end
#=> Good
issue = create(:issue, name: 'issue-name')
Project::Issues::Index.perform do |index|
expect(index).to have_issue(issue)
end
#=> Bad
issue = create(:issue, name: 'issue-name')
Project::Issues::Index.perform do |index|
expect(index).to have_issue(issue)
expect(page).to have_content(issue.name) #=> page content check is redundant as the issue was already validated in the line above.
end
```
## Prefer `aggregate_failures` when there are back-to-back expectations
See [Prefer aggregate failures when there are multiple expectations](#prefer-aggregate_failures-when-there-are-multiple-expectations)
## Prefer `aggregate_failures` when there are multiple expectations
In cases where there must be multiple expectations within a test case, it is preferable to use `aggregate_failures`.
This allows you to group a set of expectations and see all the failures altogether, rather than having the test being aborted on the first failure.
For example:
```ruby
#=> Good
Page::Search::Results.perform do |search|
search.switch_to_code
aggregate_failures 'testing search results' do
expect(search).to have_file_in_project(template[:file_name], project.name)
expect(search).to have_file_with_content(template[:file_name], content[0..33])
end
end
#=> Bad
Page::Search::Results.perform do |search|
search.switch_to_code
expect(search).to have_file_in_project(template[:file_name], project.name)
expect(search).to have_file_with_content(template[:file_name], content[0..33])
end
```
Attach the `:aggregate_failures` metadata to the example if multiple expectations are separated by statements.
```ruby
#=> Good
it 'searches', :aggregate_failures do
Page::Search::Results.perform do |search|
expect(search).to have_file_in_project(template[:file_name], project.name)
search.switch_to_code
expect(search).to have_file_with_content(template[:file_name], content[0..33])
end
end
#=> Bad
it 'searches' do
Page::Search::Results.perform do |search|
expect(search).to have_file_in_project(template[:file_name], project.name)
search.switch_to_code
expect(search).to have_file_with_content(template[:file_name], content[0..33])
end
end
```
## Avoid multiple actions in `expect do ... raise_error` blocks
When you wrap multiple actions in a single `expect do ... end.not_to raise_error` or `expect do ... end.to raise_error` block,
it can be hard to debug the actual cause of the failure, because of how the logs are printed. Important information can be truncated
or missing altogether.
For example, if you encapsulate some actions and expectations in a private method in the test, like `expect_owner_permissions_allow_delete_issue`:
```ruby
it "has Owner role with Owner permissions" do
Page::Dashboard::Projects.perform do |projects|
projects.filter_by_name(project.name)
expect(projects).to have_project_with_access_role(project.name, 'Owner')
end
expect_owner_permissions_allow_delete_issue
end
```
Then, in the method itself:
```ruby
#=> Good
def expect_owner_permissions_allow_delete_issue
issue.visit!
Page::Project::Issue::Show.perform(&:delete_issue)
Page::Project::Issue::Index.perform do |index|
expect(index).not_to have_issue(issue)
end
end
#=> Bad
def expect_owner_permissions_allow_delete_issue
expect do
issue.visit!
Page::Project::Issue::Show.perform(&:delete_issue)
Page::Project::Issue::Index.perform do |index|
expect(index).not_to have_issue(issue)
end
end.not_to raise_error
end
```
## Prefer to split tests across multiple files
Our framework includes a couple of parallelization mechanisms that work by executing spec files in parallel.
However, because tests are parallelized by spec file and not by test/example, we can't achieve greater parallelization if a new test is added to an existing file.
Nonetheless, there could be other reasons to add a new test to an existing file.
For example, if tests share state that is expensive to set up it might be more efficient to perform that setup once even if it means the tests that use the setup can't be parallelized.
In summary:
- **Do**: Split tests across separate files, unless the tests share expensive setup.
- **Don't**: Put new tests in an existing file without considering the impact on parallelization.
## `let` variables vs instance variables
By default, follow the [testing best practices](../../best_practices.md#subject-and-let-variables) when using `let`
or instance variables. However, in end-to-end tests, set-ups such as creating resources are expensive.
If you use `let` to store a resource, it will be created for each example separately.
If the resource can be shared among multiple examples, use an instance variable in the `before(:all)`
block instead of `let` to save run time.
When the variable cannot be shared by multiple examples, use `let`.
## Limit the use of the UI in `before(:context)` and `after` hooks
Limit the use of `before(:context)` hooks to perform setup tasks with only API calls,
non-UI operations, or basic UI operations such as login.
We use [`capybara-screenshot`](https://github.com/mattheworiordan/capybara-screenshot) library to automatically save a screenshot on
failure.
`capybara-screenshot` [saves the screenshot in the RSpec's `after` hook](https://github.com/mattheworiordan/capybara-screenshot/blob/master/lib/capybara-screenshot/rspec.rb#L97).
[If there is a failure in `before(:context)`, the `after` hook is not called](https://github.com/rspec/rspec-core/pull/2652/files#diff-5e04af96d5156e787f28d519a8c99615R148) and so the screenshot is not saved.
Given this fact, we should limit the use of `before(:context)` to only those operations where a screenshot is not needed.
Similarly, the `after` hook should only be used for non-UI operations. Any UI operations in `after` hook in a test file
would execute before the `after` hook that takes the screenshot. This would result in moving the UI status away from the
point of failure and so the screenshot would not be captured at the right moment.
## Ensure tests do not leave the browser logged in
All tests expect to be able to sign in at the start of the test.
For an example see [issue #34736](https://gitlab.com/gitlab-org/gitlab/-/issues/34736).
Ideally, actions performed in an `after(:context)` (or
[`before(:context)`](#limit-the-use-of-the-ui-in-beforecontext-and-after-hooks))
block are performed using the API. If it's necessary to do so with the user
interface (for example, if API functionality doesn't exist), be sure to sign
out at the end of the block.
```ruby
after(:all) do
login unless Page::Main::Menu.perform(&:signed_in?)
# Do something while logged in
Page::Main::Menu.perform(&:sign_out)
end
```
## Tag tests that require administrator access
We don't run tests that require administrator access against our Production environments.
When you add a new test that requires administrator access, apply the RSpec metadata `:requires_admin` so that the test will not be included in the test suites executed against Production and other environments on which we don't want to run those tests.
When running tests locally or configuring a pipeline, the environment variable `QA_CAN_TEST_ADMIN_FEATURES` can be set to `false` to skip tests that have the `:requires_admin` tag.
{{< alert type="note" >}}
If the only action in the test that requires administrator access is to toggle a feature flag, use the `feature_flag` tag instead. More details can be found in [testing with feature flags](feature_flags.md).
{{< /alert >}}
## Prefer `Commit` resource over `ProjectPush`
In line with [using the API](#prefer-api-over-ui), use a `Commit` resource whenever possible.
`ProjectPush` uses raw shell commands from the Git command-line interface (CLI), and the `Commit` resource makes an HTTP request.
```ruby
# Using a commit resource
Resource::Repository::Commit.fabricate_via_api! do |commit|
commit.commit_message = 'Initial commit'
commit.add_files([
{ file_path: 'README.md', content: 'Hello, GitLab' }
])
end
# Using a ProjectPush
Resource::Repository::ProjectPush.fabricate! do |push|
push.commit_message = 'Initial commit'
push.file_name = 'README.md'
push.file_content = 'Hello, GitLab'
end
```
A few exceptions for using a `ProjectPush` would be when your test calls for testing SSH integration or
using the Git CLI.
## Preferred method to blur elements
To blur an element, the preferred method is to select another element that does not alter the test state.
If there's a mask that blocks the page elements, such as may occur with some dropdowns,
use WebDriver's native mouse events to simulate a click event on the coordinates of an element. Use the following method: `click_element_coordinates`.
Avoid clicking the `body` for blurring elements such as inputs and dropdowns because it clicks the center of the viewport.
This action can also unintentionally click other elements, altering the test state and causing it to fail.
```ruby
# Clicking another element to blur an input
def add_issue_to_epic(issue_url)
find_element(:issue_actions_split_button).find('button', text: 'Add an issue').click
fill_element(:add_issue_input, issue_url)
# Clicking the title blurs the input
click_element(:title)
click_element(:add_issue_button)
end
# Using native mouse click events in the case of a mask/overlay
click_element_coordinates(:title)
```
## Ensure `expect` statements wait efficiently
In general, we use an `expect` statement to check that something is as we expect it. For example:
```ruby
Page::Project::Pipeline::Show.perform do |pipeline|
expect(pipeline).to have_job('a_job')
end
```
### Use `eventually_` matchers for expectations that require waiting
When something requires waiting to be matched, use `eventually_` matchers with clear wait duration definition.
`Eventually` matchers use the following naming pattern: `eventually_${rspec_matcher_name}`. They are defined in [eventually_matcher.rb](https://gitlab.com/gitlab-org/gitlab/-/blob/master/qa/qa/support/matchers/eventually_matcher.rb).
```ruby
expect { async_value }.to eventually_eq(value).within(max_duration: 120, max_attempts: 60, reload_page: page)
```
### Create negatable matchers to speed `expect` checks
However, sometimes we want to check that something is not as we don't want it to be. In other
words, we want to make sure something is absent. For unit tests and feature specs,
we commonly use `not_to`
because RSpec's built-in matchers are negatable, as are Capybara's, which means the following two statements are
equivalent.
```ruby
except(page).not_to have_text('hidden')
except(page).to have_no_text('hidden')
```
Unfortunately, that's not automatically the case for the predicate methods that we add to our
[page objects](../beginners_guide/page_objects.md). We need to [create our own negatable matchers](https://rspec.info/features/3-12/rspec-expectations/custom-matchers/define-matcher/).
The initial example uses the `have_job` matcher which is derived from the
[`has_job?` predicate method of the `Page::Project::Pipeline::Show` page object](https://gitlab.com/gitlab-org/gitlab/-/blob/87864b3047c23b4308f59c27a3757045944af447/qa/qa/page/project/pipeline/show.rb#L53).
To create a negatable matcher, we use `has_no_job?` for the negative case:
```ruby
RSpec::Matchers.define :have_job do |job_name|
match do |page_object|
page_object.has_job?(job_name)
end
match_when_negated do |page_object|
page_object.has_no_job?(job_name)
end
end
```
And then the two `expect` statements in the following example are equivalent:
```ruby
Page::Project::Pipeline::Show.perform do |pipeline|
expect(pipeline).not_to have_job('a_job')
expect(pipeline).to have_no_job('a_job')
end
```
[See this merge request for a real example of adding a custom matcher](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/46302).
We are creating custom negatable matchers in `qa/spec/support/matchers`.
{{< alert type="note" >}}
We need to create custom negatable matchers only for the predicate methods we've added to the test framework, and only if we're using `not_to`. If we use `to have_no_*` a negatable matcher is not necessary but it increases code readability.
{{< /alert >}}
### Why we need negatable matchers
Consider the following code, but assume that we don't have a custom negatable matcher for `have_job`.
```ruby
# Bad
Page::Project::Pipeline::Show.perform do |pipeline|
expect(pipeline).not_to have_job('a_job')
end
```
For this statement to pass, `have_job('a_job')` has to return `false` so that `not_to` can negate it.
The problem is that `have_job('a_job')` waits up to ten seconds for `'a job'` to appear before
returning `false`. Under the expected condition this test will take ten seconds longer than it needs to.
Instead, we could force no wait:
```ruby
# Not as bad but potentially flaky
Page::Project::Pipeline::Show.perform do |pipeline|
expect(pipeline).not_to have_job('a_job', wait: 0)
end
```
The problem is that if `'a_job'` is present and we're waiting for it to disappear, this statement will fail.
Neither problem is present if we create a custom negatable matcher because the `has_no_job?` predicate method
would be used, which would wait only as long as necessary for the job to disappear.
Lastly, negatable matchers are preferred over using matchers of the form `have_no_*` because it's a common and familiar practice to negate matchers using `not_to`. If we facilitate that practice by adding negatable matchers, we make it easier for subsequent test authors to write efficient tests.
## Use logger over puts
We currently use Rails `logger` to handle logs in both GitLab QA application and end-to-end tests.
This provides additional functionalities when compared with `puts`, such as:
- Ability to specify the logging level.
- Ability to tag similar logs.
- Auto-formatting log messages.
|
https://docs.gitlab.com/development/testing_guide/end_to_end/dynamic_element_validation
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/testing_guide/end_to_end/dynamic_element_validation.md
|
2025-08-13
|
doc/development/testing_guide/end_to_end/best_practices
|
[
"doc",
"development",
"testing_guide",
"end_to_end",
"best_practices"
] |
dynamic_element_validation.md
|
none
|
unassigned
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Dynamic Element Validation
| null |
We devised a solution to solve common test automation problems such as the dreaded `NoSuchElementException`.
Other problems that dynamic element validations solve are...
- When we perform an action with the mouse, we expect something to occur.
- When our test is navigating to (or from) a page, we ensure that we are on the page we expect before
test continuation.
## How dynamic element validation works
We interpret user actions on the page to have some sort of effect. These actions are
- [Navigation](#navigation)
- [Clicks](#clicks)
### Navigation
When a page is navigated to, there are elements that always appear on the page unconditionally.
Dynamic element validation is instituted when using
```ruby
Runtime::Browser.visit(:gitlab, Some::Page)
```
### Clicks
When we perform a click within our tests, we expect something to occur. That something could be a component to now
appear on the webpage, or the test to navigate away from the page entirely.
Dynamic element validation is instituted when using
```ruby
click_element('my-element', Some::Page)
```
### Required Elements
#### Definition
First it is important to define what a "required element" is.
A required element is a visible HTML element that appears on a UI component without any user input.
"Visible" can be defined as
- Not having any CSS preventing its display, for example, `display: none` or `width: 0px; height: 0px;`
- Being able to be interacted with by the user
"UI component" can be defined as
- Anything the user sees
- A button, a text field
- A layer that sits atop the page
#### Application
Requiring elements is very easy. By adding `required: true` as a parameter to an `element`, you've now made it
a requirement that the element appear on the page upon navigation.
## Examples
Given ...
```ruby
class MyPage < Page::Base
view 'app/views/view.html.haml' do
element 'my-element', required: true
element 'another-element', required: true
element 'conditional-element'
end
def open_layer
click_element('my-element', Layer::MyLayer)
end
end
class Layer < Page::Component
view 'app/views/mylayer/layer.html.haml' do
element 'message-content', required: true
end
end
```
### Navigating
Given the [source](#examples) ...
```ruby
Runtime::Browser.visit(:gitlab, Page::MyPage)
execute_stuff
```
invokes GitLab QA to scan `MyPage` for `my-element` and `another-element` to be on the page before continuing to
`execute_stuff`
### Clicking
Given the [source](#examples) ...
```ruby
def open_layer
click_element('my-element', Layer::MyLayer)
end
```
invokes GitLab QA to ensure that `message-content` appears on
the Layer upon clicking `my-element`.
This implies that the Layer is indeed rendered before we continue our test.
|
---
stage: none
group: unassigned
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: Dynamic Element Validation
breadcrumbs:
- doc
- development
- testing_guide
- end_to_end
- best_practices
---
We devised a solution to solve common test automation problems such as the dreaded `NoSuchElementException`.
Other problems that dynamic element validations solve are...
- When we perform an action with the mouse, we expect something to occur.
- When our test is navigating to (or from) a page, we ensure that we are on the page we expect before
test continuation.
## How dynamic element validation works
We interpret user actions on the page to have some sort of effect. These actions are
- [Navigation](#navigation)
- [Clicks](#clicks)
### Navigation
When a page is navigated to, there are elements that always appear on the page unconditionally.
Dynamic element validation is instituted when using
```ruby
Runtime::Browser.visit(:gitlab, Some::Page)
```
### Clicks
When we perform a click within our tests, we expect something to occur. That something could be a component to now
appear on the webpage, or the test to navigate away from the page entirely.
Dynamic element validation is instituted when using
```ruby
click_element('my-element', Some::Page)
```
### Required Elements
#### Definition
First it is important to define what a "required element" is.
A required element is a visible HTML element that appears on a UI component without any user input.
"Visible" can be defined as
- Not having any CSS preventing its display, for example, `display: none` or `width: 0px; height: 0px;`
- Being able to be interacted with by the user
"UI component" can be defined as
- Anything the user sees
- A button, a text field
- A layer that sits atop the page
#### Application
Requiring elements is very easy. By adding `required: true` as a parameter to an `element`, you've now made it
a requirement that the element appear on the page upon navigation.
## Examples
Given ...
```ruby
class MyPage < Page::Base
view 'app/views/view.html.haml' do
element 'my-element', required: true
element 'another-element', required: true
element 'conditional-element'
end
def open_layer
click_element('my-element', Layer::MyLayer)
end
end
class Layer < Page::Component
view 'app/views/mylayer/layer.html.haml' do
element 'message-content', required: true
end
end
```
### Navigating
Given the [source](#examples) ...
```ruby
Runtime::Browser.visit(:gitlab, Page::MyPage)
execute_stuff
```
invokes GitLab QA to scan `MyPage` for `my-element` and `another-element` to be on the page before continuing to
`execute_stuff`
### Clicking
Given the [source](#examples) ...
```ruby
def open_layer
click_element('my-element', Layer::MyLayer)
end
```
invokes GitLab QA to ensure that `message-content` appears on
the Layer upon clicking `my-element`.
This implies that the Layer is indeed rendered before we continue our test.
|
https://docs.gitlab.com/development/testing_guide/end_to_end/waits
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/testing_guide/end_to_end/waits.md
|
2025-08-13
|
doc/development/testing_guide/end_to_end/best_practices
|
[
"doc",
"development",
"testing_guide",
"end_to_end",
"best_practices"
] |
waits.md
|
none
|
unassigned
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Waits
| null |
All Capybara Node Finders utilize a waiting mechanism.
Per the [Capybara API](https://www.rubydoc.info/github/jnicklas/capybara/Capybara/Node/Finders:find) -
> If the driver is capable of executing JavaScript, `find` will wait for a set amount of time and continuously retry finding the element until either the element is found or the time expires. The length of time find will wait is controlled through `Capybara.default_max_wait_time` and defaults to `2` seconds. `find` takes the same options as all.
Ideally the [GitLab QA Framework](https://gitlab.com/gitlab-org/gitlab-ce/tree/master/qa) should implement its own explicit waiting to avoid hard sleeps but currently that is [not the case](https://gitlab.com/gitlab-org/gitlab-qa/issues/280).
## Hard Sleeps
**[qa/qa/page/base.rb](https://gitlab.com/gitlab-org/gitlab-ce/blob/master/qa/qa/page/base.rb#L16)**
```ruby
def wait(max: 60, time: 0.1, reload: true)
...
end
```
- `max` : Specifies the max amount of seconds to wait until the block given is satisfied
- `time` : The interval/poll time to sleep *in seconds*. If this time reaches `max`, the wait returns `false`
- `reload` : If the wait is not satiated, the test will sleep then reload the page if `:reload` is set to `true`
|
---
stage: none
group: unassigned
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: Waits
breadcrumbs:
- doc
- development
- testing_guide
- end_to_end
- best_practices
---
All Capybara Node Finders utilize a waiting mechanism.
Per the [Capybara API](https://www.rubydoc.info/github/jnicklas/capybara/Capybara/Node/Finders:find) -
> If the driver is capable of executing JavaScript, `find` will wait for a set amount of time and continuously retry finding the element until either the element is found or the time expires. The length of time find will wait is controlled through `Capybara.default_max_wait_time` and defaults to `2` seconds. `find` takes the same options as all.
Ideally the [GitLab QA Framework](https://gitlab.com/gitlab-org/gitlab-ce/tree/master/qa) should implement its own explicit waiting to avoid hard sleeps but currently that is [not the case](https://gitlab.com/gitlab-org/gitlab-qa/issues/280).
## Hard Sleeps
**[qa/qa/page/base.rb](https://gitlab.com/gitlab-org/gitlab-ce/blob/master/qa/qa/page/base.rb#L16)**
```ruby
def wait(max: 60, time: 0.1, reload: true)
...
end
```
- `max` : Specifies the max amount of seconds to wait until the block given is satisfied
- `time` : The interval/poll time to sleep *in seconds*. If this time reaches `max`, the wait returns `false`
- `reload` : If the wait is not satiated, the test will sleep then reload the page if `:reload` is set to `true`
|
https://docs.gitlab.com/development/testing_guide/end_to_end/rspec_metadata_tests
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/testing_guide/end_to_end/rspec_metadata_tests.md
|
2025-08-13
|
doc/development/testing_guide/end_to_end/best_practices
|
[
"doc",
"development",
"testing_guide",
"end_to_end",
"best_practices"
] |
rspec_metadata_tests.md
|
none
|
unassigned
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
RSpec metadata for end-to-end tests
| null |
This is a partial list of the [RSpec metadata](https://rspec.info/features/3-12/rspec-core/metadata/user-defined/)
(a.k.a. tags) that are used in our end-to-end tests.
<!-- Please keep the tags in alphabetical order -->
| Tag | Description |
|--------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `:elasticsearch` | The test requires an Elasticsearch service. It is used by the [instance-level scenario](https://gitlab.com/gitlab-org/gitlab-qa#definitions) [`Test::Integration::Elasticsearch`](https://gitlab.com/gitlab-org/gitlab/-/blob/72b62b51bdf513e2936301cb6c7c91ec27c35b4d/qa/qa/ee/scenario/test/integration/elasticsearch.rb) to include only tests that require Elasticsearch. |
| `:except` | The test is to be run in their typical execution contexts except as specified. See [test execution context selection](execution_context_selection.md) for more information. |
| `:external_api_calls` | The test requires interaction with a network external to the Docker network. |
| `:external_ai_provider` | The test requires an environment that is integrated with a real external AI provider. |
| `:feature_flag` | The test uses a feature flag and therefore requires an administrator account to run. When `scope` is set to `:global`, the test will be skipped on all live .com environments. Otherwise, it will be skipped only on Canary, Production, and Pre-production. See [testing with feature flags](feature_flags.md) for more details. |
| `:geo` | The test requires two GitLab Geo instances - a primary and a secondary - to be spun up. |
| `:gitaly_cluster` | The test runs against a GitLab instance where repositories are stored on redundant Gitaly nodes behind a Praefect node. All nodes are [separate containers](../../../../administration/gitaly/praefect/configure.md#requirements). Tests that use this tag have a longer setup time since there are three additional containers that need to be started. |
| `:github` | The test requires a GitHub personal access token. |
| `:group_saml` | The test requires a GitLab instance that has SAML SSO enabled for the group. Interacts with an external SAML identity provider. Paired with the `:orchestrated` tag. |
| `:instance_saml` | The test requires a GitLab instance that has SAML SSO enabled for the instance. Interacts with an external SAML identity provider. Paired with the `:orchestrated` tag. |
| `:integrations` | This aims to test the available [integrations](../../../../user/project/integrations/_index.md#available-integrations). The test requires Docker to be installed in the run context. It will provision the containers and can be run against a local instance or using the `gitlab-qa` scenario `Test::Integration::Integrations`. |
| `:issue`, `:issue_${num}` | Optional links to issues which might be related to the spec. Helps keep track of related issues and can also be used by tools that create test reports. Currently added automatically to `Allure` test report. Multiple tags can be used by adding an optional numeric suffix like `issue_1`, `issue_2` etc. |
| `:service_ping_disabled` | The test interacts with the GitLab configuration service ping at the instance level to turn **Admin** area setting service ping checkbox on or off. This tag will have the test run only in the `service_ping_disabled` job and must be paired with the `:orchestrated` and `:requires_admin` tags. |
| `:jira` | The test requires a Jira Server. [GitLab-QA](https://gitlab.com/gitlab-org/gitlab-qa) provisions the Jira Server in a Docker container when the `Test::Integration::Jira` test scenario is run. |
| `:kubernetes` | The test includes a GitLab instance that is configured to be run behind an SSH tunnel, allowing a TLS-accessible GitLab. This test also includes provisioning of at least one Kubernetes cluster to test against. _This tag is often be paired with `:orchestrated`._ |
| `:ldap_no_server` | The test requires a GitLab instance to be configured to use LDAP. To be used with the `:orchestrated` tag. It does not spin up an LDAP server at orchestration time. Instead, it creates the LDAP server at runtime. |
| `:ldap_no_tls` | The test requires a GitLab instance to be configured to use an external LDAP server with TLS not enabled. |
| `:ldap_tls` | The test requires a GitLab instance to be configured to use an external LDAP server with TLS enabled. |
| `:mattermost` | The test requires a GitLab Mattermost service on the GitLab instance. |
| `:metrics` | The test requires a GitLab instance where [dedicated metrics exporters](../../../../administration/monitoring/prometheus/web_exporter.md) are running alongside Puma and Sidekiq. |
| `:mixed_env` | The test should only be executed in environments that have a paired canary version available through traffic routing based on the existence of the `gitlab_canary=true` cookie. Tests in this category are switching the cookie mid-test to validate mixed deployment environments. |
| `:oauth` | The test uses and external OmniAuth provider to sign in to GitLab. |
| `:object_storage` | The test requires a GitLab instance to be configured to use multiple [object storage types](../../../../administration/object_storage.md). Uses MinIO as the object storage server. |
| `:only` | The test is only to be run in specific execution contexts. See [test execution context selection](execution_context_selection.md) for more information. |
| `:orchestrated` | The GitLab instance under test may be [configured by `gitlab-qa`](https://gitlab.com/gitlab-org/gitlab-qa/-/blob/master/docs/what_tests_can_be_run.md#orchestrated-tests) to be different to the default GitLab configuration, or `gitlab-qa` may launch additional services in separate Docker containers, or both. Tests tagged with `:orchestrated` are excluded when testing environments where we can't dynamically modify the GitLab configuration (for example, Staging). |
| `:product_group` | Specifies what product group the test belongs to. See [Product sections, stages, groups, and categories](https://handbook.gitlab.com/handbook/product/categories/) for the comprehensive groups list. |
| `:quarantine` | The test has been [quarantined](https://handbook.gitlab.com/handbook/engineering/infrastructure/test-platform/debugging-qa-test-failures/#quarantining-tests), runs in a separate job that only includes quarantined tests, and is allowed to fail. The test is skipped in its regular job so that if it fails it doesn't hold up the pipeline. Note that you can also [quarantine a test only when it runs in a specific context](execution_context_selection.md#quarantine-a-test-for-a-specific-environment). |
| `:relative_url` | The test requires a GitLab instance to be installed under a [relative URL](../../../../install/relative_url.md). |
| `:repository_storage` | The test requires a GitLab instance to be configured to use multiple [repository storage paths](../../../../administration/repository_storage_paths.md). Paired with the `:orchestrated` tag. |
| `:requires_admin` | The test requires an administrator account. Tests with the tag are excluded when run against Canary and Production environments. |
| `:requires_git_protocol_v2` | The test requires that Git protocol version 2 is enabled on the server. It's assumed to be enabled by default but if not the test can be skipped by setting `QA_CAN_TEST_GIT_PROTOCOL_V2` to `false`. |
| `:requires_praefect` | The test requires that the GitLab instance uses [Gitaly Cluster (Praefect)](../../../../administration/gitaly/praefect/_index.md) as the repository storage. It's assumed to be used by default but if not the test can be skipped by setting `QA_CAN_TEST_PRAEFECT` to `false`. |
| `:skip_live_env` | The test is excluded when run against live deployed environments such as Staging, Canary, and Production. |
| `:skip_fips_env` | The test is excluded when run against an environment in FIPS mode. |
| `:skip_signup_disabled` | The test uses UI to sign up a new user and is skipped in any environment that does not allow new user registration via the UI. |
| `:smoke` | The test belongs to the test suite which verifies basic functionality of a GitLab instance. |
| `:health_check` | The test belongs to the smallest test suite, a subset of smoke. Used to monitor the status and health of the application |
| `:smtp` | The test requires a GitLab instance to be configured to use an SMTP server. Tests SMTP notification email delivery from GitLab by using MailHog. |
| `:testcase` | The link to the test case issue in the [GitLab Project test cases](https://gitlab.com/gitlab-org/gitlab/-/quality/test_cases). |
| `:ai_gateway` | The test requires a GitLab instance configured to use a local [AI gateway](https://gitlab.com/gitlab-org/modelops/applied-ml/code-suggestions/ai-assist) with a valid cloud license, Duo Pro add-on and Duo Pro seat assigned to the administrator user. Paired with the `:orchestrated` tag. |
| `:ai_gateway_no_seat_assigned` | The test requires a GitLab instance configured to use a local [AI gateway](https://gitlab.com/gitlab-org/modelops/applied-ml/code-suggestions/ai-assist) where there is no seat assigned to the administrator user. Paired with the `:orchestrated` tag. |
| `:ai_gateway_no_license` | The test requires a GitLab instance configured to use a local [AI gateway](https://gitlab.com/gitlab-org/modelops/applied-ml/code-suggestions/ai-assist) without a valid cloud license. Paired with the `:orchestrated` tag. |
| `:ai_gateway_no_add_on` | The test requires a GitLab instance configured to use a local [AI gateway](https://gitlab.com/gitlab-org/modelops/applied-ml/code-suggestions/ai-assist) with a valid cloud license, but with no Duo Pro add-on assigned. Paired with the `:orchestrated` tag. |
|
---
stage: none
group: unassigned
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: RSpec metadata for end-to-end tests
breadcrumbs:
- doc
- development
- testing_guide
- end_to_end
- best_practices
---
This is a partial list of the [RSpec metadata](https://rspec.info/features/3-12/rspec-core/metadata/user-defined/)
(a.k.a. tags) that are used in our end-to-end tests.
<!-- Please keep the tags in alphabetical order -->
| Tag | Description |
|--------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `:elasticsearch` | The test requires an Elasticsearch service. It is used by the [instance-level scenario](https://gitlab.com/gitlab-org/gitlab-qa#definitions) [`Test::Integration::Elasticsearch`](https://gitlab.com/gitlab-org/gitlab/-/blob/72b62b51bdf513e2936301cb6c7c91ec27c35b4d/qa/qa/ee/scenario/test/integration/elasticsearch.rb) to include only tests that require Elasticsearch. |
| `:except` | The test is to be run in their typical execution contexts except as specified. See [test execution context selection](execution_context_selection.md) for more information. |
| `:external_api_calls` | The test requires interaction with a network external to the Docker network. |
| `:external_ai_provider` | The test requires an environment that is integrated with a real external AI provider. |
| `:feature_flag` | The test uses a feature flag and therefore requires an administrator account to run. When `scope` is set to `:global`, the test will be skipped on all live .com environments. Otherwise, it will be skipped only on Canary, Production, and Pre-production. See [testing with feature flags](feature_flags.md) for more details. |
| `:geo` | The test requires two GitLab Geo instances - a primary and a secondary - to be spun up. |
| `:gitaly_cluster` | The test runs against a GitLab instance where repositories are stored on redundant Gitaly nodes behind a Praefect node. All nodes are [separate containers](../../../../administration/gitaly/praefect/configure.md#requirements). Tests that use this tag have a longer setup time since there are three additional containers that need to be started. |
| `:github` | The test requires a GitHub personal access token. |
| `:group_saml` | The test requires a GitLab instance that has SAML SSO enabled for the group. Interacts with an external SAML identity provider. Paired with the `:orchestrated` tag. |
| `:instance_saml` | The test requires a GitLab instance that has SAML SSO enabled for the instance. Interacts with an external SAML identity provider. Paired with the `:orchestrated` tag. |
| `:integrations` | This aims to test the available [integrations](../../../../user/project/integrations/_index.md#available-integrations). The test requires Docker to be installed in the run context. It will provision the containers and can be run against a local instance or using the `gitlab-qa` scenario `Test::Integration::Integrations`. |
| `:issue`, `:issue_${num}` | Optional links to issues which might be related to the spec. Helps keep track of related issues and can also be used by tools that create test reports. Currently added automatically to `Allure` test report. Multiple tags can be used by adding an optional numeric suffix like `issue_1`, `issue_2` etc. |
| `:service_ping_disabled` | The test interacts with the GitLab configuration service ping at the instance level to turn **Admin** area setting service ping checkbox on or off. This tag will have the test run only in the `service_ping_disabled` job and must be paired with the `:orchestrated` and `:requires_admin` tags. |
| `:jira` | The test requires a Jira Server. [GitLab-QA](https://gitlab.com/gitlab-org/gitlab-qa) provisions the Jira Server in a Docker container when the `Test::Integration::Jira` test scenario is run. |
| `:kubernetes` | The test includes a GitLab instance that is configured to be run behind an SSH tunnel, allowing a TLS-accessible GitLab. This test also includes provisioning of at least one Kubernetes cluster to test against. _This tag is often be paired with `:orchestrated`._ |
| `:ldap_no_server` | The test requires a GitLab instance to be configured to use LDAP. To be used with the `:orchestrated` tag. It does not spin up an LDAP server at orchestration time. Instead, it creates the LDAP server at runtime. |
| `:ldap_no_tls` | The test requires a GitLab instance to be configured to use an external LDAP server with TLS not enabled. |
| `:ldap_tls` | The test requires a GitLab instance to be configured to use an external LDAP server with TLS enabled. |
| `:mattermost` | The test requires a GitLab Mattermost service on the GitLab instance. |
| `:metrics` | The test requires a GitLab instance where [dedicated metrics exporters](../../../../administration/monitoring/prometheus/web_exporter.md) are running alongside Puma and Sidekiq. |
| `:mixed_env` | The test should only be executed in environments that have a paired canary version available through traffic routing based on the existence of the `gitlab_canary=true` cookie. Tests in this category are switching the cookie mid-test to validate mixed deployment environments. |
| `:oauth` | The test uses and external OmniAuth provider to sign in to GitLab. |
| `:object_storage` | The test requires a GitLab instance to be configured to use multiple [object storage types](../../../../administration/object_storage.md). Uses MinIO as the object storage server. |
| `:only` | The test is only to be run in specific execution contexts. See [test execution context selection](execution_context_selection.md) for more information. |
| `:orchestrated` | The GitLab instance under test may be [configured by `gitlab-qa`](https://gitlab.com/gitlab-org/gitlab-qa/-/blob/master/docs/what_tests_can_be_run.md#orchestrated-tests) to be different to the default GitLab configuration, or `gitlab-qa` may launch additional services in separate Docker containers, or both. Tests tagged with `:orchestrated` are excluded when testing environments where we can't dynamically modify the GitLab configuration (for example, Staging). |
| `:product_group` | Specifies what product group the test belongs to. See [Product sections, stages, groups, and categories](https://handbook.gitlab.com/handbook/product/categories/) for the comprehensive groups list. |
| `:quarantine` | The test has been [quarantined](https://handbook.gitlab.com/handbook/engineering/infrastructure/test-platform/debugging-qa-test-failures/#quarantining-tests), runs in a separate job that only includes quarantined tests, and is allowed to fail. The test is skipped in its regular job so that if it fails it doesn't hold up the pipeline. Note that you can also [quarantine a test only when it runs in a specific context](execution_context_selection.md#quarantine-a-test-for-a-specific-environment). |
| `:relative_url` | The test requires a GitLab instance to be installed under a [relative URL](../../../../install/relative_url.md). |
| `:repository_storage` | The test requires a GitLab instance to be configured to use multiple [repository storage paths](../../../../administration/repository_storage_paths.md). Paired with the `:orchestrated` tag. |
| `:requires_admin` | The test requires an administrator account. Tests with the tag are excluded when run against Canary and Production environments. |
| `:requires_git_protocol_v2` | The test requires that Git protocol version 2 is enabled on the server. It's assumed to be enabled by default but if not the test can be skipped by setting `QA_CAN_TEST_GIT_PROTOCOL_V2` to `false`. |
| `:requires_praefect` | The test requires that the GitLab instance uses [Gitaly Cluster (Praefect)](../../../../administration/gitaly/praefect/_index.md) as the repository storage. It's assumed to be used by default but if not the test can be skipped by setting `QA_CAN_TEST_PRAEFECT` to `false`. |
| `:skip_live_env` | The test is excluded when run against live deployed environments such as Staging, Canary, and Production. |
| `:skip_fips_env` | The test is excluded when run against an environment in FIPS mode. |
| `:skip_signup_disabled` | The test uses UI to sign up a new user and is skipped in any environment that does not allow new user registration via the UI. |
| `:smoke` | The test belongs to the test suite which verifies basic functionality of a GitLab instance. |
| `:health_check` | The test belongs to the smallest test suite, a subset of smoke. Used to monitor the status and health of the application |
| `:smtp` | The test requires a GitLab instance to be configured to use an SMTP server. Tests SMTP notification email delivery from GitLab by using MailHog. |
| `:testcase` | The link to the test case issue in the [GitLab Project test cases](https://gitlab.com/gitlab-org/gitlab/-/quality/test_cases). |
| `:ai_gateway` | The test requires a GitLab instance configured to use a local [AI gateway](https://gitlab.com/gitlab-org/modelops/applied-ml/code-suggestions/ai-assist) with a valid cloud license, Duo Pro add-on and Duo Pro seat assigned to the administrator user. Paired with the `:orchestrated` tag. |
| `:ai_gateway_no_seat_assigned` | The test requires a GitLab instance configured to use a local [AI gateway](https://gitlab.com/gitlab-org/modelops/applied-ml/code-suggestions/ai-assist) where there is no seat assigned to the administrator user. Paired with the `:orchestrated` tag. |
| `:ai_gateway_no_license` | The test requires a GitLab instance configured to use a local [AI gateway](https://gitlab.com/gitlab-org/modelops/applied-ml/code-suggestions/ai-assist) without a valid cloud license. Paired with the `:orchestrated` tag. |
| `:ai_gateway_no_add_on` | The test requires a GitLab instance configured to use a local [AI gateway](https://gitlab.com/gitlab-org/modelops/applied-ml/code-suggestions/ai-assist) with a valid cloud license, but with no Duo Pro add-on assigned. Paired with the `:orchestrated` tag. |
|
https://docs.gitlab.com/development/testing_guide/end_to_end/running_tests
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/testing_guide/end_to_end/_index.md
|
2025-08-13
|
doc/development/testing_guide/end_to_end/running_tests
|
[
"doc",
"development",
"testing_guide",
"end_to_end",
"running_tests"
] |
_index.md
|
none
|
unassigned
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Running the tests
| null |
## Against your GDK environment
First, follow the instructions to [install GDK](https://gitlab.com/gitlab-org/gitlab-development-kit/blob/main/doc/index.md) as your local GitLab development environment.
Then, navigate to the QA folder, install the gems, and run the tests via RSpec:
```shell
cd gitlab-development-kit/gitlab/qa
bundle install
bundle exec rspec <path/to/spec.rb>
```
{{< alert type="note" >}}
- If you want to run tests requiring SSH against GDK, you will need to [modify your GDK setup](https://gitlab.com/gitlab-org/gitlab-qa/blob/master/docs/run_qa_against_gdk.md).
- You may be able to use the password pre-set for `root` in your GDK installation [See GDK help](https://gitlab.com/gitlab-org/gitlab-development-kit/-/blob/14bd8b6eb875d72eb1b482e0ec00cbf8fc3ebf99/HELP#L62). If you have changed your `root` password from the default, export the password as `GITLAB_ADMIN_PASSWORD`.
- By default the tests will run in a headless browser. If you'd like to watch the test execution, you can export `WEBDRIVER_HEADLESS=false`.
- Tests that are tagged `:orchestrated` require special setup (for example, a custom GitLab configuration, or additional services such as LDAP). All [orchestrated tests can be run via `gitlab-qa`](https://gitlab.com/gitlab-org/gitlab-qa/-/blob/master/docs/what_tests_can_be_run.md). There are also [setup instructions](running_tests_that_require_special_setup.md) for running some of those tests against GDK or another local GitLab instance.
{{< /alert >}}
### Remote development
For [VSCode](https://code.visualstudio.com/) user, [.devcontainer](https://gitlab.com/gitlab-org/gitlab/-/blob/master/qa/.devcontainer/devcontainer.json) defines configuration to develop E2E tests inside a Docker container which by default is attached to the same network as environments started by [`gitlab-qa`](https://gitlab.com/gitlab-org/gitlab-qa) gem. For more information on how to use `dev containers`, see [tutorial](https://code.visualstudio.com/docs/devcontainers/tutorial).
This is useful when developing E2E tests that require GitLab instance with specific omnibus configuration. Typical workflow example:
- Start `GitLab` omnibus instance with specific configuration without running tests, for example: `gitlab-qa Test::Integration::Import EE --no-tests`. For available configurations, see [docs](https://gitlab.com/gitlab-org/gitlab-qa/-/blob/master/docs/what_tests_can_be_run.md)
- Start dev container from `VSCode` environment
- Develop and run tests from within the container which will automatically execute against started GitLab instance
### Generic command for a typical GDK installation
The following is an example command you can use if you have configured GDK to run on a specific IP address and port, that aren't the defaults, and you would like the test framework to show debug logs:
```shell
QA_LOG_LEVEL=DEBUG \
QA_GITLAB_URL="http://{GDK IP ADDRESS}:{GDK PORT}" \
bundle exec rspec <path/to/spec.rb>
```
For an explanation of the variables see the [additional examples below](#overriding-gitlab-address) and the [list of supported environment variables](https://gitlab.com/gitlab-org/gitlab-qa/blob/master/docs/what_tests_can_be_run.md#supported-gitlab-environment-variables).
## Against GitLab in Docker
GitLab can be [installed in Docker](../../../../install/docker/_index.md).
See the section above for situations that might require adjustment to the commands below or to the configuration of the GitLab instance. [You can find more information in the documentation](../../../../install/docker/_index.md).
### On a Unix like operating system
1. Use the following command to start an instance that you can visit at `http://127.0.0.1`:
```shell
docker run \
--hostname 127.0.0.1 \
--publish 80:80 --publish 22:22 \
--name gitlab \
--shm-size 256m \
--env GITLAB_OMNIBUS_CONFIG="gitlab_rails['initial_root_password']='5iveL\!fe';" \
gitlab/gitlab-ee:nightly
```
{{< alert type="note" >}}
If you are on a Mac with [Apple Silicon](https://support.apple.com/en-us/HT211814), you will also need to add: `--platform=linux/amd64`
{{< /alert >}}
1. Once GitLab is up and accessible on `http://127.0.0.1`, in another shell tab, navigate to the `qa` directory of the checkout of the GitLab repository on your computer and run the following commands.
```shell
bundle install
export WEBDRIVER_HEADLESS=false
export GITLAB_ADMIN_PASSWORD=5iveL\!fe
export QA_GITLAB_URL="http://127.0.0.1"
```
1. Most tests that do not require special setup could then be run with the following command. We will run `log_in_spec.rb` in this example.
```shell
bundle exec rspec ./qa/specs/features/browser_ui/1_manage/login/log_in_spec.rb
```
### On a Windows PC
1. If you don't already have these, install:
- [Google Chrome](https://www.google.com/chrome/)
- [Docker Desktop](https://docs.docker.com/desktop/install/windows-install/)
- [Git](https://git-scm.com/download/win)
- [Ruby](https://rubyinstaller.org/downloads/). Refer to the [`.ruby-version` file](https://gitlab.com/gitlab-org/gitlab/-/blob/master/.ruby-version)
for the exact version of Ruby to install.
{{< alert type="note" >}}
Be aware that [Docker Desktop must be set to use Linux containers](https://learn.microsoft.com/en-us/virtualization/windowscontainers/quick-start/quick-start-windows-10-linux#run-your-first-linux-container).
{{< /alert >}}
1. Use the following command to start an instance that you can visit at `http://127.0.0.1`. You might need to grant admin rights if asked:
```shell
docker run --hostname 127.0.0.1 --publish 80:80 --publish 22:22 --name gitlab --shm-size 256m --env GITLAB_OMNIBUS_CONFIG="gitlab_rails['initial_root_password']='5iveL\!fe';" gitlab/gitlab-ee:nightly
```
1. Once GitLab is up and accessible on `http://127.0.0.1`, in another command prompt window, navigate to the `qa` directory of the checkout of the GitLab repository on your computer and run the following commands.
```shell
bundle install
set WEBDRIVER_HEADLESS=false
set GITLAB_ADMIN_PASSWORD=5iveL\!fe
set QA_GITLAB_URL=http://127.0.0.1
```
1. Most tests that do not require special setup could then be run with the following command. We will run `log_in_spec.rb` in this example.
```shell
bundle exec rspec .\qa\specs\features\browser_ui\1_manage\login\log_in_spec.rb
```
## Specific types of tests
You can supply specific tests to run as another parameter. For example, to run the repository-related specs, you can execute:
```shell
bundle exec rspec qa/specs/features/browser_ui/3_create/repository
```
### EE tests
When running EE tests you'll need to have a license available. GitLab engineers can [request a license](https://about.gitlab.com/handbook/developer-onboarding/#working-on-gitlab-ee).
Once you have the license file you can export it as an environment variable and then the framework can use it. If you do so it will be installed automatically.
```shell
export QA_EE_LICENSE=$(cat /path/to/gitlab_license)
```
### Quarantined tests
Tests can be put in quarantine by assigning `:quarantine` metadata. This means they will be skipped unless run with `--tag quarantine`. This can be used for tests that are expected to fail while a fix is in progress (similar to how [`skip` or `pending`](https://relishapp.com/rspec/rspec-core/v/3-8/docs/pending-and-skipped-examples) can be used).
```shell
bundle exec rspec --tag quarantine
```
Alternatively, the `DISABLE_QUARATINE` variable can be used
```shell
DISABLE_QUARANTINE=true bundle exec bin/qa Test::Instance::All http://localhost:3000
```
### Custom `bin/qa` test runner
`bin/qa` is an additional custom wrapper script that abstracts away some of the more complicated setups that some tests require. This option requires test scenario and test instance's GitLab address to be specified in the command. For example, to run any `Instance` scenario test, the following command can be used:
```shell
bundle exec bin/qa Test::Instance::All http://localhost:3000
```
### Feature flags
Tests can be run with a feature flag enabled or disabled by using the command-line
option `--enable-feature FEATURE_FLAG` or `--disable-feature FEATURE_FLAG`.
For example, to enable the feature flag that enforces Gitaly request limits,
you would use the command:
```shell
bundle exec bin/qa Test::Instance::All http://localhost:3000 --enable-feature gitaly_enforce_requests_limits
```
This will instruct the QA framework to enable the `gitaly_enforce_requests_limits` feature flag ([via the API](../../../../api/features.md)), run all the tests in the `Test::Instance::All` scenario, and then disable the feature flag again.
Similarly, to disable the feature flag that enforces Gitaly request limits, you would use the command:
```shell
bundle exec bin/qa Test::Instance::All http://localhost:3000 --disable-feature gitaly_enforce_requests_limits
```
This will instruct the QA framework to disable the `gitaly_enforce_requests_limits` feature flag ([via the API](../../../../api/features.md)) if not already disabled, run all the tests in the `Test::Instance::All` scenario, and then enable the feature flag again if it was enabled earlier.
{{< alert type="note" >}}
You can also [toggle feature flags in the tests themselves](../best_practices/feature_flags.md).
{{< /alert >}}
Note also that the `--` separator isn't used because `--enable-feature` and `--disable-feature` are QA framework options, not `rspec` options.
## Test configuration
### Overriding GitLab address
When running tests against GDK, the default address is `http://127.0.0.1:3000`. This value can be overridden by providing environment variable `QA_GITLAB_URL`:
```shell
QA_GITLAB_URL=https://gdk.test:3000 bundle exec rspec
```
### Overriding the authenticated user
By default `root` user seeded by the GDK is used by all tests to create new unique test user for each test.
Tests will also use seeded administrator user's personal access token.
If you need to authenticate with different admin credentials, you can provide the `GITLAB_ADMIN_USERNAME`, `GITLAB_ADMIN_PASSWORD` environment variables and if administrator user has a token created, additionally `GITLAB_QA_ADMIN_ACCESS_TOKEN` can be set as well:
```shell
GITLAB_ADMIN_USERNAME=admin GITLAB_ADMIN_PASSWORD=myadminpassword GITLAB_QA_ADMIN_ACCESS_TOKEN=token bundle exec rspec
```
All [supported environment variables are here](https://gitlab.com/gitlab-org/gitlab-qa/blob/master/docs/what_tests_can_be_run.md#supported-environment-variables).
### Sending additional cookies
The environment variable `QA_COOKIES` can be set to send additional cookies on every request. This is necessary on `gitlab.com` to direct traffic to the canary fleet. To do this set `QA_COOKIES="gitlab_canary=true"`.
To set multiple cookies, separate them with the `;` character, for example: `QA_COOKIES="cookie1=value;cookie2=value2"`
### Headless browser
By default tests use headless browser. To override that, `WEBDRIVER_HEADLESS` must be set to `false`:
```shell
WEBDRIVER_HEADLESS=false bundle exec rspec
```
### Log level
By default, the tests use the `info` log level. To change the test's log level, the environment variable `QA_LOG_LEVEL` can be set:
```shell
QA_LOG_LEVEL=debug bundle exec rspec
```
|
---
stage: none
group: unassigned
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: Running the tests
breadcrumbs:
- doc
- development
- testing_guide
- end_to_end
- running_tests
---
## Against your GDK environment
First, follow the instructions to [install GDK](https://gitlab.com/gitlab-org/gitlab-development-kit/blob/main/doc/index.md) as your local GitLab development environment.
Then, navigate to the QA folder, install the gems, and run the tests via RSpec:
```shell
cd gitlab-development-kit/gitlab/qa
bundle install
bundle exec rspec <path/to/spec.rb>
```
{{< alert type="note" >}}
- If you want to run tests requiring SSH against GDK, you will need to [modify your GDK setup](https://gitlab.com/gitlab-org/gitlab-qa/blob/master/docs/run_qa_against_gdk.md).
- You may be able to use the password pre-set for `root` in your GDK installation [See GDK help](https://gitlab.com/gitlab-org/gitlab-development-kit/-/blob/14bd8b6eb875d72eb1b482e0ec00cbf8fc3ebf99/HELP#L62). If you have changed your `root` password from the default, export the password as `GITLAB_ADMIN_PASSWORD`.
- By default the tests will run in a headless browser. If you'd like to watch the test execution, you can export `WEBDRIVER_HEADLESS=false`.
- Tests that are tagged `:orchestrated` require special setup (for example, a custom GitLab configuration, or additional services such as LDAP). All [orchestrated tests can be run via `gitlab-qa`](https://gitlab.com/gitlab-org/gitlab-qa/-/blob/master/docs/what_tests_can_be_run.md). There are also [setup instructions](running_tests_that_require_special_setup.md) for running some of those tests against GDK or another local GitLab instance.
{{< /alert >}}
### Remote development
For [VSCode](https://code.visualstudio.com/) user, [.devcontainer](https://gitlab.com/gitlab-org/gitlab/-/blob/master/qa/.devcontainer/devcontainer.json) defines configuration to develop E2E tests inside a Docker container which by default is attached to the same network as environments started by [`gitlab-qa`](https://gitlab.com/gitlab-org/gitlab-qa) gem. For more information on how to use `dev containers`, see [tutorial](https://code.visualstudio.com/docs/devcontainers/tutorial).
This is useful when developing E2E tests that require GitLab instance with specific omnibus configuration. Typical workflow example:
- Start `GitLab` omnibus instance with specific configuration without running tests, for example: `gitlab-qa Test::Integration::Import EE --no-tests`. For available configurations, see [docs](https://gitlab.com/gitlab-org/gitlab-qa/-/blob/master/docs/what_tests_can_be_run.md)
- Start dev container from `VSCode` environment
- Develop and run tests from within the container which will automatically execute against started GitLab instance
### Generic command for a typical GDK installation
The following is an example command you can use if you have configured GDK to run on a specific IP address and port, that aren't the defaults, and you would like the test framework to show debug logs:
```shell
QA_LOG_LEVEL=DEBUG \
QA_GITLAB_URL="http://{GDK IP ADDRESS}:{GDK PORT}" \
bundle exec rspec <path/to/spec.rb>
```
For an explanation of the variables see the [additional examples below](#overriding-gitlab-address) and the [list of supported environment variables](https://gitlab.com/gitlab-org/gitlab-qa/blob/master/docs/what_tests_can_be_run.md#supported-gitlab-environment-variables).
## Against GitLab in Docker
GitLab can be [installed in Docker](../../../../install/docker/_index.md).
See the section above for situations that might require adjustment to the commands below or to the configuration of the GitLab instance. [You can find more information in the documentation](../../../../install/docker/_index.md).
### On a Unix like operating system
1. Use the following command to start an instance that you can visit at `http://127.0.0.1`:
```shell
docker run \
--hostname 127.0.0.1 \
--publish 80:80 --publish 22:22 \
--name gitlab \
--shm-size 256m \
--env GITLAB_OMNIBUS_CONFIG="gitlab_rails['initial_root_password']='5iveL\!fe';" \
gitlab/gitlab-ee:nightly
```
{{< alert type="note" >}}
If you are on a Mac with [Apple Silicon](https://support.apple.com/en-us/HT211814), you will also need to add: `--platform=linux/amd64`
{{< /alert >}}
1. Once GitLab is up and accessible on `http://127.0.0.1`, in another shell tab, navigate to the `qa` directory of the checkout of the GitLab repository on your computer and run the following commands.
```shell
bundle install
export WEBDRIVER_HEADLESS=false
export GITLAB_ADMIN_PASSWORD=5iveL\!fe
export QA_GITLAB_URL="http://127.0.0.1"
```
1. Most tests that do not require special setup could then be run with the following command. We will run `log_in_spec.rb` in this example.
```shell
bundle exec rspec ./qa/specs/features/browser_ui/1_manage/login/log_in_spec.rb
```
### On a Windows PC
1. If you don't already have these, install:
- [Google Chrome](https://www.google.com/chrome/)
- [Docker Desktop](https://docs.docker.com/desktop/install/windows-install/)
- [Git](https://git-scm.com/download/win)
- [Ruby](https://rubyinstaller.org/downloads/). Refer to the [`.ruby-version` file](https://gitlab.com/gitlab-org/gitlab/-/blob/master/.ruby-version)
for the exact version of Ruby to install.
{{< alert type="note" >}}
Be aware that [Docker Desktop must be set to use Linux containers](https://learn.microsoft.com/en-us/virtualization/windowscontainers/quick-start/quick-start-windows-10-linux#run-your-first-linux-container).
{{< /alert >}}
1. Use the following command to start an instance that you can visit at `http://127.0.0.1`. You might need to grant admin rights if asked:
```shell
docker run --hostname 127.0.0.1 --publish 80:80 --publish 22:22 --name gitlab --shm-size 256m --env GITLAB_OMNIBUS_CONFIG="gitlab_rails['initial_root_password']='5iveL\!fe';" gitlab/gitlab-ee:nightly
```
1. Once GitLab is up and accessible on `http://127.0.0.1`, in another command prompt window, navigate to the `qa` directory of the checkout of the GitLab repository on your computer and run the following commands.
```shell
bundle install
set WEBDRIVER_HEADLESS=false
set GITLAB_ADMIN_PASSWORD=5iveL\!fe
set QA_GITLAB_URL=http://127.0.0.1
```
1. Most tests that do not require special setup could then be run with the following command. We will run `log_in_spec.rb` in this example.
```shell
bundle exec rspec .\qa\specs\features\browser_ui\1_manage\login\log_in_spec.rb
```
## Specific types of tests
You can supply specific tests to run as another parameter. For example, to run the repository-related specs, you can execute:
```shell
bundle exec rspec qa/specs/features/browser_ui/3_create/repository
```
### EE tests
When running EE tests you'll need to have a license available. GitLab engineers can [request a license](https://about.gitlab.com/handbook/developer-onboarding/#working-on-gitlab-ee).
Once you have the license file you can export it as an environment variable and then the framework can use it. If you do so it will be installed automatically.
```shell
export QA_EE_LICENSE=$(cat /path/to/gitlab_license)
```
### Quarantined tests
Tests can be put in quarantine by assigning `:quarantine` metadata. This means they will be skipped unless run with `--tag quarantine`. This can be used for tests that are expected to fail while a fix is in progress (similar to how [`skip` or `pending`](https://relishapp.com/rspec/rspec-core/v/3-8/docs/pending-and-skipped-examples) can be used).
```shell
bundle exec rspec --tag quarantine
```
Alternatively, the `DISABLE_QUARATINE` variable can be used
```shell
DISABLE_QUARANTINE=true bundle exec bin/qa Test::Instance::All http://localhost:3000
```
### Custom `bin/qa` test runner
`bin/qa` is an additional custom wrapper script that abstracts away some of the more complicated setups that some tests require. This option requires test scenario and test instance's GitLab address to be specified in the command. For example, to run any `Instance` scenario test, the following command can be used:
```shell
bundle exec bin/qa Test::Instance::All http://localhost:3000
```
### Feature flags
Tests can be run with a feature flag enabled or disabled by using the command-line
option `--enable-feature FEATURE_FLAG` or `--disable-feature FEATURE_FLAG`.
For example, to enable the feature flag that enforces Gitaly request limits,
you would use the command:
```shell
bundle exec bin/qa Test::Instance::All http://localhost:3000 --enable-feature gitaly_enforce_requests_limits
```
This will instruct the QA framework to enable the `gitaly_enforce_requests_limits` feature flag ([via the API](../../../../api/features.md)), run all the tests in the `Test::Instance::All` scenario, and then disable the feature flag again.
Similarly, to disable the feature flag that enforces Gitaly request limits, you would use the command:
```shell
bundle exec bin/qa Test::Instance::All http://localhost:3000 --disable-feature gitaly_enforce_requests_limits
```
This will instruct the QA framework to disable the `gitaly_enforce_requests_limits` feature flag ([via the API](../../../../api/features.md)) if not already disabled, run all the tests in the `Test::Instance::All` scenario, and then enable the feature flag again if it was enabled earlier.
{{< alert type="note" >}}
You can also [toggle feature flags in the tests themselves](../best_practices/feature_flags.md).
{{< /alert >}}
Note also that the `--` separator isn't used because `--enable-feature` and `--disable-feature` are QA framework options, not `rspec` options.
## Test configuration
### Overriding GitLab address
When running tests against GDK, the default address is `http://127.0.0.1:3000`. This value can be overridden by providing environment variable `QA_GITLAB_URL`:
```shell
QA_GITLAB_URL=https://gdk.test:3000 bundle exec rspec
```
### Overriding the authenticated user
By default `root` user seeded by the GDK is used by all tests to create new unique test user for each test.
Tests will also use seeded administrator user's personal access token.
If you need to authenticate with different admin credentials, you can provide the `GITLAB_ADMIN_USERNAME`, `GITLAB_ADMIN_PASSWORD` environment variables and if administrator user has a token created, additionally `GITLAB_QA_ADMIN_ACCESS_TOKEN` can be set as well:
```shell
GITLAB_ADMIN_USERNAME=admin GITLAB_ADMIN_PASSWORD=myadminpassword GITLAB_QA_ADMIN_ACCESS_TOKEN=token bundle exec rspec
```
All [supported environment variables are here](https://gitlab.com/gitlab-org/gitlab-qa/blob/master/docs/what_tests_can_be_run.md#supported-environment-variables).
### Sending additional cookies
The environment variable `QA_COOKIES` can be set to send additional cookies on every request. This is necessary on `gitlab.com` to direct traffic to the canary fleet. To do this set `QA_COOKIES="gitlab_canary=true"`.
To set multiple cookies, separate them with the `;` character, for example: `QA_COOKIES="cookie1=value;cookie2=value2"`
### Headless browser
By default tests use headless browser. To override that, `WEBDRIVER_HEADLESS` must be set to `false`:
```shell
WEBDRIVER_HEADLESS=false bundle exec rspec
```
### Log level
By default, the tests use the `info` log level. To change the test's log level, the environment variable `QA_LOG_LEVEL` can be set:
```shell
QA_LOG_LEVEL=debug bundle exec rspec
```
|
https://docs.gitlab.com/development/testing_guide/end_to_end/running_tests_that_require_special_setup
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/testing_guide/end_to_end/running_tests_that_require_special_setup.md
|
2025-08-13
|
doc/development/testing_guide/end_to_end/running_tests
|
[
"doc",
"development",
"testing_guide",
"end_to_end",
"running_tests"
] |
running_tests_that_require_special_setup.md
|
none
|
unassigned
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Running tests that require special setup
| null |
## Jenkins tests
The [`jenkins_build_status_spec`](https://gitlab.com/gitlab-org/gitlab/-/blob/24a86debf49f3aed6f2ecfd6e8f9233b3a214181/qa/qa/specs/features/browser_ui/3_create/jenkins/jenkins_build_status_spec.rb)
spins up a Jenkins instance in a Docker container with the Jenkins GitLab plugin pre-installed. Due to a license restriction we are unable to distribute this image.
To build a QA compatible image, visit the [third party images project](https://gitlab.com/gitlab-org/quality/third-party-docker-public), where third party Dockerfiles can be found.
The project also has instructions for forking and building the images automatically in CI.
Some extra environment variables for the location of the forked repository are also needed.
- `QA_THIRD_PARTY_DOCKER_REGISTRY` (the container registry where the repository/images are hosted, for example `registry.gitlab.com`)
- `QA_THIRD_PARTY_DOCKER_REPOSITORY` (the base repository path where the images are hosted, for example `registry.gitlab.com/<project path>`)
- `QA_THIRD_PARTY_DOCKER_USER` (a username that has access to the container registry for this repository)
- `QA_THIRD_PARTY_DOCKER_PASSWORD` (a password/token for the username to authenticate with)
The test configures the GitLab plugin in Jenkins with a URL of the GitLab instance that are used
to run the tests. Bi-directional networking is needed between a GitLab instance and Jenkins, so GitLab can also be started in a Docker container.
To start a Docker container for GitLab based on the nightly image:
```shell
docker run \
--publish 80:80 \
--name gitlab \
--hostname localhost \
--network test
gitlab/gitlab-ee:nightly
```
To run the tests from the `/qa` directory:
```shell
export QA_THIRD_PARTY_DOCKER_REGISTRY=<registry>
export QA_THIRD_PARTY_DOCKER_REPOSITORY=<repository>
export QA_THIRD_PARTY_DOCKER_USER=<user with registry access>
export QA_THIRD_PARTY_DOCKER_PASSWORD=<password for user>
export WEBDRIVER_HEADLESS=0
bin/qa Test::Instance::All http://localhost -- qa/specs/features/ee/browser_ui/3_create/jenkins/jenkins_build_status_spec.rb
```
The test automatically spins up a Docker container for Jenkins and tear down once the test completes.
If you need to run Jenkins manually outside of the tests, refer to the README for the
[third party images project](https://gitlab.com/gitlab-org/quality/third-party-docker-public/-/blob/main/jenkins/README.md)
### Troubleshooting
If Jenkins Docker container exits without providing any information in the logs, try increasing the memory used by
the Docker Engine.
## Gitaly Cluster (Praefect) tests
The tests tagged `:gitaly_ha` are orchestrated tests that can only be run against a set of Docker containers as configured and started by [the `Test::Integration::GitalyCluster` GitLab QA scenario](https://gitlab.com/gitlab-org/gitlab-qa/-/blob/master/docs/what_tests_can_be_run.md#testintegrationgitalycluster-ceeefull-image-address).
As described in the documentation about the scenario noted above, the following command runs the tests:
```shell
gitlab-qa Test::Integration::GitalyCluster EE
```
However, that removes the containers after it finishes running the tests. If you would like to do further testing, for example, if you would like to run a single test via a debugger, you can use [the `--no-tests` option](https://gitlab.com/gitlab-org/gitlab-qa#command-line-options) to make `gitlab-qa` skip running the tests, and to leave the containers running so that you can continue to use them.
```shell
gitlab-qa Test::Integration::GitalyCluster EE --no-tests
```
When all the containers are running, the output of the `docker ps` command shows which ports the GitLab container can be accessed on. For example:
```plaintext
CONTAINER ID ... PORTS NAMES
d15d3386a0a8 ... 22/tcp, 443/tcp, 0.0.0.0:32772->80/tcp gitlab-gitaly-cluster
```
That shows that the GitLab instance running in the `gitlab-gitaly-cluster` container can be reached via `http://localhost:32772`. However, Git operations like cloning and pushing are performed against the URL revealed via the UI as the clone URL. It uses the hostname configured for the GitLab instance, which in this case matches the Docker container name and network, `gitlab-gitaly-cluster.test`. Before you can run the tests you need to configure your computer to access the container via that address. One option is to [use Caddy server as described for running tests against GDK](https://gitlab.com/gitlab-org/gitlab-qa/-/blob/master/docs/run_qa_against_gdk.md#workarounds).
Another option is to use NGINX.
In both cases you must configure your machine to translate `gitlab-gitaly-cluster.test` into an appropriate IP address:
```shell
echo '127.0.0.1 gitlab-gitaly-cluster.test' | sudo tee -a /etc/hosts
```
Then install NGINX:
```shell
# on macOS
brew install nginx
# on Debian/Ubuntu
apt install nginx
# on Fedora
yum install nginx
```
Finally, configure NGINX to pass requests for `gitlab-gitaly-cluster.test` to the GitLab instance:
```plaintext
# On Debian/Ubuntu, in /etc/nginx/sites-enabled/gitlab-cluster
# On macOS, in /usr/local/etc/nginx/nginx.conf
server {
server_name gitlab-gitaly-cluster.test;
client_max_body_size 500m;
location / {
proxy_pass http://127.0.0.1:32772;
proxy_set_header Host gitlab-gitaly-cluster.test;
}
}
```
Restart NGINX for the configuration to take effect. For example:
```shell
# On Debian/Ubuntu
sudo systemctl restart nginx
# on macOS
sudo nginx -s reload
```
You could then run the tests from the `/qa` directory:
```shell
WEBDRIVER_HEADLESS=false bin/qa Test::Instance::All http://gitlab-gitaly-cluster.test -- --tag gitaly_cluster
```
Once you have finished testing you can stop and remove the Docker containers:
```shell
docker stop gitlab-gitaly-cluster praefect postgres gitaly3 gitaly2 gitaly1
docker rm gitlab-gitaly-cluster praefect postgres gitaly3 gitaly2 gitaly1
```
## Tests that require a runner
To execute tests that use a runner without errors, while creating the GitLab Docker instance the `--hostname` parameter in the Docker `run` command should be given a specific interface IP address or a non-loopback hostname accessible from the runner container. Having `localhost` (or `127.0.0.1`) as the GitLab hostname won't work (unless the GitLab Runner is created with the Docker network as `host`)
Examples of tests which require a runner:
- `qa/qa/specs/features/ee/browser_ui/13_secure/create_merge_request_with_secure_spec.rb`
- `qa/qa/specs/features/browser_ui/4_verify/runner/register_runner_spec.rb`
Example:
```shell
docker run \
--detach \
--hostname interface_ip_address \
--publish 80:80 \
--name gitlab \
--restart always \
--volume ~/ee_volume/config:/etc/gitlab \
--volume ~/ee_volume/logs:/var/log/gitlab \
--volume ~/ee_volume/data:/var/opt/gitlab \
--shm-size 256m \
gitlab/gitlab-ee:latest
```
Where `interface_ip_address` is your local network's interface IP, which you can find with the `ifconfig` command.
The same would apply to GDK running with the instance address as `localhost` too.
## Geo tests
Geo end-to-end tests can run locally against a [Geo GDK setup](https://gitlab.com/gitlab-org/gitlab-development-kit/-/blob/main/doc/howto/geo.md) or on Geo spun up in Docker containers.
### Using Geo GDK
Run from the [`qa/` directory](https://gitlab.com/gitlab-org/gitlab/-/blob/f7272b77e80215c39d1ffeaed27794c220dbe03f/qa) with both GDK Geo primary and Geo secondary instances running:
```shell
WEBDRIVER_HEADLESS=false bundle exec bin/qa QA::EE::Scenario::Test::Geo --primary-address http://localhost:3001 --secondary-address http://localhost:3002 --without-setup
```
### Using Geo in Docker
You can use [GitLab-QA Orchestrator](https://gitlab.com/gitlab-org/gitlab-qa) to orchestrate two GitLab containers and configure them as a Geo setup.
Geo requires an EE license. To visit the Geo sites in your browser, you need a reverse proxy server (for example, [NGINX](https://www.f5.com/go/product/welcome-to-nginx)).
1. Export your EE license
```shell
export EE_LICENSE=$(cat <path/to/your/gitlab_license>)
```
1. Optional. Pull the GitLab image
This step is optional because pulling the Docker image is part of the [`Test::Integration::Geo` orchestrated scenario](https://gitlab.com/gitlab-org/gitlab-qa/-/blob/d8c5c40607c2be0eda58bbca1b9f534b00889a0b/lib/gitlab/qa/scenario/test/integration/geo.rb). However, it's easier to monitor the download progress if you pull the image first, and the scenario skips this step after checking that the image is up to date.
```shell
# For the most recent nightly image
docker pull gitlab/gitlab-ee:nightly
# For a specific release
docker pull gitlab/gitlab-ee:13.0.10-ee.0
# For a specific image
docker pull registry.gitlab.com/gitlab-org/build/omnibus-gitlab-mirror/gitlab-ee:examplesha123456789
```
1. Run the [`Test::Integration::Geo` orchestrated scenario](https://gitlab.com/gitlab-org/gitlab-qa/-/blob/d8c5c40607c2be0eda58bbca1b9f534b00889a0b/lib/gitlab/qa/scenario/test/integration/geo.rb) with the `--no-teardown` option to build the GitLab containers, configure the Geo setup, and run Geo end-to-end tests. Running the tests after the Geo setup is complete is optional; the containers keep running after you stop the tests.
```shell
# Using the most recent nightly image
gitlab-qa Test::Integration::Geo EE --no-teardown
# Using a specific GitLab release
gitlab-qa Test::Integration::Geo EE:13.0.10-ee.0 --no-teardown
# Using a full image address
GITLAB_QA_ACCESS_TOKEN=your-token-here gitlab-qa Test::Integration::Geo registry.gitlab.com/gitlab-org/build/omnibus-gitlab-mirror/gitlab-ee:examplesha123456789 --no-teardown
```
You can use the `--no-tests` option to build the containers only, and then run the [`EE::Scenario::Test::Geo` scenario](https://gitlab.com/gitlab-org/gitlab/-/blob/f7272b77e80215c39d1ffeaed27794c220dbe03f/qa/qa/ee/scenario/test/geo.rb) from your GDK to complete setup and run tests. However, there might be configuration issues if your GDK and the containers are based on different GitLab versions. With the `--no-teardown` option, GitLab-QA uses the same GitLab version for the GitLab containers and the GitLab QA container used to configure the Geo setup.
1. To visit the Geo sites in your browser, proxy requests to the hostnames used inside the containers. NGINX is used as the reverse proxy server for this example.
_Map the hostnames to the local IP in `/etc/hosts` file on your machine:_
```plaintext
127.0.0.1 gitlab-primary.geo gitlab-secondary.geo
```
_Note the assigned ports:_
```shell
$ docker port gitlab-primary
80/tcp -> 0.0.0.0:32768
$ docker port gitlab-secondary
80/tcp -> 0.0.0.0:32769
```
_Configure the reverse proxy server with the assigned ports in `nginx.conf` file (usually found in `/usr/local/etc/nginx` on a Mac):_
```plaintext
server {
server_name gitlab-primary.geo;
location / {
proxy_pass http://localhost:32768; # Change port to your assigned port
proxy_set_header Host gitlab-primary.geo;
}
}
server {
server_name gitlab-secondary.geo;
location / {
proxy_pass http://localhost:32769; # Change port to your assigned port
proxy_set_header Host gitlab-secondary.geo;
}
}
```
_Start or reload the reverse proxy server:_
```shell
sudo nginx
# or
sudo nginx -s reload
```
1. To run end-to-end tests from your local GDK, run the [`EE::Scenario::Test::Geo` scenario](https://gitlab.com/gitlab-org/gitlab/-/blob/f7272b77e80215c39d1ffeaed27794c220dbe03f/qa/qa/ee/scenario/test/geo.rb) from the [`gitlab/qa/` directory](https://gitlab.com/gitlab-org/gitlab/-/blob/f7272b77e80215c39d1ffeaed27794c220dbe03f/qa). Include `--without-setup` to skip the Geo configuration steps.
```shell
QA_LOG_LEVEL=debug GITLAB_QA_ACCESS_TOKEN=[add token here] GITLAB_QA_ADMIN_ACCESS_TOKEN=[add token here] bundle exec bin/qa QA::EE::Scenario::Test::Geo \
--primary-address http://gitlab-primary.geo \
--secondary-address http://gitlab-secondary.geo \
--without-setup
```
If the containers need to be configured first (for example, if you used the `--no-tests` option in the previous step), run the `QA::EE::Scenario::Test::Geo scenario` as shown below to first do the Geo configuration steps, and then run Geo end-to-end tests. Make sure that `EE_LICENSE` is (still) defined in your shell session.
```shell
QA_LOG_LEVEL=debug bundle exec bin/qa QA::EE::Scenario::Test::Geo \
--primary-address http://gitlab-primary.geo \
--primary-name gitlab-primary \
--secondary-address http://gitlab-secondary.geo \
--secondary-name gitlab-secondary
```
1. Stop and remove containers
```shell
docker stop gitlab-primary gitlab-secondary
docker rm gitlab-primary gitlab-secondary
```
#### Notes
- You can find the full image address from a pipeline by [following these instructions](https://handbook.gitlab.com/handbook/engineering/infrastructure/test-platform/tips-and-tricks/#running-gitlab-qa-pipeline-against-a-specific-gitlab-release). You might be prompted to set the `GITLAB_QA_ACCESS_TOKEN` variable if you specify the full image address.
- You can increase the wait time for replication by setting `GEO_MAX_FILE_REPLICATION_TIME` and `GEO_MAX_DB_REPLICATION_TIME`. The default is 120 seconds.
- To save time during tests, create a personal access token with API access on the Geo primary node, and pass that value in as `GITLAB_QA_ACCESS_TOKEN` and `GITLAB_QA_ADMIN_ACCESS_TOKEN`.
## Group SAML Tests
Tests that are tagged with `:group_saml` meta are orchestrated tests where the user accesses a group via SAML SSO.
These tests depend on a SAML IDP Docker container ([jamedjo/test-SAML-idp](https://hub.docker.com/r/jamedjo/test-saml-idp)). The tests spin up the container themselves.
To run these tests on your computer against the GDK:
1. Add these settings to your `gitlab.yml` file:
```yaml
omniauth:
enabled: true
providers:
- { name: 'group_saml' }
```
1. Run a group SAML test from [`gitlab/qa`](https://gitlab.com/gitlab-org/gitlab/-/tree/d5447ebb5f99d4c72780681ddf4dc25b0738acba/qa) directory:
```shell
QA_DEBUG=true CHROME_HEADLESS=false bundle exec bin/qa Test::Instance::All http://localhost:3000 qa/specs/features/ee/browser_ui/1_manage/group/group_saml_enforced_sso_spec.rb -- --tag orchestrated
```
For instructions on how to run these tests using the `gitlab-qa` gem, refer to [the GitLab QA documentation](https://gitlab.com/gitlab-org/gitlab-qa/-/blob/master/docs/what_tests_can_be_run.md#testintegrationgroupsaml-eefull-image-address).
## Instance SAML Tests
Tests that are tagged with `:instance_saml` meta are orchestrated tests where the instance level sign-in happens using SAML SSO.
These tests require a SAML IDP Docker container ([jamedjo/test-SAML-idp](https://hub.docker.com/r/jamedjo/test-saml-idp)) to be configured and running.
To run these tests on your computer against the GDK:
1. Add these settings to your `gitlab.yml` file:
```yaml
omniauth:
enabled: true
allow_single_sign_on: ["saml"]
block_auto_created_users: false
auto_link_saml_user: true
providers:
- { name: 'saml',
args: {
assertion_consumer_service_url: 'http://gdk.test:3000/users/auth/saml/callback',
idp_cert_fingerprint: '11:9b:9e:02:79:59:cd:b7:c6:62:cf:d0:75:d9:e2:ef:38:4e:44:5f',
idp_sso_target_url: 'https://gdk.test:8443/simplesaml/saml2/idp/SSOService.php',
issuer: 'http://gdk.test:3000',
name_identifier_format: 'urn:oasis:names:tc:SAML:2.0:nameid-format:persistent'
} }
```
1. Start the SAML IDP Docker container:
```shell
docker run --name=group_saml_qa_idp -p 8080:8080 -p 8443:8443 \
-e SIMPLESAMLPHP_SP_ENTITY_ID=http://localhost:3000 \
-e SIMPLESAMLPHP_SP_ASSERTION_CONSUMER_SERVICE=http://localhost:3000/users/auth/saml/callback \
-d jamedjo/test-saml-idp
```
1. Run the test from [`gitlab/qa`](https://gitlab.com/gitlab-org/gitlab/-/tree/d5447ebb5f99d4c72780681ddf4dc25b0738acba/qa) directory:
```shell
QA_DEBUG=true CHROME_HEADLESS=false bundle exec bin/qa Test::Instance::All http://localhost:3000 qa/specs/features/browser_ui/1_manage/login/login_via_instance_wide_saml_sso_spec.rb -- --tag orchestrated
```
For instructions on how to run these tests using the `gitlab-qa` gem, refer to [the GitLab QA documentation](https://gitlab.com/gitlab-org/gitlab-qa/-/blob/master/docs/what_tests_can_be_run.md#testintegrationinstancesaml-ceeefull-image-address).
## LDAP Tests
Tests that are tagged with `:ldap_tls` and `:ldap_no_tls` meta are orchestrated tests where the sign-in happens via LDAP.
These tests spin up a Docker container [(`osixia/openldap`)](https://hub.docker.com/r/osixia/openldap) running an instance of [OpenLDAP](https://www.openldap.org/).
The container uses fixtures [checked into the GitLab-QA repository](https://gitlab.com/gitlab-org/gitlab-qa/-/tree/9ffb9ad3be847a9054967d792d6772a74220fb42/fixtures/ldap) to create
base data such as users and groups including the administrator group. The password for [all users](https://gitlab.com/gitlab-org/gitlab-qa/-/blob/9ffb9ad3be847a9054967d792d6772a74220fb42/fixtures/ldap/2_add_users.ldif) including [the `tanuki` user](https://gitlab.com/gitlab-org/gitlab-qa/-/blob/9ffb9ad3be847a9054967d792d6772a74220fb42/fixtures/ldap/tanuki.ldif) is `password`.
A GitLab instance is also created in a Docker container based on our [LDAP setup](../../../../administration/auth/ldap/_index.md) documentation.
Tests that are tagged `:ldap_tls` enable TLS on GitLab using the certificate [checked into the GitLab-QA repository](https://gitlab.com/gitlab-org/gitlab-qa/-/tree/9ffb9ad3be847a9054967d792d6772a74220fb42/tls_certificates/gitlab).
The certificate was generated with OpenSSL using this command:
```shell
openssl req -x509 -newkey rsa:4096 -keyout gitlab.test.key -out gitlab.test.crt -days 3650 -nodes -subj "/C=US/ST=CA/L=San Francisco/O=GitLab/OU=Org/CN=gitlab.test"
```
The OpenLDAP container also uses its [auto-generated TLS certificates](https://github.com/osixia/docker-openldap#use-auto-generated-certificate).
### Running LDAP tests with TLS enabled
To run the LDAP tests on your local with TLS enabled, follow these steps:
1. Include the following entry in your `/etc/hosts` file:
`127.0.0.1 gitlab.test`
You can then run tests against GitLab in a Docker container on `https://gitlab.test`. The TLS certificate [checked into the GitLab-QA repository](https://gitlab.com/gitlab-org/gitlab-qa/-/tree/9ffb9ad3be847a9054967d792d6772a74220fb42/tls_certificates/gitlab) is configured for this domain.
1. Run the OpenLDAP container with TLS enabled. Change the path to [`gitlab-qa/fixtures/ldap`](https://gitlab.com/gitlab-org/gitlab-qa/-/tree/9ffb9ad3be847a9054967d792d6772a74220fb42/fixtures/ldap) directory to your local checkout path:
```shell
docker network create test && docker run --name ldap-server --net test --hostname ldap-server.test --volume /path/to/gitlab-qa/fixtures/ldap:/container/service/slapd/assets/config/bootstrap/ldif/custom:Z --env LDAP_TLS_CRT_FILENAME="ldap-server.test.crt" --env LDAP_TLS_KEY_FILENAME="ldap-server.test.key" --env LDAP_TLS_ENFORCE="true" --env LDAP_TLS_VERIFY_CLIENT="never" osixia/openldap:latest --copy-service
```
1. Run the GitLab container with TLS enabled. Change the path to [`gitlab-qa/tls_certificates/gitlab`](https://gitlab.com/gitlab-org/gitlab-qa/-/tree/9ffb9ad3be847a9054967d792d6772a74220fb42/tls_certificates/gitlab) directory to your local checkout path:
```shell
sudo docker run \
--hostname gitlab.test \
--net test \
--publish 443:443 --publish 80:80 --publish 22:22 \
--name gitlab \
--volume /path/to/gitlab-qa/tls_certificates/gitlab:/etc/gitlab/ssl \
--env GITLAB_OMNIBUS_CONFIG="gitlab_rails['ldap_enabled'] = true; gitlab_rails['ldap_servers'] = {\"main\"=>{\"label\"=>\"LDAP\", \"host\"=>\"ldap-server.test\", \"port\"=>636, \"uid\"=>\"uid\", \"bind_dn\"=>\"cn=admin,dc=example,dc=org\", \"password\"=>\"admin\", \"encryption\"=>\"simple_tls\", \"verify_certificates\"=>false, \"base\"=>\"dc=example,dc=org\", \"user_filter\"=>\"\", \"group_base\"=>\"ou=Global Groups,dc=example,dc=org\", \"admin_group\"=>\"AdminGroup\", \"external_groups\"=>\"\", \"sync_ssh_keys\"=>false}}; letsencrypt['enable'] = false; external_url 'https://gitlab.test'; gitlab_rails['ldap_sync_worker_cron'] = '* * * * *'; gitlab_rails['ldap_group_sync_worker_cron'] = '* * * * *'; " \
gitlab/gitlab-ee:latest
```
1. Run an LDAP test from [`gitlab/qa`](https://gitlab.com/gitlab-org/gitlab/-/tree/d5447ebb5f99d4c72780681ddf4dc25b0738acba/qa) directory:
```shell
GITLAB_LDAP_USERNAME="tanuki" GITLAB_LDAP_PASSWORD="password" QA_LOG_LEVEL=debug WEBDRIVER_HEADLESS=false bin/qa Test::Instance::All https://gitlab.test qa/specs/features/browser_ui/1_manage/login/log_into_gitlab_via_ldap_spec.rb
```
### Running LDAP tests with TLS disabled
To run the LDAP tests on your local with TLS disabled, follow these steps:
1. Run OpenLDAP container with TLS disabled. Change the path to [`gitlab-qa/fixtures/ldap`](https://gitlab.com/gitlab-org/gitlab-qa/-/tree/9ffb9ad3be847a9054967d792d6772a74220fb42/fixtures/ldap) directory to your local checkout path:
```shell
docker network create test && docker run --net test --publish 389:389 --publish 636:636 --name ldap-server --hostname ldap-server.test --volume /path/to/gitlab-qa/fixtures/ldap:/container/service/slapd/assets/config/bootstrap/ldif/custom:Z --env LDAP_TLS="false" osixia/openldap:latest --copy-service
```
1. Run the GitLab container:
```shell
sudo docker run \
--hostname localhost \
--net test \
--publish 443:443 --publish 80:80 --publish 22:22 \
--name gitlab \
--env GITLAB_OMNIBUS_CONFIG="gitlab_rails['ldap_enabled'] = true; gitlab_rails['ldap_servers'] = {\"main\"=>{\"label\"=>\"LDAP\", \"host\"=>\"ldap-server.test\", \"port\"=>389, \"uid\"=>\"uid\", \"bind_dn\"=>\"cn=admin,dc=example,dc=org\", \"password\"=>\"admin\", \"encryption\"=>\"plain\", \"verify_certificates\"=>false, \"base\"=>\"dc=example,dc=org\", \"user_filter\"=>\"\", \"group_base\"=>\"ou=Global Groups,dc=example,dc=org\", \"admin_group\"=>\"AdminGroup\", \"external_groups\"=>\"\", \"sync_ssh_keys\"=>false}}; gitlab_rails['ldap_sync_worker_cron'] = '* * * * *'; gitlab_rails['ldap_group_sync_worker_cron'] = '* * * * *'; " \
gitlab/gitlab-ee:latest
```
1. Run an LDAP test from [`gitlab/qa`](https://gitlab.com/gitlab-org/gitlab/-/tree/d5447ebb5f99d4c72780681ddf4dc25b0738acba/qa) directory:
```shell
GITLAB_LDAP_USERNAME="tanuki" GITLAB_LDAP_PASSWORD="password" QA_LOG_LEVEL=debug WEBDRIVER_HEADLESS=false bin/qa Test::Instance::All http://localhost qa/specs/features/browser_ui/1_manage/login/log_into_gitlab_via_ldap_spec.rb
```
## SMTP tests
Tests that are tagged with `:smtp` meta tag are orchestrated tests that ensure email notifications are received by a user.
These tests require a GitLab instance with SMTP enabled and integrated with an SMTP server, [MailHog](https://github.com/mailhog/MailHog).
To run these tests locally against the GDK:
1. Add these settings to your `gitlab.yml` file:
```yaml
smtp:
enabled: true
address: "mailhog.test"
port: 1025
```
1. Start MailHog in a Docker container:
```shell
docker network create test && docker run \
--network test \
--hostname mailhog.test \
--name mailhog \
--publish 1025:1025 \
--publish 8025:8025 \
mailhog/mailhog:v1.0.0
```
1. Run the test from [`gitlab/qa`](https://gitlab.com/gitlab-org/gitlab/-/tree/d5447ebb5f99d4c72780681ddf4dc25b0738acba/qa) directory:
```shell
QA_LOG_LEVEL=debug WEBDRIVER_HEADLESS=false bin/qa Test::Instance::All http://localhost:3000 qa/specs/features/browser_ui/2_plan/email/trigger_email_notification_spec.rb -- --tag orchestrated
```
For instructions on how to run these tests using the `gitlab-qa` gem, refer to [the GitLab QA documentation](https://gitlab.com/gitlab-org/gitlab-qa/-/blob/master/docs/what_tests_can_be_run.md#testintegrationsmtp-ceeefull-image-address).
## Targeting canary vs non-canary components in live environments
Use the `QA_COOKIES` ENV variable to have the entire test target a `canary` (`staging-canary` or `canary`) or `non-canary` (`staging` or `production`) environment.
Locally, that would mean prepending the ENV variable to your call to bin/qa. To target the `canary` version of that environment:
```shell
QA_COOKIES="gitlab_canary=true" WEBDRIVER_HEADLESS=false bin/qa Test::Instance::Staging <YOUR SPECIFIC TAGS OR TESTS>
```
Alternatively, you may set the cookie to `false` to ensure the `non-canary` version is targeted.
You can also export the cookie for your current session to avoid prepending it each time:
```shell
export QA_COOKIES="gitlab_canary=true"
```
### Updating the cookie within a running spec
Within a specific test, you can target either the `canary` or `non-canary` nodes within live environments, such as `staging` and `production`.
For example, to switch back and forth between the two environments, you could utilize the `target_canary` method:
```ruby
it 'tests toggling between canary and non-canary nodes' do
Runtime::Browser.visit(:gitlab, Page::Main::Login)
# After starting the browser session, use the target_canary method ...
Runtime::Browser::Session.target_canary(true)
Flow::Login.sign_in
verify_session_on_canary(true)
Runtime::Browser::Session.target_canary(false)
# Refresh the page ...
verify_session_on_canary(false)
# Log out and clean up ...
end
def verify_session_on_canary(enable_canary)
Page::Main::Menu.perform do |menu|
aggregate_failures 'testing session log in' do
expect(menu.canary?).to be(enable_canary)
end
end
end
```
You can verify whether GitLab is appropriately redirecting your session to the `canary` or `non-canary` nodes with the `menu.canary?` method.
The above spec is verbose, written specifically this way to ensure the idea behind the implementation is clear. We recommend following the practices detailed within our [Beginner's guide to writing end-to-end tests](../beginners_guide/_index.md).
## Tests for GitLab as OpenID Connect (OIDC) and OAuth provider
To run the [`login_via_oauth_and_oidc_with_gitlab_as_idp_spec`](https://gitlab.com/gitlab-org/gitlab/-/blob/2e2c8bcfa4f68cd39041806af531038ce4d2ab04/qa/qa/specs/features/browser_ui/1_manage/login/login_via_oauth_and_oidc_with_gitlab_as_idp_spec.rb) on your local machine:
1. Make sure your GDK is set to run on a non-localhost address such as `gdk.test:3000`.
1. Configure a [loopback interface to 172.16.123.1](https://gitlab.com/gitlab-org/gitlab-development-kit/-/blob/6fe7b46403229f12ab6d903f99b024e0b82cb94a/doc/howto/local_network.md#create-loopback-interface).
1. Make sure Docker Desktop or Rancher Desktop is running.
1. Add an entry to your `/etc/hosts` file for `gitlab-oidc-consumer.bridge` and `gitlab-oauth-consumer.bridge` pointing to `127.0.0.1`.
1. From the `qa` directory, run the following command. To set the GitLab image you want to use, update the `RELEASE` variable. For example, to use the latest EE image, set `RELEASE` to `gitlab/gitlab-ee:latest`:
```shell
bundle install
RELEASE_REGISTRY_URL='registry.gitlab.com' RELEASE_REGISTRY_USERNAME='<your_gitlab_username>' RELEASE_REGISTRY_PASSWORD='<your_gitlab_personal_access_token>' RELEASE='registry.gitlab.com/gitlab-org/build/omnibus-gitlab-mirror/gitlab-ee:c0ae46db6b31ea231b2de88961cd687acf634179' GITLAB_QA_ADMIN_ACCESS_TOKEN="<your_gdk_admin_personal_access_token>" QA_DEBUG=true CHROME_HEADLESS=false bundle exec bin/qa Test::Instance::All http://gdk.test:3000 qa/specs/features/browser_ui/1_manage/login/login_via_oauth_and_oidc_with_gitlab_as_idp_spec.rb
```
## Product Analytics tests
Product Analytics e2e tests require Product Analytics services running and connected to your GDK.
In order to run Product Analytics services, devkit can be used. Instructions to set it up and connect to your GDK can be found in the [devkit project's `README.md`](https://gitlab.com/gitlab-org/analytics-section/product-analytics/devkit).
Additionally, the following setup is required on the GDK:
- Set environment variables for product analytics configuration. The following variables are default for running devkit locally.
```shell
export PA_CONFIGURATOR_URL=http://test:test@localhost:4567
export PA_COLLECTOR_HOST=http://localhost:9091
export PA_CUBE_API_URL=http://localhost:4000
export PA_CUBE_API_KEY=thisisnotarealkey43ff15165ce01e4ff47d75092e3b25b2c0b20dc27f6cd5a8aed7b7bd855df88c9e0748d7afd37adda6d981c16177b086acf496bbdc62dbb
```
- Ultimate license applied.
- [How to request the license](https://handbook.gitlab.com/handbook/developer-onboarding/#working-on-gitlab-ee-developer-licenses).
- [How to activate GitLab EE with a license file or key](https://gitlab.com/gitlab-org/gitlab/-/blob/master/doc/administration/license_file.md#activate-gitlab-ee-with-a-license-file-or-key).
- Simulate SaaS enabled. Instructions can be [found here](https://gitlab.com/gitlab-org/gitlab/-/blob/master/doc/development/ee_features.md#simulate-a-saas-instance).
Once Product Analytics services are running and are connected to your GDK, the tests can be executed with:
```shell
bundle exec rspec qa/specs/features/ee/browser_ui/8_monitor/product_analytics/onboarding_spec.rb
```
## Tests that require a global server hook
The [`tag_revision_trigger_prereceive_hook_spec`](https://gitlab.com/gitlab-org/gitlab/-/blob/c3342dac0c6c8e9e11ec049b910eac832600b0bf/qa/qa/specs/features/api/3_create/repository/tag_revision_trigger_prereceive_hook_spec.rb) requires a global server hook to be pre-configured in the target test environment. When running this tests against a local GDK, the server hook will need to be configured with:
```shell
# From the gdk directory
mkdir -p gitaly-custom-hooks/pre-receive.d
cp gitlab/qa/gdk/pre-receive gitaly-custom-hooks/pre-receive.d
chmod +x gitaly-custom-hooks/pre-receive.d/pre-receive
```
More information on global server hooks can be found in the [server hooks documentation](../../../../administration/server_hooks.md#create-the-global-server-hook)
|
---
stage: none
group: unassigned
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: Running tests that require special setup
breadcrumbs:
- doc
- development
- testing_guide
- end_to_end
- running_tests
---
## Jenkins tests
The [`jenkins_build_status_spec`](https://gitlab.com/gitlab-org/gitlab/-/blob/24a86debf49f3aed6f2ecfd6e8f9233b3a214181/qa/qa/specs/features/browser_ui/3_create/jenkins/jenkins_build_status_spec.rb)
spins up a Jenkins instance in a Docker container with the Jenkins GitLab plugin pre-installed. Due to a license restriction we are unable to distribute this image.
To build a QA compatible image, visit the [third party images project](https://gitlab.com/gitlab-org/quality/third-party-docker-public), where third party Dockerfiles can be found.
The project also has instructions for forking and building the images automatically in CI.
Some extra environment variables for the location of the forked repository are also needed.
- `QA_THIRD_PARTY_DOCKER_REGISTRY` (the container registry where the repository/images are hosted, for example `registry.gitlab.com`)
- `QA_THIRD_PARTY_DOCKER_REPOSITORY` (the base repository path where the images are hosted, for example `registry.gitlab.com/<project path>`)
- `QA_THIRD_PARTY_DOCKER_USER` (a username that has access to the container registry for this repository)
- `QA_THIRD_PARTY_DOCKER_PASSWORD` (a password/token for the username to authenticate with)
The test configures the GitLab plugin in Jenkins with a URL of the GitLab instance that are used
to run the tests. Bi-directional networking is needed between a GitLab instance and Jenkins, so GitLab can also be started in a Docker container.
To start a Docker container for GitLab based on the nightly image:
```shell
docker run \
--publish 80:80 \
--name gitlab \
--hostname localhost \
--network test
gitlab/gitlab-ee:nightly
```
To run the tests from the `/qa` directory:
```shell
export QA_THIRD_PARTY_DOCKER_REGISTRY=<registry>
export QA_THIRD_PARTY_DOCKER_REPOSITORY=<repository>
export QA_THIRD_PARTY_DOCKER_USER=<user with registry access>
export QA_THIRD_PARTY_DOCKER_PASSWORD=<password for user>
export WEBDRIVER_HEADLESS=0
bin/qa Test::Instance::All http://localhost -- qa/specs/features/ee/browser_ui/3_create/jenkins/jenkins_build_status_spec.rb
```
The test automatically spins up a Docker container for Jenkins and tear down once the test completes.
If you need to run Jenkins manually outside of the tests, refer to the README for the
[third party images project](https://gitlab.com/gitlab-org/quality/third-party-docker-public/-/blob/main/jenkins/README.md)
### Troubleshooting
If Jenkins Docker container exits without providing any information in the logs, try increasing the memory used by
the Docker Engine.
## Gitaly Cluster (Praefect) tests
The tests tagged `:gitaly_ha` are orchestrated tests that can only be run against a set of Docker containers as configured and started by [the `Test::Integration::GitalyCluster` GitLab QA scenario](https://gitlab.com/gitlab-org/gitlab-qa/-/blob/master/docs/what_tests_can_be_run.md#testintegrationgitalycluster-ceeefull-image-address).
As described in the documentation about the scenario noted above, the following command runs the tests:
```shell
gitlab-qa Test::Integration::GitalyCluster EE
```
However, that removes the containers after it finishes running the tests. If you would like to do further testing, for example, if you would like to run a single test via a debugger, you can use [the `--no-tests` option](https://gitlab.com/gitlab-org/gitlab-qa#command-line-options) to make `gitlab-qa` skip running the tests, and to leave the containers running so that you can continue to use them.
```shell
gitlab-qa Test::Integration::GitalyCluster EE --no-tests
```
When all the containers are running, the output of the `docker ps` command shows which ports the GitLab container can be accessed on. For example:
```plaintext
CONTAINER ID ... PORTS NAMES
d15d3386a0a8 ... 22/tcp, 443/tcp, 0.0.0.0:32772->80/tcp gitlab-gitaly-cluster
```
That shows that the GitLab instance running in the `gitlab-gitaly-cluster` container can be reached via `http://localhost:32772`. However, Git operations like cloning and pushing are performed against the URL revealed via the UI as the clone URL. It uses the hostname configured for the GitLab instance, which in this case matches the Docker container name and network, `gitlab-gitaly-cluster.test`. Before you can run the tests you need to configure your computer to access the container via that address. One option is to [use Caddy server as described for running tests against GDK](https://gitlab.com/gitlab-org/gitlab-qa/-/blob/master/docs/run_qa_against_gdk.md#workarounds).
Another option is to use NGINX.
In both cases you must configure your machine to translate `gitlab-gitaly-cluster.test` into an appropriate IP address:
```shell
echo '127.0.0.1 gitlab-gitaly-cluster.test' | sudo tee -a /etc/hosts
```
Then install NGINX:
```shell
# on macOS
brew install nginx
# on Debian/Ubuntu
apt install nginx
# on Fedora
yum install nginx
```
Finally, configure NGINX to pass requests for `gitlab-gitaly-cluster.test` to the GitLab instance:
```plaintext
# On Debian/Ubuntu, in /etc/nginx/sites-enabled/gitlab-cluster
# On macOS, in /usr/local/etc/nginx/nginx.conf
server {
server_name gitlab-gitaly-cluster.test;
client_max_body_size 500m;
location / {
proxy_pass http://127.0.0.1:32772;
proxy_set_header Host gitlab-gitaly-cluster.test;
}
}
```
Restart NGINX for the configuration to take effect. For example:
```shell
# On Debian/Ubuntu
sudo systemctl restart nginx
# on macOS
sudo nginx -s reload
```
You could then run the tests from the `/qa` directory:
```shell
WEBDRIVER_HEADLESS=false bin/qa Test::Instance::All http://gitlab-gitaly-cluster.test -- --tag gitaly_cluster
```
Once you have finished testing you can stop and remove the Docker containers:
```shell
docker stop gitlab-gitaly-cluster praefect postgres gitaly3 gitaly2 gitaly1
docker rm gitlab-gitaly-cluster praefect postgres gitaly3 gitaly2 gitaly1
```
## Tests that require a runner
To execute tests that use a runner without errors, while creating the GitLab Docker instance the `--hostname` parameter in the Docker `run` command should be given a specific interface IP address or a non-loopback hostname accessible from the runner container. Having `localhost` (or `127.0.0.1`) as the GitLab hostname won't work (unless the GitLab Runner is created with the Docker network as `host`)
Examples of tests which require a runner:
- `qa/qa/specs/features/ee/browser_ui/13_secure/create_merge_request_with_secure_spec.rb`
- `qa/qa/specs/features/browser_ui/4_verify/runner/register_runner_spec.rb`
Example:
```shell
docker run \
--detach \
--hostname interface_ip_address \
--publish 80:80 \
--name gitlab \
--restart always \
--volume ~/ee_volume/config:/etc/gitlab \
--volume ~/ee_volume/logs:/var/log/gitlab \
--volume ~/ee_volume/data:/var/opt/gitlab \
--shm-size 256m \
gitlab/gitlab-ee:latest
```
Where `interface_ip_address` is your local network's interface IP, which you can find with the `ifconfig` command.
The same would apply to GDK running with the instance address as `localhost` too.
## Geo tests
Geo end-to-end tests can run locally against a [Geo GDK setup](https://gitlab.com/gitlab-org/gitlab-development-kit/-/blob/main/doc/howto/geo.md) or on Geo spun up in Docker containers.
### Using Geo GDK
Run from the [`qa/` directory](https://gitlab.com/gitlab-org/gitlab/-/blob/f7272b77e80215c39d1ffeaed27794c220dbe03f/qa) with both GDK Geo primary and Geo secondary instances running:
```shell
WEBDRIVER_HEADLESS=false bundle exec bin/qa QA::EE::Scenario::Test::Geo --primary-address http://localhost:3001 --secondary-address http://localhost:3002 --without-setup
```
### Using Geo in Docker
You can use [GitLab-QA Orchestrator](https://gitlab.com/gitlab-org/gitlab-qa) to orchestrate two GitLab containers and configure them as a Geo setup.
Geo requires an EE license. To visit the Geo sites in your browser, you need a reverse proxy server (for example, [NGINX](https://www.f5.com/go/product/welcome-to-nginx)).
1. Export your EE license
```shell
export EE_LICENSE=$(cat <path/to/your/gitlab_license>)
```
1. Optional. Pull the GitLab image
This step is optional because pulling the Docker image is part of the [`Test::Integration::Geo` orchestrated scenario](https://gitlab.com/gitlab-org/gitlab-qa/-/blob/d8c5c40607c2be0eda58bbca1b9f534b00889a0b/lib/gitlab/qa/scenario/test/integration/geo.rb). However, it's easier to monitor the download progress if you pull the image first, and the scenario skips this step after checking that the image is up to date.
```shell
# For the most recent nightly image
docker pull gitlab/gitlab-ee:nightly
# For a specific release
docker pull gitlab/gitlab-ee:13.0.10-ee.0
# For a specific image
docker pull registry.gitlab.com/gitlab-org/build/omnibus-gitlab-mirror/gitlab-ee:examplesha123456789
```
1. Run the [`Test::Integration::Geo` orchestrated scenario](https://gitlab.com/gitlab-org/gitlab-qa/-/blob/d8c5c40607c2be0eda58bbca1b9f534b00889a0b/lib/gitlab/qa/scenario/test/integration/geo.rb) with the `--no-teardown` option to build the GitLab containers, configure the Geo setup, and run Geo end-to-end tests. Running the tests after the Geo setup is complete is optional; the containers keep running after you stop the tests.
```shell
# Using the most recent nightly image
gitlab-qa Test::Integration::Geo EE --no-teardown
# Using a specific GitLab release
gitlab-qa Test::Integration::Geo EE:13.0.10-ee.0 --no-teardown
# Using a full image address
GITLAB_QA_ACCESS_TOKEN=your-token-here gitlab-qa Test::Integration::Geo registry.gitlab.com/gitlab-org/build/omnibus-gitlab-mirror/gitlab-ee:examplesha123456789 --no-teardown
```
You can use the `--no-tests` option to build the containers only, and then run the [`EE::Scenario::Test::Geo` scenario](https://gitlab.com/gitlab-org/gitlab/-/blob/f7272b77e80215c39d1ffeaed27794c220dbe03f/qa/qa/ee/scenario/test/geo.rb) from your GDK to complete setup and run tests. However, there might be configuration issues if your GDK and the containers are based on different GitLab versions. With the `--no-teardown` option, GitLab-QA uses the same GitLab version for the GitLab containers and the GitLab QA container used to configure the Geo setup.
1. To visit the Geo sites in your browser, proxy requests to the hostnames used inside the containers. NGINX is used as the reverse proxy server for this example.
_Map the hostnames to the local IP in `/etc/hosts` file on your machine:_
```plaintext
127.0.0.1 gitlab-primary.geo gitlab-secondary.geo
```
_Note the assigned ports:_
```shell
$ docker port gitlab-primary
80/tcp -> 0.0.0.0:32768
$ docker port gitlab-secondary
80/tcp -> 0.0.0.0:32769
```
_Configure the reverse proxy server with the assigned ports in `nginx.conf` file (usually found in `/usr/local/etc/nginx` on a Mac):_
```plaintext
server {
server_name gitlab-primary.geo;
location / {
proxy_pass http://localhost:32768; # Change port to your assigned port
proxy_set_header Host gitlab-primary.geo;
}
}
server {
server_name gitlab-secondary.geo;
location / {
proxy_pass http://localhost:32769; # Change port to your assigned port
proxy_set_header Host gitlab-secondary.geo;
}
}
```
_Start or reload the reverse proxy server:_
```shell
sudo nginx
# or
sudo nginx -s reload
```
1. To run end-to-end tests from your local GDK, run the [`EE::Scenario::Test::Geo` scenario](https://gitlab.com/gitlab-org/gitlab/-/blob/f7272b77e80215c39d1ffeaed27794c220dbe03f/qa/qa/ee/scenario/test/geo.rb) from the [`gitlab/qa/` directory](https://gitlab.com/gitlab-org/gitlab/-/blob/f7272b77e80215c39d1ffeaed27794c220dbe03f/qa). Include `--without-setup` to skip the Geo configuration steps.
```shell
QA_LOG_LEVEL=debug GITLAB_QA_ACCESS_TOKEN=[add token here] GITLAB_QA_ADMIN_ACCESS_TOKEN=[add token here] bundle exec bin/qa QA::EE::Scenario::Test::Geo \
--primary-address http://gitlab-primary.geo \
--secondary-address http://gitlab-secondary.geo \
--without-setup
```
If the containers need to be configured first (for example, if you used the `--no-tests` option in the previous step), run the `QA::EE::Scenario::Test::Geo scenario` as shown below to first do the Geo configuration steps, and then run Geo end-to-end tests. Make sure that `EE_LICENSE` is (still) defined in your shell session.
```shell
QA_LOG_LEVEL=debug bundle exec bin/qa QA::EE::Scenario::Test::Geo \
--primary-address http://gitlab-primary.geo \
--primary-name gitlab-primary \
--secondary-address http://gitlab-secondary.geo \
--secondary-name gitlab-secondary
```
1. Stop and remove containers
```shell
docker stop gitlab-primary gitlab-secondary
docker rm gitlab-primary gitlab-secondary
```
#### Notes
- You can find the full image address from a pipeline by [following these instructions](https://handbook.gitlab.com/handbook/engineering/infrastructure/test-platform/tips-and-tricks/#running-gitlab-qa-pipeline-against-a-specific-gitlab-release). You might be prompted to set the `GITLAB_QA_ACCESS_TOKEN` variable if you specify the full image address.
- You can increase the wait time for replication by setting `GEO_MAX_FILE_REPLICATION_TIME` and `GEO_MAX_DB_REPLICATION_TIME`. The default is 120 seconds.
- To save time during tests, create a personal access token with API access on the Geo primary node, and pass that value in as `GITLAB_QA_ACCESS_TOKEN` and `GITLAB_QA_ADMIN_ACCESS_TOKEN`.
## Group SAML Tests
Tests that are tagged with `:group_saml` meta are orchestrated tests where the user accesses a group via SAML SSO.
These tests depend on a SAML IDP Docker container ([jamedjo/test-SAML-idp](https://hub.docker.com/r/jamedjo/test-saml-idp)). The tests spin up the container themselves.
To run these tests on your computer against the GDK:
1. Add these settings to your `gitlab.yml` file:
```yaml
omniauth:
enabled: true
providers:
- { name: 'group_saml' }
```
1. Run a group SAML test from [`gitlab/qa`](https://gitlab.com/gitlab-org/gitlab/-/tree/d5447ebb5f99d4c72780681ddf4dc25b0738acba/qa) directory:
```shell
QA_DEBUG=true CHROME_HEADLESS=false bundle exec bin/qa Test::Instance::All http://localhost:3000 qa/specs/features/ee/browser_ui/1_manage/group/group_saml_enforced_sso_spec.rb -- --tag orchestrated
```
For instructions on how to run these tests using the `gitlab-qa` gem, refer to [the GitLab QA documentation](https://gitlab.com/gitlab-org/gitlab-qa/-/blob/master/docs/what_tests_can_be_run.md#testintegrationgroupsaml-eefull-image-address).
## Instance SAML Tests
Tests that are tagged with `:instance_saml` meta are orchestrated tests where the instance level sign-in happens using SAML SSO.
These tests require a SAML IDP Docker container ([jamedjo/test-SAML-idp](https://hub.docker.com/r/jamedjo/test-saml-idp)) to be configured and running.
To run these tests on your computer against the GDK:
1. Add these settings to your `gitlab.yml` file:
```yaml
omniauth:
enabled: true
allow_single_sign_on: ["saml"]
block_auto_created_users: false
auto_link_saml_user: true
providers:
- { name: 'saml',
args: {
assertion_consumer_service_url: 'http://gdk.test:3000/users/auth/saml/callback',
idp_cert_fingerprint: '11:9b:9e:02:79:59:cd:b7:c6:62:cf:d0:75:d9:e2:ef:38:4e:44:5f',
idp_sso_target_url: 'https://gdk.test:8443/simplesaml/saml2/idp/SSOService.php',
issuer: 'http://gdk.test:3000',
name_identifier_format: 'urn:oasis:names:tc:SAML:2.0:nameid-format:persistent'
} }
```
1. Start the SAML IDP Docker container:
```shell
docker run --name=group_saml_qa_idp -p 8080:8080 -p 8443:8443 \
-e SIMPLESAMLPHP_SP_ENTITY_ID=http://localhost:3000 \
-e SIMPLESAMLPHP_SP_ASSERTION_CONSUMER_SERVICE=http://localhost:3000/users/auth/saml/callback \
-d jamedjo/test-saml-idp
```
1. Run the test from [`gitlab/qa`](https://gitlab.com/gitlab-org/gitlab/-/tree/d5447ebb5f99d4c72780681ddf4dc25b0738acba/qa) directory:
```shell
QA_DEBUG=true CHROME_HEADLESS=false bundle exec bin/qa Test::Instance::All http://localhost:3000 qa/specs/features/browser_ui/1_manage/login/login_via_instance_wide_saml_sso_spec.rb -- --tag orchestrated
```
For instructions on how to run these tests using the `gitlab-qa` gem, refer to [the GitLab QA documentation](https://gitlab.com/gitlab-org/gitlab-qa/-/blob/master/docs/what_tests_can_be_run.md#testintegrationinstancesaml-ceeefull-image-address).
## LDAP Tests
Tests that are tagged with `:ldap_tls` and `:ldap_no_tls` meta are orchestrated tests where the sign-in happens via LDAP.
These tests spin up a Docker container [(`osixia/openldap`)](https://hub.docker.com/r/osixia/openldap) running an instance of [OpenLDAP](https://www.openldap.org/).
The container uses fixtures [checked into the GitLab-QA repository](https://gitlab.com/gitlab-org/gitlab-qa/-/tree/9ffb9ad3be847a9054967d792d6772a74220fb42/fixtures/ldap) to create
base data such as users and groups including the administrator group. The password for [all users](https://gitlab.com/gitlab-org/gitlab-qa/-/blob/9ffb9ad3be847a9054967d792d6772a74220fb42/fixtures/ldap/2_add_users.ldif) including [the `tanuki` user](https://gitlab.com/gitlab-org/gitlab-qa/-/blob/9ffb9ad3be847a9054967d792d6772a74220fb42/fixtures/ldap/tanuki.ldif) is `password`.
A GitLab instance is also created in a Docker container based on our [LDAP setup](../../../../administration/auth/ldap/_index.md) documentation.
Tests that are tagged `:ldap_tls` enable TLS on GitLab using the certificate [checked into the GitLab-QA repository](https://gitlab.com/gitlab-org/gitlab-qa/-/tree/9ffb9ad3be847a9054967d792d6772a74220fb42/tls_certificates/gitlab).
The certificate was generated with OpenSSL using this command:
```shell
openssl req -x509 -newkey rsa:4096 -keyout gitlab.test.key -out gitlab.test.crt -days 3650 -nodes -subj "/C=US/ST=CA/L=San Francisco/O=GitLab/OU=Org/CN=gitlab.test"
```
The OpenLDAP container also uses its [auto-generated TLS certificates](https://github.com/osixia/docker-openldap#use-auto-generated-certificate).
### Running LDAP tests with TLS enabled
To run the LDAP tests on your local with TLS enabled, follow these steps:
1. Include the following entry in your `/etc/hosts` file:
`127.0.0.1 gitlab.test`
You can then run tests against GitLab in a Docker container on `https://gitlab.test`. The TLS certificate [checked into the GitLab-QA repository](https://gitlab.com/gitlab-org/gitlab-qa/-/tree/9ffb9ad3be847a9054967d792d6772a74220fb42/tls_certificates/gitlab) is configured for this domain.
1. Run the OpenLDAP container with TLS enabled. Change the path to [`gitlab-qa/fixtures/ldap`](https://gitlab.com/gitlab-org/gitlab-qa/-/tree/9ffb9ad3be847a9054967d792d6772a74220fb42/fixtures/ldap) directory to your local checkout path:
```shell
docker network create test && docker run --name ldap-server --net test --hostname ldap-server.test --volume /path/to/gitlab-qa/fixtures/ldap:/container/service/slapd/assets/config/bootstrap/ldif/custom:Z --env LDAP_TLS_CRT_FILENAME="ldap-server.test.crt" --env LDAP_TLS_KEY_FILENAME="ldap-server.test.key" --env LDAP_TLS_ENFORCE="true" --env LDAP_TLS_VERIFY_CLIENT="never" osixia/openldap:latest --copy-service
```
1. Run the GitLab container with TLS enabled. Change the path to [`gitlab-qa/tls_certificates/gitlab`](https://gitlab.com/gitlab-org/gitlab-qa/-/tree/9ffb9ad3be847a9054967d792d6772a74220fb42/tls_certificates/gitlab) directory to your local checkout path:
```shell
sudo docker run \
--hostname gitlab.test \
--net test \
--publish 443:443 --publish 80:80 --publish 22:22 \
--name gitlab \
--volume /path/to/gitlab-qa/tls_certificates/gitlab:/etc/gitlab/ssl \
--env GITLAB_OMNIBUS_CONFIG="gitlab_rails['ldap_enabled'] = true; gitlab_rails['ldap_servers'] = {\"main\"=>{\"label\"=>\"LDAP\", \"host\"=>\"ldap-server.test\", \"port\"=>636, \"uid\"=>\"uid\", \"bind_dn\"=>\"cn=admin,dc=example,dc=org\", \"password\"=>\"admin\", \"encryption\"=>\"simple_tls\", \"verify_certificates\"=>false, \"base\"=>\"dc=example,dc=org\", \"user_filter\"=>\"\", \"group_base\"=>\"ou=Global Groups,dc=example,dc=org\", \"admin_group\"=>\"AdminGroup\", \"external_groups\"=>\"\", \"sync_ssh_keys\"=>false}}; letsencrypt['enable'] = false; external_url 'https://gitlab.test'; gitlab_rails['ldap_sync_worker_cron'] = '* * * * *'; gitlab_rails['ldap_group_sync_worker_cron'] = '* * * * *'; " \
gitlab/gitlab-ee:latest
```
1. Run an LDAP test from [`gitlab/qa`](https://gitlab.com/gitlab-org/gitlab/-/tree/d5447ebb5f99d4c72780681ddf4dc25b0738acba/qa) directory:
```shell
GITLAB_LDAP_USERNAME="tanuki" GITLAB_LDAP_PASSWORD="password" QA_LOG_LEVEL=debug WEBDRIVER_HEADLESS=false bin/qa Test::Instance::All https://gitlab.test qa/specs/features/browser_ui/1_manage/login/log_into_gitlab_via_ldap_spec.rb
```
### Running LDAP tests with TLS disabled
To run the LDAP tests on your local with TLS disabled, follow these steps:
1. Run OpenLDAP container with TLS disabled. Change the path to [`gitlab-qa/fixtures/ldap`](https://gitlab.com/gitlab-org/gitlab-qa/-/tree/9ffb9ad3be847a9054967d792d6772a74220fb42/fixtures/ldap) directory to your local checkout path:
```shell
docker network create test && docker run --net test --publish 389:389 --publish 636:636 --name ldap-server --hostname ldap-server.test --volume /path/to/gitlab-qa/fixtures/ldap:/container/service/slapd/assets/config/bootstrap/ldif/custom:Z --env LDAP_TLS="false" osixia/openldap:latest --copy-service
```
1. Run the GitLab container:
```shell
sudo docker run \
--hostname localhost \
--net test \
--publish 443:443 --publish 80:80 --publish 22:22 \
--name gitlab \
--env GITLAB_OMNIBUS_CONFIG="gitlab_rails['ldap_enabled'] = true; gitlab_rails['ldap_servers'] = {\"main\"=>{\"label\"=>\"LDAP\", \"host\"=>\"ldap-server.test\", \"port\"=>389, \"uid\"=>\"uid\", \"bind_dn\"=>\"cn=admin,dc=example,dc=org\", \"password\"=>\"admin\", \"encryption\"=>\"plain\", \"verify_certificates\"=>false, \"base\"=>\"dc=example,dc=org\", \"user_filter\"=>\"\", \"group_base\"=>\"ou=Global Groups,dc=example,dc=org\", \"admin_group\"=>\"AdminGroup\", \"external_groups\"=>\"\", \"sync_ssh_keys\"=>false}}; gitlab_rails['ldap_sync_worker_cron'] = '* * * * *'; gitlab_rails['ldap_group_sync_worker_cron'] = '* * * * *'; " \
gitlab/gitlab-ee:latest
```
1. Run an LDAP test from [`gitlab/qa`](https://gitlab.com/gitlab-org/gitlab/-/tree/d5447ebb5f99d4c72780681ddf4dc25b0738acba/qa) directory:
```shell
GITLAB_LDAP_USERNAME="tanuki" GITLAB_LDAP_PASSWORD="password" QA_LOG_LEVEL=debug WEBDRIVER_HEADLESS=false bin/qa Test::Instance::All http://localhost qa/specs/features/browser_ui/1_manage/login/log_into_gitlab_via_ldap_spec.rb
```
## SMTP tests
Tests that are tagged with `:smtp` meta tag are orchestrated tests that ensure email notifications are received by a user.
These tests require a GitLab instance with SMTP enabled and integrated with an SMTP server, [MailHog](https://github.com/mailhog/MailHog).
To run these tests locally against the GDK:
1. Add these settings to your `gitlab.yml` file:
```yaml
smtp:
enabled: true
address: "mailhog.test"
port: 1025
```
1. Start MailHog in a Docker container:
```shell
docker network create test && docker run \
--network test \
--hostname mailhog.test \
--name mailhog \
--publish 1025:1025 \
--publish 8025:8025 \
mailhog/mailhog:v1.0.0
```
1. Run the test from [`gitlab/qa`](https://gitlab.com/gitlab-org/gitlab/-/tree/d5447ebb5f99d4c72780681ddf4dc25b0738acba/qa) directory:
```shell
QA_LOG_LEVEL=debug WEBDRIVER_HEADLESS=false bin/qa Test::Instance::All http://localhost:3000 qa/specs/features/browser_ui/2_plan/email/trigger_email_notification_spec.rb -- --tag orchestrated
```
For instructions on how to run these tests using the `gitlab-qa` gem, refer to [the GitLab QA documentation](https://gitlab.com/gitlab-org/gitlab-qa/-/blob/master/docs/what_tests_can_be_run.md#testintegrationsmtp-ceeefull-image-address).
## Targeting canary vs non-canary components in live environments
Use the `QA_COOKIES` ENV variable to have the entire test target a `canary` (`staging-canary` or `canary`) or `non-canary` (`staging` or `production`) environment.
Locally, that would mean prepending the ENV variable to your call to bin/qa. To target the `canary` version of that environment:
```shell
QA_COOKIES="gitlab_canary=true" WEBDRIVER_HEADLESS=false bin/qa Test::Instance::Staging <YOUR SPECIFIC TAGS OR TESTS>
```
Alternatively, you may set the cookie to `false` to ensure the `non-canary` version is targeted.
You can also export the cookie for your current session to avoid prepending it each time:
```shell
export QA_COOKIES="gitlab_canary=true"
```
### Updating the cookie within a running spec
Within a specific test, you can target either the `canary` or `non-canary` nodes within live environments, such as `staging` and `production`.
For example, to switch back and forth between the two environments, you could utilize the `target_canary` method:
```ruby
it 'tests toggling between canary and non-canary nodes' do
Runtime::Browser.visit(:gitlab, Page::Main::Login)
# After starting the browser session, use the target_canary method ...
Runtime::Browser::Session.target_canary(true)
Flow::Login.sign_in
verify_session_on_canary(true)
Runtime::Browser::Session.target_canary(false)
# Refresh the page ...
verify_session_on_canary(false)
# Log out and clean up ...
end
def verify_session_on_canary(enable_canary)
Page::Main::Menu.perform do |menu|
aggregate_failures 'testing session log in' do
expect(menu.canary?).to be(enable_canary)
end
end
end
```
You can verify whether GitLab is appropriately redirecting your session to the `canary` or `non-canary` nodes with the `menu.canary?` method.
The above spec is verbose, written specifically this way to ensure the idea behind the implementation is clear. We recommend following the practices detailed within our [Beginner's guide to writing end-to-end tests](../beginners_guide/_index.md).
## Tests for GitLab as OpenID Connect (OIDC) and OAuth provider
To run the [`login_via_oauth_and_oidc_with_gitlab_as_idp_spec`](https://gitlab.com/gitlab-org/gitlab/-/blob/2e2c8bcfa4f68cd39041806af531038ce4d2ab04/qa/qa/specs/features/browser_ui/1_manage/login/login_via_oauth_and_oidc_with_gitlab_as_idp_spec.rb) on your local machine:
1. Make sure your GDK is set to run on a non-localhost address such as `gdk.test:3000`.
1. Configure a [loopback interface to 172.16.123.1](https://gitlab.com/gitlab-org/gitlab-development-kit/-/blob/6fe7b46403229f12ab6d903f99b024e0b82cb94a/doc/howto/local_network.md#create-loopback-interface).
1. Make sure Docker Desktop or Rancher Desktop is running.
1. Add an entry to your `/etc/hosts` file for `gitlab-oidc-consumer.bridge` and `gitlab-oauth-consumer.bridge` pointing to `127.0.0.1`.
1. From the `qa` directory, run the following command. To set the GitLab image you want to use, update the `RELEASE` variable. For example, to use the latest EE image, set `RELEASE` to `gitlab/gitlab-ee:latest`:
```shell
bundle install
RELEASE_REGISTRY_URL='registry.gitlab.com' RELEASE_REGISTRY_USERNAME='<your_gitlab_username>' RELEASE_REGISTRY_PASSWORD='<your_gitlab_personal_access_token>' RELEASE='registry.gitlab.com/gitlab-org/build/omnibus-gitlab-mirror/gitlab-ee:c0ae46db6b31ea231b2de88961cd687acf634179' GITLAB_QA_ADMIN_ACCESS_TOKEN="<your_gdk_admin_personal_access_token>" QA_DEBUG=true CHROME_HEADLESS=false bundle exec bin/qa Test::Instance::All http://gdk.test:3000 qa/specs/features/browser_ui/1_manage/login/login_via_oauth_and_oidc_with_gitlab_as_idp_spec.rb
```
## Product Analytics tests
Product Analytics e2e tests require Product Analytics services running and connected to your GDK.
In order to run Product Analytics services, devkit can be used. Instructions to set it up and connect to your GDK can be found in the [devkit project's `README.md`](https://gitlab.com/gitlab-org/analytics-section/product-analytics/devkit).
Additionally, the following setup is required on the GDK:
- Set environment variables for product analytics configuration. The following variables are default for running devkit locally.
```shell
export PA_CONFIGURATOR_URL=http://test:test@localhost:4567
export PA_COLLECTOR_HOST=http://localhost:9091
export PA_CUBE_API_URL=http://localhost:4000
export PA_CUBE_API_KEY=thisisnotarealkey43ff15165ce01e4ff47d75092e3b25b2c0b20dc27f6cd5a8aed7b7bd855df88c9e0748d7afd37adda6d981c16177b086acf496bbdc62dbb
```
- Ultimate license applied.
- [How to request the license](https://handbook.gitlab.com/handbook/developer-onboarding/#working-on-gitlab-ee-developer-licenses).
- [How to activate GitLab EE with a license file or key](https://gitlab.com/gitlab-org/gitlab/-/blob/master/doc/administration/license_file.md#activate-gitlab-ee-with-a-license-file-or-key).
- Simulate SaaS enabled. Instructions can be [found here](https://gitlab.com/gitlab-org/gitlab/-/blob/master/doc/development/ee_features.md#simulate-a-saas-instance).
Once Product Analytics services are running and are connected to your GDK, the tests can be executed with:
```shell
bundle exec rspec qa/specs/features/ee/browser_ui/8_monitor/product_analytics/onboarding_spec.rb
```
## Tests that require a global server hook
The [`tag_revision_trigger_prereceive_hook_spec`](https://gitlab.com/gitlab-org/gitlab/-/blob/c3342dac0c6c8e9e11ec049b910eac832600b0bf/qa/qa/specs/features/api/3_create/repository/tag_revision_trigger_prereceive_hook_spec.rb) requires a global server hook to be pre-configured in the target test environment. When running this tests against a local GDK, the server hook will need to be configured with:
```shell
# From the gdk directory
mkdir -p gitaly-custom-hooks/pre-receive.d
cp gitlab/qa/gdk/pre-receive gitaly-custom-hooks/pre-receive.d
chmod +x gitaly-custom-hooks/pre-receive.d/pre-receive
```
More information on global server hooks can be found in the [server hooks documentation](../../../../administration/server_hooks.md#create-the-global-server-hook)
|
https://docs.gitlab.com/development/activitypub
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/_index.md
|
2025-08-13
|
doc/development/activitypub
|
[
"doc",
"development",
"activitypub"
] |
_index.md
|
Create
|
Source Code
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
ActivityPub
| null |
{{< details >}}
- Status: Experiment
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/127023) in GitLab 16.5 [with two flags](../../administration/feature_flags/_index.md) named `activity_pub` and `activity_pub_project`. Disabled by default. This feature is an [experiment](../../policy/development_stages_support.md).
{{< /history >}}
{{< alert type="flag" >}}
On GitLab Self-Managed, by default this feature is not available. To make it available,
an administrator can [enable the feature flags](../../administration/feature_flags/_index.md)
named `activity_pub` and `activity_pub_project`.
On GitLab.com and GitLab Dedicated, this feature is not available.
This feature is not ready for production use.
{{< /alert >}}
Usage of ActivityPub in GitLab is governed by the
[GitLab Testing Agreement](https://handbook.gitlab.com/handbook/legal/testing-agreement/).
The goal of those documents is to provide an implementation path for adding
Fediverse capabilities to GitLab.
ActivityPub requires two feature flags:
- `activity_pub`: Enables or disables all ActivityPub-related features.
- `activity_pub_project`: Enables and disables ActivityPub features specific to
projects. Requires the `activity_pub` flag to also be enabled.
Most of the implementation is being discussed in
[an architecture design document](https://handbook.gitlab.com/handbook/engineering/architecture/design-documents/activity_pub/),
see this document for more information.
For now, see [how to implement an ActivityPub actor](actors/_index.md).
|
---
stage: Create
group: Source Code
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: ActivityPub
breadcrumbs:
- doc
- development
- activitypub
---
{{< details >}}
- Status: Experiment
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/127023) in GitLab 16.5 [with two flags](../../administration/feature_flags/_index.md) named `activity_pub` and `activity_pub_project`. Disabled by default. This feature is an [experiment](../../policy/development_stages_support.md).
{{< /history >}}
{{< alert type="flag" >}}
On GitLab Self-Managed, by default this feature is not available. To make it available,
an administrator can [enable the feature flags](../../administration/feature_flags/_index.md)
named `activity_pub` and `activity_pub_project`.
On GitLab.com and GitLab Dedicated, this feature is not available.
This feature is not ready for production use.
{{< /alert >}}
Usage of ActivityPub in GitLab is governed by the
[GitLab Testing Agreement](https://handbook.gitlab.com/handbook/legal/testing-agreement/).
The goal of those documents is to provide an implementation path for adding
Fediverse capabilities to GitLab.
ActivityPub requires two feature flags:
- `activity_pub`: Enables or disables all ActivityPub-related features.
- `activity_pub_project`: Enables and disables ActivityPub features specific to
projects. Requires the `activity_pub` flag to also be enabled.
Most of the implementation is being discussed in
[an architecture design document](https://handbook.gitlab.com/handbook/engineering/architecture/design-documents/activity_pub/),
see this document for more information.
For now, see [how to implement an ActivityPub actor](actors/_index.md).
|
https://docs.gitlab.com/development/activitypub/actors
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/activitypub/_index.md
|
2025-08-13
|
doc/development/activitypub/actors
|
[
"doc",
"development",
"activitypub",
"actors"
] |
_index.md
|
Create
|
Source Code
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Implement an ActivityPub actor
| null |
{{< details >}}
- Status: Experiment
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/127023) in GitLab 16.5 [with two flags](../../../administration/feature_flags/_index.md) named `activity_pub` and `activity_pub_project`. Disabled by default. This feature is an [experiment](../../../policy/development_stages_support.md).
{{< /history >}}
{{< alert type="flag" >}}
On GitLab Self-Managed, by default this feature is not available. To make it available,
an administrator can [enable the feature flags](../../../administration/feature_flags/_index.md)
named `activity_pub` and `activity_pub_project`.
On GitLab.com and GitLab Dedicated, this feature is not available.
This feature is not ready for production use.
{{< /alert >}}
This feature requires two feature flags:
- `activity_pub`: Enables or disables all ActivityPub-related features.
- `activity_pub_project`: Enables and disable ActivityPub features specific to
projects. Requires the `activity_pub` flag to also be enabled.
ActivityPub is based on three standard documents:
- [ActivityPub](https://www.w3.org/TR/activitypub/) defines the HTTP
requests happening to implement federation.
- [ActivityStreams](https://www.w3.org/TR/activitystreams-core/) defines the
format of the JSON messages exchanged by the users of the protocol.
- [Activity Vocabulary](https://www.w3.org/TR/activitystreams-vocabulary/)
defines the various messages recognized by default.
The first one is typically handled by controllers, while the two others are
related to what happen in serializers.
To implement an ActivityPub actor, you must:
- Implement the profile page of the resource.
- Implement the outbox page.
- Handle incoming requests on the inbox.
All requests are made using
`application/ld+json; profile="https://www.w3.org/ns/activitystreams"` as `Accept` HTTP header.
The actors we've implemented for the social features:
- [Releases](releases.md)
For more information on planned actors, see [epic 11247](https://gitlab.com/groups/gitlab-org/-/epics/11247).
## Profile page
Querying the profile page is used to retrieve:
- General information about it, like name and description.
- URLs for the inbox and the outbox.
To implement a profile page, create an ActivityStreams
serializer in `app/serializers/activity_pub/`, making your serializer
inherit from `ActivityStreamsSerializer`. See below in the serializers
section about the mandatory fields.
To call your serializer in your controller:
```ruby
opts = {
inbox: nil,
outbox: outbox_project_releases_url(project)
}
render json: ActivityPub::ReleasesActorSerializer.new.represent(project, opts)
```
- `outbox` is the endpoint where to find the activities feed for this
actor.
- `inbox` is where to POST to subscribe to the feed. Not yet implemented, so pass `nil`.
## Outbox page
The outbox is the list of activities for the resource. It's a feed for the
resource, and it allows ActivityPub clients to show public activities for
this actor without having yet subscribed to it.
To implement an outbox page, create an ActivityStreams
serializer in `app/serializers/activity_pub/`, making your serializer
inherit from `ActivityStreamsSerializer`. See below in the serializers
section about the mandatory fields.
You call your serializer in your controller like this:
```ruby
serializer = ActivityPub::ReleasesOutboxSerializer.new.with_pagination(request, response)
render json: serializer.represent(releases)
```
This converts the response to an `OrderedCollection`
ActivityPub type, with all the correct fields.
## Inbox
Not yet implemented.
The inbox is where the ActivityPub compatible third-parties makes their
requests, to subscribe to the actor or send it messages.
## ActivityStreams serializers
The serializers implement half the core of ActivityPub support: they're all
about [ActivityStreams](https://www.w3.org/TR/activitystreams-core/), the
message format used by ActivityPub.
To leverage the features doing most of the formatting for you, your
serializer should inherit from `ActivityPub::ActivityStreamsSerializer`.
To use it, call the `#represent` method. It requires you to provide
`inbox` and `outbox` options (as mentioned above) if it
is an actor profile page. You don't need those if your serializer
represents an object that is just meant to be embedded as part of actors,
like the object representing the contact information for a user.
Each resource serialized (included other objects embedded in your
actor) must provide an `id` and a `type` field.
`id` is a URL. It's meant to be a unique identifier for the resource, and
it must point to an existing page: ideally, an actor. Otherwise, you can
just reference the closest actor and use an anchor, like this:
```plaintext
https://gitlab.com/user/project/-/releases#release-1
```
`type` should be taken from ActivityStreams core vocabulary:
- [Activity types](https://www.w3.org/TR/activitystreams-vocabulary/#activity-types)
- [Actor types](https://www.w3.org/TR/activitystreams-vocabulary/#actor-types)
- [Object types](https://www.w3.org/TR/activitystreams-vocabulary/#object-types)
The properties you can use are all documented in
[the ActivityStreams vocabulary document](https://www.w3.org/TR/activitystreams-vocabulary/).
Given the type you have chosen for your resource, find the
`properties` list, telling you all available properties, direct or
inherited.
It's worth noting that Mastodon adds one more property, `preferredName`.
Mastodon expects it to be set on any actor, or that actor is not recognized by
Mastodon.
|
---
stage: Create
group: Source Code
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Implement an ActivityPub actor
breadcrumbs:
- doc
- development
- activitypub
- actors
---
{{< details >}}
- Status: Experiment
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/127023) in GitLab 16.5 [with two flags](../../../administration/feature_flags/_index.md) named `activity_pub` and `activity_pub_project`. Disabled by default. This feature is an [experiment](../../../policy/development_stages_support.md).
{{< /history >}}
{{< alert type="flag" >}}
On GitLab Self-Managed, by default this feature is not available. To make it available,
an administrator can [enable the feature flags](../../../administration/feature_flags/_index.md)
named `activity_pub` and `activity_pub_project`.
On GitLab.com and GitLab Dedicated, this feature is not available.
This feature is not ready for production use.
{{< /alert >}}
This feature requires two feature flags:
- `activity_pub`: Enables or disables all ActivityPub-related features.
- `activity_pub_project`: Enables and disable ActivityPub features specific to
projects. Requires the `activity_pub` flag to also be enabled.
ActivityPub is based on three standard documents:
- [ActivityPub](https://www.w3.org/TR/activitypub/) defines the HTTP
requests happening to implement federation.
- [ActivityStreams](https://www.w3.org/TR/activitystreams-core/) defines the
format of the JSON messages exchanged by the users of the protocol.
- [Activity Vocabulary](https://www.w3.org/TR/activitystreams-vocabulary/)
defines the various messages recognized by default.
The first one is typically handled by controllers, while the two others are
related to what happen in serializers.
To implement an ActivityPub actor, you must:
- Implement the profile page of the resource.
- Implement the outbox page.
- Handle incoming requests on the inbox.
All requests are made using
`application/ld+json; profile="https://www.w3.org/ns/activitystreams"` as `Accept` HTTP header.
The actors we've implemented for the social features:
- [Releases](releases.md)
For more information on planned actors, see [epic 11247](https://gitlab.com/groups/gitlab-org/-/epics/11247).
## Profile page
Querying the profile page is used to retrieve:
- General information about it, like name and description.
- URLs for the inbox and the outbox.
To implement a profile page, create an ActivityStreams
serializer in `app/serializers/activity_pub/`, making your serializer
inherit from `ActivityStreamsSerializer`. See below in the serializers
section about the mandatory fields.
To call your serializer in your controller:
```ruby
opts = {
inbox: nil,
outbox: outbox_project_releases_url(project)
}
render json: ActivityPub::ReleasesActorSerializer.new.represent(project, opts)
```
- `outbox` is the endpoint where to find the activities feed for this
actor.
- `inbox` is where to POST to subscribe to the feed. Not yet implemented, so pass `nil`.
## Outbox page
The outbox is the list of activities for the resource. It's a feed for the
resource, and it allows ActivityPub clients to show public activities for
this actor without having yet subscribed to it.
To implement an outbox page, create an ActivityStreams
serializer in `app/serializers/activity_pub/`, making your serializer
inherit from `ActivityStreamsSerializer`. See below in the serializers
section about the mandatory fields.
You call your serializer in your controller like this:
```ruby
serializer = ActivityPub::ReleasesOutboxSerializer.new.with_pagination(request, response)
render json: serializer.represent(releases)
```
This converts the response to an `OrderedCollection`
ActivityPub type, with all the correct fields.
## Inbox
Not yet implemented.
The inbox is where the ActivityPub compatible third-parties makes their
requests, to subscribe to the actor or send it messages.
## ActivityStreams serializers
The serializers implement half the core of ActivityPub support: they're all
about [ActivityStreams](https://www.w3.org/TR/activitystreams-core/), the
message format used by ActivityPub.
To leverage the features doing most of the formatting for you, your
serializer should inherit from `ActivityPub::ActivityStreamsSerializer`.
To use it, call the `#represent` method. It requires you to provide
`inbox` and `outbox` options (as mentioned above) if it
is an actor profile page. You don't need those if your serializer
represents an object that is just meant to be embedded as part of actors,
like the object representing the contact information for a user.
Each resource serialized (included other objects embedded in your
actor) must provide an `id` and a `type` field.
`id` is a URL. It's meant to be a unique identifier for the resource, and
it must point to an existing page: ideally, an actor. Otherwise, you can
just reference the closest actor and use an anchor, like this:
```plaintext
https://gitlab.com/user/project/-/releases#release-1
```
`type` should be taken from ActivityStreams core vocabulary:
- [Activity types](https://www.w3.org/TR/activitystreams-vocabulary/#activity-types)
- [Actor types](https://www.w3.org/TR/activitystreams-vocabulary/#actor-types)
- [Object types](https://www.w3.org/TR/activitystreams-vocabulary/#object-types)
The properties you can use are all documented in
[the ActivityStreams vocabulary document](https://www.w3.org/TR/activitystreams-vocabulary/).
Given the type you have chosen for your resource, find the
`properties` list, telling you all available properties, direct or
inherited.
It's worth noting that Mastodon adds one more property, `preferredName`.
Mastodon expects it to be set on any actor, or that actor is not recognized by
Mastodon.
|
https://docs.gitlab.com/development/activitypub/releases
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/activitypub/releases.md
|
2025-08-13
|
doc/development/activitypub/actors
|
[
"doc",
"development",
"activitypub",
"actors"
] |
releases.md
|
Create
|
Source Code
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Activities for following releases actor
| null |
{{< details >}}
- Status: Experiment
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/127023) in GitLab 16.5 [with two flags](../../../administration/feature_flags/_index.md) named `activity_pub` and `activity_pub_project`. Disabled by default. This feature is an [experiment](../../../policy/development_stages_support.md).
{{< /history >}}
{{< alert type="flag" >}}
On GitLab Self-Managed, by default this feature is not available. To make it available,
an administrator can [enable the feature flags](../../../administration/feature_flags/_index.md)
named `activity_pub` and `activity_pub_project`.
On GitLab.com and GitLab Dedicated, this feature is not available.
This feature is not ready for production use.
{{< /alert >}}
This feature requires two feature flags:
- `activity_pub`: Enables or disables all ActivityPub-related features.
- `activity_pub_project`: Enables and disable ActivityPub features specific to
projects. Requires the `activity_pub` flag to also be enabled.
## Profile
The profile is this actor is a bit different from other actors. We don't want to
show activities for a given release, but instead the releases for a given project.
The profile endpoint is handled by `Projects::ReleasesController#index`
on the list of releases, and should reply with something like this:
```javascript
{
"@context": "https://www.w3.org/ns/activitystreams",
"id": PROJECT_RELEASES_URL,
"type": "Application",
"name": PROJECT_NAME + " releases",
"url": PROJECT_RELEASES_URL,
"content": PROJECT_DESCRIPTION,
"context": {
"id": PROJECT_URL,
"type": "Application",
"name": PROJECT_NAME,
"summary": PROJECT_DESCRIPTION,
"url": PROJECT_URL,
},
"outbox": PROJECT_RELEASES_OUTBOX_URL,
"inbox": null,
}
```
## Outbox
The release actor is relatively simple: the only activity happening is the
**Create release** event.
```javascript
{
"id": PROJECT_RELEASES_OUTBOX_URL#release_id,
"type": "Create",
"to": [
"https://www.w3.org/ns/activitystreams#Public"
],
"actor": {
"id": USER_PROFILE_URL,
"type": "Person",
"name": USER_NAME,
"url": USER_PROFILE_URL,
},
"object": {
"id": RELEASE_URL,
"type": "Application",
"name": RELEASE_TITLE,
"url": RELEASE_URL,
"content": RELEASE_DESCRIPTION,
"context": {
"id": PROJECT_URL,
"type": "Application",
"name": PROJECT_NAME,
"summary": PROJECT_DESCRIPTION,
"url": PROJECT_URL,
},
},
}
```
|
---
stage: Create
group: Source Code
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Activities for following releases actor
breadcrumbs:
- doc
- development
- activitypub
- actors
---
{{< details >}}
- Status: Experiment
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/127023) in GitLab 16.5 [with two flags](../../../administration/feature_flags/_index.md) named `activity_pub` and `activity_pub_project`. Disabled by default. This feature is an [experiment](../../../policy/development_stages_support.md).
{{< /history >}}
{{< alert type="flag" >}}
On GitLab Self-Managed, by default this feature is not available. To make it available,
an administrator can [enable the feature flags](../../../administration/feature_flags/_index.md)
named `activity_pub` and `activity_pub_project`.
On GitLab.com and GitLab Dedicated, this feature is not available.
This feature is not ready for production use.
{{< /alert >}}
This feature requires two feature flags:
- `activity_pub`: Enables or disables all ActivityPub-related features.
- `activity_pub_project`: Enables and disable ActivityPub features specific to
projects. Requires the `activity_pub` flag to also be enabled.
## Profile
The profile is this actor is a bit different from other actors. We don't want to
show activities for a given release, but instead the releases for a given project.
The profile endpoint is handled by `Projects::ReleasesController#index`
on the list of releases, and should reply with something like this:
```javascript
{
"@context": "https://www.w3.org/ns/activitystreams",
"id": PROJECT_RELEASES_URL,
"type": "Application",
"name": PROJECT_NAME + " releases",
"url": PROJECT_RELEASES_URL,
"content": PROJECT_DESCRIPTION,
"context": {
"id": PROJECT_URL,
"type": "Application",
"name": PROJECT_NAME,
"summary": PROJECT_DESCRIPTION,
"url": PROJECT_URL,
},
"outbox": PROJECT_RELEASES_OUTBOX_URL,
"inbox": null,
}
```
## Outbox
The release actor is relatively simple: the only activity happening is the
**Create release** event.
```javascript
{
"id": PROJECT_RELEASES_OUTBOX_URL#release_id,
"type": "Create",
"to": [
"https://www.w3.org/ns/activitystreams#Public"
],
"actor": {
"id": USER_PROFILE_URL,
"type": "Person",
"name": USER_NAME,
"url": USER_PROFILE_URL,
},
"object": {
"id": RELEASE_URL,
"type": "Application",
"name": RELEASE_TITLE,
"url": RELEASE_URL,
"content": RELEASE_DESCRIPTION,
"context": {
"id": PROJECT_URL,
"type": "Application",
"name": PROJECT_NAME,
"summary": PROJECT_DESCRIPTION,
"url": PROJECT_URL,
},
},
}
```
|
https://docs.gitlab.com/development/graphql_pro
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/graphql_pro.md
|
2025-08-13
|
doc/development/graphql_guide
|
[
"doc",
"development",
"graphql_guide"
] |
graphql_pro.md
|
Create
|
Import
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
GraphQL Pro
| null |
GraphQL has become a key technology in GitLab and is implemented using the
[GraphQL Ruby gem](https://graphql-ruby.org). As such, we've purchased a subscription to
[GraphQL Pro](https://graphql.pro).
The main purpose is for support. Per the website:
> As a GraphQL::Pro customer, you get direct access to the GraphQL Ruby gem
> creator and maintainer. Get prioritized support for issues and requests.
Note that we **cannot** use the Pro version directly in our product, since we are
an Open Core product - we cannot require customers to purchase the Pro version, nor can we ship it.
Details on the billing account and gem licensing can be found in the Engineering 1Password vault.
|
---
stage: Create
group: Import
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: GraphQL Pro
breadcrumbs:
- doc
- development
- graphql_guide
---
GraphQL has become a key technology in GitLab and is implemented using the
[GraphQL Ruby gem](https://graphql-ruby.org). As such, we've purchased a subscription to
[GraphQL Pro](https://graphql.pro).
The main purpose is for support. Per the website:
> As a GraphQL::Pro customer, you get direct access to the GraphQL Ruby gem
> creator and maintainer. Get prioritized support for issues and requests.
Note that we **cannot** use the Pro version directly in our product, since we are
an Open Core product - we cannot require customers to purchase the Pro version, nor can we ship it.
Details on the billing account and gem licensing can be found in the Engineering 1Password vault.
|
https://docs.gitlab.com/development/graphql_guide
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/_index.md
|
2025-08-13
|
doc/development/graphql_guide
|
[
"doc",
"development",
"graphql_guide"
] |
_index.md
|
Create
|
Import
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
GraphQL development guidelines
| null |
This guide contains all the information to successfully contribute to the GitLab
GraphQL API. This is a living document, and we welcome contributions,
feedback, and suggestions.
## Resources
- [GraphQL API development style guide](../api_graphql_styleguide.md): development style guide for
GraphQL.
- [GraphQL API documentation style guide](../documentation/graphql_styleguide.md): documentation
style guide for GraphQL.
- [GraphQL API](../../api/graphql/_index.md): user documentation for the GitLab GraphQL API.
- [GraphQL authorization](authorization.md): guide to using authorization in GraphQL.
- [GraphQL BatchLoader](batchloader.md): development documentation on the BatchLoader.
- [GraphQL pagination](pagination.md): development documentation on pagination.
- [GraphQL Pro](graphql_pro.md): information on our GraphQL Pro subscription.
- [GraphQL monitoring](monitoring.md): tips on how to use our monitoring tools to inspect GraphQL queries.
|
---
stage: Create
group: Import
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: GraphQL development guidelines
breadcrumbs:
- doc
- development
- graphql_guide
---
This guide contains all the information to successfully contribute to the GitLab
GraphQL API. This is a living document, and we welcome contributions,
feedback, and suggestions.
## Resources
- [GraphQL API development style guide](../api_graphql_styleguide.md): development style guide for
GraphQL.
- [GraphQL API documentation style guide](../documentation/graphql_styleguide.md): documentation
style guide for GraphQL.
- [GraphQL API](../../api/graphql/_index.md): user documentation for the GitLab GraphQL API.
- [GraphQL authorization](authorization.md): guide to using authorization in GraphQL.
- [GraphQL BatchLoader](batchloader.md): development documentation on the BatchLoader.
- [GraphQL pagination](pagination.md): development documentation on pagination.
- [GraphQL Pro](graphql_pro.md): information on our GraphQL Pro subscription.
- [GraphQL monitoring](monitoring.md): tips on how to use our monitoring tools to inspect GraphQL queries.
|
https://docs.gitlab.com/development/batchloader
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/batchloader.md
|
2025-08-13
|
doc/development/graphql_guide
|
[
"doc",
"development",
"graphql_guide"
] |
batchloader.md
|
Data Access
|
Database Frameworks
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
GraphQL BatchLoader
| null |
GitLab uses the [batch-loader](https://github.com/exAspArk/batch-loader) Ruby gem to optimize and avoid N+1 SQL queries.
It is the properties of the GraphQL query tree that create opportunities for batching like this - disconnected nodes might need the same data, but cannot know about themselves.
## When should you use it?
We should try to batch DB requests as much as possible during GraphQL **query** execution. There is no need to batch loading during **mutations** because they are executed serially. If you need to make a database query, and it is possible to combine two similar (but not necessarily identical) queries, then consider using the batch-loader.
When implementing a new endpoint we should aim to minimise the number of SQL queries. For stability and scalability we must also ensure that our queries do not suffer from N+1 performance issues.
## Implementation
Batch loading is useful when a series of queries for inputs `Qα, Qβ, ... Qω` can be combined to a single query for `Q[α, β, ... ω]`. An example of this is lookups by ID, where we can find two users by usernames as cheaply as one, but real-world examples can be more complex.
Batch loading is not suitable when the result sets have different sort orders, grouping, aggregation, or other non-composable features.
There are two ways to use the batch-loader in your code. For simple ID lookups, use `::Gitlab::Graphql::Loaders::BatchModelLoader.new(model, id).find`. For more complex cases, you can use the batch API directly.
For example, to load a `User` by `username`, we can add batching as follows:
```ruby
class UserResolver < BaseResolver
type UserType, null: true
argument :username, ::GraphQL::Types::String, required: true
def resolve(**args)
BatchLoader::GraphQL.for(username).batch do |usernames, loader|
User.by_username(usernames).each do |user|
loader.call(user.username, user)
end
end
end
end
```
- `username` is the username we want to query. It can be one name or multiple names.
- `loader.call` is used to map the result back to the input key (here user is mapped to its username)
- `BatchLoader::GraphQL` returns a lazy object (suspended promise to fetch the data)
Here an [example MR](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/46549) illustrating how to use our `BatchLoading` mechanism.
## The `BatchModelLoader`
For ID lookups, the advice is to use the `BatchModelLoader`:
```ruby
def project
::Gitlab::Graphql::Loaders::BatchModelLoader.new(::Project, object.project_id).find
end
```
To preload associations, you can pass an array of them:
```ruby
def issue(lookahead:)
preloads = [:author] if lookahead.selects?(:author)
::Gitlab::Graphql::Loaders::BatchModelLoader.new(::Issue, object.issue_id, preloads).find
end
```
## How does it work exactly?
Each lazy object knows which data it needs to load and how to batch the query. When we need to use the lazy objects (which we announce by calling `#sync`), they are loaded along with all other similar objects in the current batch.
Inside the block we execute a batch query for our items (`User`). After that, all we have to do is to call loader by passing an item which was used in `BatchLoader::GraphQL.for` method (`usernames`) and the loaded object itself (`user`):
```ruby
BatchLoader::GraphQL.for(username).batch do |usernames, loader|
User.by_username(usernames).each do |user|
loader.call(user.username, user)
end
end
```
The batch-loader uses the source code location of the block to determine
which requests belong in the same queue, but only one instance of the block
is evaluated for each batch. You do not control which one.
For this reason, it is important that:
- The block must not refer to (close over) any instance state on objects. The best practice
is to pass all data the block needs through to it in the `for(data)` call.
- The block must be specific to a kind of batched data. Implementing generic
loaders (such as the `BatchModelLoader`) is possible, but it requires the use
of an injective `key` argument.
- Batches are not shared unless they refer to the same block - two identical blocks
with the same behavior, parameters, and keys do not get shared. For this reason,
never implement batched ID lookups on your own, instead use the `BatchModelLoader` for
maximum sharing. If you see two fields define the same batch-loading, consider
extracting that out to a new `Loader`, and enabling them to share.
### What does lazy mean?
It is important to avoid syncing batches (forcing their evaluation) too early. The following example shows how calling sync too early can eliminate opportunities for batching.
This example calls sync on `x` too early:
```ruby
x = find_lazy(1)
y = find_lazy(2)
# calling .sync will flush the current batch and will inhibit maximum laziness
x.sync
z = find_lazy(3)
y.sync
z.sync
# => will run 2 queries
```
However, this example waits until all requests are queued, and eliminates the extra query:
```ruby
x = find_lazy(1)
y = find_lazy(2)
z = find_lazy(3)
x.sync
y.sync
z.sync
# => will run 1 query
```
{{< alert type="note" >}}
There is no dependency analysis in the use of batch-loading. There is
a pending queue of requests, and as soon as any one result is needed, all pending
requests are evaluated.
{{< /alert >}}
You should never call `batch.sync` or use `Lazy.force` in resolver code.
If you depend on a lazy value, use `Lazy.with_value` instead:
```ruby
def publisher
::Gitlab::Graphql::Loaders::BatchModelLoader.new(::Publisher, object.publisher_id).find
end
# Here we need the publisher to generate the catalog URL
def catalog_url
::Gitlab::Graphql::Lazy.with_value(publisher) do |p|
UrlHelpers.book_catalog_url(publisher, object.isbn)
end
end
```
We commonly use `#sync` in a mutation after finding a record with `GitlabSchema.find_by_gid` or `.object_from_id`, as those methods return the result in a batch loader wrapper. Mutations are executed serially, so batch loading is not necessary and the object can be evaluated immediately.
## Testing
Ideally, do all your testing using request specs, and using `Schema.execute`. If
you do so, you do not need to manage the lifecycle of lazy values yourself, and
you are assured accurate results.
GraphQL fields that return lazy values may need these values forced in tests.
Forcing refers to explicit demands for evaluation, where this would usually
be arranged by the framework.
You can force a lazy value with the `GraphqlHelpers#batch_sync` method available in [GraphQLHelpers](https://gitlab.com/gitlab-org/gitlab/-/blob/master/spec/support/helpers/graphql_helpers.rb), or by using `Gitlab::Graphql::Lazy.force`. For example:
```ruby
it 'returns data as a batch' do
results = batch_sync(max_queries: 1) do
[{ id: 1 }, { id: 2 }].map { |args| resolve(args) }
end
expect(results).to eq(expected_results)
end
def resolve(args = {}, context = { current_user: current_user })
resolve(described_class, obj: obj, args: args, ctx: context)
end
```
We can also use [QueryRecorder](../database/query_recorder.md) to make sure we are performing only **one SQL query** per call.
```ruby
it 'executes only 1 SQL query' do
query_count = ActiveRecord::QueryRecorder.new { subject }
expect(query_count).not_to exceed_query_limit(1)
end
```
|
---
stage: Data Access
group: Database Frameworks
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: GraphQL BatchLoader
breadcrumbs:
- doc
- development
- graphql_guide
---
GitLab uses the [batch-loader](https://github.com/exAspArk/batch-loader) Ruby gem to optimize and avoid N+1 SQL queries.
It is the properties of the GraphQL query tree that create opportunities for batching like this - disconnected nodes might need the same data, but cannot know about themselves.
## When should you use it?
We should try to batch DB requests as much as possible during GraphQL **query** execution. There is no need to batch loading during **mutations** because they are executed serially. If you need to make a database query, and it is possible to combine two similar (but not necessarily identical) queries, then consider using the batch-loader.
When implementing a new endpoint we should aim to minimise the number of SQL queries. For stability and scalability we must also ensure that our queries do not suffer from N+1 performance issues.
## Implementation
Batch loading is useful when a series of queries for inputs `Qα, Qβ, ... Qω` can be combined to a single query for `Q[α, β, ... ω]`. An example of this is lookups by ID, where we can find two users by usernames as cheaply as one, but real-world examples can be more complex.
Batch loading is not suitable when the result sets have different sort orders, grouping, aggregation, or other non-composable features.
There are two ways to use the batch-loader in your code. For simple ID lookups, use `::Gitlab::Graphql::Loaders::BatchModelLoader.new(model, id).find`. For more complex cases, you can use the batch API directly.
For example, to load a `User` by `username`, we can add batching as follows:
```ruby
class UserResolver < BaseResolver
type UserType, null: true
argument :username, ::GraphQL::Types::String, required: true
def resolve(**args)
BatchLoader::GraphQL.for(username).batch do |usernames, loader|
User.by_username(usernames).each do |user|
loader.call(user.username, user)
end
end
end
end
```
- `username` is the username we want to query. It can be one name or multiple names.
- `loader.call` is used to map the result back to the input key (here user is mapped to its username)
- `BatchLoader::GraphQL` returns a lazy object (suspended promise to fetch the data)
Here an [example MR](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/46549) illustrating how to use our `BatchLoading` mechanism.
## The `BatchModelLoader`
For ID lookups, the advice is to use the `BatchModelLoader`:
```ruby
def project
::Gitlab::Graphql::Loaders::BatchModelLoader.new(::Project, object.project_id).find
end
```
To preload associations, you can pass an array of them:
```ruby
def issue(lookahead:)
preloads = [:author] if lookahead.selects?(:author)
::Gitlab::Graphql::Loaders::BatchModelLoader.new(::Issue, object.issue_id, preloads).find
end
```
## How does it work exactly?
Each lazy object knows which data it needs to load and how to batch the query. When we need to use the lazy objects (which we announce by calling `#sync`), they are loaded along with all other similar objects in the current batch.
Inside the block we execute a batch query for our items (`User`). After that, all we have to do is to call loader by passing an item which was used in `BatchLoader::GraphQL.for` method (`usernames`) and the loaded object itself (`user`):
```ruby
BatchLoader::GraphQL.for(username).batch do |usernames, loader|
User.by_username(usernames).each do |user|
loader.call(user.username, user)
end
end
```
The batch-loader uses the source code location of the block to determine
which requests belong in the same queue, but only one instance of the block
is evaluated for each batch. You do not control which one.
For this reason, it is important that:
- The block must not refer to (close over) any instance state on objects. The best practice
is to pass all data the block needs through to it in the `for(data)` call.
- The block must be specific to a kind of batched data. Implementing generic
loaders (such as the `BatchModelLoader`) is possible, but it requires the use
of an injective `key` argument.
- Batches are not shared unless they refer to the same block - two identical blocks
with the same behavior, parameters, and keys do not get shared. For this reason,
never implement batched ID lookups on your own, instead use the `BatchModelLoader` for
maximum sharing. If you see two fields define the same batch-loading, consider
extracting that out to a new `Loader`, and enabling them to share.
### What does lazy mean?
It is important to avoid syncing batches (forcing their evaluation) too early. The following example shows how calling sync too early can eliminate opportunities for batching.
This example calls sync on `x` too early:
```ruby
x = find_lazy(1)
y = find_lazy(2)
# calling .sync will flush the current batch and will inhibit maximum laziness
x.sync
z = find_lazy(3)
y.sync
z.sync
# => will run 2 queries
```
However, this example waits until all requests are queued, and eliminates the extra query:
```ruby
x = find_lazy(1)
y = find_lazy(2)
z = find_lazy(3)
x.sync
y.sync
z.sync
# => will run 1 query
```
{{< alert type="note" >}}
There is no dependency analysis in the use of batch-loading. There is
a pending queue of requests, and as soon as any one result is needed, all pending
requests are evaluated.
{{< /alert >}}
You should never call `batch.sync` or use `Lazy.force` in resolver code.
If you depend on a lazy value, use `Lazy.with_value` instead:
```ruby
def publisher
::Gitlab::Graphql::Loaders::BatchModelLoader.new(::Publisher, object.publisher_id).find
end
# Here we need the publisher to generate the catalog URL
def catalog_url
::Gitlab::Graphql::Lazy.with_value(publisher) do |p|
UrlHelpers.book_catalog_url(publisher, object.isbn)
end
end
```
We commonly use `#sync` in a mutation after finding a record with `GitlabSchema.find_by_gid` or `.object_from_id`, as those methods return the result in a batch loader wrapper. Mutations are executed serially, so batch loading is not necessary and the object can be evaluated immediately.
## Testing
Ideally, do all your testing using request specs, and using `Schema.execute`. If
you do so, you do not need to manage the lifecycle of lazy values yourself, and
you are assured accurate results.
GraphQL fields that return lazy values may need these values forced in tests.
Forcing refers to explicit demands for evaluation, where this would usually
be arranged by the framework.
You can force a lazy value with the `GraphqlHelpers#batch_sync` method available in [GraphQLHelpers](https://gitlab.com/gitlab-org/gitlab/-/blob/master/spec/support/helpers/graphql_helpers.rb), or by using `Gitlab::Graphql::Lazy.force`. For example:
```ruby
it 'returns data as a batch' do
results = batch_sync(max_queries: 1) do
[{ id: 1 }, { id: 2 }].map { |args| resolve(args) }
end
expect(results).to eq(expected_results)
end
def resolve(args = {}, context = { current_user: current_user })
resolve(described_class, obj: obj, args: args, ctx: context)
end
```
We can also use [QueryRecorder](../database/query_recorder.md) to make sure we are performing only **one SQL query** per call.
```ruby
it 'executes only 1 SQL query' do
query_count = ActiveRecord::QueryRecorder.new { subject }
expect(query_count).not_to exceed_query_limit(1)
end
```
|
https://docs.gitlab.com/development/monitoring
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/monitoring.md
|
2025-08-13
|
doc/development/graphql_guide
|
[
"doc",
"development",
"graphql_guide"
] |
monitoring.md
|
Create
|
Import
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Reading GraphQL logs
| null |
We use Kibana to filter GraphQL query logs. Sign in to [Kibana](https://log.gprd.gitlab.net/)
with a `@gitlab.com` email address.
In Kibana we can inspect two kinds of GraphQL logs:
- Logs of each GraphQL query executed within the request.
- Logs of the full request, which due to [query multiplexing](https://graphql-ruby.org/queries/multiplex.html)
may have executed multiple queries.
## Logs of each GraphQL query
In a [multiplex query](https://graphql-ruby.org/queries/multiplex.html), each individual query
is logged separately. We can use subcomponent filtering to inspect these logs.
[Visit Kibana with this filter enabled](https://log.gprd.gitlab.net/goto/a0da8c9a1e9c1f533a058b7d29d13956)
or set up the subcomponent filter using these steps:
1. Add a filter:
1. Filter: `json.subcomponent`
1. Operator: `is`
1. Value: `graphql_json`
1. Select **Refresh**.
You can select Kibana fields from the **Available fields** section of the sidebar to
add columns to the log table, or [visit this view](https://log.gprd.gitlab.net/goto/5826d3d3affb41cac52e637ffc205905),
which already has a set of Kibana fields selected. Some relevant Kibana fields include:
| Kibana field | Description |
| --- | --- |
| `json.operation_name` | The [operation name](https://graphql.org/learn/queries/#operation-name) used by the client. |
| `json.operation_fingerprint`| The [fingerprint](https://graphql-ruby.org/api-doc/1.12.20/GraphQL/Query#fingerprint-instance_method) of the query, used to recognize repeated queries over time. |
| `json.meta.caller_id` | Appears as `graphql:<operation_name>` for queries that came from the GitLab frontend, otherwise as `graphql:unknown`. Can be used to identify internal versus external queries. |
| `json.query_string` | The query string itself. |
| `json.is_mutation` | `true` when a mutation, `false` when not. |
| `json.query_analysis.used_fields` | List of GraphQL fields selected by the query. |
| `json.query_analysis.used_deprecated_fields` | List of deprecated GraphQL fields selected by the query. |
| `json.query_analysis.used_deprecated_arguments` | List of deprecated GraphQL arguments selected by the query. |
| `json.query_analysis.duration_s` | Duration of query execution in seconds. |
| `json.query_analysis.complexity` | The [complexity](../api_graphql_styleguide.md#max-complexity) score of the query. |
### Useful filters
Below are some examples of common Kibana filters.
#### See field usage
[See example of filter](https://log.gprd.gitlab.net/app/r/s/M2QA1).
1. Combine the [subcomponent filter](#logs-of-each-graphql-query) with the following Kibana filter:
1. Filter: `json.query_analysis.used_fields`
1. Operator: `is`
1. Value: `Type.myField`, where `Type.myField` is the type name and field name as it
appears in [our GraphQL API resources documentation](../../api/graphql/reference/_index.md).
1. Select **Refresh**.
#### See deprecated field usage
[See example of filter](https://log.gprd.gitlab.net/app/r/s/A0TY0).
1. Combine the [subcomponent filter](#logs-of-each-graphql-query) with the following Kibana filter:
1. Filter: `json.query_analysis.used_deprecated_fields`
1. Operator: `is`
1. Value: `Type.myField`, where `Type.myField` is the type name and field name as it
appears in [our GraphQL API resources documentation](../../api/graphql/reference/_index.md).
1. Select **Refresh**.
#### See queries that were not made by our frontend
[See example filter](https://log.gprd.gitlab.net/app/r/s/cWkK1).
As mentioned [above](#logs-of-each-graphql-query), `json.meta.caller_id` appears as `graphql:<operation_name>` for queries that
came from the GitLab frontend, otherwise as `graphql:unknown`. This filter be used to identify internal versus external queries.
1. Combine the [subcomponent filter](#logs-of-each-graphql-query) with the following Kibana filter:
1. Filter: `json.meta.caller_id`
1. Operator: `is`
1. Value: `graphql:unknown`
1. Select **Refresh**.
## Logs of the full request
The full request logs encompass log data for all [multiplexed queries](https://graphql-ruby.org/queries/multiplex.html)
in the request, as well as data from time spent outside of `GraphQLController#execute`.
To see the full request logs, do **not** apply the `json.subcomponent` [filter](#logs-of-each-graphql-query), and instead:
1. Add a filter:
1. Filter: `json.meta.caller_id`
1. Operator: `is`
1. Value: `GraphqlController#execute`
1. Select **Refresh**.
Some differences from the [query logs](#logs-of-each-graphql-query) described above:
- Some of the [Kibana fields mentioned above](#logs-of-each-graphql-query) are not available to the full request logs.
- The names of filters differ. For example, instead of `json.query_analysis.used_fields` you select `json.graphql.used_fields`.
|
---
stage: Create
group: Import
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: Reading GraphQL logs
breadcrumbs:
- doc
- development
- graphql_guide
---
We use Kibana to filter GraphQL query logs. Sign in to [Kibana](https://log.gprd.gitlab.net/)
with a `@gitlab.com` email address.
In Kibana we can inspect two kinds of GraphQL logs:
- Logs of each GraphQL query executed within the request.
- Logs of the full request, which due to [query multiplexing](https://graphql-ruby.org/queries/multiplex.html)
may have executed multiple queries.
## Logs of each GraphQL query
In a [multiplex query](https://graphql-ruby.org/queries/multiplex.html), each individual query
is logged separately. We can use subcomponent filtering to inspect these logs.
[Visit Kibana with this filter enabled](https://log.gprd.gitlab.net/goto/a0da8c9a1e9c1f533a058b7d29d13956)
or set up the subcomponent filter using these steps:
1. Add a filter:
1. Filter: `json.subcomponent`
1. Operator: `is`
1. Value: `graphql_json`
1. Select **Refresh**.
You can select Kibana fields from the **Available fields** section of the sidebar to
add columns to the log table, or [visit this view](https://log.gprd.gitlab.net/goto/5826d3d3affb41cac52e637ffc205905),
which already has a set of Kibana fields selected. Some relevant Kibana fields include:
| Kibana field | Description |
| --- | --- |
| `json.operation_name` | The [operation name](https://graphql.org/learn/queries/#operation-name) used by the client. |
| `json.operation_fingerprint`| The [fingerprint](https://graphql-ruby.org/api-doc/1.12.20/GraphQL/Query#fingerprint-instance_method) of the query, used to recognize repeated queries over time. |
| `json.meta.caller_id` | Appears as `graphql:<operation_name>` for queries that came from the GitLab frontend, otherwise as `graphql:unknown`. Can be used to identify internal versus external queries. |
| `json.query_string` | The query string itself. |
| `json.is_mutation` | `true` when a mutation, `false` when not. |
| `json.query_analysis.used_fields` | List of GraphQL fields selected by the query. |
| `json.query_analysis.used_deprecated_fields` | List of deprecated GraphQL fields selected by the query. |
| `json.query_analysis.used_deprecated_arguments` | List of deprecated GraphQL arguments selected by the query. |
| `json.query_analysis.duration_s` | Duration of query execution in seconds. |
| `json.query_analysis.complexity` | The [complexity](../api_graphql_styleguide.md#max-complexity) score of the query. |
### Useful filters
Below are some examples of common Kibana filters.
#### See field usage
[See example of filter](https://log.gprd.gitlab.net/app/r/s/M2QA1).
1. Combine the [subcomponent filter](#logs-of-each-graphql-query) with the following Kibana filter:
1. Filter: `json.query_analysis.used_fields`
1. Operator: `is`
1. Value: `Type.myField`, where `Type.myField` is the type name and field name as it
appears in [our GraphQL API resources documentation](../../api/graphql/reference/_index.md).
1. Select **Refresh**.
#### See deprecated field usage
[See example of filter](https://log.gprd.gitlab.net/app/r/s/A0TY0).
1. Combine the [subcomponent filter](#logs-of-each-graphql-query) with the following Kibana filter:
1. Filter: `json.query_analysis.used_deprecated_fields`
1. Operator: `is`
1. Value: `Type.myField`, where `Type.myField` is the type name and field name as it
appears in [our GraphQL API resources documentation](../../api/graphql/reference/_index.md).
1. Select **Refresh**.
#### See queries that were not made by our frontend
[See example filter](https://log.gprd.gitlab.net/app/r/s/cWkK1).
As mentioned [above](#logs-of-each-graphql-query), `json.meta.caller_id` appears as `graphql:<operation_name>` for queries that
came from the GitLab frontend, otherwise as `graphql:unknown`. This filter be used to identify internal versus external queries.
1. Combine the [subcomponent filter](#logs-of-each-graphql-query) with the following Kibana filter:
1. Filter: `json.meta.caller_id`
1. Operator: `is`
1. Value: `graphql:unknown`
1. Select **Refresh**.
## Logs of the full request
The full request logs encompass log data for all [multiplexed queries](https://graphql-ruby.org/queries/multiplex.html)
in the request, as well as data from time spent outside of `GraphQLController#execute`.
To see the full request logs, do **not** apply the `json.subcomponent` [filter](#logs-of-each-graphql-query), and instead:
1. Add a filter:
1. Filter: `json.meta.caller_id`
1. Operator: `is`
1. Value: `GraphqlController#execute`
1. Select **Refresh**.
Some differences from the [query logs](#logs-of-each-graphql-query) described above:
- Some of the [Kibana fields mentioned above](#logs-of-each-graphql-query) are not available to the full request logs.
- The names of filters differ. For example, instead of `json.query_analysis.used_fields` you select `json.graphql.used_fields`.
|
https://docs.gitlab.com/development/pagination
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/pagination.md
|
2025-08-13
|
doc/development/graphql_guide
|
[
"doc",
"development",
"graphql_guide"
] |
pagination.md
|
Create
|
Import
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
GraphQL pagination
| null |
## Types of pagination
GitLab uses two primary types of pagination: **offset** and **keyset**
(sometimes called cursor-based) pagination.
The GraphQL API mainly uses keyset pagination, falling back to offset pagination when needed.
### Performance considerations
See the [general pagination guidelines section](../database/pagination_guidelines.md) for more information.
### Offset pagination
This is the traditional, page-by-page pagination, that is most common,
and used across much of GitLab. You can recognize it by
a list of page numbers near the bottom of a page, which, when selected,
take you to that page of results.
For example, when you select **Page 100**, we send `100` to the
backend. For example, if each page has say 20 items, the
backend calculates `20 * 100 = 2000`,
and it queries the database by offsetting (skipping) the first 2000
records and pulls the next 20.
```plaintext
page number * page size = where to find my records
```
There are a couple of problems with this:
- Performance. When we query for page 100 (which gives an offset of
2000), then the database has to scan through the table to that
specific offset, and then pick up the next 20 records. As the offset
increases, the performance degrades quickly.
Read more in
[The SQL I Love <3. Efficient pagination of a table with 100M records](http://allyouneedisbackend.com/blog/2017/09/24/the-sql-i-love-part-1-scanning-large-table/).
- Data stability. When you get the 20 items for page 100 (at
offset 2000), GitLab shows those 20 items. If someone then
deletes or adds records in page 99 or before, the items at
offset 2000 become a different set of items. You can even get into a
situation where, when paginating, you could skip over items,
because the list keeps changing.
Read more in
[Pagination: You're (Probably) Doing It Wrong](https://coderwall.com/p/lkcaag/pagination-you-re-probably-doing-it-wrong).
### Keyset pagination
Given any specific record, if you know how to calculate what comes
after it, you can query the database for those specific records.
For example, suppose you have a list of issues sorted by creation date.
If you know the first item on a page has a specific date (say Jan 1), you can ask
for all records that were created after that date and take the first 20.
It no longer matters if many are deleted or added, as you always ask for
the ones after that date, and so get the correct items.
Unfortunately, there is no easy way to know if the issue created
on Jan 1 is on page 20 or page 100.
Some of the benefits and tradeoffs of keyset pagination are
- Performance is much better.
- More data stability for end-users since records are not missing from lists due to
deletions or insertions.
- It's the best way to do infinite scrolling.
- It's more difficult to program and maintain. Easy for `updated_at` and
`sort_order`, complicated (or impossible) for [complex sorting scenarios](#query-complexity).
## Implementation
When pagination is supported for a query, GitLab defaults to using
keyset pagination. You can see where this is configured in
[`pagination/connections.rb`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/lib/gitlab/graphql/pagination/connections.rb).
If a query returns `ActiveRecord::Relation`, keyset pagination is automatically used.
This was a conscious decision to support performance and data stability.
However, there are some cases where we have to use the offset
pagination connection, `OffsetActiveRecordRelationConnection`, such as when
sorting by label priority in issues, due to the complexity of the sort.
If you return a relation from a resolver that is not suitable for keyset
pagination (due to the sort order for example), then you can use the
`BaseResolver#offset_pagination` method to wrap the relation in the correct
connection type. For example:
```ruby
def resolve(**args)
result = Finder.new(object, current_user, args).execute
result = offset_pagination(result) if needs_offset?(args[:sort])
result
end
```
### Keyset pagination
The keyset pagination implementation is a subclass of `GraphQL::Pagination::ActiveRecordRelationConnection`,
which is a part of the `graphql` gem. This is installed as the default for all `ActiveRecord::Relation`.
However, instead of using a cursor based on an offset (which is the default), GitLab uses a more specialized cursor.
The cursor is created by encoding a JSON object which contains the relevant ordering fields. For example:
```ruby
ordering = {"id"=>"72410125", "created_at"=>"2020-10-08 18:05:21.953398000 UTC"}
json = ordering.to_json
cursor = Base64.urlsafe_encode64(json, padding: false)
"eyJpZCI6IjcyNDEwMTI1IiwiY3JlYXRlZF9hdCI6IjIwMjAtMTAtMDggMTg6MDU6MjEuOTUzMzk4MDAwIFVUQyJ9"
json = Base64.urlsafe_decode64(cursor)
Gitlab::Json.parse(json)
{"id"=>"72410125", "created_at"=>"2020-10-08 18:05:21.953398000 UTC"}
```
The benefits of storing the order attribute values in the cursor:
- If only the ID of the object were stored, the object and its attributes could be queried.
That would require an additional query, and if the object is no longer there, then the needed
attributes are not available.
- If an attribute is `NULL`, then one SQL query can be used. If it's not `NULL`, then a
different SQL query can be used.
Based on whether the main attribute field being sorted on is `NULL` in the cursor, the proper query
condition is built. The last ordering field is considered to be unique (a primary key), meaning the
column never contains `NULL` values.
#### Query complexity
We only support two ordering fields, and one of those fields needs to be the primary key.
Here are two examples of pseudocode for the query:
- **Two-condition query.** `X` represents the values from the cursor. `C` represents
the columns in the database, sorted in ascending order, using an `:after` cursor, and with `NULL`
values sorted last.
```plaintext
X1 IS NOT NULL
AND
(C1 > X1)
OR
(C1 IS NULL)
OR
(C1 = X1
AND
C2 > X2)
X1 IS NULL
AND
(C1 IS NULL
AND
C2 > X2)
```
Below is an example based on the relation `Issue.order(relative_position: :asc).order(id: :asc)`
with an after cursor of `relative_position: 1500, id: 500`:
```plaintext
when cursor[relative_position] is not NULL
("issues"."relative_position" > 1500)
OR (
"issues"."relative_position" = 1500
AND
"issues"."id" > 500
)
OR ("issues"."relative_position" IS NULL)
when cursor[relative_position] is NULL
"issues"."relative_position" IS NULL
AND
"issues"."id" > 500
```
- **Three-condition query.** The example below is not complete, but shows the
complexity of adding one more condition. `X` represents the values from the cursor. `C` represents
the columns in the database, sorted in ascending order, using an `:after` cursor, and with `NULL`
values sorted last.
```plaintext
X1 IS NOT NULL
AND
(C1 > X1)
OR
(C1 IS NULL)
OR
(C1 = X1 AND C2 > X2)
OR
(C1 = X1
AND
X2 IS NOT NULL
AND
((C2 > X2)
OR
(C2 IS NULL)
OR
(C2 = X2 AND C3 > X3)
OR
X2 IS NULL.....
```
By using
[`Gitlab::Graphql::Pagination::Keyset::QueryBuilder`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/lib/gitlab/graphql/pagination/keyset/query_builder.rb),
we're able to build the necessary SQL conditions and apply them to the Active Record relation.
Complex queries can be difficult or impossible to use. For example,
in [`issuable.rb`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/app/models/concerns/issuable.rb),
the `order_due_date_and_labels_priority` method creates a very complex query.
These types of queries are not supported. In these instances, you can use offset pagination.
#### Gotchas
Do not define a collection's order using the string syntax:
```ruby
# Bad
items.order('created_at DESC')
```
Instead, use the hash syntax:
```ruby
# Good
items.order(created_at: :desc)
```
The first example won't correctly embed the sort information (`created_at`, in
the example above) into the pagination cursors, which will result in an
incorrect sort order.
### Offset pagination
There are times when the [complexity of sorting](#query-complexity)
is more than our keyset pagination can handle.
For example, in [`ProjectIssuesResolver`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/app/graphql/resolvers/project_issues_resolver.rb),
when sorting by `priority_asc`, we can't use keyset pagination as the ordering is much
too complex. For more information, read [`issuable.rb`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/app/models/concerns/issuable.rb).
In cases like this, we can fall back to regular offset pagination by returning a
[`Gitlab::Graphql::Pagination::OffsetActiveRecordRelationConnection`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/lib/gitlab/graphql/pagination/offset_active_record_relation_connection.rb)
instead of an `ActiveRecord::Relation`:
```ruby
def resolve(parent, finder, **args)
issues = apply_lookahead(Gitlab::Graphql::Loaders::IssuableLoader.new(parent, finder).batching_find_all)
if non_stable_cursor_sort?(args[:sort])
# Certain complex sorts are not supported by the stable cursor pagination yet.
# In these cases, we use offset pagination, so we return the correct connection.
offset_pagination(issues)
else
issues
end
end
```
<!-- ### External pagination -->
### External pagination
There may be times where you need to return data through the GitLab API that is stored in
another system. In these cases you may have to paginate a third-party's API.
An example of this is with our [Error Tracking](../../operations/error_tracking.md) implementation,
where we proxy [Sentry errors](../../operations/sentry_error_tracking.md) through
the GitLab API. We do this by calling the Sentry API which enforces its own pagination rules.
This means we cannot access the collection within GitLab to perform our own custom pagination.
For consistency, we manually set the pagination cursors based on values returned by the external API, using `Gitlab::Graphql::ExternallyPaginatedArray.new(previous_cursor, next_cursor, *items)`.
You can see an example implementation in the following files:
- [`types/error__tracking/sentry_error_collection_type.rb`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/app/graphql/types/error_tracking/sentry_error_collection_type.rb) which adds an extension to `field :errors`.
- [`resolvers/error_tracking/sentry_errors_resolver.rb`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/app/graphql/resolvers/error_tracking/sentry_errors_resolver.rb) which returns the data from the resolver.
## Testing
Any GraphQL field that supports pagination and sorting should be tested
using the sorted paginated query shared example found in
[`graphql/sorted_paginated_query_shared_examples.rb`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/spec/support/shared_examples/graphql/sorted_paginated_query_shared_examples.rb).
It helps verify that your sort keys are compatible and that cursors
work properly.
This is particularly important when using keyset pagination, as some sort keys might not be supported.
Add a section to your request specs like this:
```ruby
describe 'sorting and pagination' do
...
end
```
You can then use
[`issues_spec.rb`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/spec/requests/api/graphql/project/issues_spec.rb)
as an example to construct your tests.
[`graphql/sorted_paginated_query_shared_examples.rb`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/spec/support/shared_examples/graphql/sorted_paginated_query_shared_examples.rb)
also contains some documentation on how to use the shared examples.
The shared example requires certain `let` variables and methods to be set up:
```ruby
describe 'sorting and pagination' do
let_it_be(:sort_project) { create(:project, :public) }
let(:data_path) { [:project, :issues] }
def pagination_query(params)
graphql_query_for( :project, { full_path: sort_project.full_path },
query_nodes(:issues, :id, include_pagination_info: true, args: params))
)
end
def pagination_results_data(nodes)
nodes.map { |issue| issue['iid'].to_i }
end
context 'when sorting by weight' do
let_it_be(:issues) { make_some_issues_with_weights }
context 'when ascending' do
let(:ordered_issues) { issues.sort_by(&:weight) }
it_behaves_like 'sorted paginated query' do
let(:sort_param) { :WEIGHT_ASC }
let(:first_param) { 2 }
let(:all_records) { ordered_issues.map(&:iid) }
end
end
end
```
|
---
stage: Create
group: Import
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: GraphQL pagination
breadcrumbs:
- doc
- development
- graphql_guide
---
## Types of pagination
GitLab uses two primary types of pagination: **offset** and **keyset**
(sometimes called cursor-based) pagination.
The GraphQL API mainly uses keyset pagination, falling back to offset pagination when needed.
### Performance considerations
See the [general pagination guidelines section](../database/pagination_guidelines.md) for more information.
### Offset pagination
This is the traditional, page-by-page pagination, that is most common,
and used across much of GitLab. You can recognize it by
a list of page numbers near the bottom of a page, which, when selected,
take you to that page of results.
For example, when you select **Page 100**, we send `100` to the
backend. For example, if each page has say 20 items, the
backend calculates `20 * 100 = 2000`,
and it queries the database by offsetting (skipping) the first 2000
records and pulls the next 20.
```plaintext
page number * page size = where to find my records
```
There are a couple of problems with this:
- Performance. When we query for page 100 (which gives an offset of
2000), then the database has to scan through the table to that
specific offset, and then pick up the next 20 records. As the offset
increases, the performance degrades quickly.
Read more in
[The SQL I Love <3. Efficient pagination of a table with 100M records](http://allyouneedisbackend.com/blog/2017/09/24/the-sql-i-love-part-1-scanning-large-table/).
- Data stability. When you get the 20 items for page 100 (at
offset 2000), GitLab shows those 20 items. If someone then
deletes or adds records in page 99 or before, the items at
offset 2000 become a different set of items. You can even get into a
situation where, when paginating, you could skip over items,
because the list keeps changing.
Read more in
[Pagination: You're (Probably) Doing It Wrong](https://coderwall.com/p/lkcaag/pagination-you-re-probably-doing-it-wrong).
### Keyset pagination
Given any specific record, if you know how to calculate what comes
after it, you can query the database for those specific records.
For example, suppose you have a list of issues sorted by creation date.
If you know the first item on a page has a specific date (say Jan 1), you can ask
for all records that were created after that date and take the first 20.
It no longer matters if many are deleted or added, as you always ask for
the ones after that date, and so get the correct items.
Unfortunately, there is no easy way to know if the issue created
on Jan 1 is on page 20 or page 100.
Some of the benefits and tradeoffs of keyset pagination are
- Performance is much better.
- More data stability for end-users since records are not missing from lists due to
deletions or insertions.
- It's the best way to do infinite scrolling.
- It's more difficult to program and maintain. Easy for `updated_at` and
`sort_order`, complicated (or impossible) for [complex sorting scenarios](#query-complexity).
## Implementation
When pagination is supported for a query, GitLab defaults to using
keyset pagination. You can see where this is configured in
[`pagination/connections.rb`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/lib/gitlab/graphql/pagination/connections.rb).
If a query returns `ActiveRecord::Relation`, keyset pagination is automatically used.
This was a conscious decision to support performance and data stability.
However, there are some cases where we have to use the offset
pagination connection, `OffsetActiveRecordRelationConnection`, such as when
sorting by label priority in issues, due to the complexity of the sort.
If you return a relation from a resolver that is not suitable for keyset
pagination (due to the sort order for example), then you can use the
`BaseResolver#offset_pagination` method to wrap the relation in the correct
connection type. For example:
```ruby
def resolve(**args)
result = Finder.new(object, current_user, args).execute
result = offset_pagination(result) if needs_offset?(args[:sort])
result
end
```
### Keyset pagination
The keyset pagination implementation is a subclass of `GraphQL::Pagination::ActiveRecordRelationConnection`,
which is a part of the `graphql` gem. This is installed as the default for all `ActiveRecord::Relation`.
However, instead of using a cursor based on an offset (which is the default), GitLab uses a more specialized cursor.
The cursor is created by encoding a JSON object which contains the relevant ordering fields. For example:
```ruby
ordering = {"id"=>"72410125", "created_at"=>"2020-10-08 18:05:21.953398000 UTC"}
json = ordering.to_json
cursor = Base64.urlsafe_encode64(json, padding: false)
"eyJpZCI6IjcyNDEwMTI1IiwiY3JlYXRlZF9hdCI6IjIwMjAtMTAtMDggMTg6MDU6MjEuOTUzMzk4MDAwIFVUQyJ9"
json = Base64.urlsafe_decode64(cursor)
Gitlab::Json.parse(json)
{"id"=>"72410125", "created_at"=>"2020-10-08 18:05:21.953398000 UTC"}
```
The benefits of storing the order attribute values in the cursor:
- If only the ID of the object were stored, the object and its attributes could be queried.
That would require an additional query, and if the object is no longer there, then the needed
attributes are not available.
- If an attribute is `NULL`, then one SQL query can be used. If it's not `NULL`, then a
different SQL query can be used.
Based on whether the main attribute field being sorted on is `NULL` in the cursor, the proper query
condition is built. The last ordering field is considered to be unique (a primary key), meaning the
column never contains `NULL` values.
#### Query complexity
We only support two ordering fields, and one of those fields needs to be the primary key.
Here are two examples of pseudocode for the query:
- **Two-condition query.** `X` represents the values from the cursor. `C` represents
the columns in the database, sorted in ascending order, using an `:after` cursor, and with `NULL`
values sorted last.
```plaintext
X1 IS NOT NULL
AND
(C1 > X1)
OR
(C1 IS NULL)
OR
(C1 = X1
AND
C2 > X2)
X1 IS NULL
AND
(C1 IS NULL
AND
C2 > X2)
```
Below is an example based on the relation `Issue.order(relative_position: :asc).order(id: :asc)`
with an after cursor of `relative_position: 1500, id: 500`:
```plaintext
when cursor[relative_position] is not NULL
("issues"."relative_position" > 1500)
OR (
"issues"."relative_position" = 1500
AND
"issues"."id" > 500
)
OR ("issues"."relative_position" IS NULL)
when cursor[relative_position] is NULL
"issues"."relative_position" IS NULL
AND
"issues"."id" > 500
```
- **Three-condition query.** The example below is not complete, but shows the
complexity of adding one more condition. `X` represents the values from the cursor. `C` represents
the columns in the database, sorted in ascending order, using an `:after` cursor, and with `NULL`
values sorted last.
```plaintext
X1 IS NOT NULL
AND
(C1 > X1)
OR
(C1 IS NULL)
OR
(C1 = X1 AND C2 > X2)
OR
(C1 = X1
AND
X2 IS NOT NULL
AND
((C2 > X2)
OR
(C2 IS NULL)
OR
(C2 = X2 AND C3 > X3)
OR
X2 IS NULL.....
```
By using
[`Gitlab::Graphql::Pagination::Keyset::QueryBuilder`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/lib/gitlab/graphql/pagination/keyset/query_builder.rb),
we're able to build the necessary SQL conditions and apply them to the Active Record relation.
Complex queries can be difficult or impossible to use. For example,
in [`issuable.rb`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/app/models/concerns/issuable.rb),
the `order_due_date_and_labels_priority` method creates a very complex query.
These types of queries are not supported. In these instances, you can use offset pagination.
#### Gotchas
Do not define a collection's order using the string syntax:
```ruby
# Bad
items.order('created_at DESC')
```
Instead, use the hash syntax:
```ruby
# Good
items.order(created_at: :desc)
```
The first example won't correctly embed the sort information (`created_at`, in
the example above) into the pagination cursors, which will result in an
incorrect sort order.
### Offset pagination
There are times when the [complexity of sorting](#query-complexity)
is more than our keyset pagination can handle.
For example, in [`ProjectIssuesResolver`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/app/graphql/resolvers/project_issues_resolver.rb),
when sorting by `priority_asc`, we can't use keyset pagination as the ordering is much
too complex. For more information, read [`issuable.rb`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/app/models/concerns/issuable.rb).
In cases like this, we can fall back to regular offset pagination by returning a
[`Gitlab::Graphql::Pagination::OffsetActiveRecordRelationConnection`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/lib/gitlab/graphql/pagination/offset_active_record_relation_connection.rb)
instead of an `ActiveRecord::Relation`:
```ruby
def resolve(parent, finder, **args)
issues = apply_lookahead(Gitlab::Graphql::Loaders::IssuableLoader.new(parent, finder).batching_find_all)
if non_stable_cursor_sort?(args[:sort])
# Certain complex sorts are not supported by the stable cursor pagination yet.
# In these cases, we use offset pagination, so we return the correct connection.
offset_pagination(issues)
else
issues
end
end
```
<!-- ### External pagination -->
### External pagination
There may be times where you need to return data through the GitLab API that is stored in
another system. In these cases you may have to paginate a third-party's API.
An example of this is with our [Error Tracking](../../operations/error_tracking.md) implementation,
where we proxy [Sentry errors](../../operations/sentry_error_tracking.md) through
the GitLab API. We do this by calling the Sentry API which enforces its own pagination rules.
This means we cannot access the collection within GitLab to perform our own custom pagination.
For consistency, we manually set the pagination cursors based on values returned by the external API, using `Gitlab::Graphql::ExternallyPaginatedArray.new(previous_cursor, next_cursor, *items)`.
You can see an example implementation in the following files:
- [`types/error__tracking/sentry_error_collection_type.rb`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/app/graphql/types/error_tracking/sentry_error_collection_type.rb) which adds an extension to `field :errors`.
- [`resolvers/error_tracking/sentry_errors_resolver.rb`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/app/graphql/resolvers/error_tracking/sentry_errors_resolver.rb) which returns the data from the resolver.
## Testing
Any GraphQL field that supports pagination and sorting should be tested
using the sorted paginated query shared example found in
[`graphql/sorted_paginated_query_shared_examples.rb`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/spec/support/shared_examples/graphql/sorted_paginated_query_shared_examples.rb).
It helps verify that your sort keys are compatible and that cursors
work properly.
This is particularly important when using keyset pagination, as some sort keys might not be supported.
Add a section to your request specs like this:
```ruby
describe 'sorting and pagination' do
...
end
```
You can then use
[`issues_spec.rb`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/spec/requests/api/graphql/project/issues_spec.rb)
as an example to construct your tests.
[`graphql/sorted_paginated_query_shared_examples.rb`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/spec/support/shared_examples/graphql/sorted_paginated_query_shared_examples.rb)
also contains some documentation on how to use the shared examples.
The shared example requires certain `let` variables and methods to be set up:
```ruby
describe 'sorting and pagination' do
let_it_be(:sort_project) { create(:project, :public) }
let(:data_path) { [:project, :issues] }
def pagination_query(params)
graphql_query_for( :project, { full_path: sort_project.full_path },
query_nodes(:issues, :id, include_pagination_info: true, args: params))
)
end
def pagination_results_data(nodes)
nodes.map { |issue| issue['iid'].to_i }
end
context 'when sorting by weight' do
let_it_be(:issues) { make_some_issues_with_weights }
context 'when ascending' do
let(:ordered_issues) { issues.sort_by(&:weight) }
it_behaves_like 'sorted paginated query' do
let(:sort_param) { :WEIGHT_ASC }
let(:first_param) { 2 }
let(:all_records) { ordered_issues.map(&:iid) }
end
end
end
```
|
https://docs.gitlab.com/development/reviewing
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/reviewing.md
|
2025-08-13
|
doc/development/graphql_guide
|
[
"doc",
"development",
"graphql_guide"
] |
reviewing.md
|
none
|
unassigned
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
GraphQL API merge request checklist
| null |
The GitLab GraphQL API has a fair degree of complexity so it's important that merge requests containing GraphQL changes be reviewed by someone familiar with GraphQL.
You can ping one via the `@gitlab-org/graphql-experts` group in a MR or in the [`#f_graphql` channel](https://gitlab.slack.com/archives/C6MLS3XEU) in Slack (available to GitLab team members only).
GraphQL queries need to be reviewed for:
- breaking changes
- authorization
- performance
## Review criteria
This is not an exhaustive list.
### Description with sample query
Ensure that the description includes a sample query with setup instructions.
Try running the query in [GraphiQL](../api_graphql_styleguide.md#graphiql) on your local GDK instance.
### No breaking changes (unless after full deprecation cycle)
Check the MR for any [breaking changes](../api_graphql_styleguide.md#breaking-changes).
If a feature is marked as an [experiment](../api_graphql_styleguide.md#mark-schema-items-as-experiments), you can make breaking changes immediately, with no deprecation period.
For more information, see [deprecation and removal process](../../api/graphql/_index.md#deprecation-and-removal-process).
### Multiversion compatibility
Ensure that multi-version compatibility is guaranteed.
This generally means frontend and backend code for the same GraphQL feature can't be shipped in the same release.
For details, see [multiple version compatibility](../multi_version_compatibility.md).
### Technical writing review
Changes to the generated API docs require a technical writer review.
### Changelog
Public-facing changes that are not marked as an [experiment](../api_graphql_styleguide.md#mark-schema-items-as-experiments) require a [changelog entry](../changelog.md).
### Use the framework
GraphQL is a framework with many moving parts. It's important that the framework is followed.
- Do not manually invoke framework bits. For example, do not instantiate resolvers during execution and instead let the framework do that.
- You can subclass resolvers, as in `MyResolver.single` (see [deriving resolvers](../api_graphql_styleguide.md#deriving-resolvers)).
- Use the `ready?` method for more complex argument logic (see [correct use of resolver#ready](../api_graphql_styleguide.md#correct-use-of-resolverready)).
- Use the `prepare` method for more complex argument validation (see [Preprocessing](https://graphql-ruby.org/fields/arguments.html#preprocessing)).
For details, see [resolver guide](../api_graphql_styleguide.md#writing-resolvers).
### Authorization
Ensure proper authorization is followed and that `authorize :some_ability` is tested in the specs.
For details, see [authorization guide](authorization.md).
### Performance
Ensure:
- You have [checked for N+1s](../api_graphql_styleguide.md#how-to-see-n1-problems-in-development) and
used [optimizations](../api_graphql_styleguide.md#optimizations) to remove N+1s whenever possible.
- You use [laziness](../api_graphql_styleguide.md#laziness) appropriately.
### Use appropriate types
For example:
- [`TimeType`](../api_graphql_styleguide.md#typestimetype) for Ruby `Time` and `DateTime` objects.
- Global IDs for `id` fields
For details, see [types](../api_graphql_styleguide.md#types).
### Appropriate complexity
Query complexity is a way of quantifying how expensive a query is likely to be. Query complexity limits are defined as constants in the schema.
When a resolver or type is expensive to call we need to ensure that the query complexity reflects that.
For details, see [max complexity](../api_graphql_styleguide.md#max-complexity), [field complexity](../api_graphql_styleguide.md#field-complexity) and [query limits](../api_graphql_styleguide.md#query-limits).
### Testing
- Resolver (unit) specs are deprecated in favour of request (integration) specs.
- Many aspects of our framework are outside the `resolve` method and a request spec is the only way to ensure they behave properly.
- Every GraphQL change MR should ideally have changes to API specs.
For details, see [testing guide](../api_graphql_styleguide.md#testing).
|
---
stage: none
group: unassigned
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: GraphQL API merge request checklist
breadcrumbs:
- doc
- development
- graphql_guide
---
The GitLab GraphQL API has a fair degree of complexity so it's important that merge requests containing GraphQL changes be reviewed by someone familiar with GraphQL.
You can ping one via the `@gitlab-org/graphql-experts` group in a MR or in the [`#f_graphql` channel](https://gitlab.slack.com/archives/C6MLS3XEU) in Slack (available to GitLab team members only).
GraphQL queries need to be reviewed for:
- breaking changes
- authorization
- performance
## Review criteria
This is not an exhaustive list.
### Description with sample query
Ensure that the description includes a sample query with setup instructions.
Try running the query in [GraphiQL](../api_graphql_styleguide.md#graphiql) on your local GDK instance.
### No breaking changes (unless after full deprecation cycle)
Check the MR for any [breaking changes](../api_graphql_styleguide.md#breaking-changes).
If a feature is marked as an [experiment](../api_graphql_styleguide.md#mark-schema-items-as-experiments), you can make breaking changes immediately, with no deprecation period.
For more information, see [deprecation and removal process](../../api/graphql/_index.md#deprecation-and-removal-process).
### Multiversion compatibility
Ensure that multi-version compatibility is guaranteed.
This generally means frontend and backend code for the same GraphQL feature can't be shipped in the same release.
For details, see [multiple version compatibility](../multi_version_compatibility.md).
### Technical writing review
Changes to the generated API docs require a technical writer review.
### Changelog
Public-facing changes that are not marked as an [experiment](../api_graphql_styleguide.md#mark-schema-items-as-experiments) require a [changelog entry](../changelog.md).
### Use the framework
GraphQL is a framework with many moving parts. It's important that the framework is followed.
- Do not manually invoke framework bits. For example, do not instantiate resolvers during execution and instead let the framework do that.
- You can subclass resolvers, as in `MyResolver.single` (see [deriving resolvers](../api_graphql_styleguide.md#deriving-resolvers)).
- Use the `ready?` method for more complex argument logic (see [correct use of resolver#ready](../api_graphql_styleguide.md#correct-use-of-resolverready)).
- Use the `prepare` method for more complex argument validation (see [Preprocessing](https://graphql-ruby.org/fields/arguments.html#preprocessing)).
For details, see [resolver guide](../api_graphql_styleguide.md#writing-resolvers).
### Authorization
Ensure proper authorization is followed and that `authorize :some_ability` is tested in the specs.
For details, see [authorization guide](authorization.md).
### Performance
Ensure:
- You have [checked for N+1s](../api_graphql_styleguide.md#how-to-see-n1-problems-in-development) and
used [optimizations](../api_graphql_styleguide.md#optimizations) to remove N+1s whenever possible.
- You use [laziness](../api_graphql_styleguide.md#laziness) appropriately.
### Use appropriate types
For example:
- [`TimeType`](../api_graphql_styleguide.md#typestimetype) for Ruby `Time` and `DateTime` objects.
- Global IDs for `id` fields
For details, see [types](../api_graphql_styleguide.md#types).
### Appropriate complexity
Query complexity is a way of quantifying how expensive a query is likely to be. Query complexity limits are defined as constants in the schema.
When a resolver or type is expensive to call we need to ensure that the query complexity reflects that.
For details, see [max complexity](../api_graphql_styleguide.md#max-complexity), [field complexity](../api_graphql_styleguide.md#field-complexity) and [query limits](../api_graphql_styleguide.md#query-limits).
### Testing
- Resolver (unit) specs are deprecated in favour of request (integration) specs.
- Many aspects of our framework are outside the `resolve` method and a request spec is the only way to ensure they behave properly.
- Every GraphQL change MR should ideally have changes to API specs.
For details, see [testing guide](../api_graphql_styleguide.md#testing).
|
https://docs.gitlab.com/development/authorization
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/authorization.md
|
2025-08-13
|
doc/development/graphql_guide
|
[
"doc",
"development",
"graphql_guide"
] |
authorization.md
|
none
|
unassigned
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
GraphQL Authorization
| null |
Authorizations can be applied in these places:
- Types:
- Objects (all classes descending from `::Types::BaseObject`)
- Enums (all classes descending from `::Types::BaseEnum`)
- Resolvers:
- Field resolvers (all classes descending from `::Types::BaseResolver`)
- Mutations (all classes descending from `::Types::BaseMutation`)
- Fields (all fields declared using the `field` DSL method)
Authorizations cannot be specified for abstract types (interfaces and
unions). Abstract types delegate to their member types.
Basic built in scalars (such as integers) do not have authorizations.
Our authorization system uses the same [`DeclarativePolicy`](../policies.md)
system as throughout the rest of the application.
- For single values (such as `Query.project`), if the currently authenticated
user fails the authorization, the field resolves to `null`.
- For collections (such as `Project.issues`), the collection is filtered to
exclude the objects that the user's authorization checks failed against. This
process of filtering (also known as _redaction_) happens after pagination, so
some pages may be smaller than the requested page size, due to redacted
objects being removed.
Also see [authorizing resources in a mutation](../api_graphql_styleguide.md#authorizing-resources).
{{< alert type="note" >}}
The best practice is to load only what the currently authenticated user is allowed to
view with our existing finders first, without relying on authorization
to filter the records. This minimizes database queries and unnecessary
authorization checks of the loaded records. It also avoids situations,
such as short pages, which can expose the presence of confidential resources.
{{< /alert >}}
See [`authorization_spec.rb`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/spec/graphql/features/authorization_spec.rb)
for examples of all the authorization schemes discussed here.
<!--
if you change this heading (or the location to this file), make sure to update
the referenced link in rubocop/cop/graphql/authorize_types.rb
-->
## Type authorization
Authorize a type by passing an ability to the `authorize` method. All
fields with the same type is authorized by checking that the
currently authenticated user has the required ability.
For example, the following authorization ensures that the currently
authenticated user can only see projects that they have the
`read_project` ability for (so long as the project is returned in a
field that uses `Types::ProjectType`):
```ruby
module Types
class ProjectType < BaseObject
authorize :read_project
end
end
```
You can also authorize against multiple abilities, in which case all of
the ability checks must pass.
For example, the following authorization ensures that the currently
authenticated user must have `read_project` and `another_ability`
abilities to see a project:
```ruby
module Types
class ProjectType < BaseObject
authorize [:read_project, :another_ability]
end
end
```
## Resolver authorization
Resolvers can have their own authorizations, which can be applied either to the
parent object or to the resolved values.
An example of a resolver that authorizes against the parent is
`Resolvers::BoardListsResolver`, which requires that the parent
satisfy `:read_list` before it runs.
An example which authorizes against the resolved resource is
`Resolvers::Ci::ConfigResolver`, which requires that the resolved value satisfy
`:read_pipeline`.
To authorize against the parent, the resolver must _opt in_ (because this
was not the default value initially), by declaring this with `authorizes_object!`:
```ruby
module Resolvers
class MyResolver < BaseResolver
authorizes_object!
authorize :some_permission
end
end
```
To authorize against the resolved value, the resolver must apply the
authorization at some point, typically by using `#authorized_find!(**args)`:
```ruby
module Resolvers
class MyResolver < BaseResolver
authorize :some_permission
def resolve(**args)
authorized_find!(**args) # calls find_object
end
def find_object(id:)
MyThing.find(id)
end
end
end
```
Of the two approaches, authorizing the object is more efficient, because it
helps avoid unnecessary queries.
## Field authorization
Fields can be authorized with the `authorize` option.
Fields authorization is checked against the current object, and
authorization happens before resolution, which means that
fields do not have access to the resolved resource. If you need to
apply an authorization check to a field, you probably want to add
authorization to the resolver, or ideally to the type.
For example, the following authorization ensures that the
authenticated user must have administrator level access to the project
to view the `secretName` field:
```ruby
module Types
class ProjectType < BaseObject
field :secret_name, ::GraphQL::Types::String, null: true, authorize: :owner_access
end
end
```
In this example, we use field authorization (such as
`Ability.allowed?(current_user, :read_transactions, bank_account)`) to avoid
a more expensive query:
```ruby
module Types
class BankAccountType < BaseObject
field :transactions, ::Types::TransactionType.connection_type, null: true,
authorize: :read_transactions
end
end
```
Field authorization is recommended for:
- Scalar fields (strings, booleans, or numbers) that should have different levels
of access controls to other fields.
- Object and collection fields where an access check can be applied to the
parent to save the field resolution, and avoid individual policy checks
on each resolved object.
Field authorization does not replace object level checks, unless the object
precisely matches the access level of the parent project. For example, issues
can be confidential, independent of the access level of the parent. Therefore,
we should not use field authorization for `Project.issue`.
You can also authorize fields against multiple abilities. Pass the abilities
as an array instead of as a single value:
```ruby
module Types
class MyType < BaseObject
field :hidden_field, ::GraphQL::Types::Int,
null: true,
authorize: [:owner_access, :another_ability]
end
end
```
The field authorization on `MyType.hiddenField` implies the following tests:
```ruby
Ability.allowed?(current_user, :owner_access, object_of_my_type) &&
Ability.allowed?(current_user, :another_ability, object_of_my_type)
```
## Type and Field authorizations together
Authorizations are cumulative. In other words, the currently authenticated
user may need to pass authorization requirements on both a field and a field's
type.
In the following simplified example the currently authenticated user
needs both `first_permission` on the user and `second_permission` on the
issue to see the author of the issue.
```ruby
class UserType
authorize :first_permission
end
```
```ruby
class IssueType
field :author, UserType, authorize: :second_permission
end
```
The combination of the object authorization on `UserType` and the field authorization on `IssueType.author` implies the following tests:
```ruby
Ability.allowed?(current_user, :second_permission, issue) &&
Ability.allowed?(current_user, :first_permission, issue.author)
```
### Skip Type authorization for a given field
In some scenarios, a given field is resolved with a dedicated `resolver` and the resolver takes care of checking the
resolved objects' authorization.
In such cases, especially when the field resolves a collection of objects, we'd like to skip the `Type` level
authorization. Depending on the GraphQL query, having these overlapping authorization checks, can add significant overhead.
For such situations, we can specify which abilities should be skipped at `Type` level by specifying the list of abilities
through `skip_type_authorization` on a given field. This option cascades down to all descendant fields as well.
For a real-world example, see
[field :discussions, Types::Notes::DiscussionType](https://gitlab.com/gitlab-org/gitlab/-/blob/84721e500a9a95e22bfd1b34c228db0053b793fb/app/graphql/types/work_items/widgets/notes_type.rb#L24).
In that example, we have `DiscussionType` which specifies `authorize :read_note`. `Discussion` is composed of multiple `notes` of type `NoteType` and `NoteType` also specifies `authorize: :read_note`.
Some of these `notes` may be system notes and may have some specific metadata of type `SystemNoteMetadataType`.
`SystemNoteMetadataType` also specifies the `authorize: :read_note`. Each note can have emojis, which are authorized
with `read_emoji`, which is equivalent to `read_note` in this case.
To represent this in a GraphQL example, we'd have following types:
```ruby
class SomeType < BaseObject
field :discussions, Types::Notes::DiscussionType.connection_type, null: true, resolver: SomeResolver
end
class DiscussionType < BaseObject
authorize :read_note
field :notes, Types::Notes::NoteType.connection_type, null: true
end
class NoteType < BaseObject
authorize :read_note
field :system_note_metadata, SystemNoteMetadataType
field :award_emoji, AwardEmojiType
end
class SystemNoteMetadataType < BaseObject
authorize :read_note
end
class AwardEmojiType < BaseObject
authorize :read_emoji
end
```
And a query like:
```graphql
query {
someType(identified: ID) {
discussions {
nodes {
notes {
nodes {
award_emoji {
name
}
}
}
}
}
}
}
```
For example, if the root object of type `SomeType` has 10 discussions. Each of the 10 discussions have 10 notes. And the first note of each discussion has one emoji.
In this case, we authorize the discussions in `SomeResolver`, that is 10 authorization calls.
Then when we represent each discussion with `DiscussionType`, we authorize each discussion object, again 10 calls. These
specific calls may be fine, as these would have been cached in the request store during resolver authorization because we are authorizing the same objects.
Next, we authorize each note for these 10 discussions, resulting in 10*10 = 100 authorization calls. And lastly for the
first note in each discussion, we would authorize one emoji, that is another 10 calls. So in total we have 130 authorization calls:
- 10 discussions authorized in resolver
- 10 (cached) discussions authorized through `DiscussionType`
- 100 notes authorized through `NoteType`
- 10 emoji authorized through `EmojiType`
We can reduce these 130 calls to just 10 calls by specifying the `skip_type_authorization` on the `discussions` field.
For that, `SomeType` definition changes to:
```ruby
class SomeType < BaseObject
field :discussions, Types::Notes::DiscussionType.connection_type, null: true, resolver: SomeResolver,
skip_type_authorization: [:read_note, :read_emoji]
end
```
{{< alert type="note" >}}
We can optimize the authorization calls with `skip_type_authorization` in this case, because:
{{< /alert >}}
- We already authorize the discussions in `SomeResolver`
- Permissions to read one note or all notes are the same for a discussion
- Permission to read a note or read an emoji are equivalent
|
---
stage: none
group: unassigned
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: GraphQL Authorization
breadcrumbs:
- doc
- development
- graphql_guide
---
Authorizations can be applied in these places:
- Types:
- Objects (all classes descending from `::Types::BaseObject`)
- Enums (all classes descending from `::Types::BaseEnum`)
- Resolvers:
- Field resolvers (all classes descending from `::Types::BaseResolver`)
- Mutations (all classes descending from `::Types::BaseMutation`)
- Fields (all fields declared using the `field` DSL method)
Authorizations cannot be specified for abstract types (interfaces and
unions). Abstract types delegate to their member types.
Basic built in scalars (such as integers) do not have authorizations.
Our authorization system uses the same [`DeclarativePolicy`](../policies.md)
system as throughout the rest of the application.
- For single values (such as `Query.project`), if the currently authenticated
user fails the authorization, the field resolves to `null`.
- For collections (such as `Project.issues`), the collection is filtered to
exclude the objects that the user's authorization checks failed against. This
process of filtering (also known as _redaction_) happens after pagination, so
some pages may be smaller than the requested page size, due to redacted
objects being removed.
Also see [authorizing resources in a mutation](../api_graphql_styleguide.md#authorizing-resources).
{{< alert type="note" >}}
The best practice is to load only what the currently authenticated user is allowed to
view with our existing finders first, without relying on authorization
to filter the records. This minimizes database queries and unnecessary
authorization checks of the loaded records. It also avoids situations,
such as short pages, which can expose the presence of confidential resources.
{{< /alert >}}
See [`authorization_spec.rb`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/spec/graphql/features/authorization_spec.rb)
for examples of all the authorization schemes discussed here.
<!--
if you change this heading (or the location to this file), make sure to update
the referenced link in rubocop/cop/graphql/authorize_types.rb
-->
## Type authorization
Authorize a type by passing an ability to the `authorize` method. All
fields with the same type is authorized by checking that the
currently authenticated user has the required ability.
For example, the following authorization ensures that the currently
authenticated user can only see projects that they have the
`read_project` ability for (so long as the project is returned in a
field that uses `Types::ProjectType`):
```ruby
module Types
class ProjectType < BaseObject
authorize :read_project
end
end
```
You can also authorize against multiple abilities, in which case all of
the ability checks must pass.
For example, the following authorization ensures that the currently
authenticated user must have `read_project` and `another_ability`
abilities to see a project:
```ruby
module Types
class ProjectType < BaseObject
authorize [:read_project, :another_ability]
end
end
```
## Resolver authorization
Resolvers can have their own authorizations, which can be applied either to the
parent object or to the resolved values.
An example of a resolver that authorizes against the parent is
`Resolvers::BoardListsResolver`, which requires that the parent
satisfy `:read_list` before it runs.
An example which authorizes against the resolved resource is
`Resolvers::Ci::ConfigResolver`, which requires that the resolved value satisfy
`:read_pipeline`.
To authorize against the parent, the resolver must _opt in_ (because this
was not the default value initially), by declaring this with `authorizes_object!`:
```ruby
module Resolvers
class MyResolver < BaseResolver
authorizes_object!
authorize :some_permission
end
end
```
To authorize against the resolved value, the resolver must apply the
authorization at some point, typically by using `#authorized_find!(**args)`:
```ruby
module Resolvers
class MyResolver < BaseResolver
authorize :some_permission
def resolve(**args)
authorized_find!(**args) # calls find_object
end
def find_object(id:)
MyThing.find(id)
end
end
end
```
Of the two approaches, authorizing the object is more efficient, because it
helps avoid unnecessary queries.
## Field authorization
Fields can be authorized with the `authorize` option.
Fields authorization is checked against the current object, and
authorization happens before resolution, which means that
fields do not have access to the resolved resource. If you need to
apply an authorization check to a field, you probably want to add
authorization to the resolver, or ideally to the type.
For example, the following authorization ensures that the
authenticated user must have administrator level access to the project
to view the `secretName` field:
```ruby
module Types
class ProjectType < BaseObject
field :secret_name, ::GraphQL::Types::String, null: true, authorize: :owner_access
end
end
```
In this example, we use field authorization (such as
`Ability.allowed?(current_user, :read_transactions, bank_account)`) to avoid
a more expensive query:
```ruby
module Types
class BankAccountType < BaseObject
field :transactions, ::Types::TransactionType.connection_type, null: true,
authorize: :read_transactions
end
end
```
Field authorization is recommended for:
- Scalar fields (strings, booleans, or numbers) that should have different levels
of access controls to other fields.
- Object and collection fields where an access check can be applied to the
parent to save the field resolution, and avoid individual policy checks
on each resolved object.
Field authorization does not replace object level checks, unless the object
precisely matches the access level of the parent project. For example, issues
can be confidential, independent of the access level of the parent. Therefore,
we should not use field authorization for `Project.issue`.
You can also authorize fields against multiple abilities. Pass the abilities
as an array instead of as a single value:
```ruby
module Types
class MyType < BaseObject
field :hidden_field, ::GraphQL::Types::Int,
null: true,
authorize: [:owner_access, :another_ability]
end
end
```
The field authorization on `MyType.hiddenField` implies the following tests:
```ruby
Ability.allowed?(current_user, :owner_access, object_of_my_type) &&
Ability.allowed?(current_user, :another_ability, object_of_my_type)
```
## Type and Field authorizations together
Authorizations are cumulative. In other words, the currently authenticated
user may need to pass authorization requirements on both a field and a field's
type.
In the following simplified example the currently authenticated user
needs both `first_permission` on the user and `second_permission` on the
issue to see the author of the issue.
```ruby
class UserType
authorize :first_permission
end
```
```ruby
class IssueType
field :author, UserType, authorize: :second_permission
end
```
The combination of the object authorization on `UserType` and the field authorization on `IssueType.author` implies the following tests:
```ruby
Ability.allowed?(current_user, :second_permission, issue) &&
Ability.allowed?(current_user, :first_permission, issue.author)
```
### Skip Type authorization for a given field
In some scenarios, a given field is resolved with a dedicated `resolver` and the resolver takes care of checking the
resolved objects' authorization.
In such cases, especially when the field resolves a collection of objects, we'd like to skip the `Type` level
authorization. Depending on the GraphQL query, having these overlapping authorization checks, can add significant overhead.
For such situations, we can specify which abilities should be skipped at `Type` level by specifying the list of abilities
through `skip_type_authorization` on a given field. This option cascades down to all descendant fields as well.
For a real-world example, see
[field :discussions, Types::Notes::DiscussionType](https://gitlab.com/gitlab-org/gitlab/-/blob/84721e500a9a95e22bfd1b34c228db0053b793fb/app/graphql/types/work_items/widgets/notes_type.rb#L24).
In that example, we have `DiscussionType` which specifies `authorize :read_note`. `Discussion` is composed of multiple `notes` of type `NoteType` and `NoteType` also specifies `authorize: :read_note`.
Some of these `notes` may be system notes and may have some specific metadata of type `SystemNoteMetadataType`.
`SystemNoteMetadataType` also specifies the `authorize: :read_note`. Each note can have emojis, which are authorized
with `read_emoji`, which is equivalent to `read_note` in this case.
To represent this in a GraphQL example, we'd have following types:
```ruby
class SomeType < BaseObject
field :discussions, Types::Notes::DiscussionType.connection_type, null: true, resolver: SomeResolver
end
class DiscussionType < BaseObject
authorize :read_note
field :notes, Types::Notes::NoteType.connection_type, null: true
end
class NoteType < BaseObject
authorize :read_note
field :system_note_metadata, SystemNoteMetadataType
field :award_emoji, AwardEmojiType
end
class SystemNoteMetadataType < BaseObject
authorize :read_note
end
class AwardEmojiType < BaseObject
authorize :read_emoji
end
```
And a query like:
```graphql
query {
someType(identified: ID) {
discussions {
nodes {
notes {
nodes {
award_emoji {
name
}
}
}
}
}
}
}
```
For example, if the root object of type `SomeType` has 10 discussions. Each of the 10 discussions have 10 notes. And the first note of each discussion has one emoji.
In this case, we authorize the discussions in `SomeResolver`, that is 10 authorization calls.
Then when we represent each discussion with `DiscussionType`, we authorize each discussion object, again 10 calls. These
specific calls may be fine, as these would have been cached in the request store during resolver authorization because we are authorizing the same objects.
Next, we authorize each note for these 10 discussions, resulting in 10*10 = 100 authorization calls. And lastly for the
first note in each discussion, we would authorize one emoji, that is another 10 calls. So in total we have 130 authorization calls:
- 10 discussions authorized in resolver
- 10 (cached) discussions authorized through `DiscussionType`
- 100 notes authorized through `NoteType`
- 10 emoji authorized through `EmojiType`
We can reduce these 130 calls to just 10 calls by specifying the `skip_type_authorization` on the `discussions` field.
For that, `SomeType` definition changes to:
```ruby
class SomeType < BaseObject
field :discussions, Types::Notes::DiscussionType.connection_type, null: true, resolver: SomeResolver,
skip_type_authorization: [:read_note, :read_emoji]
end
```
{{< alert type="note" >}}
We can optimize the authorization calls with `skip_type_authorization` in this case, because:
{{< /alert >}}
- We already authorize the discussions in `SomeResolver`
- Permissions to read one note or all notes are the same for a discussion
- Permission to read a note or read an emoji are equivalent
|
https://docs.gitlab.com/development/dnsmasq
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/dnsmasq.md
|
2025-08-13
|
doc/development/pages
|
[
"doc",
"development",
"pages"
] |
dnsmasq.md
|
Plan
|
Knowledge
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Using `dnsmasq` to dynamically handle GitLab Pages subdomains
|
dnsmasq configuration guidelines for GitLab Pages
|
You can use [`dnsmasq`](https://wiki.debian.org/dnsmasq) to test
GitLab Pages sites locally without having to configure each site on `/etc/hosts`.
## Use `dnsmasq` on macOS
To use `dnsmasq` on macOS:
1. Install `dnsmasq`:
```console
brew install dnsmasq
```
1. Set up the `*.test` domain lookup:
```console
# Ensure the configuration directory exists
mkdir -p $(brew --prefix)/etc/
# Add `*.test` to the `127.0.0.1` lookup
echo 'address=/.test/127.0.0.1' >> $(brew --prefix)/etc/dnsmasq.conf
# Start `dnsmasq`
sudo brew services start dnsmasq
```
1. Create a DNS resolver:
```console
# Ensure the resolver directory exists
sudo mkdir -p /etc/resolver
# Add the localhost address as a resolver for `.test` domains
echo "nameserver 127.0.0.1" | sudo tee /etc/resolver/test
```
You can now create a GitLab Pages site locally with a dynamic domain.
If you [configure GitLab Pages](_index.md#configuring-gitlab-pages-with-gdk) and
create a `root/html` project, that project is accessible through `http://root.gdk.pages.test:3010/html`.
## Troubleshooting
For GitLab Runner, you must define `gdk.test` in `/etc/hosts`.
If you're using GitLab Runner locally, you must also configure `/etc/hosts`:
```console
# Append GDK configuration in `/etc/hosts`
cat <<-EOF | sudo tee -a /etc/hosts
## GDK
127.0.0.1 gdk.test
::1 gdk.test
# ----------------------------
EOF
```
|
---
stage: Plan
group: Knowledge
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
description: dnsmasq configuration guidelines for GitLab Pages
title: Using `dnsmasq` to dynamically handle GitLab Pages subdomains
breadcrumbs:
- doc
- development
- pages
---
You can use [`dnsmasq`](https://wiki.debian.org/dnsmasq) to test
GitLab Pages sites locally without having to configure each site on `/etc/hosts`.
## Use `dnsmasq` on macOS
To use `dnsmasq` on macOS:
1. Install `dnsmasq`:
```console
brew install dnsmasq
```
1. Set up the `*.test` domain lookup:
```console
# Ensure the configuration directory exists
mkdir -p $(brew --prefix)/etc/
# Add `*.test` to the `127.0.0.1` lookup
echo 'address=/.test/127.0.0.1' >> $(brew --prefix)/etc/dnsmasq.conf
# Start `dnsmasq`
sudo brew services start dnsmasq
```
1. Create a DNS resolver:
```console
# Ensure the resolver directory exists
sudo mkdir -p /etc/resolver
# Add the localhost address as a resolver for `.test` domains
echo "nameserver 127.0.0.1" | sudo tee /etc/resolver/test
```
You can now create a GitLab Pages site locally with a dynamic domain.
If you [configure GitLab Pages](_index.md#configuring-gitlab-pages-with-gdk) and
create a `root/html` project, that project is accessible through `http://root.gdk.pages.test:3010/html`.
## Troubleshooting
For GitLab Runner, you must define `gdk.test` in `/etc/hosts`.
If you're using GitLab Runner locally, you must also configure `/etc/hosts`:
```console
# Append GDK configuration in `/etc/hosts`
cat <<-EOF | sudo tee -a /etc/hosts
## GDK
127.0.0.1 gdk.test
::1 gdk.test
# ----------------------------
EOF
```
|
https://docs.gitlab.com/development/pages
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/_index.md
|
2025-08-13
|
doc/development/pages
|
[
"doc",
"development",
"pages"
] |
_index.md
|
Plan
|
Knowledge
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Contribute to GitLab Pages development
|
Configuration and contribution guidelines.
|
Learn how to configure GitLab Pages so you can help develop the feature.
## Configuring GitLab Pages hostname
GitLab Pages needs a hostname or domain, as each different GitLab Pages site is accessed through a
subdomain. You can set the GitLab Pages hostname:
- [Without wildcard, editing your hosts file](#without-wildcard-editing-your-hosts-file).
- [With DNS wildcard alternatives](#with-dns-wildcard-alternatives).
### Without wildcard, editing your hosts file
As `/etc/hosts` don't support wildcard hostnames, you must configure one entry
for GitLab Pages, and then one entry for each page site:
```plaintext
127.0.0.1 gdk.test # If you're using GDK
127.0.0.1 pages.gdk.test # Pages host
# Any namespace/group/user needs to be added
# as a subdomain to the pages host. This is because
# /etc/hosts doesn't accept wildcards
127.0.0.1 root.pages.gdk.test # for the root pages
```
### With DNS wildcard alternatives
If instead of editing your `/etc/hosts` you'd prefer to use a DNS wildcard, you can use:
- [`nip.io`](https://nip.io)
- [`dnsmasq`](dnsmasq.md)
## Configuring GitLab Pages without GDK
Create a `gitlab-pages.conf` in the root of the GitLab Pages site, like:
```toml
# Default port is 3010, but you can use any other
listen-http=:3010
# Your local GitLab Pages domain
pages-domain=pages.gdk.test
# Directory where the pages are stored
pages-root=shared/pages
# Show more information in the logs
log-verbose=true
```
To see more options you can check
[`internal/config/flags.go`](https://gitlab.com/gitlab-org/gitlab-pages/blob/master/internal/config/flags.go)
or run `gitlab-pages --help`.
### Running GitLab Pages manually
For any changes in the code, you must run `make` to build the app. It's best to just always run
it before you start the app. It's quick to build so don't worry!
```shell
make && ./gitlab-pages -config=gitlab-pages.conf
```
## Configuring GitLab Pages with GDK
In the following steps, `$GDK_ROOT` is the directory where you cloned GDK.
1. Set up the [GDK hostname](https://gitlab.com/gitlab-org/gitlab-development-kit/-/blob/main/doc/howto/local_network.md).
1. Add a [GitLab Pages hostname](#configuring-gitlab-pages-hostname) to the `gdk.yml`:
```yaml
gitlab_pages:
enabled: true # enable GitLab Pages to be managed by gdk
port: 3010 # default port is 3010
host: pages.gdk.test # the GitLab Pages domain
auto_update: true # if gdk must update GitLab Pages git
verbose: true # show more information in the logs
```
### Running GitLab Pages with GDK
After these configurations are set, GDK manages a GitLab Pages process, giving you access to
it with commands like:
- Start: `gdk start gitlab-pages`
- Stop: `gdk stop gitlab-pages`
- Restart: `gdk restart gitlab-pages`
- Tail logs: `gdk tail gitlab-pages`
### Running GitLab Pages manually
You can also build and start the app independently of GDK processes management.
For any changes in the code, you must run `make` to build the app. It's best to just always run
it before you start the app. It's quick to build so don't worry!
```shell
make && ./gitlab-pages -config=gitlab-pages.conf
```
#### Building GitLab Pages in FIPS mode
```shell
FIPS_MODE=1 make && ./gitlab-pages -config=gitlab-pages.conf
```
### Creating GitLab Pages site
To build a GitLab Pages site locally you must
[configure `gitlab-runner`](https://gitlab.com/gitlab-org/gitlab-development-kit/-/blob/main/doc/howto/runner.md).
For more information, refer to the [user manual](../../user/project/pages/_index.md).
### Enabling access control
GitLab Pages support private sites. Private sites can be accessed only by users
who have access to your GitLab project.
GitLab Pages access control is disabled by default. To enable it:
1. Enable the GitLab Pages access control in GitLab itself. You can do this in two ways:
- If you're not using GDK, edit `gitlab.yml`:
```yaml
# gitlab/config/gitlab.yml
pages:
access_control: true
```
- If you're using GDK, edit `gdk.yml`:
```yaml
# $GDK_ROOT/gdk.yml
gitlab_pages:
enabled: true
access_control: true
```
1. Restart GitLab (if running through the GDK, run `gdk restart`). Running
`gdk reconfigure` overwrites the value of `access_control` in `config/gitlab.yml`.
1. In your local GitLab instance, in the browser go to `http://gdk.test:3000/admin/applications`.
1. Create an [Instance-wide OAuth application](../../integration/oauth_provider.md#create-an-instance-wide-application)
with the `api` scope.
1. Set the value of your `redirect-uri` to the `pages-domain` authorization endpoint
(for example, `http://pages.gdk.test:3010/auth`).
The `redirect-uri` must not contain any GitLab Pages site domain.
1. Add the auth client configuration:
- With GDK, in `gdk.yml`:
```yaml
gitlab_pages:
enabled: true
access_control: true
auth_client_id: $CLIENT_ID # the OAuth application id created in http://gdk.test:3000/admin/applications
auth_client_secret: $CLIENT_SECRET # the OAuth application secret created in http://gdk.test:3000/admin/applications
```
GDK generates random `auth_secret` and builds the `auth_redirect_uri` based on GitLab Pages
host configuration.
- Without GDK, in `gitlab-pages.conf`:
```conf
## the following are only needed if you want to test auth for private projects
auth-client-id=$CLIENT_ID # the OAuth application id created in http://gdk.test:3000/admin/applications
auth-client-secret=$CLIENT_SECRET # the OAuth application secret created in http://gdk.test:3000/admin/applications
auth-secret=$SOME_RANDOM_STRING # should be at least 32 bytes long
auth-redirect-uri=http://pages.gdk.test:3010/auth # the authentication callback url for GitLab Pages
```
1. If running Pages inside the GDK, you can use GDK `protected_config_files` section under `gdk` in
your `gdk.yml` to avoid getting `gitlab-pages.conf` configuration rewritten:
```yaml
gdk:
protected_config_files:
- 'gitlab-pages/gitlab-pages.conf'
```
### Enabling object storage
GitLab Pages support using object storage for storing artifacts, but object storage
is disabled by default. You can enable it in the GDK:
1. Edit `gdk.yml` to enable the object storage in GitLab itself:
```yaml
# $GDK_ROOT/gdk.yml
object_store:
enabled: true
```
1. Reconfigure and restart GitLab by running the commands `gdk reconfigure` and `gdk restart`.
For more information, refer to the [GDK documentation](https://gitlab.com/gitlab-org/gitlab-development-kit/-/blob/main/doc/configuration.md#object-storage-configuration).
## Linting
```shell
# Run the linter locally
make lint
# Run linter and fix issues (if supported by the linter)
make format
```
## Testing
To run tests, you can use these commands:
```shell
# This will run all of the tests in the codebase
make test
# Run a specific test file
go test ./internal/serving/disk/
# Run a specific test in a file
go test ./internal/serving/disk/ -run TestDisk_ServeFileHTTP
# Run all unit tests except acceptance_test.go
go test ./... -short
# Run acceptance_test.go only
make acceptance
# Run specific acceptance tests
# We add `make` here because acceptance tests use the last binary that was compiled,
# so we want to have the latest changes in the build that is tested
make && go test ./ -run TestRedirect
```
## Contributing
### Feature flags
{{< alert type="warning" >}}
All newly-introduced feature flags should be [disabled by default](https://handbook.gitlab.com/handbook/product-development-flow/feature-flag-lifecycle/#how-to-use-feature-flags).
{{< /alert >}}
Consider adding a [feature flag](../feature_flags/_index.md) for any non-trivial changes.
Feature flags can make the release and rollback of these changes easier, avoiding
incidents and downtime. To add a new feature flag to GitLab Pages:
1. Create the feature flag in
[`internal/feature/feature.go`](https://gitlab.com/gitlab-org/gitlab-pages/-/blob/master/internal/feature/feature.go),
which must be **off** by default.
1. Create an issue to track the feature flag using the `Feature flag` template.
1. Add the `~"feature flag"` label to any merge requests that handle feature flags.
For GitLab Pages, the feature flags are controlled by environment variables at a global level.
A deployment at the service level is required to change the state of a feature flag.
Example of a merge request enabling a GitLab Pages feature flag:
[Enforce GitLab Pages rate limits](https://gitlab.com/gitlab-com/gl-infra/k8s-workloads/gitlab-com/-/merge_requests/1500)
## Related topics
- [Feature flags in the development of GitLab](../feature_flags/_index.md)
## Becoming a GitLab Pages maintainer
This document serves as a guideline for GitLab team members that want to become maintainers for the GitLab Pages project.
Maintainers should have an advanced understanding of the GitLab Pages codebase.
Prior to applying for maintainer of a project, a person should gain a good feel for the codebase, expertise in one or more functionalities,
and deep understanding of our coding standards.
### Expectations
The process to [become a maintainer at GitLab is defined in the handbook](https://handbook.gitlab.com/handbook/engineering/workflow/code-review/#how-to-become-a-project-maintainer),
and it is the baseline for this process. One thing that is expected is a high number of reviews, however;
the rate of change of the GitLab Pages compared to the GitLab Rails project is too little.
To work around that problem, one must be comfortable in the following areas of the codebase:
Main areas:
- Namespace/project resolution
- ZIP serving and the virtual file system
- Authentication
Smaller areas:
- Redirects
- Artifacts proxying
- Handling of TLS certificates
- Rate-limiting
- Metrics and monitoring
To achieve this, you should try to make relevant contributions in all main areas and 2-3 smaller areas
mentioned above so that you have a better understanding of the functionality. A relevant contribution may be a bug fix,
a performance improvement, a new feature, or a significant refactoring.
### Reviewer
Prior to becoming a maintainer, you should first become a reviewer of the project. This should include changes
to any part of the codebase including the documentation.
To become a reviewer follow the steps [outlined in the handbook](https://handbook.gitlab.com/handbook/engineering/workflow/code-review/#reviewer).
There is no set timeline of how long you should be a reviewer before becoming a maintainer, but you should
gain enough experience in the areas mentioned in the [expectations section](#expectations) of this document.
### Maintainer
To become a maintainer follow the steps [outlined in the handbook](https://handbook.gitlab.com/handbook/engineering/workflow/code-review/#how-to-become-a-project-maintainer).
You are probably ready to become a maintainer when these statements feel true:
- The MRs you have reviewed consistently make it through maintainer review without significant additionally required changes
- The MRs you have created consistently make it through reviewer and maintainer review without significant required changes
- You feel comfortable working through operational tasks
If those subjective requirements are satisfied, [open an MR](https://gitlab.com/gitlab-com/www-gitlab-com/-/blob/master/.gitlab/merge_request_templates/Backend%20maintainer.md)
promoting you to maintainer and tag the existing maintainers.
|
---
stage: Plan
group: Knowledge
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
description: Configuration and contribution guidelines.
title: Contribute to GitLab Pages development
breadcrumbs:
- doc
- development
- pages
---
Learn how to configure GitLab Pages so you can help develop the feature.
## Configuring GitLab Pages hostname
GitLab Pages needs a hostname or domain, as each different GitLab Pages site is accessed through a
subdomain. You can set the GitLab Pages hostname:
- [Without wildcard, editing your hosts file](#without-wildcard-editing-your-hosts-file).
- [With DNS wildcard alternatives](#with-dns-wildcard-alternatives).
### Without wildcard, editing your hosts file
As `/etc/hosts` don't support wildcard hostnames, you must configure one entry
for GitLab Pages, and then one entry for each page site:
```plaintext
127.0.0.1 gdk.test # If you're using GDK
127.0.0.1 pages.gdk.test # Pages host
# Any namespace/group/user needs to be added
# as a subdomain to the pages host. This is because
# /etc/hosts doesn't accept wildcards
127.0.0.1 root.pages.gdk.test # for the root pages
```
### With DNS wildcard alternatives
If instead of editing your `/etc/hosts` you'd prefer to use a DNS wildcard, you can use:
- [`nip.io`](https://nip.io)
- [`dnsmasq`](dnsmasq.md)
## Configuring GitLab Pages without GDK
Create a `gitlab-pages.conf` in the root of the GitLab Pages site, like:
```toml
# Default port is 3010, but you can use any other
listen-http=:3010
# Your local GitLab Pages domain
pages-domain=pages.gdk.test
# Directory where the pages are stored
pages-root=shared/pages
# Show more information in the logs
log-verbose=true
```
To see more options you can check
[`internal/config/flags.go`](https://gitlab.com/gitlab-org/gitlab-pages/blob/master/internal/config/flags.go)
or run `gitlab-pages --help`.
### Running GitLab Pages manually
For any changes in the code, you must run `make` to build the app. It's best to just always run
it before you start the app. It's quick to build so don't worry!
```shell
make && ./gitlab-pages -config=gitlab-pages.conf
```
## Configuring GitLab Pages with GDK
In the following steps, `$GDK_ROOT` is the directory where you cloned GDK.
1. Set up the [GDK hostname](https://gitlab.com/gitlab-org/gitlab-development-kit/-/blob/main/doc/howto/local_network.md).
1. Add a [GitLab Pages hostname](#configuring-gitlab-pages-hostname) to the `gdk.yml`:
```yaml
gitlab_pages:
enabled: true # enable GitLab Pages to be managed by gdk
port: 3010 # default port is 3010
host: pages.gdk.test # the GitLab Pages domain
auto_update: true # if gdk must update GitLab Pages git
verbose: true # show more information in the logs
```
### Running GitLab Pages with GDK
After these configurations are set, GDK manages a GitLab Pages process, giving you access to
it with commands like:
- Start: `gdk start gitlab-pages`
- Stop: `gdk stop gitlab-pages`
- Restart: `gdk restart gitlab-pages`
- Tail logs: `gdk tail gitlab-pages`
### Running GitLab Pages manually
You can also build and start the app independently of GDK processes management.
For any changes in the code, you must run `make` to build the app. It's best to just always run
it before you start the app. It's quick to build so don't worry!
```shell
make && ./gitlab-pages -config=gitlab-pages.conf
```
#### Building GitLab Pages in FIPS mode
```shell
FIPS_MODE=1 make && ./gitlab-pages -config=gitlab-pages.conf
```
### Creating GitLab Pages site
To build a GitLab Pages site locally you must
[configure `gitlab-runner`](https://gitlab.com/gitlab-org/gitlab-development-kit/-/blob/main/doc/howto/runner.md).
For more information, refer to the [user manual](../../user/project/pages/_index.md).
### Enabling access control
GitLab Pages support private sites. Private sites can be accessed only by users
who have access to your GitLab project.
GitLab Pages access control is disabled by default. To enable it:
1. Enable the GitLab Pages access control in GitLab itself. You can do this in two ways:
- If you're not using GDK, edit `gitlab.yml`:
```yaml
# gitlab/config/gitlab.yml
pages:
access_control: true
```
- If you're using GDK, edit `gdk.yml`:
```yaml
# $GDK_ROOT/gdk.yml
gitlab_pages:
enabled: true
access_control: true
```
1. Restart GitLab (if running through the GDK, run `gdk restart`). Running
`gdk reconfigure` overwrites the value of `access_control` in `config/gitlab.yml`.
1. In your local GitLab instance, in the browser go to `http://gdk.test:3000/admin/applications`.
1. Create an [Instance-wide OAuth application](../../integration/oauth_provider.md#create-an-instance-wide-application)
with the `api` scope.
1. Set the value of your `redirect-uri` to the `pages-domain` authorization endpoint
(for example, `http://pages.gdk.test:3010/auth`).
The `redirect-uri` must not contain any GitLab Pages site domain.
1. Add the auth client configuration:
- With GDK, in `gdk.yml`:
```yaml
gitlab_pages:
enabled: true
access_control: true
auth_client_id: $CLIENT_ID # the OAuth application id created in http://gdk.test:3000/admin/applications
auth_client_secret: $CLIENT_SECRET # the OAuth application secret created in http://gdk.test:3000/admin/applications
```
GDK generates random `auth_secret` and builds the `auth_redirect_uri` based on GitLab Pages
host configuration.
- Without GDK, in `gitlab-pages.conf`:
```conf
## the following are only needed if you want to test auth for private projects
auth-client-id=$CLIENT_ID # the OAuth application id created in http://gdk.test:3000/admin/applications
auth-client-secret=$CLIENT_SECRET # the OAuth application secret created in http://gdk.test:3000/admin/applications
auth-secret=$SOME_RANDOM_STRING # should be at least 32 bytes long
auth-redirect-uri=http://pages.gdk.test:3010/auth # the authentication callback url for GitLab Pages
```
1. If running Pages inside the GDK, you can use GDK `protected_config_files` section under `gdk` in
your `gdk.yml` to avoid getting `gitlab-pages.conf` configuration rewritten:
```yaml
gdk:
protected_config_files:
- 'gitlab-pages/gitlab-pages.conf'
```
### Enabling object storage
GitLab Pages support using object storage for storing artifacts, but object storage
is disabled by default. You can enable it in the GDK:
1. Edit `gdk.yml` to enable the object storage in GitLab itself:
```yaml
# $GDK_ROOT/gdk.yml
object_store:
enabled: true
```
1. Reconfigure and restart GitLab by running the commands `gdk reconfigure` and `gdk restart`.
For more information, refer to the [GDK documentation](https://gitlab.com/gitlab-org/gitlab-development-kit/-/blob/main/doc/configuration.md#object-storage-configuration).
## Linting
```shell
# Run the linter locally
make lint
# Run linter and fix issues (if supported by the linter)
make format
```
## Testing
To run tests, you can use these commands:
```shell
# This will run all of the tests in the codebase
make test
# Run a specific test file
go test ./internal/serving/disk/
# Run a specific test in a file
go test ./internal/serving/disk/ -run TestDisk_ServeFileHTTP
# Run all unit tests except acceptance_test.go
go test ./... -short
# Run acceptance_test.go only
make acceptance
# Run specific acceptance tests
# We add `make` here because acceptance tests use the last binary that was compiled,
# so we want to have the latest changes in the build that is tested
make && go test ./ -run TestRedirect
```
## Contributing
### Feature flags
{{< alert type="warning" >}}
All newly-introduced feature flags should be [disabled by default](https://handbook.gitlab.com/handbook/product-development-flow/feature-flag-lifecycle/#how-to-use-feature-flags).
{{< /alert >}}
Consider adding a [feature flag](../feature_flags/_index.md) for any non-trivial changes.
Feature flags can make the release and rollback of these changes easier, avoiding
incidents and downtime. To add a new feature flag to GitLab Pages:
1. Create the feature flag in
[`internal/feature/feature.go`](https://gitlab.com/gitlab-org/gitlab-pages/-/blob/master/internal/feature/feature.go),
which must be **off** by default.
1. Create an issue to track the feature flag using the `Feature flag` template.
1. Add the `~"feature flag"` label to any merge requests that handle feature flags.
For GitLab Pages, the feature flags are controlled by environment variables at a global level.
A deployment at the service level is required to change the state of a feature flag.
Example of a merge request enabling a GitLab Pages feature flag:
[Enforce GitLab Pages rate limits](https://gitlab.com/gitlab-com/gl-infra/k8s-workloads/gitlab-com/-/merge_requests/1500)
## Related topics
- [Feature flags in the development of GitLab](../feature_flags/_index.md)
## Becoming a GitLab Pages maintainer
This document serves as a guideline for GitLab team members that want to become maintainers for the GitLab Pages project.
Maintainers should have an advanced understanding of the GitLab Pages codebase.
Prior to applying for maintainer of a project, a person should gain a good feel for the codebase, expertise in one or more functionalities,
and deep understanding of our coding standards.
### Expectations
The process to [become a maintainer at GitLab is defined in the handbook](https://handbook.gitlab.com/handbook/engineering/workflow/code-review/#how-to-become-a-project-maintainer),
and it is the baseline for this process. One thing that is expected is a high number of reviews, however;
the rate of change of the GitLab Pages compared to the GitLab Rails project is too little.
To work around that problem, one must be comfortable in the following areas of the codebase:
Main areas:
- Namespace/project resolution
- ZIP serving and the virtual file system
- Authentication
Smaller areas:
- Redirects
- Artifacts proxying
- Handling of TLS certificates
- Rate-limiting
- Metrics and monitoring
To achieve this, you should try to make relevant contributions in all main areas and 2-3 smaller areas
mentioned above so that you have a better understanding of the functionality. A relevant contribution may be a bug fix,
a performance improvement, a new feature, or a significant refactoring.
### Reviewer
Prior to becoming a maintainer, you should first become a reviewer of the project. This should include changes
to any part of the codebase including the documentation.
To become a reviewer follow the steps [outlined in the handbook](https://handbook.gitlab.com/handbook/engineering/workflow/code-review/#reviewer).
There is no set timeline of how long you should be a reviewer before becoming a maintainer, but you should
gain enough experience in the areas mentioned in the [expectations section](#expectations) of this document.
### Maintainer
To become a maintainer follow the steps [outlined in the handbook](https://handbook.gitlab.com/handbook/engineering/workflow/code-review/#how-to-become-a-project-maintainer).
You are probably ready to become a maintainer when these statements feel true:
- The MRs you have reviewed consistently make it through maintainer review without significant additionally required changes
- The MRs you have created consistently make it through reviewer and maintainer review without significant required changes
- You feel comfortable working through operational tasks
If those subjective requirements are satisfied, [open an MR](https://gitlab.com/gitlab-com/www-gitlab-com/-/blob/master/.gitlab/merge_request_templates/Backend%20maintainer.md)
promoting you to maintainer and tag the existing maintainers.
|
https://docs.gitlab.com/development/proxying
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/proxying.md
|
2025-08-13
|
doc/development/geo
|
[
"doc",
"development",
"geo"
] |
proxying.md
|
Tenant Scale
|
Geo
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Geo proxying
| null |
Secondaries proxy nearly all HTTP requests through Workhorse to the primary, so users navigating to the
secondary see a read-write UI, and are able to do all operations that they can do on the primary.
## High-level components
Proxying of GitLab UI and API HTTP requests is handled by the [`gitlab-workhorse`](../architecture.md#gitlab-workhorse) component. Traffic usually sent to the Rails application on the Geo secondary site is proxied to the [internal URL](../../administration/geo/_index.md#internal-url) of the primary Geo site instead.
Proxying of Git over HTTP requests is handled by the [`gitlab-workhorse`](../architecture.md#gitlab-workhorse) component, but the decision to proxy or not is handled by the Rails application, taking into account whether the request is push or pull, and whether the desired Git data is up-to-date.
Proxying of Git over SSH traffic is handled by the [`gitlab-shell`](../architecture.md#gitlab-shell) component, but the decision to proxy or not is handled by the Rails application, taking into account whether the request is push or pull, and whether the desired Git data is up-to-date.
## Request lifecycle
### Top-level view
The proxying interaction can be explained at a high level through the following diagram:
```mermaid
sequenceDiagram
actor client
participant secondary
participant primary
client->>secondary: GET /explore
secondary-->>primary: GET /explore (proxied)
primary-->>secondary: HTTP/1.1 200 OK [..]
secondary->>client: HTTP/1.1 200 OK [..]
```
### Proxy detection mechanism
To know whether or not it should proxy requests to the primary, and the URL of the primary (as it is stored in
the database), Workhorse polls the internal API when Geo is enabled. When proxying should be enabled, the internal
API responds with the primary URL and JWT-signed data that is passed on to the primary for every request.
```mermaid
sequenceDiagram
participant W as Workhorse (secondary)
participant API as Internal Rails API
W->API: GET /api/v4/geo/proxy (internal)
loop Poll every 10 seconds
API-->W: {geo_proxy_primary_url, geo_proxy_extra_data}, update config
end
```
### In-depth request flow and local data acceleration compared with proxying
Detailing implementation, Workhorse on the secondary (requested) site decides whether to proxy the data or not. If it
can "accelerate" the data type (that is, can serve locally to save a roundtrip request), it returns the data
immediately. Otherwise, traffic is sent to the primary's internal URL, served by Workhorse on the primary exactly
as a direct request would. The response is then be proxied back to the user through the secondary Workhorse in the
same connection.
```mermaid
flowchart LR
A[Client]--->W1["Workhorse (secondary)"]
W1 --> W1C[Serve data locally?]
W1C -- "Yes" ----> W1
W1C -- "No (proxy)" ----> W2["Workhorse (primary)"]
W2 --> W1 ----> A
```
## Sign-in
### Requests proxied to the primary requiring authorization
```mermaid
sequenceDiagram
autoNumber
participant Client
participant Secondary
participant Primary
Client->>Secondary: `/group/project` request
Secondary->>Primary: proxy /group/project
opt primary not signed in
Primary-->>Secondary: 302 redirect
Secondary-->>Client: proxy 302 redirect
Client->>Secondary: /users/sign_in
Secondary->>Primary: proxy /users/sign_in
Note right of Primary: authentication happens, POST to same URL etc
Primary-->>Secondary: 302 redirect
Secondary-->>Client: proxy 302 redirect
Client->>Secondary: /group/project
Secondary->>Primary: proxy /group/project
end
Primary-->>Secondary: /group/project logged in response (session on primary created)
Secondary-->>Client: proxy full response
```
## Git pull
The Git pull forward path was [renamed from the legacy name `push_from_secondary` to `from_secondary` for more clarity in GitLab 17.10](https://gitlab.com/gitlab-org/gitlab/-/issues/292690).
### Git pull over HTTP(s)
#### Accelerated repositories
When a repository exists on the secondary and we detect is up to date with the primary, we serve it directly instead of
proxying.
```mermaid
sequenceDiagram
participant C as Git client
participant Wsec as "Workhorse (secondary)"
participant Rsec as "Rails (secondary)"
participant Gsec as "Gitaly (secondary)"
C->>Wsec: GET /foo/bar.git/info/refs/?service=git-upload-pack
Wsec->>Rsec: <internal API check>
note over Rsec: decide that the repo is synced and up to date
Rsec-->>Wsec: 401 Unauthorized
Wsec-->>C: <response>
C->>Wsec: GET /foo/bar.git/info/refs/?service=git-upload-pack
Wsec->>Rsec: <internal API check>
Rsec-->>Wsec: Render Workhorse OK
Wsec-->>C: 200 OK
C->>Wsec: POST /foo/bar.git/git-upload-pack
Wsec->>Rsec: GitHttpController#git_receive_pack
Rsec-->>Wsec: Render Workhorse OK
Wsec->>Gsec: Workhorse gets the connection details from Rails, connects to Gitaly: SmartHTTP Service, UploadPack RPC (check the proto for details)
Gsec-->>Wsec: Return a stream of Proto messages
Wsec-->>C: Pipe messages to the Git client
```
#### Proxied repositories
If a requested repository isn't synced, or we detect is not up to date, the request will be proxied to the primary, in
order to get the latest version of the changes.
```mermaid
sequenceDiagram
participant C as Git client
participant Wsec as "Workhorse (secondary)"
participant Rsec as "Rails (secondary)"
participant W as "Workhorse (primary)"
participant R as "Rails (primary)"
participant G as "Gitaly (primary)"
C->>Wsec: GET /foo/bar.git/info/refs/?service=git-upload-pack
Wsec->>Rsec: <response>
note over Rsec: decide that the repo is out of date
Rsec-->>Wsec: 302 Redirect to /-/from_secondary/2/foo/bar.git/info/refs?service=git-upload-pack
Wsec-->>C: <response>
C->>Wsec: GET /-/from_secondary/2/foo/bar.git/info/refs/?service=git-upload-pack
Wsec->>W: <proxied request>
W->>R: <data>
R-->>W: 401 Unauthorized
W-->>Wsec: <proxied response>
Wsec-->>C: <response>
C->>Wsec: GET /-/from_secondary/2/foo/bar.git/info/refs/?service=git-upload-pack
note over W: proxied
Wsec->>W: <proxied request>
W->>R: <data>
R-->>W: Render Workhorse OK
W-->>Wsec: <proxied response>
Wsec-->>C: <response>
C->>Wsec: POST /-/from_secondary/2/foo/bar.git/git-upload-pack
Wsec->>W: <proxied request>
W->>R: GitHttpController#git_receive_pack
R-->>W: Render Workhorse OK
W->>G: Workhorse gets the connection details from Rails, connects to Gitaly: SmartHTTP Service, UploadPack RPC (check the proto for details)
G-->>W: Return a stream of Proto messages
W-->>Wsec: Pipe messages to the Git client
Wsec-->>C: Return piped messages from Git
```
### Git pull over SSH
As SSH operations go through GitLab Shell instead of Workhorse, they are not proxied through the mechanism used for
Workhorse requests. With SSH operations, they are proxied as Git HTTP requests to the primary site by the secondary
Rails internal API.
#### Accelerated repositories
When a repository exists on the secondary and we detect is up to date with the primary, we serve it directly instead of
proxying.
```mermaid
sequenceDiagram
participant C as Git client
participant S as GitLab Shell (secondary)
participant I as Internal API (secondary Rails)
participant G as Gitaly (secondary)
C->>S: git pull
S->>I: SSH key validation (api/v4/internal/authorized_keys?key=..)
I-->>S: HTTP/1.1 200 OK
S->>G: InfoRefs:UploadPack RPC
G-->>S: stream Git response back
S-->>C: stream Git response back
C-->>S: stream Git data to push
S->>G: UploadPack RPC
G-->>S: stream Git response back
S-->>C: stream Git response back
```
#### Proxied repositories
If a requested repository isn't synced, or we detect is not up to date, the request will be proxied to the primary, in
order to get the latest version of the changes.
```mermaid
sequenceDiagram
participant C as Git client
participant S as GitLab Shell (secondary)
participant I as Internal API (secondary Rails)
participant P as Primary API
C->>S: git pull
S->>I: SSH key validation (api/v4/internal/authorized_keys?key=..)
I-->>S: HTTP/1.1 300 (custom action status) with {endpoint, msg, primary_repo}
S->>I: POST /api/v4/geo/proxy_git_ssh/info_refs_upload_pack
I->>P: POST $PRIMARY/foo/bar.git/info/refs/?service=git-upload-pack
P-->>I: HTTP/1.1 200 OK
I-->>S: <response>
S-->>C: return Git response from primary
C-->>S: stream Git data to push
S->>I: POST /api/v4/geo/proxy_git_ssh/upload_pack
I->>P: POST $PRIMARY/foo/bar.git/git-upload-pack
P-->>I: HTTP/1.1 200 OK
I-->>S: <response>
S-->>C: return Git response from primary
```
## Git push
### Git push over SSH
As SSH operations go through GitLab Shell instead of Workhorse, they are not proxied through the mechanism used for
Workhorse requests. With SSH operations, they are proxied as Git HTTP requests to the primary site by the secondary
Rails internal API.
```mermaid
sequenceDiagram
participant C as Git client
participant S as GitLab Shell (secondary)
participant I as Internal API (secondary Rails)
participant P as Primary API
C->>S: git push
S->>I: SSH key validation (api/v4/internal/authorized_keys?key=..)
I-->>S: HTTP/1.1 300 (custom action status) with {endpoint, msg, primary_repo}
S->>I: POST /api/v4/geo/proxy_git_ssh/info_refs_receive_pack
I->>P: POST $PRIMARY/foo/bar.git/info/refs/?service=git-receive-pack
P-->>I: HTTP/1.1 200 OK
I-->>S: <response>
S-->>C: return Git response from primary
C-->>S: stream Git data to push
S->>I: POST /api/v4/geo/proxy_git_ssh/receive_pack
I->>P: POST $PRIMARY/foo/bar.git/git-receive-pack
P-->>I: HTTP/1.1 200 OK
I-->>S: <response>
S-->>C: return Git response from primary
```
### Git push over HTTP(S)
If a requested repository isn't synced, or we detect is not up to date, the request will be proxied to the primary, a push redirects to a local path formatted as `/-/from_secondary/$SECONDARY_ID/*`.
Further, requests through this path are proxied to the primary, which will handle the push.
```mermaid
sequenceDiagram
participant C as Git client
participant Wsec as Workhorse (secondary)
participant W as Workhorse (primary)
participant R as Rails (primary)
participant G as Gitaly (primary)
C->>Wsec: GET /foo/bar.git/info/refs/?service=git-receive-pack
Wsec->>C: 302 Redirect to /-/from_secondary/2/foo/bar.git/info/refs?service=git-receive-pack
C->>Wsec: GET /-/from_secondary/2/foo/bar.git/info/refs/?service=git-receive-pack
Wsec->>W: <proxied request>
W->>R: <data>
R-->>W: 401 Unauthorized
W-->>Wsec: <proxied response>
Wsec-->>C: <response>
C->>Wsec: GET /-/from_secondary/2/foo/bar.git/info/refs/?service=git-receive-pack
Wsec->>W: <proxied request>
W->>R: <data>
R-->>W: Render Workhorse OK
W-->>Wsec: <proxied response>
Wsec-->>C: <response>
C->>Wsec: POST /-/from_secondary/2/foo/bar.git/git-receive-pack
Wsec->>W: <proxied request>
W->>R: GitHttpController:git_receive_pack
R-->>W: Render Workhorse OK
W->>G: Get connection details from Rails and connects to SmartHTTP Service, ReceivePack RPC
G-->>W: Return a stream of Proto messages
W-->>Wsec: Pipe messages to the Git client
Wsec-->>C: Return piped messages from Git
```
|
---
stage: Tenant Scale
group: Geo
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: Geo proxying
breadcrumbs:
- doc
- development
- geo
---
Secondaries proxy nearly all HTTP requests through Workhorse to the primary, so users navigating to the
secondary see a read-write UI, and are able to do all operations that they can do on the primary.
## High-level components
Proxying of GitLab UI and API HTTP requests is handled by the [`gitlab-workhorse`](../architecture.md#gitlab-workhorse) component. Traffic usually sent to the Rails application on the Geo secondary site is proxied to the [internal URL](../../administration/geo/_index.md#internal-url) of the primary Geo site instead.
Proxying of Git over HTTP requests is handled by the [`gitlab-workhorse`](../architecture.md#gitlab-workhorse) component, but the decision to proxy or not is handled by the Rails application, taking into account whether the request is push or pull, and whether the desired Git data is up-to-date.
Proxying of Git over SSH traffic is handled by the [`gitlab-shell`](../architecture.md#gitlab-shell) component, but the decision to proxy or not is handled by the Rails application, taking into account whether the request is push or pull, and whether the desired Git data is up-to-date.
## Request lifecycle
### Top-level view
The proxying interaction can be explained at a high level through the following diagram:
```mermaid
sequenceDiagram
actor client
participant secondary
participant primary
client->>secondary: GET /explore
secondary-->>primary: GET /explore (proxied)
primary-->>secondary: HTTP/1.1 200 OK [..]
secondary->>client: HTTP/1.1 200 OK [..]
```
### Proxy detection mechanism
To know whether or not it should proxy requests to the primary, and the URL of the primary (as it is stored in
the database), Workhorse polls the internal API when Geo is enabled. When proxying should be enabled, the internal
API responds with the primary URL and JWT-signed data that is passed on to the primary for every request.
```mermaid
sequenceDiagram
participant W as Workhorse (secondary)
participant API as Internal Rails API
W->API: GET /api/v4/geo/proxy (internal)
loop Poll every 10 seconds
API-->W: {geo_proxy_primary_url, geo_proxy_extra_data}, update config
end
```
### In-depth request flow and local data acceleration compared with proxying
Detailing implementation, Workhorse on the secondary (requested) site decides whether to proxy the data or not. If it
can "accelerate" the data type (that is, can serve locally to save a roundtrip request), it returns the data
immediately. Otherwise, traffic is sent to the primary's internal URL, served by Workhorse on the primary exactly
as a direct request would. The response is then be proxied back to the user through the secondary Workhorse in the
same connection.
```mermaid
flowchart LR
A[Client]--->W1["Workhorse (secondary)"]
W1 --> W1C[Serve data locally?]
W1C -- "Yes" ----> W1
W1C -- "No (proxy)" ----> W2["Workhorse (primary)"]
W2 --> W1 ----> A
```
## Sign-in
### Requests proxied to the primary requiring authorization
```mermaid
sequenceDiagram
autoNumber
participant Client
participant Secondary
participant Primary
Client->>Secondary: `/group/project` request
Secondary->>Primary: proxy /group/project
opt primary not signed in
Primary-->>Secondary: 302 redirect
Secondary-->>Client: proxy 302 redirect
Client->>Secondary: /users/sign_in
Secondary->>Primary: proxy /users/sign_in
Note right of Primary: authentication happens, POST to same URL etc
Primary-->>Secondary: 302 redirect
Secondary-->>Client: proxy 302 redirect
Client->>Secondary: /group/project
Secondary->>Primary: proxy /group/project
end
Primary-->>Secondary: /group/project logged in response (session on primary created)
Secondary-->>Client: proxy full response
```
## Git pull
The Git pull forward path was [renamed from the legacy name `push_from_secondary` to `from_secondary` for more clarity in GitLab 17.10](https://gitlab.com/gitlab-org/gitlab/-/issues/292690).
### Git pull over HTTP(s)
#### Accelerated repositories
When a repository exists on the secondary and we detect is up to date with the primary, we serve it directly instead of
proxying.
```mermaid
sequenceDiagram
participant C as Git client
participant Wsec as "Workhorse (secondary)"
participant Rsec as "Rails (secondary)"
participant Gsec as "Gitaly (secondary)"
C->>Wsec: GET /foo/bar.git/info/refs/?service=git-upload-pack
Wsec->>Rsec: <internal API check>
note over Rsec: decide that the repo is synced and up to date
Rsec-->>Wsec: 401 Unauthorized
Wsec-->>C: <response>
C->>Wsec: GET /foo/bar.git/info/refs/?service=git-upload-pack
Wsec->>Rsec: <internal API check>
Rsec-->>Wsec: Render Workhorse OK
Wsec-->>C: 200 OK
C->>Wsec: POST /foo/bar.git/git-upload-pack
Wsec->>Rsec: GitHttpController#git_receive_pack
Rsec-->>Wsec: Render Workhorse OK
Wsec->>Gsec: Workhorse gets the connection details from Rails, connects to Gitaly: SmartHTTP Service, UploadPack RPC (check the proto for details)
Gsec-->>Wsec: Return a stream of Proto messages
Wsec-->>C: Pipe messages to the Git client
```
#### Proxied repositories
If a requested repository isn't synced, or we detect is not up to date, the request will be proxied to the primary, in
order to get the latest version of the changes.
```mermaid
sequenceDiagram
participant C as Git client
participant Wsec as "Workhorse (secondary)"
participant Rsec as "Rails (secondary)"
participant W as "Workhorse (primary)"
participant R as "Rails (primary)"
participant G as "Gitaly (primary)"
C->>Wsec: GET /foo/bar.git/info/refs/?service=git-upload-pack
Wsec->>Rsec: <response>
note over Rsec: decide that the repo is out of date
Rsec-->>Wsec: 302 Redirect to /-/from_secondary/2/foo/bar.git/info/refs?service=git-upload-pack
Wsec-->>C: <response>
C->>Wsec: GET /-/from_secondary/2/foo/bar.git/info/refs/?service=git-upload-pack
Wsec->>W: <proxied request>
W->>R: <data>
R-->>W: 401 Unauthorized
W-->>Wsec: <proxied response>
Wsec-->>C: <response>
C->>Wsec: GET /-/from_secondary/2/foo/bar.git/info/refs/?service=git-upload-pack
note over W: proxied
Wsec->>W: <proxied request>
W->>R: <data>
R-->>W: Render Workhorse OK
W-->>Wsec: <proxied response>
Wsec-->>C: <response>
C->>Wsec: POST /-/from_secondary/2/foo/bar.git/git-upload-pack
Wsec->>W: <proxied request>
W->>R: GitHttpController#git_receive_pack
R-->>W: Render Workhorse OK
W->>G: Workhorse gets the connection details from Rails, connects to Gitaly: SmartHTTP Service, UploadPack RPC (check the proto for details)
G-->>W: Return a stream of Proto messages
W-->>Wsec: Pipe messages to the Git client
Wsec-->>C: Return piped messages from Git
```
### Git pull over SSH
As SSH operations go through GitLab Shell instead of Workhorse, they are not proxied through the mechanism used for
Workhorse requests. With SSH operations, they are proxied as Git HTTP requests to the primary site by the secondary
Rails internal API.
#### Accelerated repositories
When a repository exists on the secondary and we detect is up to date with the primary, we serve it directly instead of
proxying.
```mermaid
sequenceDiagram
participant C as Git client
participant S as GitLab Shell (secondary)
participant I as Internal API (secondary Rails)
participant G as Gitaly (secondary)
C->>S: git pull
S->>I: SSH key validation (api/v4/internal/authorized_keys?key=..)
I-->>S: HTTP/1.1 200 OK
S->>G: InfoRefs:UploadPack RPC
G-->>S: stream Git response back
S-->>C: stream Git response back
C-->>S: stream Git data to push
S->>G: UploadPack RPC
G-->>S: stream Git response back
S-->>C: stream Git response back
```
#### Proxied repositories
If a requested repository isn't synced, or we detect is not up to date, the request will be proxied to the primary, in
order to get the latest version of the changes.
```mermaid
sequenceDiagram
participant C as Git client
participant S as GitLab Shell (secondary)
participant I as Internal API (secondary Rails)
participant P as Primary API
C->>S: git pull
S->>I: SSH key validation (api/v4/internal/authorized_keys?key=..)
I-->>S: HTTP/1.1 300 (custom action status) with {endpoint, msg, primary_repo}
S->>I: POST /api/v4/geo/proxy_git_ssh/info_refs_upload_pack
I->>P: POST $PRIMARY/foo/bar.git/info/refs/?service=git-upload-pack
P-->>I: HTTP/1.1 200 OK
I-->>S: <response>
S-->>C: return Git response from primary
C-->>S: stream Git data to push
S->>I: POST /api/v4/geo/proxy_git_ssh/upload_pack
I->>P: POST $PRIMARY/foo/bar.git/git-upload-pack
P-->>I: HTTP/1.1 200 OK
I-->>S: <response>
S-->>C: return Git response from primary
```
## Git push
### Git push over SSH
As SSH operations go through GitLab Shell instead of Workhorse, they are not proxied through the mechanism used for
Workhorse requests. With SSH operations, they are proxied as Git HTTP requests to the primary site by the secondary
Rails internal API.
```mermaid
sequenceDiagram
participant C as Git client
participant S as GitLab Shell (secondary)
participant I as Internal API (secondary Rails)
participant P as Primary API
C->>S: git push
S->>I: SSH key validation (api/v4/internal/authorized_keys?key=..)
I-->>S: HTTP/1.1 300 (custom action status) with {endpoint, msg, primary_repo}
S->>I: POST /api/v4/geo/proxy_git_ssh/info_refs_receive_pack
I->>P: POST $PRIMARY/foo/bar.git/info/refs/?service=git-receive-pack
P-->>I: HTTP/1.1 200 OK
I-->>S: <response>
S-->>C: return Git response from primary
C-->>S: stream Git data to push
S->>I: POST /api/v4/geo/proxy_git_ssh/receive_pack
I->>P: POST $PRIMARY/foo/bar.git/git-receive-pack
P-->>I: HTTP/1.1 200 OK
I-->>S: <response>
S-->>C: return Git response from primary
```
### Git push over HTTP(S)
If a requested repository isn't synced, or we detect is not up to date, the request will be proxied to the primary, a push redirects to a local path formatted as `/-/from_secondary/$SECONDARY_ID/*`.
Further, requests through this path are proxied to the primary, which will handle the push.
```mermaid
sequenceDiagram
participant C as Git client
participant Wsec as Workhorse (secondary)
participant W as Workhorse (primary)
participant R as Rails (primary)
participant G as Gitaly (primary)
C->>Wsec: GET /foo/bar.git/info/refs/?service=git-receive-pack
Wsec->>C: 302 Redirect to /-/from_secondary/2/foo/bar.git/info/refs?service=git-receive-pack
C->>Wsec: GET /-/from_secondary/2/foo/bar.git/info/refs/?service=git-receive-pack
Wsec->>W: <proxied request>
W->>R: <data>
R-->>W: 401 Unauthorized
W-->>Wsec: <proxied response>
Wsec-->>C: <response>
C->>Wsec: GET /-/from_secondary/2/foo/bar.git/info/refs/?service=git-receive-pack
Wsec->>W: <proxied request>
W->>R: <data>
R-->>W: Render Workhorse OK
W-->>Wsec: <proxied response>
Wsec-->>C: <response>
C->>Wsec: POST /-/from_secondary/2/foo/bar.git/git-receive-pack
Wsec->>W: <proxied request>
W->>R: GitHttpController:git_receive_pack
R-->>W: Render Workhorse OK
W->>G: Get connection details from Rails and connects to SmartHTTP Service, ReceivePack RPC
G-->>W: Return a stream of Proto messages
W-->>Wsec: Pipe messages to the Git client
Wsec-->>C: Return piped messages from Git
```
|
https://docs.gitlab.com/development/geo_validation_tests
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/geo_validation_tests.md
|
2025-08-13
|
doc/development/geo
|
[
"doc",
"development",
"geo"
] |
geo_validation_tests.md
|
Tenant Scale
|
Geo
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Geo validation tests
| null |
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
The Geo team performs manual testing and validation on common deployment configurations to ensure
that Geo works when upgrading between minor GitLab versions and major PostgreSQL database versions.
This section contains a journal of validation tests and links to the relevant issues.
## GitLab upgrades
The following are GitLab upgrade validation tests we performed.
<!-- vale gitlab_base.OutdatedVersions = NO -->
### July 2020
[Upgrade Geo multi-node installation](https://gitlab.com/gitlab-org/gitlab/-/issues/225359):
- Description: Tested upgrading from GitLab 12.10.12 to 13.0.10 package in a multi-node
configuration. As part of the issue to [Fix zero-downtime upgrade process/instructions for multi-node Geo deployments](https://gitlab.com/gitlab-org/gitlab/-/issues/225684), we monitored for downtime using the looping pipeline, HAProxy stats dashboards, and a script to log readiness status on both nodes.
- Outcome: Partial success because we observed downtime during the upgrade of the primary and secondary sites.
- Follow up issues/actions:
- [Investigate why `reconfigure` and `hup` cause downtime on multi-node Geo deployments](https://gitlab.com/gitlab-org/gitlab/-/issues/228898)
- [Geo multi-node deployment upgrade: investigate order when upgrading non-deploy nodes](https://gitlab.com/gitlab-org/gitlab/-/issues/228954)
[Switch from repmgr to Patroni on a Geo primary site](https://gitlab.com/gitlab-org/gitlab/-/issues/224652):
- Description: Tested switching from repmgr to Patroni on a multi-node Geo primary site. Used [the orchestrator tool](https://gitlab.com/gitlab-org/gitlab-orchestrator) to deploy a Geo installation with 3 database nodes managed by repmgr. With this approach, we were also able to address a related issue for [verifying a Geo installation with Patroni and PostgreSQL 11](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/5113).
- Outcome: Partial success. We enabled Patroni on the primary site and set up database replication on the secondary site. However, we found that Patroni would delete the secondary site's replication slot whenever Patroni was restarted. Another issue is that when Patroni elects a new leader in the cluster, the secondary site fails to automatically follow the new leader. Until these issues are resolved, we cannot officially support and recommend Patroni for Geo installations.
- Follow up issues/actions:
- [Investigate permanent replication slot for Patroni with Geo single node secondary](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/5528)
### June 2020
[Upgrade Geo multi-node installation](https://gitlab.com/gitlab-org/gitlab/-/issues/223284):
- Description: Tested upgrading from GitLab 12.9.10 to 12.10.12 package in a multi-node
configuration. Monitored for downtime using the looping pipeline and HAProxy stats dashboards.
- Outcome: Partial success because we observed downtime during the upgrade of the primary and secondary sites.
- Follow up issues/actions:
- [Fix zero-downtime upgrade process/instructions for multi-node Geo deployments](https://gitlab.com/gitlab-org/gitlab/-/issues/225684)
- [`Geo:check` Rake task: Exclude AuthorizedKeysCommand check if node not running Puma](https://gitlab.com/gitlab-org/gitlab/-/issues/225454)
- [Update instructions in the next upgrade issue to include monitoring HAProxy dashboards](https://gitlab.com/gitlab-org/gitlab/-/issues/225359)
[Upgrade Geo multi-node installation](https://gitlab.com/gitlab-org/gitlab/-/issues/208104):
- Description: Tested upgrading from GitLab 12.8.1 to 12.9.10 package in a multi-node
configuration.
- Outcome: Partial success because we did not run the looping pipeline during the demo to validate
zero-downtime.
- Follow up issues:
- [Clarify how Puma should include deploy node](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/5460)
- [Investigate MR creation failure after upgrade to 12.9.10](https://gitlab.com/gitlab-org/gitlab/-/issues/223282) Closed as false positive.
### February 2020
[Upgrade Geo multi-node installation](https://gitlab.com/gitlab-org/gitlab/-/issues/201837):
- Description: Tested upgrading from GitLab 12.7.5 to the latest GitLab 12.8 package in a multi-node
configuration.
- Outcome: Partial success because we did not run the looping pipeline during the demo to monitor
downtime.
### January 2020
[Upgrade Geo multi-node installation](https://gitlab.com/gitlab-org/gitlab/-/issues/200085):
- Description: Tested upgrading from GitLab 12.6.x to the latest GitLab 12.7 package in a multi-node
configuration.
- Outcome: Upgrade test was successful.
- Follow up issues:
- [Investigate Geo end-to-end test failures](https://gitlab.com/gitlab-org/gitlab/-/issues/201823).
- [Add more logging to Geo end-to-end tests](https://gitlab.com/gitlab-org/gitlab/-/issues/201830).
- [Excess service restarts during zero-downtime upgrade](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/5047).
[Upgrade Geo multi-node installation](https://gitlab.com/gitlab-org/gitlab/-/issues/199836):
- Description: Tested upgrading from GitLab 12.5.7 to GitLab 12.6.6 in a multi-node configuration.
- Outcome: Upgrade test was successful.
- Follow up issue:
[Update documentation for zero-downtime upgrades to ensure deploy node it not in use](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/5046).
[Upgrade Geo multi-node installation](https://gitlab.com/gitlab-org/gitlab/-/issues/37044):
- Description: Tested upgrading from GitLab 12.4.x to the latest GitLab 12.5 package in a multi-node
configuration.
- Outcome: Upgrade test was successful.
- Follow up issues:
- [Investigate why HTTP push spec failed on primary node](https://gitlab.com/gitlab-org/gitlab/-/issues/199825).
- [Investigate if documentation should be modified to include refresh foreign tables task](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/5041).
### October 2019
[Upgrade Geo multi-node installation](https://gitlab.com/gitlab-org/gitlab/-/issues/35262):
- Description: Tested upgrading from GitLab 12.3.5 to GitLab 12.4.1 in a multi-node configuration.
- Outcome: Upgrade test was successful.
[Upgrade Geo multi-node installation](https://gitlab.com/gitlab-org/gitlab/-/issues/32437):
- Description: Tested upgrading from GitLab 12.2.8 to GitLab 12.3.5.
- Outcome: Upgrade test was successful.
[Upgrade Geo multi-node installation](https://gitlab.com/gitlab-org/gitlab/-/issues/32435):
- Description: Tested upgrading from GitLab 12.1.9 to GitLab 12.2.8.
- Outcome: Partial success due to possible misconfiguration issues.
## PostgreSQL upgrades
The following are PostgreSQL upgrade validation tests we performed.
### September 2021
[Verify Geo installation with PostgreSQL 13](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/6131):
- Description: With PostgreSQL 13 available as an opt-in version in GitLab 14.1, we tested fresh installations of GitLab with Geo when PostgreSQL 13 is enabled.
- Outcome: Successfully built an environment with Geo and PostgreSQL 13 using [GitLab Environment Toolkit](https://gitlab.com/gitlab-org/gitlab-environment-toolkit) and performed Geo QA tests against the environment without failures.
### September 2020
[Verify PostgreSQL 12 upgrade for Geo installations](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/5454):
- Description: With PostgreSQL 12 available as an opt-in version in GitLab 13.3, we tested upgrading
existing Geo installations from PostgreSQL 11 to 12. We also re-tested fresh installations of GitLab
with Geo after fixes were made to support PostgreSQL 12. These tests were done using a
nightly build of GitLab 13.4.
- Outcome: Tests were successful for Geo deployments with a single database node on the primary and secondary.
We encountered known issues with repmgr and Patroni managed PostgreSQL clusters on the Geo primary. Using
PostgreSQL 12 with a database cluster on the primary is not recommended until the issues are resolved.
- Known issues for PostgreSQL clusters:
- [Ensure Patroni detects PostgreSQL update](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/5423)
- [Allow configuring permanent replication slots in Patroni](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/5628)
### August 2020
[Verify Geo installation with PostgreSQL 12](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/5453):
- Description: Prior to PostgreSQL 12 becoming available as an opt-in version in GitLab 13.3,
we tested fresh installations of GitLab 13.3 with PostgreSQL 12 enabled and Geo installed.
- Outcome: Setting up a Geo secondary required manual intervention because the `recovery.conf` file
is no longer supported in PostgreSQL 12. We do not recommend deploying Geo with PostgreSQL 12 until
the appropriate changes have been made to the Linux package and verified.
- Follow up issues:
- [Update `replicate-geo-database` to support PostgreSQL 12](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/5575)
- [Remove PostgreSQL 12 check in `replicate-geo-database` for 14.0](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/5576)
### April 2020
[PostgreSQL 11 upgrade procedure for Geo installations](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/4975):
- Description: Prior to making PostgreSQL 11 the default version of PostgreSQL in GitLab 12.10, we
tested upgrading to PostgreSQL 11 in Geo deployments in GitLab 12.9.
- Outcome: Partially successful. Issues were discovered in multi-node configurations with a separate
tracking database and concerns were raised about allowing automatic upgrades when Geo enabled.
- Follow up issues:
- [`replicate-geo-database` incorrectly tries to back up repositories](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/5241).
- [`pg-upgrade` fails to upgrade a standalone Geo tracking database](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/5242).
- [`revert-pg-upgrade` fails to downgrade the PostgreSQL data of a Geo secondary's standalone tracking database](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/5243).
- [Timeout error on Geo secondary read-replica near the end of `gitlab-ctl pg-upgrade`](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/5235).
[Verify Geo installation with PostgreSQL 11](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/4971):
- Description: Prior to making PostgreSQL 11 the default version of PostgreSQL in GitLab 12.10, we
tested fresh installations of GitLab 12.9 with Geo installed with PostgreSQL 11.
- Outcome: Installation test was successful.
### September 2019
[Test and validate PostgreSQL 10.0 upgrade for Geo](https://gitlab.com/gitlab-org/gitlab/-/issues/12092):
- Description: With the 12.0 release, GitLab required an upgrade to PostgreSQL 10.0. We tested
various upgrade scenarios up to GitLab 12.1.8.
- Outcome: Multiple issues were found when upgrading and addressed in follow-up issues.
- Follow up issues:
- [`gitlab-ctl` reconfigure fails on Redis node in multi-node Geo setup](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/4706).
- [Geo multi-node upgrade from 12.0.9 to 12.1.9 does not upgrade PostgreSQL](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/4705).
- [Refresh foreign tables fails on app server in multi-node setup after upgrade to 12.1.9](https://gitlab.com/gitlab-org/gitlab/-/issues/32119).
## Object storage replication tests
The following are additional validation tests we performed.
### April 2022
[Validate Object storage replication using AWS based object storage](https://gitlab.com/gitlab-org/gitlab/-/issues/351463):
- Description: Tested the average time it takes for a single image to replicate from the primary object storage location to the secondary when using AWS based object storage replication and [GitLab based object storage replication](../../administration/geo/replication/object_storage.md#enabling-gitlab-managed-object-storage-replication). This was tested by uploading a 1 MB image to a project on the primary site every second for 60 seconds. The time was then measured until a image was available on the secondary site. This was achieved using a [Ruby Script](https://gitlab.com/gitlab-org/quality/geo-replication-tester).
- Outcome: When using AWS managed replication the average time for an image to replicate between sites is about 49 seconds, this is true for when sites are located in the same region and when they are further apart (Europe to America). When using Geo managed replication in the same region the average time for replication took just 5 seconds, however when replicating cross region the average time rose to 33 seconds.
[Validate Object storage replication using GCP based object storage](https://gitlab.com/gitlab-org/gitlab/-/issues/351464):
- Description: Tested the average time it takes for a single image to replicate from the primary object storage location to the secondary when using GCP based object storage replication and [GitLab based object storage replication](../../administration/geo/replication/object_storage.md#enabling-gitlab-managed-object-storage-replication). This was tested by uploading a 1 MB image to a project on the primary site every second for 60 seconds. The time was then measured until a image was available on the secondary site. This was achieved using a [Ruby Script](https://gitlab.com/gitlab-org/quality/geo-replication-tester).
- Outcome: GCP handles replication differently than other Cloud Providers. In GCP, the process is to a create single bucket that is either multi, dual, or single region based. This means that the bucket automatically stores replicas in a region based on the option chosen. Even when using multi region, this only replicates in a single continent, the options being America, Europe, or Asia. At current there doesn't seem to be any way to replicate objects between continents using GCP based replication. For Geo managed replication the average time when replicating in the same region was 6 seconds, and when replicating cross region this rose to just 9 seconds.
### January 2022
[Validate Object storage replication using Azure based object storage](https://gitlab.com/gitlab-org/gitlab/-/issues/348804#note_821294631):
- Description: Tested the average time it takes for a single image to replicate from the primary object storage location to the secondary when using Azure based object storage replication and [GitLab based object storage replication](../../administration/geo/replication/object_storage.md#enabling-gitlab-managed-object-storage-replication). This was tested by uploading a 1 MB image to a project on the primary site every second for 60 seconds. The time was then measured until a image was available on the secondary site. This was achieved using a [Ruby Script](https://gitlab.com/gitlab-org/quality/geo-replication-tester).
- Outcome: When using Azure based replication the average time for an image to replicate from the primary object storage to the secondary was recorded as 40 seconds, the longest replication time was 70 seconds and the quickest was 11 seconds. When using GitLab based replication the average time for replication to complete was 5 seconds, the longest replication time was 10 seconds and the quickest was 3 seconds.
- Follow up issue:
- [Validate Cross Region Object storage replication using Azure based object storage](https://gitlab.com/gitlab-org/gitlab/-/issues/358154)
### May 2021
[Test failover with object storage replication enabled](https://gitlab.com/gitlab-org/gitlab/-/issues/330362):
- Description: At the time of testing, Geo's object storage replication functionality was in beta. We tested that object storage replication works as intended and that the data was present on the new primary after a failover.
- Outcome: The test was successful. Data in object storage was replicated and present after a failover.
- Follow up issues:
- [Geo: Failing to replicate initial Monitoring project](https://gitlab.com/gitlab-org/gitlab/-/issues/330485)
## Other tests
### August 2020
[Test Gitaly Cluster on a Geo Deployment](https://gitlab.com/gitlab-org/gitlab/-/issues/223210):
- Description: Tested a Geo deployment with Gitaly clusters configured on both the primary and secondary Geo sites. Triggered automatic Gitaly cluster failover on the primary Geo site, and ran end-to-end Geo tests. Then triggered Gitaly cluster failover on the secondary Geo site, and re-ran the end-to-end Geo tests.
- Outcome: Successful end-to-end tests before and after Gitaly cluster failover on the primary site, and before and after Gitaly cluster failover on the secondary site.
|
---
stage: Tenant Scale
group: Geo
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
gitlab_dedicated: false
title: Geo validation tests
breadcrumbs:
- doc
- development
- geo
---
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
The Geo team performs manual testing and validation on common deployment configurations to ensure
that Geo works when upgrading between minor GitLab versions and major PostgreSQL database versions.
This section contains a journal of validation tests and links to the relevant issues.
## GitLab upgrades
The following are GitLab upgrade validation tests we performed.
<!-- vale gitlab_base.OutdatedVersions = NO -->
### July 2020
[Upgrade Geo multi-node installation](https://gitlab.com/gitlab-org/gitlab/-/issues/225359):
- Description: Tested upgrading from GitLab 12.10.12 to 13.0.10 package in a multi-node
configuration. As part of the issue to [Fix zero-downtime upgrade process/instructions for multi-node Geo deployments](https://gitlab.com/gitlab-org/gitlab/-/issues/225684), we monitored for downtime using the looping pipeline, HAProxy stats dashboards, and a script to log readiness status on both nodes.
- Outcome: Partial success because we observed downtime during the upgrade of the primary and secondary sites.
- Follow up issues/actions:
- [Investigate why `reconfigure` and `hup` cause downtime on multi-node Geo deployments](https://gitlab.com/gitlab-org/gitlab/-/issues/228898)
- [Geo multi-node deployment upgrade: investigate order when upgrading non-deploy nodes](https://gitlab.com/gitlab-org/gitlab/-/issues/228954)
[Switch from repmgr to Patroni on a Geo primary site](https://gitlab.com/gitlab-org/gitlab/-/issues/224652):
- Description: Tested switching from repmgr to Patroni on a multi-node Geo primary site. Used [the orchestrator tool](https://gitlab.com/gitlab-org/gitlab-orchestrator) to deploy a Geo installation with 3 database nodes managed by repmgr. With this approach, we were also able to address a related issue for [verifying a Geo installation with Patroni and PostgreSQL 11](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/5113).
- Outcome: Partial success. We enabled Patroni on the primary site and set up database replication on the secondary site. However, we found that Patroni would delete the secondary site's replication slot whenever Patroni was restarted. Another issue is that when Patroni elects a new leader in the cluster, the secondary site fails to automatically follow the new leader. Until these issues are resolved, we cannot officially support and recommend Patroni for Geo installations.
- Follow up issues/actions:
- [Investigate permanent replication slot for Patroni with Geo single node secondary](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/5528)
### June 2020
[Upgrade Geo multi-node installation](https://gitlab.com/gitlab-org/gitlab/-/issues/223284):
- Description: Tested upgrading from GitLab 12.9.10 to 12.10.12 package in a multi-node
configuration. Monitored for downtime using the looping pipeline and HAProxy stats dashboards.
- Outcome: Partial success because we observed downtime during the upgrade of the primary and secondary sites.
- Follow up issues/actions:
- [Fix zero-downtime upgrade process/instructions for multi-node Geo deployments](https://gitlab.com/gitlab-org/gitlab/-/issues/225684)
- [`Geo:check` Rake task: Exclude AuthorizedKeysCommand check if node not running Puma](https://gitlab.com/gitlab-org/gitlab/-/issues/225454)
- [Update instructions in the next upgrade issue to include monitoring HAProxy dashboards](https://gitlab.com/gitlab-org/gitlab/-/issues/225359)
[Upgrade Geo multi-node installation](https://gitlab.com/gitlab-org/gitlab/-/issues/208104):
- Description: Tested upgrading from GitLab 12.8.1 to 12.9.10 package in a multi-node
configuration.
- Outcome: Partial success because we did not run the looping pipeline during the demo to validate
zero-downtime.
- Follow up issues:
- [Clarify how Puma should include deploy node](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/5460)
- [Investigate MR creation failure after upgrade to 12.9.10](https://gitlab.com/gitlab-org/gitlab/-/issues/223282) Closed as false positive.
### February 2020
[Upgrade Geo multi-node installation](https://gitlab.com/gitlab-org/gitlab/-/issues/201837):
- Description: Tested upgrading from GitLab 12.7.5 to the latest GitLab 12.8 package in a multi-node
configuration.
- Outcome: Partial success because we did not run the looping pipeline during the demo to monitor
downtime.
### January 2020
[Upgrade Geo multi-node installation](https://gitlab.com/gitlab-org/gitlab/-/issues/200085):
- Description: Tested upgrading from GitLab 12.6.x to the latest GitLab 12.7 package in a multi-node
configuration.
- Outcome: Upgrade test was successful.
- Follow up issues:
- [Investigate Geo end-to-end test failures](https://gitlab.com/gitlab-org/gitlab/-/issues/201823).
- [Add more logging to Geo end-to-end tests](https://gitlab.com/gitlab-org/gitlab/-/issues/201830).
- [Excess service restarts during zero-downtime upgrade](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/5047).
[Upgrade Geo multi-node installation](https://gitlab.com/gitlab-org/gitlab/-/issues/199836):
- Description: Tested upgrading from GitLab 12.5.7 to GitLab 12.6.6 in a multi-node configuration.
- Outcome: Upgrade test was successful.
- Follow up issue:
[Update documentation for zero-downtime upgrades to ensure deploy node it not in use](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/5046).
[Upgrade Geo multi-node installation](https://gitlab.com/gitlab-org/gitlab/-/issues/37044):
- Description: Tested upgrading from GitLab 12.4.x to the latest GitLab 12.5 package in a multi-node
configuration.
- Outcome: Upgrade test was successful.
- Follow up issues:
- [Investigate why HTTP push spec failed on primary node](https://gitlab.com/gitlab-org/gitlab/-/issues/199825).
- [Investigate if documentation should be modified to include refresh foreign tables task](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/5041).
### October 2019
[Upgrade Geo multi-node installation](https://gitlab.com/gitlab-org/gitlab/-/issues/35262):
- Description: Tested upgrading from GitLab 12.3.5 to GitLab 12.4.1 in a multi-node configuration.
- Outcome: Upgrade test was successful.
[Upgrade Geo multi-node installation](https://gitlab.com/gitlab-org/gitlab/-/issues/32437):
- Description: Tested upgrading from GitLab 12.2.8 to GitLab 12.3.5.
- Outcome: Upgrade test was successful.
[Upgrade Geo multi-node installation](https://gitlab.com/gitlab-org/gitlab/-/issues/32435):
- Description: Tested upgrading from GitLab 12.1.9 to GitLab 12.2.8.
- Outcome: Partial success due to possible misconfiguration issues.
## PostgreSQL upgrades
The following are PostgreSQL upgrade validation tests we performed.
### September 2021
[Verify Geo installation with PostgreSQL 13](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/6131):
- Description: With PostgreSQL 13 available as an opt-in version in GitLab 14.1, we tested fresh installations of GitLab with Geo when PostgreSQL 13 is enabled.
- Outcome: Successfully built an environment with Geo and PostgreSQL 13 using [GitLab Environment Toolkit](https://gitlab.com/gitlab-org/gitlab-environment-toolkit) and performed Geo QA tests against the environment without failures.
### September 2020
[Verify PostgreSQL 12 upgrade for Geo installations](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/5454):
- Description: With PostgreSQL 12 available as an opt-in version in GitLab 13.3, we tested upgrading
existing Geo installations from PostgreSQL 11 to 12. We also re-tested fresh installations of GitLab
with Geo after fixes were made to support PostgreSQL 12. These tests were done using a
nightly build of GitLab 13.4.
- Outcome: Tests were successful for Geo deployments with a single database node on the primary and secondary.
We encountered known issues with repmgr and Patroni managed PostgreSQL clusters on the Geo primary. Using
PostgreSQL 12 with a database cluster on the primary is not recommended until the issues are resolved.
- Known issues for PostgreSQL clusters:
- [Ensure Patroni detects PostgreSQL update](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/5423)
- [Allow configuring permanent replication slots in Patroni](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/5628)
### August 2020
[Verify Geo installation with PostgreSQL 12](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/5453):
- Description: Prior to PostgreSQL 12 becoming available as an opt-in version in GitLab 13.3,
we tested fresh installations of GitLab 13.3 with PostgreSQL 12 enabled and Geo installed.
- Outcome: Setting up a Geo secondary required manual intervention because the `recovery.conf` file
is no longer supported in PostgreSQL 12. We do not recommend deploying Geo with PostgreSQL 12 until
the appropriate changes have been made to the Linux package and verified.
- Follow up issues:
- [Update `replicate-geo-database` to support PostgreSQL 12](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/5575)
- [Remove PostgreSQL 12 check in `replicate-geo-database` for 14.0](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/5576)
### April 2020
[PostgreSQL 11 upgrade procedure for Geo installations](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/4975):
- Description: Prior to making PostgreSQL 11 the default version of PostgreSQL in GitLab 12.10, we
tested upgrading to PostgreSQL 11 in Geo deployments in GitLab 12.9.
- Outcome: Partially successful. Issues were discovered in multi-node configurations with a separate
tracking database and concerns were raised about allowing automatic upgrades when Geo enabled.
- Follow up issues:
- [`replicate-geo-database` incorrectly tries to back up repositories](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/5241).
- [`pg-upgrade` fails to upgrade a standalone Geo tracking database](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/5242).
- [`revert-pg-upgrade` fails to downgrade the PostgreSQL data of a Geo secondary's standalone tracking database](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/5243).
- [Timeout error on Geo secondary read-replica near the end of `gitlab-ctl pg-upgrade`](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/5235).
[Verify Geo installation with PostgreSQL 11](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/4971):
- Description: Prior to making PostgreSQL 11 the default version of PostgreSQL in GitLab 12.10, we
tested fresh installations of GitLab 12.9 with Geo installed with PostgreSQL 11.
- Outcome: Installation test was successful.
### September 2019
[Test and validate PostgreSQL 10.0 upgrade for Geo](https://gitlab.com/gitlab-org/gitlab/-/issues/12092):
- Description: With the 12.0 release, GitLab required an upgrade to PostgreSQL 10.0. We tested
various upgrade scenarios up to GitLab 12.1.8.
- Outcome: Multiple issues were found when upgrading and addressed in follow-up issues.
- Follow up issues:
- [`gitlab-ctl` reconfigure fails on Redis node in multi-node Geo setup](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/4706).
- [Geo multi-node upgrade from 12.0.9 to 12.1.9 does not upgrade PostgreSQL](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/4705).
- [Refresh foreign tables fails on app server in multi-node setup after upgrade to 12.1.9](https://gitlab.com/gitlab-org/gitlab/-/issues/32119).
## Object storage replication tests
The following are additional validation tests we performed.
### April 2022
[Validate Object storage replication using AWS based object storage](https://gitlab.com/gitlab-org/gitlab/-/issues/351463):
- Description: Tested the average time it takes for a single image to replicate from the primary object storage location to the secondary when using AWS based object storage replication and [GitLab based object storage replication](../../administration/geo/replication/object_storage.md#enabling-gitlab-managed-object-storage-replication). This was tested by uploading a 1 MB image to a project on the primary site every second for 60 seconds. The time was then measured until a image was available on the secondary site. This was achieved using a [Ruby Script](https://gitlab.com/gitlab-org/quality/geo-replication-tester).
- Outcome: When using AWS managed replication the average time for an image to replicate between sites is about 49 seconds, this is true for when sites are located in the same region and when they are further apart (Europe to America). When using Geo managed replication in the same region the average time for replication took just 5 seconds, however when replicating cross region the average time rose to 33 seconds.
[Validate Object storage replication using GCP based object storage](https://gitlab.com/gitlab-org/gitlab/-/issues/351464):
- Description: Tested the average time it takes for a single image to replicate from the primary object storage location to the secondary when using GCP based object storage replication and [GitLab based object storage replication](../../administration/geo/replication/object_storage.md#enabling-gitlab-managed-object-storage-replication). This was tested by uploading a 1 MB image to a project on the primary site every second for 60 seconds. The time was then measured until a image was available on the secondary site. This was achieved using a [Ruby Script](https://gitlab.com/gitlab-org/quality/geo-replication-tester).
- Outcome: GCP handles replication differently than other Cloud Providers. In GCP, the process is to a create single bucket that is either multi, dual, or single region based. This means that the bucket automatically stores replicas in a region based on the option chosen. Even when using multi region, this only replicates in a single continent, the options being America, Europe, or Asia. At current there doesn't seem to be any way to replicate objects between continents using GCP based replication. For Geo managed replication the average time when replicating in the same region was 6 seconds, and when replicating cross region this rose to just 9 seconds.
### January 2022
[Validate Object storage replication using Azure based object storage](https://gitlab.com/gitlab-org/gitlab/-/issues/348804#note_821294631):
- Description: Tested the average time it takes for a single image to replicate from the primary object storage location to the secondary when using Azure based object storage replication and [GitLab based object storage replication](../../administration/geo/replication/object_storage.md#enabling-gitlab-managed-object-storage-replication). This was tested by uploading a 1 MB image to a project on the primary site every second for 60 seconds. The time was then measured until a image was available on the secondary site. This was achieved using a [Ruby Script](https://gitlab.com/gitlab-org/quality/geo-replication-tester).
- Outcome: When using Azure based replication the average time for an image to replicate from the primary object storage to the secondary was recorded as 40 seconds, the longest replication time was 70 seconds and the quickest was 11 seconds. When using GitLab based replication the average time for replication to complete was 5 seconds, the longest replication time was 10 seconds and the quickest was 3 seconds.
- Follow up issue:
- [Validate Cross Region Object storage replication using Azure based object storage](https://gitlab.com/gitlab-org/gitlab/-/issues/358154)
### May 2021
[Test failover with object storage replication enabled](https://gitlab.com/gitlab-org/gitlab/-/issues/330362):
- Description: At the time of testing, Geo's object storage replication functionality was in beta. We tested that object storage replication works as intended and that the data was present on the new primary after a failover.
- Outcome: The test was successful. Data in object storage was replicated and present after a failover.
- Follow up issues:
- [Geo: Failing to replicate initial Monitoring project](https://gitlab.com/gitlab-org/gitlab/-/issues/330485)
## Other tests
### August 2020
[Test Gitaly Cluster on a Geo Deployment](https://gitlab.com/gitlab-org/gitlab/-/issues/223210):
- Description: Tested a Geo deployment with Gitaly clusters configured on both the primary and secondary Geo sites. Triggered automatic Gitaly cluster failover on the primary Geo site, and ran end-to-end Geo tests. Then triggered Gitaly cluster failover on the secondary Geo site, and re-ran the end-to-end Geo tests.
- Outcome: Successful end-to-end tests before and after Gitaly cluster failover on the primary site, and before and after Gitaly cluster failover on the secondary site.
|
https://docs.gitlab.com/development/framework
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/framework.md
|
2025-08-13
|
doc/development/geo
|
[
"doc",
"development",
"geo"
] |
framework.md
|
Tenant Scale
|
Geo
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Geo self-service framework
| null |
{{< alert type="note" >}}
This document is subject to change as we continue to implement and iterate on the framework.
Follow the progress in the [epic](https://gitlab.com/groups/gitlab-org/-/epics/2161).
If you need to replicate a new data type, reach out to the Geo
team to discuss the options. You can contact them in `#g_geo` on Slack
or mention `@geo-team` in the issue or merge request.
{{< /alert >}}
Geo provides an API to make it possible to easily replicate data types
across Geo sites. This API is presented as a Ruby Domain-Specific
Language (DSL) and aims to make it possible to replicate data with
minimal effort of the engineer who created a data type.
## Geo is a requirement in the definition of done
Geo is the GitLab solution for [disaster recovery](https://about.gitlab.com/direction/geo/disaster_recovery/). A robust disaster recovery solution must replicate **all GitLab data** such that all GitLab services can be successfully restored in their entirety with minimal data loss in the event of a disaster.
For this reason, Geo replication and verification support for GitLab generated data is part of the [definition of done](../contributing/merge_request_workflow.md#definition-of-done). This ensures that new features ship with Geo support and our customers are not exposed to data loss.
Adding Geo support with the Self Service Framework (SSF) is easy and outlined in detail on this page for various types of data. However, for a more general guide that can help you decide if and how you need to add Geo support for a new GitLab feature, [you may start here](../geo.md#ensuring-a-new-feature-has-geo-support).
## Nomenclature
Before digging into the API, developers need to know some Geo-specific
naming conventions:
- **Model**:
A model is an Active Model, which is how it is known in the entire
Rails codebase. It usually is tied to a database table. From Geo
perspective, a model can have one or more resources.
- **Resource**:
A resource is a piece of data that belongs to a model and is
produced by a GitLab feature. It is persisted using a storage
mechanism. By default, a resource is not a Geo replicable.
- **Data type**:
Data type is how a resource is stored. Each resource should
fit in one of the data types Geo supports:
- Git repository
- Blob
- Database
For more detail, see [Data types](../../administration/geo/replication/datatypes.md).
- **Geo Replicable**:
A Replicable is a resource Geo wants to sync across Geo sites. There
is a limited set of supported data types of replicables. The effort
required to implement replication of a resource that belongs to one
of the known data types is minimal.
- **Geo Replicator**:
A Geo Replicator is the object that knows how to replicate a
replicable. It's responsible for:
- Firing events (producer)
- Consuming events (consumer)
It's tied to the Geo Replicable data type. All replicators have a
common interface that can be used to process (that is, produce and
consume) events. It takes care of the communication between the
primary site (where events are produced) and the secondary site
(where events are consumed). The engineer who wants to incorporate
Geo in their feature uses the API of replicators to make this
happen.
- **Geo Domain-Specific Language**:
The syntactic sugar that allows engineers to easily specify which
resources should be replicated and how.
## Geo Domain-Specific Language
### The replicator
First of all, you need to write a replicator. The replicators live in
[`ee/app/replicators/geo`](https://gitlab.com/gitlab-org/gitlab/-/tree/master/ee/app/replicators/geo).
For each resource that needs to be replicated, there should be a
separate replicator specified, even if multiple resources are tied to
the same model.
For example, the following replicator replicates a package file:
```ruby
module Geo
class PackageFileReplicator < Gitlab::Geo::Replicator
# Include one of the strategies your resource needs
include ::Geo::BlobReplicatorStrategy
# Specify the CarrierWave uploader needed by the used strategy
def carrierwave_uploader
model_record.file
end
# Specify the model this replicator belongs to
def self.model
::Packages::PackageFile
end
end
end
```
The class name should be unique. It also is tightly coupled to the
table name for the registry, so for this example the registry table
is `package_file_registry`.
For the different data types Geo supports there are different
strategies to include. Pick one that fits your needs.
### Linking to a model
To tie this replicator to the model, you need to add the following to
the model code:
```ruby
class Packages::PackageFile < ApplicationRecord
include ::Geo::ReplicableModel
with_replicator Geo::PackageFileReplicator
end
```
### API
When this is set in place, it's easy to access the replicator through
the model:
```ruby
package_file = Packages::PackageFile.find(4) # just a random ID as example
replicator = package_file.replicator
```
Or get the model back from the replicator:
```ruby
replicator.model_record
=> <Packages::PackageFile id:4>
```
The replicator can be used to generate events, for example in
`ActiveRecord` hooks:
```ruby
after_create_commit -> { replicator.publish_created_event }
```
#### Library
The framework behind all this is located in
[`ee/lib/gitlab/geo/`](https://gitlab.com/gitlab-org/gitlab/-/tree/master/ee/lib/gitlab/geo).
## Existing Replicator Strategies
Before writing a new kind of Replicator Strategy, check below to see if your
resource can already be handled by one of the existing strategies. Consult with
the Geo team if you are unsure.
### Blob Replicator Strategy
Models that use [CarrierWave's](https://github.com/carrierwaveuploader/carrierwave) `Uploader::Base` are supported by Geo with the `Geo::BlobReplicatorStrategy` module. For example, see how [Geo replication was implemented for Pipeline Artifacts](https://gitlab.com/gitlab-org/gitlab/-/issues/238464).
Each file is expected to have its own primary ID and model. Geo strongly recommends treating every single file as a first-class citizen, because in our experience this greatly simplifies tracking replication and verification state.
To implement Geo replication of a new blob-type Model, [open an issue with the provided issue template](https://gitlab.com/gitlab-org/gitlab/-/issues/new?issuable_template=Geo%20Replicate%20a%20new%20blob%20type).
To view the implementation steps without opening an issue, [view the issue template file](https://gitlab.com/gitlab-org/gitlab/-/blob/master/.gitlab/issue_templates/Geo%20Replicate%20a%20new%20blob%20type.md).
### Repository Replicator Strategy
Models that refer to any Git repository on disk are supported by Geo with the `Geo::RepositoryReplicatorStrategy` module. For example, see how [Geo replication was implemented for Group-level Wikis](https://gitlab.com/gitlab-org/gitlab/-/issues/208147). Note that this issue does not implement verification, since verification of Git repositories was not yet added to the Geo self-service framework. An example implementing verification can be found in the merge request to [Add Snippet repository verification](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/56596).
Each Git repository is expected to have its own primary ID and model.
To implement Geo replication of a new Git repository-type Model, [open an issue with the provided issue template](https://gitlab.com/gitlab-org/gitlab/-/issues/new?issuable_template=Geo%20Replicate%20a%20new%20Git%20repository%20type).
To view the implementation steps without opening an issue, [view the issue template file](https://gitlab.com/gitlab-org/gitlab/-/blob/master/.gitlab/issue_templates/Geo%20Replicate%20a%20new%20Git%20repository%20type.md).
|
---
stage: Tenant Scale
group: Geo
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: Geo self-service framework
breadcrumbs:
- doc
- development
- geo
---
{{< alert type="note" >}}
This document is subject to change as we continue to implement and iterate on the framework.
Follow the progress in the [epic](https://gitlab.com/groups/gitlab-org/-/epics/2161).
If you need to replicate a new data type, reach out to the Geo
team to discuss the options. You can contact them in `#g_geo` on Slack
or mention `@geo-team` in the issue or merge request.
{{< /alert >}}
Geo provides an API to make it possible to easily replicate data types
across Geo sites. This API is presented as a Ruby Domain-Specific
Language (DSL) and aims to make it possible to replicate data with
minimal effort of the engineer who created a data type.
## Geo is a requirement in the definition of done
Geo is the GitLab solution for [disaster recovery](https://about.gitlab.com/direction/geo/disaster_recovery/). A robust disaster recovery solution must replicate **all GitLab data** such that all GitLab services can be successfully restored in their entirety with minimal data loss in the event of a disaster.
For this reason, Geo replication and verification support for GitLab generated data is part of the [definition of done](../contributing/merge_request_workflow.md#definition-of-done). This ensures that new features ship with Geo support and our customers are not exposed to data loss.
Adding Geo support with the Self Service Framework (SSF) is easy and outlined in detail on this page for various types of data. However, for a more general guide that can help you decide if and how you need to add Geo support for a new GitLab feature, [you may start here](../geo.md#ensuring-a-new-feature-has-geo-support).
## Nomenclature
Before digging into the API, developers need to know some Geo-specific
naming conventions:
- **Model**:
A model is an Active Model, which is how it is known in the entire
Rails codebase. It usually is tied to a database table. From Geo
perspective, a model can have one or more resources.
- **Resource**:
A resource is a piece of data that belongs to a model and is
produced by a GitLab feature. It is persisted using a storage
mechanism. By default, a resource is not a Geo replicable.
- **Data type**:
Data type is how a resource is stored. Each resource should
fit in one of the data types Geo supports:
- Git repository
- Blob
- Database
For more detail, see [Data types](../../administration/geo/replication/datatypes.md).
- **Geo Replicable**:
A Replicable is a resource Geo wants to sync across Geo sites. There
is a limited set of supported data types of replicables. The effort
required to implement replication of a resource that belongs to one
of the known data types is minimal.
- **Geo Replicator**:
A Geo Replicator is the object that knows how to replicate a
replicable. It's responsible for:
- Firing events (producer)
- Consuming events (consumer)
It's tied to the Geo Replicable data type. All replicators have a
common interface that can be used to process (that is, produce and
consume) events. It takes care of the communication between the
primary site (where events are produced) and the secondary site
(where events are consumed). The engineer who wants to incorporate
Geo in their feature uses the API of replicators to make this
happen.
- **Geo Domain-Specific Language**:
The syntactic sugar that allows engineers to easily specify which
resources should be replicated and how.
## Geo Domain-Specific Language
### The replicator
First of all, you need to write a replicator. The replicators live in
[`ee/app/replicators/geo`](https://gitlab.com/gitlab-org/gitlab/-/tree/master/ee/app/replicators/geo).
For each resource that needs to be replicated, there should be a
separate replicator specified, even if multiple resources are tied to
the same model.
For example, the following replicator replicates a package file:
```ruby
module Geo
class PackageFileReplicator < Gitlab::Geo::Replicator
# Include one of the strategies your resource needs
include ::Geo::BlobReplicatorStrategy
# Specify the CarrierWave uploader needed by the used strategy
def carrierwave_uploader
model_record.file
end
# Specify the model this replicator belongs to
def self.model
::Packages::PackageFile
end
end
end
```
The class name should be unique. It also is tightly coupled to the
table name for the registry, so for this example the registry table
is `package_file_registry`.
For the different data types Geo supports there are different
strategies to include. Pick one that fits your needs.
### Linking to a model
To tie this replicator to the model, you need to add the following to
the model code:
```ruby
class Packages::PackageFile < ApplicationRecord
include ::Geo::ReplicableModel
with_replicator Geo::PackageFileReplicator
end
```
### API
When this is set in place, it's easy to access the replicator through
the model:
```ruby
package_file = Packages::PackageFile.find(4) # just a random ID as example
replicator = package_file.replicator
```
Or get the model back from the replicator:
```ruby
replicator.model_record
=> <Packages::PackageFile id:4>
```
The replicator can be used to generate events, for example in
`ActiveRecord` hooks:
```ruby
after_create_commit -> { replicator.publish_created_event }
```
#### Library
The framework behind all this is located in
[`ee/lib/gitlab/geo/`](https://gitlab.com/gitlab-org/gitlab/-/tree/master/ee/lib/gitlab/geo).
## Existing Replicator Strategies
Before writing a new kind of Replicator Strategy, check below to see if your
resource can already be handled by one of the existing strategies. Consult with
the Geo team if you are unsure.
### Blob Replicator Strategy
Models that use [CarrierWave's](https://github.com/carrierwaveuploader/carrierwave) `Uploader::Base` are supported by Geo with the `Geo::BlobReplicatorStrategy` module. For example, see how [Geo replication was implemented for Pipeline Artifacts](https://gitlab.com/gitlab-org/gitlab/-/issues/238464).
Each file is expected to have its own primary ID and model. Geo strongly recommends treating every single file as a first-class citizen, because in our experience this greatly simplifies tracking replication and verification state.
To implement Geo replication of a new blob-type Model, [open an issue with the provided issue template](https://gitlab.com/gitlab-org/gitlab/-/issues/new?issuable_template=Geo%20Replicate%20a%20new%20blob%20type).
To view the implementation steps without opening an issue, [view the issue template file](https://gitlab.com/gitlab-org/gitlab/-/blob/master/.gitlab/issue_templates/Geo%20Replicate%20a%20new%20blob%20type.md).
### Repository Replicator Strategy
Models that refer to any Git repository on disk are supported by Geo with the `Geo::RepositoryReplicatorStrategy` module. For example, see how [Geo replication was implemented for Group-level Wikis](https://gitlab.com/gitlab-org/gitlab/-/issues/208147). Note that this issue does not implement verification, since verification of Git repositories was not yet added to the Geo self-service framework. An example implementing verification can be found in the merge request to [Add Snippet repository verification](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/56596).
Each Git repository is expected to have its own primary ID and model.
To implement Geo replication of a new Git repository-type Model, [open an issue with the provided issue template](https://gitlab.com/gitlab-org/gitlab/-/issues/new?issuable_template=Geo%20Replicate%20a%20new%20Git%20repository%20type).
To view the implementation steps without opening an issue, [view the issue template file](https://gitlab.com/gitlab-org/gitlab/-/blob/master/.gitlab/issue_templates/Geo%20Replicate%20a%20new%20Git%20repository%20type.md).
|
https://docs.gitlab.com/development/api
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/api.md
|
2025-08-13
|
doc/development/geo
|
[
"doc",
"development",
"geo"
] |
api.md
|
Tenant Scale
|
Geo
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Geo API
| null |
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
- Status: Beta
{{< /details >}}
The Geo API is used internally by GitLab components to assist in coordinating Geo actions. It is inaccessible to admins or users.
## Fetch pipeline refs
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/415179) in GitLab 16.7.
{{< /history >}}
This method returns a list of branches matching `pipeline/refs/X` that exist on the repository for `gl_repository` on the current Geo node. This endpoint is used by runners registered with a secondary Geo instance to check if a repository is up to date.
```plaintext
GET /geo/repositories/:gl_repository/pipeline_refs
```
Supported attributes:
| Attribute | Type | Required | Description |
|--------------------------|----------|----------|-----------------------|
| `gl_repository` | string | Yes | The `gl_repository` ID of the repository to query |
If successful, returns [`200`](../../api/rest/troubleshooting.md#status-codes) and the following
response attributes:
| Attribute | Type | Description |
|--------------------------|----------|-----------------------|
| `attribute` | 'array' | An array of ids matching `refs/pipeline/X` created for running pipelines. |
|
---
stage: Tenant Scale
group: Geo
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Geo API
breadcrumbs:
- doc
- development
- geo
---
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
- Status: Beta
{{< /details >}}
The Geo API is used internally by GitLab components to assist in coordinating Geo actions. It is inaccessible to admins or users.
## Fetch pipeline refs
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/415179) in GitLab 16.7.
{{< /history >}}
This method returns a list of branches matching `pipeline/refs/X` that exist on the repository for `gl_repository` on the current Geo node. This endpoint is used by runners registered with a secondary Geo instance to check if a repository is up to date.
```plaintext
GET /geo/repositories/:gl_repository/pipeline_refs
```
Supported attributes:
| Attribute | Type | Required | Description |
|--------------------------|----------|----------|-----------------------|
| `gl_repository` | string | Yes | The `gl_repository` ID of the repository to query |
If successful, returns [`200`](../../api/rest/troubleshooting.md#status-codes) and the following
response attributes:
| Attribute | Type | Description |
|--------------------------|----------|-----------------------|
| `attribute` | 'array' | An array of ids matching `refs/pipeline/X` created for running pipelines. |
|
https://docs.gitlab.com/development/advanced_search_migration_styleguide
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/advanced_search_migration_styleguide.md
|
2025-08-13
|
doc/development/search
|
[
"doc",
"development",
"search"
] |
advanced_search_migration_styleguide.md
|
AI-powered
|
Global Search
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Advanced search migration style guide
| null |
## Create a new advanced search migration
{{< alert type="note" >}}
This functionality is only supported for indices created in GitLab 13.0 and later.
{{< /alert >}}
### With a script
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/414674) in GitLab 16.3.
{{< /history >}}
Execute `scripts/elastic-migration` and follow the prompts to create:
- A migration file to define the migration: `ee/elastic/migrate/YYYYMMDDHHMMSS_migration_name.rb`
- A spec file to test the migration: `ee/spec/elastic/migrate/YYYYMMDDHHMMSS_migration_name_spec.rb`
- A dictionary file to identify the migration: `ee/elastic/docs/YYYYMMDDHHMMSS_migration_name.yml`
### Manually
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/234046) in GitLab 13.6.
{{< /history >}}
In the [`ee/elastic/migrate/`](https://gitlab.com/gitlab-org/gitlab/-/tree/master/ee/elastic/migrate) folder, create a new file with the filename format `YYYYMMDDHHMMSS_migration_name.rb`. This format is the same for Rails database migrations.
```ruby
# frozen_string_literal: true
class MigrationName < Elastic::Migration
# Important: Any updates to the Elastic index mappings must be replicated in the respective
# configuration files:
# - `Elastic::Latest::Config`, for the main index.
# - `Elastic::Latest::<Type>Config`, for standalone indices.
def migrate
end
# Check if the migration has completed
# Return true if completed, otherwise return false
def completed?
end
end
```
Applied migrations are stored in `gitlab-#{RAILS_ENV}-migrations` index. All migrations not executed
are applied by the [`Elastic::MigrationWorker`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/ee/app/workers/elastic/migration_worker.rb)
cron worker sequentially.
To update Elastic index mappings, apply the configuration to the respective files:
- For the main index: [`Elastic::Latest::Config`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/ee/lib/elastic/latest/config.rb).
- For standalone indices: `Elastic::Latest::<Type>Config`.
Migrations can be built with a retry limit and have the ability to be [failed and marked as halted](https://gitlab.com/gitlab-org/gitlab/-/blob/66e899b6637372a4faf61cfd2f254cbdd2fb9f6d/ee/lib/elastic/migration.rb#L40).
Any data or index cleanup needed to support migration retries should be handled in the migration.
### Skipped migrations
You can skip a migration by adding a `skip_if` proc which evaluates to `true` or `false`:
```ruby
class MigrationName < Elastic::Migration
skip_if ->() { true|false }
```
The migration is executed only if the condition is `false`. Skipped migrations will not be shown as part of pending migrations.
Skipped migrations can be marked as obsolete, but the `skip_if` condition must be kept so that these migrations are always skipped.
Once a skipped migration is obsolete, the only way to apply the change is by [recreating the index from scratch](../../integration/elasticsearch/troubleshooting/indexing.md#last-resort-to-recreate-an-index).
Update the skipped migration's documentation file with the following attributes:
```yaml
skippable: true
skip_condition: '<description>'
```
### Migrations for index settings and mappings changes
Changes to index settings and mappings are not immediately available to an existing index but are applied to newly created indices.
To apply setting changes, for example adding an analyzer, either:
- Use a [zero-downtime reindexing migration](#zero-downtime-reindex-migration)
- Add release notes to the feature issue, alerting users to apply the changes by either using [zero-downtime reindexing](../../integration/advanced_search/elasticsearch.md#zero-downtime-reindexing) or [re-create the index](../../integration/advanced_search/elasticsearch.md#index-the-instance).
To apply mapping changes, either:
- Use a [zero-downtime reindexing migration](#zero-downtime-reindex-migration).
- Use an [update mapping migration](#searchelasticmigrationupdatemappingshelper) to change the mapping for the existing index and optionally a follow-up [backfill migration](#searchelasticmigrationbackfillhelper) to ensure all documents in the index has this field populated.
#### Zero-downtime reindex migration
Creates a new index for the targeted index and copies existing documents over.
```ruby
class MigrationName < Elastic::Migration
def migrate
Elastic::ReindexingTask.create!(targets: %w[Issue], options: { skip_pending_migrations_check: true })
end
def completed?
true
end
end
```
### Spec support helpers
The following helper methods are available in `ElasticsearchHelpers` in `ee/spec/support/helpers/elasticsearch_helpers.rb`.
`ElasticsearchHelpers` is automatically included when using any of
the [Elasticsearch specs metadata](../testing_guide/best_practices.md#elasticsearch-specs)
#### `assert_names_in_query`
Validate that [named queries](https://www.elastic.co/guide/en/elasticsearch/reference/7.17/query-dsl-bool-query.html#named-queries)
exist (`with`) or do not exist (`without`) in an Elasticsearch query.
#### `assert_fields_in_query`
Validate that an Elasticsearch query contains the specified fields.
#### `assert_named_queries`
{{< alert type="warning" >}}
This method requires sending a search request to Elasticsearch. Use `assert_names_in_query` to test
the queries generated directly.
{{< /alert >}}
Validate that a request was made to Elasticsearch with [named queries](https://www.elastic.co/guide/en/elasticsearch/reference/8.18/query-dsl-bool-query.html#named-queries)
Use `without` to validate the named query was not in the request.
#### `assert_routing_field`
Validate that a request was made to Elasticsearch
with [a specific routing](https://www.elastic.co/docs/reference/elasticsearch/mapping-reference/mapping-routing-field).
#### `ensure_elasticsearch_index!`
Runs `execute` for all `Elastic::ProcessBookkeepingService` classes and calls `refresh_index!`. This method indexes any
records that have been queued for indexing using the `track!` method.
#### `refresh_index!`
Performs an Elasticsearch index refresh on all indices (including the migrations index). This makes recent operations
performed on an index available for search.
#### `set_elasticsearch_migration_to`
Set the current migration in the migrations index to a specific migration (by name or version). The migration is
marked as completed by default and can set to pending by sending `including: false`.
#### `es_helper`
Provides an instance of `Gitlab::Elastic::Helper.default`
#### `warm_elasticsearch_migrations_cache!`
Primes the `::Elastic::DataMigrationService` migration cache by calling `migration_has_finished?` for each migration.
#### `elastic_wiki_indexer_worker_random_delay_range`
Returns a random delay between 0 and `ElasticWikiIndexerWorker::MAX_JOBS_PER_HOUR`
#### `elastic_delete_group_wiki_worker_random_delay_range`
Returns a random delay between 0 and `Search::Wiki::ElasticDeleteGroupWikiWorker::MAX_JOBS_PER_HOUR`
#### `elastic_group_association_deletion_worker_random_delay_range`
Returns a random delay between 0 and `Search::ElasticGroupAssociationDeletionWorker::MAX_JOBS_PER_HOUR`
#### `items_in_index`
Returns an array of `id` that exist in the provided index name.
### Migration helpers
The following migration helpers are available in `ee/app/workers/concerns/elastic/`:
#### `Search::Elastic::MigrationBackfillHelper`
Backfills a specific field in an index.
Requirements:
- The mapping for the field should already be added
- The field must always have a value. If the field can be null, use `Search::Elastic::MigrationReindexBasedOnSchemaVersion`
- For single fields, define `field_name` method and `DOCUMENT_TYPE` constant
- For multiple fields, define`field_names` method and `DOCUMENT_TYPE` constant
Single field example:
```ruby
class MigrationName < Elastic::Migration
include ::Search::Elastic::MigrationBackfillHelper
DOCUMENT_TYPE = Issue
private
def field_name
:schema_version
end
end
```
Multiple fields example:
```ruby
class MigrationName < Elastic::Migration
include ::Search::Elastic::MigrationBackfillHelper
DOCUMENT_TYPE = Issue
private
def field_names
%w[schema_version visibility_level]
end
end
```
You can test this migration with the `'migration backfills fields'` shared examples.
```ruby
describe 'migration', :elastic_delete_by_query, :sidekiq_inline do
include_examples 'migration backfills fields' do
let(:expected_throttle_delay) { 1.minute }
let(:expected_batch_size) { 9000 }
let(:objects) { create_list(:issues, 3) }
let(:expected_fields) { schema_version: '25_09' }
end
end
```
#### `Search::Elastic::MigrationUpdateMappingsHelper`
Updates a mapping in an index by calling `put_mapping` with the mapping specified.
Requires the `new_mappings` method and `DOCUMENT_TYPE` constant.
```ruby
class MigrationName < Elastic::Migration
include ::Search::Elastic::MigrationUpdateMappingsHelper
DOCUMENT_TYPE = Issue
private
def new_mappings
{
schema_version: {
type: 'short'
}
}
end
end
```
You can test this migration with the `'migration adds mapping'` shared examples.
```ruby
describe 'migration', :elastic, :sidekiq_inline do
include_examples 'migration adds mapping'
end
```
#### `Search::Elastic::MigrationRemoveFieldsHelper`
Removes specified fields from an index.
Checks in batches if any documents that match `DOCUMENT_TYPE` have the fields specified in Elasticsearch. If documents exist, uses a Painless script to perform `update_by_query`.
- For single fields, define `field_to_remove` method and `DOCUMENT_TYPE` constant
- For multiple fields, define `fields_to_remove` method and `DOCUMENT_TYPE` constant
```ruby
class MigrationName < Elastic::Migration
include ::Search::Elastic::MigrationRemoveFieldsHelper
batched!
throttle_delay 1.minute
DOCUMENT_TYPE = User
private
def fields_to_remove
%w[two_factor_enabled has_projects]
end
end
```
The default batch size is `10_000`. You can override this value by specifying `BATCH_SIZE`:
```ruby
class MigrationName < Elastic::Migration
include ::Search::Elastic::MigrationRemoveFieldsHelper
batched!
BATCH_SIZE = 100
...
end
```
You can test this migration with the `'migration removes field'` shared examples.
```ruby
include_examples 'migration removes field' do
let(:expected_throttle_delay) { 1.minute }
let(:objects) { create_list(:work_item, 6) }
let(:index_name) { ::Search::Elastic::Types::WorkItem.index_name }
let(:field) { :correct_work_item_type_id }
let(:type) { 'long' }
end
```
If the mapping contains more than a `type`, omit the `type` variable and define `mapping` instead:
```ruby
include_examples 'migration removes field' do
let(:expected_throttle_delay) { 1.minute }
let(:objects) { create_list(:work_item, 6) }
let(:index_name) { ::Search::Elastic::Types::WorkItem.index_name }
let(:field) { :embedding_0 }
let(:mapping) { { type: 'dense_vector', dims: 768, index: true, similarity: 'cosine' } }
end
```
If you get an `expecting token of type [VALUE_NUMBER] but found [FIELD_NAME]` error, define the `value` variable:
```ruby
include_examples 'migration removes field' do
let(:expected_throttle_delay) { 1.minute }
let(:objects) { create_list(:work_item, 6) }
let(:index_name) { ::Search::Elastic::Types::WorkItem.index_name }
let(:field) { :embedding_0 }
let(:mapping) { { type: 'dense_vector', dims: 768, index: true, similarity: 'cosine' } }
let(:value) { Array.new(768, 1) }
end
```
#### `Search::Elastic::MigrationObsolete`
Marks a migration as obsolete when it's no longer required.
```ruby
class MigrationName < Elastic::Migration
include ::Search::Elastic::MigrationObsolete
end
```
When marking a skippable migration as obsolete, you must keep the `skip_if` condition.
You can test this migration with the `'a deprecated Advanced Search migration'`
shared examples. Follow the [process for marking migrations as obsolete](#process-for-marking-migrations-as-obsolete).
#### `Search::Elastic::MigrationCreateIndexHelper`
Creates a new index.
Requires:
- The `target_class` and `document_type` methods
- Mappings and index settings for the class
{{< alert type="warning" >}}
You must perform a follow-up migration to populate the index in the same milestone.
{{< /alert >}}
```ruby
class MigrationName < Elastic::Migration
include ::Search::Elastic::MigrationCreateIndexHelper
retry_on_failure
def document_type
:epic
end
def target_class
Epic
end
end
```
You can test this migration with the `'migration creates a new index'` shared examples.
```ruby
it_behaves_like 'migration creates a new index', 20240501134252, WorkItem
```
#### `Search::Elastic::MigrationReindexTaskHelper`
Creates a reindex task which creates a new index and copies data over to the new index.
Requires:
- The `targets` method.
```ruby
class MigrationName < Elastic::Migration
include ::Search::Elastic::MigrationReindexTaskHelper
def targets
%w[MergeRequest]
end
end
```
You can test this migration with the following specs.
```ruby
let(:migration) { described_class.new(version) }
let(:task) { Search::Elastic::ReindexingTask.last }
let(:targets) { %w[MergeRequest] }
it 'does not have migration options set', :aggregate_failures do
expect(migration).not_to be_batched
expect(migration).not_to be_retry_on_failure
end
describe '#migrate', :aggregate_failures do
it 'creates reindexing task with correct target and options' do
expect { migration.migrate }.to change { Search::Elastic::ReindexingTask.count }.by(1)
expect(task.targets).to eq(targets)
expect(task.options).to eq('skip_pending_migrations_check' => true)
end
end
describe '#completed?' do
it 'always returns true' do
expect(migration.completed?).to be(true)
end
end
```
#### `Search::Elastic::MigrationReindexBasedOnSchemaVersion`
Reindexes all documents in the index that stores the specified document type and updates `schema_version`.
Requires the `DOCUMENT_TYPE` and `NEW_SCHEMA_VERSION` constants.
The index mapping must have a `schema_version` integer field in a `YYWW` (year/week) format.
{{< alert type="note" >}}
Previously index mapping `schema_version` used `YYMM` format. New versions should use the `YYWW` format.
{{< /alert >}}
```ruby
class MigrationName < Elastic::Migration
include Search::Elastic::MigrationReindexBasedOnSchemaVersion
batched!
batch_size 9_000
throttle_delay 1.minute
DOCUMENT_TYPE = WorkItem
NEW_SCHEMA_VERSION = 24_46
UPDATE_BATCH_SIZE = 100
end
```
You can test this migration with the `'migration reindex based on schema_version'` shared examples.
```ruby
include_examples 'migration reindex based on schema_version' do
let(:expected_throttle_delay) { 1.minute }
let(:expected_batch_size) { 9_000 }
let(:objects) { create_list(:project, 3) }
end
```
#### `Search::Elastic::MigrationDeleteBasedOnSchemaVersion`
Deletes all documents in the index that stores the specified document type and has `schema_version` less than the given value.
Requires the `DOCUMENT_TYPE` constant and `schema_version` method.
The index mapping must have a `schema_version` integer field in a `YYWW` (year/week) format.
{{< alert type="note" >}}
Previously index mapping `schema_version` used `YYMM` format. New versions should use the `YYWW` format.
{{< /alert >}}
```ruby
class MigrationName < Elastic::Migration
include ::Search::Elastic::MigrationDeleteBasedOnSchemaVersion
DOCUMENT_TYPE = Issue
batch_size 10_000
batched!
throttle_delay 1.minute
retry_on_failure
def schema_version
23_12
end
end
```
You can test this migration with the `'migration deletes documents based on schema version'` shared examples.
```ruby
include_examples 'migration deletes documents based on schema version' do
let(:objects) { create_list(:issue, 3) }
let(:expected_throttle_delay) { 1.minute }
let(:expected_batch_size) { 20000 }
end
```
#### `Search::Elastic::MigrationDatabaseBackfillHelper`
Reindexes all documents in the database to the elastic search index respecting the `limited_indexing` setting.
Requires the `DOCUMENT_TYPE` constant and `respect_limited_indexing?` method.
```ruby
class MigrationName < Elastic::Migration
include ::Search::Elastic::MigrationDatabaseBackfillHelper
batch_size 10_000
batched!
throttle_delay 1.minute
retry_on_failure
DOCUMENT_TYPE = Issue
def respect_limited_indexing?
true
end
end
```
#### `Search::Elastic::MigrationHelper`
Contains methods you can use when a migration doesn't fit the previous examples.
```ruby
class MigrationName < Elastic::Migration
include ::Search::Elastic::MigrationHelper
def migrate
...
end
def completed?
...
end
end
```
### Migration options supported by the `Elastic::MigrationWorker`
[`Elastic::MigrationWorker`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/ee/app/workers/elastic/migration_worker.rb) supports the following migration options:
- `batched!` - Allow the migration to run in batches. If set, [`Elastic::MigrationWorker`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/ee/app/workers/elastic/migration_worker.rb)
re-enqueues itself with a delay which is set using the `throttle_delay` option described below. The batching
must be handled in the `migrate` method. This setting controls the re-enqueuing only.
- `batch_size` - Sets the number of documents modified during a `batched!` migration run. This size should be set to a value which allows the updates
enough time to finish. This can be tuned in combination with the `throttle_delay` option described below. The batching
must be handled in a custom `migrate` method or by using the [`Search::Elastic::MigrationBackfillHelper`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/ee/app/workers/concerns/elastic/migration_backfill_helper.rb)
`migrate` method which uses this setting. Default value is 1000 documents.
- `throttle_delay` - Sets the wait time in between batch runs. This time should be set high enough to allow each migration batch
enough time to finish. Additionally, the time should be less than 5 minutes because that is how often the
[`Elastic::MigrationWorker`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/ee/app/workers/elastic/migration_worker.rb)
cron worker runs. The default value is 3 minutes.
- `pause_indexing!` - Pause indexing while the migration runs. This setting records the indexing setting before
the migration runs and set it back to that value when the migration is completed.
- `space_requirements!` - Verify that enough free space is available in the cluster when the migration runs. This setting
halts the migration if the storage required is not available when the migration runs. The migration must provide
the space required in bytes by defining a `space_required_bytes` method.
- `retry_on_failure` - Enable the retry on failure feature. By default, it retries
the migration 30 times. After it runs out of retries, the migration is marked as halted.
To customize the number of retries, pass the `max_attempts` argument:
`retry_on_failure max_attempts: 10`
```ruby
# frozen_string_literal: true
class BatchedMigrationName < Elastic::Migration
# Declares a migration should be run in batches
batched!
throttle_delay 10.minutes
pause_indexing!
space_requirements!
retry_on_failure
# ...
end
```
## Avoiding downtime in migrations
### Reverting a migration
If a migration fails or is halted on GitLab.com, we prefer to revert the change that introduced the migration. This
prevents self-managed customers from receiving a broken migration and reduces the need for backports.
### Multi-version compatibility
Advanced search migrations, like any other GitLab changes, need to support the case where
[multiple versions of the application are running at the same time](../multi_version_compatibility.md).
Depending on the order of deployment, it's possible that the migration
has started or finished and there's still a server running the application code from before the
migration. We need to take this into consideration until we can
[ensure all advanced search migrations start after the deployment has finished](https://gitlab.com/gitlab-org/gitlab/-/issues/321619).
### High risk migrations
Because Elasticsearch does not support transactions, we always need to design our
migrations to accommodate a situation where the application
code is reverted after the migration has started or after it is finished.
For this reason we generally defer destructive actions (for example, deletions after
some data is moved) to a later merge request after the migrations have
completed successfully. To be safe, for self-managed customers we should also
defer it to another release if there is risk of important data loss.
## Calculating migration runtime
It's important to understand how long a migration might take to run on GitLab.com. Derive the number of documents that
will be processed by the migration. This number may come from querying the database or an existing Elasticsearch index.
Use the following formula to calculate the runtime:
```ruby
> batch_size = 9_000
=> 9000
> throttle_delay = 1.minute
=> 1 minute
> number_of_documents = 15_536_906
=> 15536906
> (number_of_documents / batch_size) * throttle_delay
=> 1726 minutes
> (number_of_documents / batch_size) * throttle_delay / 1.hour
=> 28
```
## Best practices for advanced search migrations
Follow these best practices for best results:
- Order all migrations for each document type so that any migrations that use
[`Search::Elastic::MigrationUpdateMappingsHelper`](#searchelasticmigrationupdatemappingshelper)
are executed before migrations that use the
[`Search::Elastic::MigrationBackfillHelper`](#searchelasticmigrationbackfillhelper). This avoids
reindexing the same documents multiple times if all of the migrations are unapplied
and reduces the backfill time.
- When working in batches, keep the batch size under 9,000 documents.
The bulk indexer is set to run every minute and process a batch
of 10,000 documents. This way, the bulk indexer has time to
process records before another migration batch is attempted.
- To ensure that document counts are up to date, you should refresh
the index before checking if a migration is completed.
- Add logging statements to each migration when the migration starts, when a
completion check occurs, and when the migration is completed. These logs
are helpful when debugging issues with migrations.
- Pause indexing if you're using any Elasticsearch Reindex API operations.
- Consider adding a retry limit if there is potential for the migration to fail.
This ensures that migrations can be halted if an issue occurs.
## Cleaning up advanced search migrations
Because advanced search migrations usually require us to support multiple
code paths for a long period of time, it's important to clean those up when we
safely can.
We choose to use GitLab [required stops](../database/required_stops.md) as a safe time to remove
backwards compatibility for indices that have not been fully migrated. We
[document this in our upgrade documentation](../../update/plan_your_upgrade.md).
[GitLab Housekeeper](https://gitlab.com/gitlab-org/gitlab/-/blob/master/gems/gitlab-housekeeper/README.md)
is used to automate the cleanup process. This process includes
marking existing migrations as obsolete and deleting obsolete migrations.
When a migration is marked as obsolete, the migration code is replaced with
obsolete migration code and tests are replaced with obsolete migration shared
examples so that:
- We don't need to maintain any code that is called from our advanced search
migrations.
- We don't waste CI time running tests for migrations that we don't support
anymore.
- Operators who have not run this migration and who upgrade directly to the
target version see a message prompting them to reindex from scratch.
To be extra safe, we do not clean up migrations that were created in the last
minor version before the last required stop. For example, if the last required stop
was `%14.0`, we should not clean up migrations that were only added in `%13.12`.
This extra safety net allows for migrations that might take multiple weeks to
finish on GitLab.com. Because our deployments to GitLab.com
are automated and we do not have automated checks to prevent this cleanup,
the extra precaution is warranted.
Additionally, even if we did have automated checks to prevent it, we wouldn't
actually want to hold up GitLab.com deployments on advanced search migrations,
as they may still have another week to go, and that's too long to block
deployments.
### Process for marking migrations as obsolete
Run the [`Keeps::MarkOldAdvancedSearchMigrationsAsObsolete` Keep](https://gitlab.com/gitlab-org/gitlab/-/blob/master/gems/gitlab-housekeeper/README.md#running-for-real)
manually to mark migrations as obsolete.
For every migration that was created two versions before the last required stop,
the Keep:
1. Retains the content of the migration and adds a prepend to the bottom:
```ruby
ClassName.prepend ::Search::Elastic::MigrationObsolete
```
1. Replaces the spec file content with the `'a deprecated Advanced Search migration'` shared example.
1. Randomly selects a Global Search backend engineer as an assignee.
1. Updates the dictionary file to mark the migration as obsolete.
The MR assignee must:
1. Ensure the dictionary file has the correct `marked_obsolete_by_url` and `marked_obsolete_in_milestone`.
1. Verify that no references to the migration or spec files exist in the `.rubocop_todo/` directory.
1. Remove any logic-handling backwards compatibility for this migration by
looking for `Elastic::DataMigrationService.migration_has_finished?(:migration_name_in_lowercase)`.
1. Push any required changes to the merge request.
### Process for removing obsolete migrations
Run the [`Keeps::DeleteObsoleteAdvancedSearchMigrations` Keep](https://gitlab.com/gitlab-org/gitlab/-/blob/master/gems/gitlab-housekeeper/README.md#running-for-real)
manually to remove obsolete migrations and specs. The Keep removes all but the most
recent obsolete migration.
1. Select obsolete migrations that were marked as obsolete before the last required stop.
1. If the first step includes all obsolete migrations, keep one obsolete migration as a safeguard for customers with unapplied migrations.
1. Delete migration files and spec files for those migrations.
1. Create a merge request and assign it to a Global Search team member.
The MR assignee must:
1. Backup migrations from the default branch to the [migration graveyard](https://gitlab.com/gitlab-org/search-team/migration-graveyard)
1. Verify that no references to the migration or spec files exist in the `.rubocop_todo/` directory.
1. Push any required changes to the merge request.
## ChatOps commands for monitoring migrations
You can check migration status from Slack (or any ChatOps‑enabled channel) at any time:
```plaintext
/chatops run search_migrations --help
/chatops run search_migrations list
/chatops run search_migrations get MigrationName
/chatops run search_migrations get VersionNumber
```
The above uses the [search_migrations](https://gitlab.com/gitlab-com/chatops/-/blob/master/lib/chatops/commands/search_migrations.rb) ChatOps plugin to fetch current migration state.
|
---
stage: AI-powered
group: Global Search
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: Advanced search migration style guide
breadcrumbs:
- doc
- development
- search
---
## Create a new advanced search migration
{{< alert type="note" >}}
This functionality is only supported for indices created in GitLab 13.0 and later.
{{< /alert >}}
### With a script
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/414674) in GitLab 16.3.
{{< /history >}}
Execute `scripts/elastic-migration` and follow the prompts to create:
- A migration file to define the migration: `ee/elastic/migrate/YYYYMMDDHHMMSS_migration_name.rb`
- A spec file to test the migration: `ee/spec/elastic/migrate/YYYYMMDDHHMMSS_migration_name_spec.rb`
- A dictionary file to identify the migration: `ee/elastic/docs/YYYYMMDDHHMMSS_migration_name.yml`
### Manually
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/234046) in GitLab 13.6.
{{< /history >}}
In the [`ee/elastic/migrate/`](https://gitlab.com/gitlab-org/gitlab/-/tree/master/ee/elastic/migrate) folder, create a new file with the filename format `YYYYMMDDHHMMSS_migration_name.rb`. This format is the same for Rails database migrations.
```ruby
# frozen_string_literal: true
class MigrationName < Elastic::Migration
# Important: Any updates to the Elastic index mappings must be replicated in the respective
# configuration files:
# - `Elastic::Latest::Config`, for the main index.
# - `Elastic::Latest::<Type>Config`, for standalone indices.
def migrate
end
# Check if the migration has completed
# Return true if completed, otherwise return false
def completed?
end
end
```
Applied migrations are stored in `gitlab-#{RAILS_ENV}-migrations` index. All migrations not executed
are applied by the [`Elastic::MigrationWorker`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/ee/app/workers/elastic/migration_worker.rb)
cron worker sequentially.
To update Elastic index mappings, apply the configuration to the respective files:
- For the main index: [`Elastic::Latest::Config`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/ee/lib/elastic/latest/config.rb).
- For standalone indices: `Elastic::Latest::<Type>Config`.
Migrations can be built with a retry limit and have the ability to be [failed and marked as halted](https://gitlab.com/gitlab-org/gitlab/-/blob/66e899b6637372a4faf61cfd2f254cbdd2fb9f6d/ee/lib/elastic/migration.rb#L40).
Any data or index cleanup needed to support migration retries should be handled in the migration.
### Skipped migrations
You can skip a migration by adding a `skip_if` proc which evaluates to `true` or `false`:
```ruby
class MigrationName < Elastic::Migration
skip_if ->() { true|false }
```
The migration is executed only if the condition is `false`. Skipped migrations will not be shown as part of pending migrations.
Skipped migrations can be marked as obsolete, but the `skip_if` condition must be kept so that these migrations are always skipped.
Once a skipped migration is obsolete, the only way to apply the change is by [recreating the index from scratch](../../integration/elasticsearch/troubleshooting/indexing.md#last-resort-to-recreate-an-index).
Update the skipped migration's documentation file with the following attributes:
```yaml
skippable: true
skip_condition: '<description>'
```
### Migrations for index settings and mappings changes
Changes to index settings and mappings are not immediately available to an existing index but are applied to newly created indices.
To apply setting changes, for example adding an analyzer, either:
- Use a [zero-downtime reindexing migration](#zero-downtime-reindex-migration)
- Add release notes to the feature issue, alerting users to apply the changes by either using [zero-downtime reindexing](../../integration/advanced_search/elasticsearch.md#zero-downtime-reindexing) or [re-create the index](../../integration/advanced_search/elasticsearch.md#index-the-instance).
To apply mapping changes, either:
- Use a [zero-downtime reindexing migration](#zero-downtime-reindex-migration).
- Use an [update mapping migration](#searchelasticmigrationupdatemappingshelper) to change the mapping for the existing index and optionally a follow-up [backfill migration](#searchelasticmigrationbackfillhelper) to ensure all documents in the index has this field populated.
#### Zero-downtime reindex migration
Creates a new index for the targeted index and copies existing documents over.
```ruby
class MigrationName < Elastic::Migration
def migrate
Elastic::ReindexingTask.create!(targets: %w[Issue], options: { skip_pending_migrations_check: true })
end
def completed?
true
end
end
```
### Spec support helpers
The following helper methods are available in `ElasticsearchHelpers` in `ee/spec/support/helpers/elasticsearch_helpers.rb`.
`ElasticsearchHelpers` is automatically included when using any of
the [Elasticsearch specs metadata](../testing_guide/best_practices.md#elasticsearch-specs)
#### `assert_names_in_query`
Validate that [named queries](https://www.elastic.co/guide/en/elasticsearch/reference/7.17/query-dsl-bool-query.html#named-queries)
exist (`with`) or do not exist (`without`) in an Elasticsearch query.
#### `assert_fields_in_query`
Validate that an Elasticsearch query contains the specified fields.
#### `assert_named_queries`
{{< alert type="warning" >}}
This method requires sending a search request to Elasticsearch. Use `assert_names_in_query` to test
the queries generated directly.
{{< /alert >}}
Validate that a request was made to Elasticsearch with [named queries](https://www.elastic.co/guide/en/elasticsearch/reference/8.18/query-dsl-bool-query.html#named-queries)
Use `without` to validate the named query was not in the request.
#### `assert_routing_field`
Validate that a request was made to Elasticsearch
with [a specific routing](https://www.elastic.co/docs/reference/elasticsearch/mapping-reference/mapping-routing-field).
#### `ensure_elasticsearch_index!`
Runs `execute` for all `Elastic::ProcessBookkeepingService` classes and calls `refresh_index!`. This method indexes any
records that have been queued for indexing using the `track!` method.
#### `refresh_index!`
Performs an Elasticsearch index refresh on all indices (including the migrations index). This makes recent operations
performed on an index available for search.
#### `set_elasticsearch_migration_to`
Set the current migration in the migrations index to a specific migration (by name or version). The migration is
marked as completed by default and can set to pending by sending `including: false`.
#### `es_helper`
Provides an instance of `Gitlab::Elastic::Helper.default`
#### `warm_elasticsearch_migrations_cache!`
Primes the `::Elastic::DataMigrationService` migration cache by calling `migration_has_finished?` for each migration.
#### `elastic_wiki_indexer_worker_random_delay_range`
Returns a random delay between 0 and `ElasticWikiIndexerWorker::MAX_JOBS_PER_HOUR`
#### `elastic_delete_group_wiki_worker_random_delay_range`
Returns a random delay between 0 and `Search::Wiki::ElasticDeleteGroupWikiWorker::MAX_JOBS_PER_HOUR`
#### `elastic_group_association_deletion_worker_random_delay_range`
Returns a random delay between 0 and `Search::ElasticGroupAssociationDeletionWorker::MAX_JOBS_PER_HOUR`
#### `items_in_index`
Returns an array of `id` that exist in the provided index name.
### Migration helpers
The following migration helpers are available in `ee/app/workers/concerns/elastic/`:
#### `Search::Elastic::MigrationBackfillHelper`
Backfills a specific field in an index.
Requirements:
- The mapping for the field should already be added
- The field must always have a value. If the field can be null, use `Search::Elastic::MigrationReindexBasedOnSchemaVersion`
- For single fields, define `field_name` method and `DOCUMENT_TYPE` constant
- For multiple fields, define`field_names` method and `DOCUMENT_TYPE` constant
Single field example:
```ruby
class MigrationName < Elastic::Migration
include ::Search::Elastic::MigrationBackfillHelper
DOCUMENT_TYPE = Issue
private
def field_name
:schema_version
end
end
```
Multiple fields example:
```ruby
class MigrationName < Elastic::Migration
include ::Search::Elastic::MigrationBackfillHelper
DOCUMENT_TYPE = Issue
private
def field_names
%w[schema_version visibility_level]
end
end
```
You can test this migration with the `'migration backfills fields'` shared examples.
```ruby
describe 'migration', :elastic_delete_by_query, :sidekiq_inline do
include_examples 'migration backfills fields' do
let(:expected_throttle_delay) { 1.minute }
let(:expected_batch_size) { 9000 }
let(:objects) { create_list(:issues, 3) }
let(:expected_fields) { schema_version: '25_09' }
end
end
```
#### `Search::Elastic::MigrationUpdateMappingsHelper`
Updates a mapping in an index by calling `put_mapping` with the mapping specified.
Requires the `new_mappings` method and `DOCUMENT_TYPE` constant.
```ruby
class MigrationName < Elastic::Migration
include ::Search::Elastic::MigrationUpdateMappingsHelper
DOCUMENT_TYPE = Issue
private
def new_mappings
{
schema_version: {
type: 'short'
}
}
end
end
```
You can test this migration with the `'migration adds mapping'` shared examples.
```ruby
describe 'migration', :elastic, :sidekiq_inline do
include_examples 'migration adds mapping'
end
```
#### `Search::Elastic::MigrationRemoveFieldsHelper`
Removes specified fields from an index.
Checks in batches if any documents that match `DOCUMENT_TYPE` have the fields specified in Elasticsearch. If documents exist, uses a Painless script to perform `update_by_query`.
- For single fields, define `field_to_remove` method and `DOCUMENT_TYPE` constant
- For multiple fields, define `fields_to_remove` method and `DOCUMENT_TYPE` constant
```ruby
class MigrationName < Elastic::Migration
include ::Search::Elastic::MigrationRemoveFieldsHelper
batched!
throttle_delay 1.minute
DOCUMENT_TYPE = User
private
def fields_to_remove
%w[two_factor_enabled has_projects]
end
end
```
The default batch size is `10_000`. You can override this value by specifying `BATCH_SIZE`:
```ruby
class MigrationName < Elastic::Migration
include ::Search::Elastic::MigrationRemoveFieldsHelper
batched!
BATCH_SIZE = 100
...
end
```
You can test this migration with the `'migration removes field'` shared examples.
```ruby
include_examples 'migration removes field' do
let(:expected_throttle_delay) { 1.minute }
let(:objects) { create_list(:work_item, 6) }
let(:index_name) { ::Search::Elastic::Types::WorkItem.index_name }
let(:field) { :correct_work_item_type_id }
let(:type) { 'long' }
end
```
If the mapping contains more than a `type`, omit the `type` variable and define `mapping` instead:
```ruby
include_examples 'migration removes field' do
let(:expected_throttle_delay) { 1.minute }
let(:objects) { create_list(:work_item, 6) }
let(:index_name) { ::Search::Elastic::Types::WorkItem.index_name }
let(:field) { :embedding_0 }
let(:mapping) { { type: 'dense_vector', dims: 768, index: true, similarity: 'cosine' } }
end
```
If you get an `expecting token of type [VALUE_NUMBER] but found [FIELD_NAME]` error, define the `value` variable:
```ruby
include_examples 'migration removes field' do
let(:expected_throttle_delay) { 1.minute }
let(:objects) { create_list(:work_item, 6) }
let(:index_name) { ::Search::Elastic::Types::WorkItem.index_name }
let(:field) { :embedding_0 }
let(:mapping) { { type: 'dense_vector', dims: 768, index: true, similarity: 'cosine' } }
let(:value) { Array.new(768, 1) }
end
```
#### `Search::Elastic::MigrationObsolete`
Marks a migration as obsolete when it's no longer required.
```ruby
class MigrationName < Elastic::Migration
include ::Search::Elastic::MigrationObsolete
end
```
When marking a skippable migration as obsolete, you must keep the `skip_if` condition.
You can test this migration with the `'a deprecated Advanced Search migration'`
shared examples. Follow the [process for marking migrations as obsolete](#process-for-marking-migrations-as-obsolete).
#### `Search::Elastic::MigrationCreateIndexHelper`
Creates a new index.
Requires:
- The `target_class` and `document_type` methods
- Mappings and index settings for the class
{{< alert type="warning" >}}
You must perform a follow-up migration to populate the index in the same milestone.
{{< /alert >}}
```ruby
class MigrationName < Elastic::Migration
include ::Search::Elastic::MigrationCreateIndexHelper
retry_on_failure
def document_type
:epic
end
def target_class
Epic
end
end
```
You can test this migration with the `'migration creates a new index'` shared examples.
```ruby
it_behaves_like 'migration creates a new index', 20240501134252, WorkItem
```
#### `Search::Elastic::MigrationReindexTaskHelper`
Creates a reindex task which creates a new index and copies data over to the new index.
Requires:
- The `targets` method.
```ruby
class MigrationName < Elastic::Migration
include ::Search::Elastic::MigrationReindexTaskHelper
def targets
%w[MergeRequest]
end
end
```
You can test this migration with the following specs.
```ruby
let(:migration) { described_class.new(version) }
let(:task) { Search::Elastic::ReindexingTask.last }
let(:targets) { %w[MergeRequest] }
it 'does not have migration options set', :aggregate_failures do
expect(migration).not_to be_batched
expect(migration).not_to be_retry_on_failure
end
describe '#migrate', :aggregate_failures do
it 'creates reindexing task with correct target and options' do
expect { migration.migrate }.to change { Search::Elastic::ReindexingTask.count }.by(1)
expect(task.targets).to eq(targets)
expect(task.options).to eq('skip_pending_migrations_check' => true)
end
end
describe '#completed?' do
it 'always returns true' do
expect(migration.completed?).to be(true)
end
end
```
#### `Search::Elastic::MigrationReindexBasedOnSchemaVersion`
Reindexes all documents in the index that stores the specified document type and updates `schema_version`.
Requires the `DOCUMENT_TYPE` and `NEW_SCHEMA_VERSION` constants.
The index mapping must have a `schema_version` integer field in a `YYWW` (year/week) format.
{{< alert type="note" >}}
Previously index mapping `schema_version` used `YYMM` format. New versions should use the `YYWW` format.
{{< /alert >}}
```ruby
class MigrationName < Elastic::Migration
include Search::Elastic::MigrationReindexBasedOnSchemaVersion
batched!
batch_size 9_000
throttle_delay 1.minute
DOCUMENT_TYPE = WorkItem
NEW_SCHEMA_VERSION = 24_46
UPDATE_BATCH_SIZE = 100
end
```
You can test this migration with the `'migration reindex based on schema_version'` shared examples.
```ruby
include_examples 'migration reindex based on schema_version' do
let(:expected_throttle_delay) { 1.minute }
let(:expected_batch_size) { 9_000 }
let(:objects) { create_list(:project, 3) }
end
```
#### `Search::Elastic::MigrationDeleteBasedOnSchemaVersion`
Deletes all documents in the index that stores the specified document type and has `schema_version` less than the given value.
Requires the `DOCUMENT_TYPE` constant and `schema_version` method.
The index mapping must have a `schema_version` integer field in a `YYWW` (year/week) format.
{{< alert type="note" >}}
Previously index mapping `schema_version` used `YYMM` format. New versions should use the `YYWW` format.
{{< /alert >}}
```ruby
class MigrationName < Elastic::Migration
include ::Search::Elastic::MigrationDeleteBasedOnSchemaVersion
DOCUMENT_TYPE = Issue
batch_size 10_000
batched!
throttle_delay 1.minute
retry_on_failure
def schema_version
23_12
end
end
```
You can test this migration with the `'migration deletes documents based on schema version'` shared examples.
```ruby
include_examples 'migration deletes documents based on schema version' do
let(:objects) { create_list(:issue, 3) }
let(:expected_throttle_delay) { 1.minute }
let(:expected_batch_size) { 20000 }
end
```
#### `Search::Elastic::MigrationDatabaseBackfillHelper`
Reindexes all documents in the database to the elastic search index respecting the `limited_indexing` setting.
Requires the `DOCUMENT_TYPE` constant and `respect_limited_indexing?` method.
```ruby
class MigrationName < Elastic::Migration
include ::Search::Elastic::MigrationDatabaseBackfillHelper
batch_size 10_000
batched!
throttle_delay 1.minute
retry_on_failure
DOCUMENT_TYPE = Issue
def respect_limited_indexing?
true
end
end
```
#### `Search::Elastic::MigrationHelper`
Contains methods you can use when a migration doesn't fit the previous examples.
```ruby
class MigrationName < Elastic::Migration
include ::Search::Elastic::MigrationHelper
def migrate
...
end
def completed?
...
end
end
```
### Migration options supported by the `Elastic::MigrationWorker`
[`Elastic::MigrationWorker`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/ee/app/workers/elastic/migration_worker.rb) supports the following migration options:
- `batched!` - Allow the migration to run in batches. If set, [`Elastic::MigrationWorker`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/ee/app/workers/elastic/migration_worker.rb)
re-enqueues itself with a delay which is set using the `throttle_delay` option described below. The batching
must be handled in the `migrate` method. This setting controls the re-enqueuing only.
- `batch_size` - Sets the number of documents modified during a `batched!` migration run. This size should be set to a value which allows the updates
enough time to finish. This can be tuned in combination with the `throttle_delay` option described below. The batching
must be handled in a custom `migrate` method or by using the [`Search::Elastic::MigrationBackfillHelper`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/ee/app/workers/concerns/elastic/migration_backfill_helper.rb)
`migrate` method which uses this setting. Default value is 1000 documents.
- `throttle_delay` - Sets the wait time in between batch runs. This time should be set high enough to allow each migration batch
enough time to finish. Additionally, the time should be less than 5 minutes because that is how often the
[`Elastic::MigrationWorker`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/ee/app/workers/elastic/migration_worker.rb)
cron worker runs. The default value is 3 minutes.
- `pause_indexing!` - Pause indexing while the migration runs. This setting records the indexing setting before
the migration runs and set it back to that value when the migration is completed.
- `space_requirements!` - Verify that enough free space is available in the cluster when the migration runs. This setting
halts the migration if the storage required is not available when the migration runs. The migration must provide
the space required in bytes by defining a `space_required_bytes` method.
- `retry_on_failure` - Enable the retry on failure feature. By default, it retries
the migration 30 times. After it runs out of retries, the migration is marked as halted.
To customize the number of retries, pass the `max_attempts` argument:
`retry_on_failure max_attempts: 10`
```ruby
# frozen_string_literal: true
class BatchedMigrationName < Elastic::Migration
# Declares a migration should be run in batches
batched!
throttle_delay 10.minutes
pause_indexing!
space_requirements!
retry_on_failure
# ...
end
```
## Avoiding downtime in migrations
### Reverting a migration
If a migration fails or is halted on GitLab.com, we prefer to revert the change that introduced the migration. This
prevents self-managed customers from receiving a broken migration and reduces the need for backports.
### Multi-version compatibility
Advanced search migrations, like any other GitLab changes, need to support the case where
[multiple versions of the application are running at the same time](../multi_version_compatibility.md).
Depending on the order of deployment, it's possible that the migration
has started or finished and there's still a server running the application code from before the
migration. We need to take this into consideration until we can
[ensure all advanced search migrations start after the deployment has finished](https://gitlab.com/gitlab-org/gitlab/-/issues/321619).
### High risk migrations
Because Elasticsearch does not support transactions, we always need to design our
migrations to accommodate a situation where the application
code is reverted after the migration has started or after it is finished.
For this reason we generally defer destructive actions (for example, deletions after
some data is moved) to a later merge request after the migrations have
completed successfully. To be safe, for self-managed customers we should also
defer it to another release if there is risk of important data loss.
## Calculating migration runtime
It's important to understand how long a migration might take to run on GitLab.com. Derive the number of documents that
will be processed by the migration. This number may come from querying the database or an existing Elasticsearch index.
Use the following formula to calculate the runtime:
```ruby
> batch_size = 9_000
=> 9000
> throttle_delay = 1.minute
=> 1 minute
> number_of_documents = 15_536_906
=> 15536906
> (number_of_documents / batch_size) * throttle_delay
=> 1726 minutes
> (number_of_documents / batch_size) * throttle_delay / 1.hour
=> 28
```
## Best practices for advanced search migrations
Follow these best practices for best results:
- Order all migrations for each document type so that any migrations that use
[`Search::Elastic::MigrationUpdateMappingsHelper`](#searchelasticmigrationupdatemappingshelper)
are executed before migrations that use the
[`Search::Elastic::MigrationBackfillHelper`](#searchelasticmigrationbackfillhelper). This avoids
reindexing the same documents multiple times if all of the migrations are unapplied
and reduces the backfill time.
- When working in batches, keep the batch size under 9,000 documents.
The bulk indexer is set to run every minute and process a batch
of 10,000 documents. This way, the bulk indexer has time to
process records before another migration batch is attempted.
- To ensure that document counts are up to date, you should refresh
the index before checking if a migration is completed.
- Add logging statements to each migration when the migration starts, when a
completion check occurs, and when the migration is completed. These logs
are helpful when debugging issues with migrations.
- Pause indexing if you're using any Elasticsearch Reindex API operations.
- Consider adding a retry limit if there is potential for the migration to fail.
This ensures that migrations can be halted if an issue occurs.
## Cleaning up advanced search migrations
Because advanced search migrations usually require us to support multiple
code paths for a long period of time, it's important to clean those up when we
safely can.
We choose to use GitLab [required stops](../database/required_stops.md) as a safe time to remove
backwards compatibility for indices that have not been fully migrated. We
[document this in our upgrade documentation](../../update/plan_your_upgrade.md).
[GitLab Housekeeper](https://gitlab.com/gitlab-org/gitlab/-/blob/master/gems/gitlab-housekeeper/README.md)
is used to automate the cleanup process. This process includes
marking existing migrations as obsolete and deleting obsolete migrations.
When a migration is marked as obsolete, the migration code is replaced with
obsolete migration code and tests are replaced with obsolete migration shared
examples so that:
- We don't need to maintain any code that is called from our advanced search
migrations.
- We don't waste CI time running tests for migrations that we don't support
anymore.
- Operators who have not run this migration and who upgrade directly to the
target version see a message prompting them to reindex from scratch.
To be extra safe, we do not clean up migrations that were created in the last
minor version before the last required stop. For example, if the last required stop
was `%14.0`, we should not clean up migrations that were only added in `%13.12`.
This extra safety net allows for migrations that might take multiple weeks to
finish on GitLab.com. Because our deployments to GitLab.com
are automated and we do not have automated checks to prevent this cleanup,
the extra precaution is warranted.
Additionally, even if we did have automated checks to prevent it, we wouldn't
actually want to hold up GitLab.com deployments on advanced search migrations,
as they may still have another week to go, and that's too long to block
deployments.
### Process for marking migrations as obsolete
Run the [`Keeps::MarkOldAdvancedSearchMigrationsAsObsolete` Keep](https://gitlab.com/gitlab-org/gitlab/-/blob/master/gems/gitlab-housekeeper/README.md#running-for-real)
manually to mark migrations as obsolete.
For every migration that was created two versions before the last required stop,
the Keep:
1. Retains the content of the migration and adds a prepend to the bottom:
```ruby
ClassName.prepend ::Search::Elastic::MigrationObsolete
```
1. Replaces the spec file content with the `'a deprecated Advanced Search migration'` shared example.
1. Randomly selects a Global Search backend engineer as an assignee.
1. Updates the dictionary file to mark the migration as obsolete.
The MR assignee must:
1. Ensure the dictionary file has the correct `marked_obsolete_by_url` and `marked_obsolete_in_milestone`.
1. Verify that no references to the migration or spec files exist in the `.rubocop_todo/` directory.
1. Remove any logic-handling backwards compatibility for this migration by
looking for `Elastic::DataMigrationService.migration_has_finished?(:migration_name_in_lowercase)`.
1. Push any required changes to the merge request.
### Process for removing obsolete migrations
Run the [`Keeps::DeleteObsoleteAdvancedSearchMigrations` Keep](https://gitlab.com/gitlab-org/gitlab/-/blob/master/gems/gitlab-housekeeper/README.md#running-for-real)
manually to remove obsolete migrations and specs. The Keep removes all but the most
recent obsolete migration.
1. Select obsolete migrations that were marked as obsolete before the last required stop.
1. If the first step includes all obsolete migrations, keep one obsolete migration as a safeguard for customers with unapplied migrations.
1. Delete migration files and spec files for those migrations.
1. Create a merge request and assign it to a Global Search team member.
The MR assignee must:
1. Backup migrations from the default branch to the [migration graveyard](https://gitlab.com/gitlab-org/search-team/migration-graveyard)
1. Verify that no references to the migration or spec files exist in the `.rubocop_todo/` directory.
1. Push any required changes to the merge request.
## ChatOps commands for monitoring migrations
You can check migration status from Slack (or any ChatOps‑enabled channel) at any time:
```plaintext
/chatops run search_migrations --help
/chatops run search_migrations list
/chatops run search_migrations get MigrationName
/chatops run search_migrations get VersionNumber
```
The above uses the [search_migrations](https://gitlab.com/gitlab-com/chatops/-/blob/master/lib/chatops/commands/search_migrations.rb) ChatOps plugin to fetch current migration state.
|
https://docs.gitlab.com/development/refactoring_guide
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/_index.md
|
2025-08-13
|
doc/development/refactoring_guide
|
[
"doc",
"development",
"refactoring_guide"
] |
_index.md
|
none
|
unassigned
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Refactoring guide
| null |
This document is a collection of techniques and best practices to consider while performing a refactor.
## Pinning tests
Pinning tests help you ensure that you don't unintentionally change the output or behavior of the entity you're refactoring. This even includes preserving any existing buggy behavior, since consumers may rely on those bugs implicitly.
### Example steps
1. Identify all the possible inputs to the refactor subject (for example, anything that's injected into the template or used in a conditional).
1. For each possible input, identify the significant possible values.
1. Create a test to save a full detailed snapshot for each helpful combination values per input. This should guarantee that we have "pinned down" the current behavior. The snapshot could be literally a screenshot, a dump of HTML, or even an ordered list of debugging statements.
1. Run all the pinning tests against the code, before you start refactoring (Oracle)
1. Perform the refactor (or check out the commit with the work done)
1. Run again all the pinning test against the post refactor code (Pin)
1. Compare the Oracle with the Pin. If the Pin is different, you know the refactoring doesn't preserve existing behavior.
1. Repeat the previous three steps as necessary until the refactoring is complete.
### Example commit history
Leaving in the commits for adding and removing pins helps others check out and verify the result of the test.
```shell
AAAAAA Add pinning tests to funky_foo
BBBBBB Refactor funky_foo into nice_foo
CCCCCC Remove pinning tests for funky_foo
```
Then you can leave a reviewer instructions on how to run the pinning test in your MR. Example:
> First revert the commit which removes the pin.
>
> ```shell
> git revert --no-commit $(git log -1 --grep="Remove pinning test for funky_foo" --pretty=format:"%H")
> ```
>
> Then run the test
>
> ```shell
> yarn run jest path/to/funky_foo_pin_spec.js
> ```
### Try to keep pins green
It's hard for a refactor to be 100% pure. This means that a pin which captures absolutely everything is bound to fail with
some trivial and expected differences. Try to keep the pins green by cleaning the pin with the expected changes. This helps
others quickly verify that a refactor was safe.
[Example](https://gitlab.com/gitlab-org/gitlab/-/commit/7b73da4078a60cf18f5c10c712c66c302174f506?merge_request_iid=29528#a061e6835fd577ccf6802c8a476f4e9d47466d16_0_23):
```javascript
// funky_foo_pin_spec.js
const cleanForSnapshot = el => {
Array.from(rootEl.querySelectorAll('[data-deprecated-attribute]')).forEach(el => {
el.removeAttribute('data-deprecated-attribute');
});
};
// ...
expect(cleanForSnapshot(wrapper.element)).toMatchSnapshot();
```
### Resources
[Unofficial wiki explanation](https://wiki.c2.com/?PinningTests)
### Examples
- [Pinning test in a Haml to Vue refactor](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/27691#pinning-tests)
- [Pinning test in isolating a bug](https://gitlab.com/gitlab-org/gitlab-foss/-/merge_requests/32198#note_212736225)
- [Pinning test in refactoring dropdown list](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/28173)
- [Pinning test in refactoring vulnerability_details.vue](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/25830/commits)
- [Pinning test in refactoring notes_award_list.vue](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/29528#pinning-test)
- <i class="fa fa-youtube-play youtube" aria-hidden="true"></i> [Video of pair programming session on pinning tests](https://youtu.be/LrakPcspBK4)
|
---
stage: none
group: unassigned
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: Refactoring guide
breadcrumbs:
- doc
- development
- refactoring_guide
---
This document is a collection of techniques and best practices to consider while performing a refactor.
## Pinning tests
Pinning tests help you ensure that you don't unintentionally change the output or behavior of the entity you're refactoring. This even includes preserving any existing buggy behavior, since consumers may rely on those bugs implicitly.
### Example steps
1. Identify all the possible inputs to the refactor subject (for example, anything that's injected into the template or used in a conditional).
1. For each possible input, identify the significant possible values.
1. Create a test to save a full detailed snapshot for each helpful combination values per input. This should guarantee that we have "pinned down" the current behavior. The snapshot could be literally a screenshot, a dump of HTML, or even an ordered list of debugging statements.
1. Run all the pinning tests against the code, before you start refactoring (Oracle)
1. Perform the refactor (or check out the commit with the work done)
1. Run again all the pinning test against the post refactor code (Pin)
1. Compare the Oracle with the Pin. If the Pin is different, you know the refactoring doesn't preserve existing behavior.
1. Repeat the previous three steps as necessary until the refactoring is complete.
### Example commit history
Leaving in the commits for adding and removing pins helps others check out and verify the result of the test.
```shell
AAAAAA Add pinning tests to funky_foo
BBBBBB Refactor funky_foo into nice_foo
CCCCCC Remove pinning tests for funky_foo
```
Then you can leave a reviewer instructions on how to run the pinning test in your MR. Example:
> First revert the commit which removes the pin.
>
> ```shell
> git revert --no-commit $(git log -1 --grep="Remove pinning test for funky_foo" --pretty=format:"%H")
> ```
>
> Then run the test
>
> ```shell
> yarn run jest path/to/funky_foo_pin_spec.js
> ```
### Try to keep pins green
It's hard for a refactor to be 100% pure. This means that a pin which captures absolutely everything is bound to fail with
some trivial and expected differences. Try to keep the pins green by cleaning the pin with the expected changes. This helps
others quickly verify that a refactor was safe.
[Example](https://gitlab.com/gitlab-org/gitlab/-/commit/7b73da4078a60cf18f5c10c712c66c302174f506?merge_request_iid=29528#a061e6835fd577ccf6802c8a476f4e9d47466d16_0_23):
```javascript
// funky_foo_pin_spec.js
const cleanForSnapshot = el => {
Array.from(rootEl.querySelectorAll('[data-deprecated-attribute]')).forEach(el => {
el.removeAttribute('data-deprecated-attribute');
});
};
// ...
expect(cleanForSnapshot(wrapper.element)).toMatchSnapshot();
```
### Resources
[Unofficial wiki explanation](https://wiki.c2.com/?PinningTests)
### Examples
- [Pinning test in a Haml to Vue refactor](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/27691#pinning-tests)
- [Pinning test in isolating a bug](https://gitlab.com/gitlab-org/gitlab-foss/-/merge_requests/32198#note_212736225)
- [Pinning test in refactoring dropdown list](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/28173)
- [Pinning test in refactoring vulnerability_details.vue](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/25830/commits)
- [Pinning test in refactoring notes_award_list.vue](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/29528#pinning-test)
- <i class="fa fa-youtube-play youtube" aria-hidden="true"></i> [Video of pair programming session on pinning tests](https://youtu.be/LrakPcspBK4)
|
https://docs.gitlab.com/development/create_triage_policy_with_gitlab_duo_agent_platform_guide
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/create_triage_policy_with_gitlab_duo_agent_platform_guide.md
|
2025-08-13
|
doc/development/duo_agent_platform
|
[
"doc",
"development",
"duo_agent_platform"
] |
create_triage_policy_with_gitlab_duo_agent_platform_guide.md
|
AI-powered
|
Duo Workflow
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Create triage policies with the assistance of GitLab Duo Agent Platform
| null |
{{< history >}}
- [Name changed](https://gitlab.com/gitlab-org/gitlab/-/issues/551382) from `Workflow` to `Agent Platform` in GitLab 18.2.
{{< /history >}}
This guide provides comprehensive instructions for writing triage automation policies in [triage-ops](https://gitlab.com/gitlab-org/quality/triage-ops) using GitLab Duo Agent Platform. You will be able to self service label migrations after a department re-org by following this page.
Todo: include instructions for writing policies to perform other types of automated tasks.
## Purpose
Triage policies are used when team members migrate labels across existing issues, merge requests, and epics using [GitLab-triage](https://gitlab.com/gitlab-org/ruby/gems/gitlab-triage). This tool automates triaging through [policies defined in YAML](https://gitlab.com/gitlab-org/ruby/gems/gitlab-triage#what-is-a-triage-policy). To optimize operational efficiency and ensure seamless implementation, we recommend self-servicing the label migration MRs using [GitLab Duo Agent Platform](../../user/duo_agent_platform/_index.md).
## Before you start
Follow the [GitLab Duo Agent Platform documentation](../../user/duo_agent_platform/_index.md) to learn how to set up and access GitLab Duo Agent Platform in your code editor.
## Build your prompt
You need to be specific about your requirements in the prompt to produce the best result.
Example prompt:
> Write a one-off label migration in `policies/one-off/auth-migration.yml` to apply a ~"DevOps::software supply chain security" label to issues, MRs, and epics currently labeled with ~"group::authentication". Target only open resources. Exclude any resource that already has the ~"DevOps::software supply chain security" label.
>
> Link the new one-off policy in `.gitlab/ci/one-off.yml` to run the policy in CI. Create two jobs: a dry-run and an actual job. The job names must follow the instructions listed in `one-off.yml`.
>
> Read instructions and example YAML files in `policies/one-off/duo-workflow-guide-and-example-policies` to ensure correct syntax.
See sections below for recommended information to include in the prompt.
### File name and location
Specify a policy file name inside the [`policies`](https://gitlab.com/gitlab-org/quality/triage-ops/-/tree/master/policies?ref_type=heads) directory except for `generated` directory.
For example, label migration policies go in [`policies/one-off`](https://gitlab.com/gitlab-org/quality/triage-ops/-/tree/master/policies/one-off) directory.
Example prompt snippet: `write a one-off label migration in policies/one-off/auth-migration.yml to...`
### Migration target
Define your migration target through `conditions` in the policy.
Example prompt snippet: `issues, MRs, and epics that are currently labeled with group::authentication`
Note: the gem only answers to [these specific conditions](https://gitlab.com/gitlab-org/ruby/gems/gitlab-triage#conditions-field).
### Action
Define the desired outcome of the automation, such as which label to apply to the targets.
Example prompt snippet: `apply a devops::software supply chain security label to issues, MRs, and epics...`
Note: the gem only performs [these actions](https://gitlab.com/gitlab-org/ruby/gems/gitlab-triage#actions-field).
### Reference material
GitLab Duo Agent Platform requires reference materials, preferably with examples, to write these files.
Example prompt snippet: `Read instructions and example yml files in policies/one-off/duo-workflow-guide-and-example-policies to ensure the result has the correct syntax.`
### CI jobs for label migration
For testing and executing migration policies, create CI jobs in the MR pipeline. Instruct Duo Agent Platform to create these jobs:
Example prompt snippet: `Link the new one-off policy in .gitlab/ci/one-off.yml to run the policy in CI. Create two jobs: a dry-run and an actual job. The job names must follow the instructions listed in one-off.yml.`
### Policy Refinement
You can start another flow to refine the policy if some policy condition was missing.
Example prompt:
> Update the policy you created in `policies/one-off/auth-migration.yml` by adding a new condition to skip resources currently labeled with ~"workflow::completed" using the forbidden_labels field
### Resulting policy written by GitLab Duo Agent Platform
The 2 prompts above generated the following policy:
```yaml
.common_conditions: &common_conditions
state: opened
labels:
- "group::authentication"
forbidden_labels:
- "devops::software supply chain security"
- "workflow::completed"
.common_actions: &common_actions
labels:
- "devops::software supply chain security"
resource_rules:
epics:
rules:
- name: (Epics) Add devops::software supply chain security label to group::authentication epics
conditions:
<<: *common_conditions
actions:
<<: *common_actions
issues:
rules:
- name: (Issues) Add devops::software supply chain security label to group::authentication issues
conditions:
<<: *common_conditions
actions:
<<: *common_actions
merge_requests:
rules:
- name: (Merge Requests) Add devops::software supply chain security label to group::authentication MRs
conditions:
<<: *common_conditions
actions:
<<: *common_actions
```
## After a triage policy is written
Submit the code changes to an MR using [this merge request template for one-off label migration](https://gitlab.com/gitlab-org/quality/triage-ops/-/blob/master/.gitlab/merge_request_templates/One-off-label-migration.md). If you have followed the instructions above, your MR should include 2 jobs under the `one-off` stage. Run the dry-run job in your merge request pipeline to validate the policy. Once the policy is validated, you can execute the label migration job (the one without the `dry-run` job name suffix).
You are welcome to request a code review to confirm the migration policy was correctly written. However, if you are confident with the result of the label migration, you can choose to skip the code review step.
Reminder, please do not merge the MR when a migration is done.
## Best practices and troubleshooting tips
Use the dry-run job to verify your policy's accuracy.
If a specified condition is ignored in the dry run, check for syntax errors in the condition field.
If the syntax looks correct, you may have used an invalid condition. The GitLab-triage gem ignores such conditions without generating an error message, so you need to review all condition keywords in the policy and compare them with the [GitLab-triage documentation](https://gitlab.com/gitlab-org/ruby/gems/gitlab-triage#defining-a-policy). It only answers to [these conditions](https://gitlab.com/gitlab-org/ruby/gems/gitlab-triage#conditions-field) and [these actions](https://gitlab.com/gitlab-org/ruby/gems/gitlab-triage#actions-field).
For example, when writing a triage policy to post comments in your targeted resources:
> In `./policies/groups/gitlab-com/csmerm/label_regression_for_on_track_with_no_activity.yml`, write a policy to apply regression label on issues labeled with ~"SP Objective::Status::On Track" when there has been no update on the issue in more than 8 days.
May produce this result with an incorrect field `last_updated_at`:
```yaml
resource_rules:
issues:
rules:
- name: Mark as regression when on track issues have no activity for 8+ days
conditions:
last_updated_at: 8d-ago
actions:
labels:
- regression
```
The correct way of specifying that condition is:
```yaml
conditions:
ruby: resource[:updated_at] < 8.days.ago.strftime('%Y-%m-%dT00:00:00.000Z')
```
After finding the solution, include this policy in the reference materials linked in your #reference-material prompt to help Workflow avoid similar mistakes.
## Demo
Watch [this video](https://www.youtube.com/watch?v=AoCD4hh2nhc) on GitLab Unfiltered for demo.
|
---
stage: AI-powered
group: Duo Workflow
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: Create triage policies with the assistance of GitLab Duo Agent Platform
breadcrumbs:
- doc
- development
- duo_agent_platform
---
{{< history >}}
- [Name changed](https://gitlab.com/gitlab-org/gitlab/-/issues/551382) from `Workflow` to `Agent Platform` in GitLab 18.2.
{{< /history >}}
This guide provides comprehensive instructions for writing triage automation policies in [triage-ops](https://gitlab.com/gitlab-org/quality/triage-ops) using GitLab Duo Agent Platform. You will be able to self service label migrations after a department re-org by following this page.
Todo: include instructions for writing policies to perform other types of automated tasks.
## Purpose
Triage policies are used when team members migrate labels across existing issues, merge requests, and epics using [GitLab-triage](https://gitlab.com/gitlab-org/ruby/gems/gitlab-triage). This tool automates triaging through [policies defined in YAML](https://gitlab.com/gitlab-org/ruby/gems/gitlab-triage#what-is-a-triage-policy). To optimize operational efficiency and ensure seamless implementation, we recommend self-servicing the label migration MRs using [GitLab Duo Agent Platform](../../user/duo_agent_platform/_index.md).
## Before you start
Follow the [GitLab Duo Agent Platform documentation](../../user/duo_agent_platform/_index.md) to learn how to set up and access GitLab Duo Agent Platform in your code editor.
## Build your prompt
You need to be specific about your requirements in the prompt to produce the best result.
Example prompt:
> Write a one-off label migration in `policies/one-off/auth-migration.yml` to apply a ~"DevOps::software supply chain security" label to issues, MRs, and epics currently labeled with ~"group::authentication". Target only open resources. Exclude any resource that already has the ~"DevOps::software supply chain security" label.
>
> Link the new one-off policy in `.gitlab/ci/one-off.yml` to run the policy in CI. Create two jobs: a dry-run and an actual job. The job names must follow the instructions listed in `one-off.yml`.
>
> Read instructions and example YAML files in `policies/one-off/duo-workflow-guide-and-example-policies` to ensure correct syntax.
See sections below for recommended information to include in the prompt.
### File name and location
Specify a policy file name inside the [`policies`](https://gitlab.com/gitlab-org/quality/triage-ops/-/tree/master/policies?ref_type=heads) directory except for `generated` directory.
For example, label migration policies go in [`policies/one-off`](https://gitlab.com/gitlab-org/quality/triage-ops/-/tree/master/policies/one-off) directory.
Example prompt snippet: `write a one-off label migration in policies/one-off/auth-migration.yml to...`
### Migration target
Define your migration target through `conditions` in the policy.
Example prompt snippet: `issues, MRs, and epics that are currently labeled with group::authentication`
Note: the gem only answers to [these specific conditions](https://gitlab.com/gitlab-org/ruby/gems/gitlab-triage#conditions-field).
### Action
Define the desired outcome of the automation, such as which label to apply to the targets.
Example prompt snippet: `apply a devops::software supply chain security label to issues, MRs, and epics...`
Note: the gem only performs [these actions](https://gitlab.com/gitlab-org/ruby/gems/gitlab-triage#actions-field).
### Reference material
GitLab Duo Agent Platform requires reference materials, preferably with examples, to write these files.
Example prompt snippet: `Read instructions and example yml files in policies/one-off/duo-workflow-guide-and-example-policies to ensure the result has the correct syntax.`
### CI jobs for label migration
For testing and executing migration policies, create CI jobs in the MR pipeline. Instruct Duo Agent Platform to create these jobs:
Example prompt snippet: `Link the new one-off policy in .gitlab/ci/one-off.yml to run the policy in CI. Create two jobs: a dry-run and an actual job. The job names must follow the instructions listed in one-off.yml.`
### Policy Refinement
You can start another flow to refine the policy if some policy condition was missing.
Example prompt:
> Update the policy you created in `policies/one-off/auth-migration.yml` by adding a new condition to skip resources currently labeled with ~"workflow::completed" using the forbidden_labels field
### Resulting policy written by GitLab Duo Agent Platform
The 2 prompts above generated the following policy:
```yaml
.common_conditions: &common_conditions
state: opened
labels:
- "group::authentication"
forbidden_labels:
- "devops::software supply chain security"
- "workflow::completed"
.common_actions: &common_actions
labels:
- "devops::software supply chain security"
resource_rules:
epics:
rules:
- name: (Epics) Add devops::software supply chain security label to group::authentication epics
conditions:
<<: *common_conditions
actions:
<<: *common_actions
issues:
rules:
- name: (Issues) Add devops::software supply chain security label to group::authentication issues
conditions:
<<: *common_conditions
actions:
<<: *common_actions
merge_requests:
rules:
- name: (Merge Requests) Add devops::software supply chain security label to group::authentication MRs
conditions:
<<: *common_conditions
actions:
<<: *common_actions
```
## After a triage policy is written
Submit the code changes to an MR using [this merge request template for one-off label migration](https://gitlab.com/gitlab-org/quality/triage-ops/-/blob/master/.gitlab/merge_request_templates/One-off-label-migration.md). If you have followed the instructions above, your MR should include 2 jobs under the `one-off` stage. Run the dry-run job in your merge request pipeline to validate the policy. Once the policy is validated, you can execute the label migration job (the one without the `dry-run` job name suffix).
You are welcome to request a code review to confirm the migration policy was correctly written. However, if you are confident with the result of the label migration, you can choose to skip the code review step.
Reminder, please do not merge the MR when a migration is done.
## Best practices and troubleshooting tips
Use the dry-run job to verify your policy's accuracy.
If a specified condition is ignored in the dry run, check for syntax errors in the condition field.
If the syntax looks correct, you may have used an invalid condition. The GitLab-triage gem ignores such conditions without generating an error message, so you need to review all condition keywords in the policy and compare them with the [GitLab-triage documentation](https://gitlab.com/gitlab-org/ruby/gems/gitlab-triage#defining-a-policy). It only answers to [these conditions](https://gitlab.com/gitlab-org/ruby/gems/gitlab-triage#conditions-field) and [these actions](https://gitlab.com/gitlab-org/ruby/gems/gitlab-triage#actions-field).
For example, when writing a triage policy to post comments in your targeted resources:
> In `./policies/groups/gitlab-com/csmerm/label_regression_for_on_track_with_no_activity.yml`, write a policy to apply regression label on issues labeled with ~"SP Objective::Status::On Track" when there has been no update on the issue in more than 8 days.
May produce this result with an incorrect field `last_updated_at`:
```yaml
resource_rules:
issues:
rules:
- name: Mark as regression when on track issues have no activity for 8+ days
conditions:
last_updated_at: 8d-ago
actions:
labels:
- regression
```
The correct way of specifying that condition is:
```yaml
conditions:
ruby: resource[:updated_at] < 8.days.ago.strftime('%Y-%m-%dT00:00:00.000Z')
```
After finding the solution, include this policy in the reference materials linked in your #reference-material prompt to help Workflow avoid similar mistakes.
## Demo
Watch [this video](https://www.youtube.com/watch?v=AoCD4hh2nhc) on GitLab Unfiltered for demo.
|
https://docs.gitlab.com/development/duo_agent_platform
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/_index.md
|
2025-08-13
|
doc/development/duo_agent_platform
|
[
"doc",
"development",
"duo_agent_platform"
] |
_index.md
|
AI-powered
|
Duo Workflow
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Development of GitLab Duo Agent Platform
| null |
{{< history >}}
- [Name changed](https://gitlab.com/gitlab-org/gitlab/-/issues/551382) from `Workflow` to `Agent Platform` in GitLab 18.2.
{{< /history >}}
How to set up the local development environment to run [GitLab Duo Agent Platform](../../user/duo_agent_platform/_index.md).
## Prerequisites
- [GitLab Ultimate license](https://handbook.gitlab.com/handbook/engineering/developer-onboarding/#working-on-gitlab-ee-developer-licenses)
- [Vertex access](https://gitlab.com/gitlab-org/gitlab-development-kit/-/blob/main/doc/howto/gitlab_ai_gateway.md#use-the-existing-project): You need access to the `ai-enablement-dev-69497ba7` project in GCP because GDK by default uses Anthropic hosted on Vertex. Access to this project should be available to all engineers at GitLab.
- If you do not have Vertex access for any reason, you should unset `DUO_WORKFLOW__VERTEX_PROJECT_ID` in the Duo Agent Platform Service and set `ANTHROPIC_API_KEY` to a regular Anthropic API key
- Various settings and feature flags, which are enabled for you by the [GDK setup script](#development-setup-for-backend-components)
## Set up local development for Agent Platform
Agent Platform consists of four separate services:
1. [GitLab instance](https://gitlab.com/gitlab-org/gitlab/)
1. GitLab Duo Agent Platform Service, which is part of [GitLab AI Gateway](https://gitlab.com/gitlab-org/modelops/applied-ml/code-suggestions/ai-assist/)
1. [GitLab Duo Agent Platform Executor](https://gitlab.com/gitlab-org/duo-workflow/duo-workflow-executor/)
1. [GitLab Duo Agent Platform Webview](https://gitlab.com/gitlab-org/editor-extensions/gitlab-lsp/-/blob/main/packages/webview_duo_workflow/README.md)
### Development Setup for Backend Components
You should [set up GitLab Duo Agent Platform with the GitLab Development Kit (GDK)](https://gitlab.com/gitlab-org/gitlab-development-kit/-/blob/main/doc/howto/duo_workflow.md)
to run local versions of GitLab, Duo Agent Platform Service, and Executor.
This setup can be used as-is with the [publicly available version of the VS Code Extension](https://marketplace.visualstudio.com/items?itemName=GitLab.gitlab-workflow).
### Development Setup for Frontend Components
There is no need to set up the backend components of the Agent Platform to test changes for the Agent Platform UI in the IDE.
A local build of the UI is required if you are making Duo Agent Platform UI changes that you need to view locally. A local build is also required if you want to use a version of the UI that has not been released yet.
Refer to the [GitLab Duo Agent Platform README](https://gitlab.com/gitlab-org/editor-extensions/gitlab-lsp/-/blob/main/packages/webview_duo_workflow/README.md) file in the Language Server project to get started with local development of GitLab Duo Agent Platform UI in the IDE.
## Development settings
Each of these settings can be turned on in your user settings in VS Code.
### Change view type
Enable the Duo Agent Platform as a sidepanel instead of fullview. This is going to be the default for public beta.
`"gitlab.featureFlags.duoWorkflowPanel": true,`
### Executor type
Allow to define which Duo Agent Platform executor is selected. Accepts:
- `shell` - Current default, runs the go binary directly on the user's machine
- `docker` - Runs the go binary inside a Docker container (deprecated)
- `node` - Runs a nodeJs/TypeScript executor directly inside the language server. Expected to become the default.
`"gitlab.duo.workflow.executor": "node",`
### Agent Platform flow
Experimental settings that allow Duo Agent Platform flow to be swapped. Includes:
- `software_development` - default
- `chat` - used by agentic chat
- `search_and_replace` - Used to scan large number of files and replace results with specific instructions
`"gitlab.duo.workflow.graph": "software_development",`
### Tool approval
Allow users to get access to tools that require approval such as running terminal commands.
`"gitlab.duo.workflow.toolApproval": true`
## Evaluate flow
### Running evals
To evaluate your local setup, please refer to [Duo Agent Platform Tests](https://gitlab.com/gitlab-org/duo-workflow/testing/duo-workflow-tests) repo.
### Comparing results
Once you finish a evaluation and have a experiment ID from LangSmith, compare results using [this notebook](https://gitlab.com/gitlab-org/duo-workflow/testing/notebooks/-/blob/main/notebooks/compare-swe-bench-evals.ipynb?ref_type=heads) from the [Duo Agent Platform Notebooks](https://gitlab.com/gitlab-org/duo-workflow/testing/notebooks) repo.
|
---
stage: AI-powered
group: Duo Workflow
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: Development of GitLab Duo Agent Platform
breadcrumbs:
- doc
- development
- duo_agent_platform
---
{{< history >}}
- [Name changed](https://gitlab.com/gitlab-org/gitlab/-/issues/551382) from `Workflow` to `Agent Platform` in GitLab 18.2.
{{< /history >}}
How to set up the local development environment to run [GitLab Duo Agent Platform](../../user/duo_agent_platform/_index.md).
## Prerequisites
- [GitLab Ultimate license](https://handbook.gitlab.com/handbook/engineering/developer-onboarding/#working-on-gitlab-ee-developer-licenses)
- [Vertex access](https://gitlab.com/gitlab-org/gitlab-development-kit/-/blob/main/doc/howto/gitlab_ai_gateway.md#use-the-existing-project): You need access to the `ai-enablement-dev-69497ba7` project in GCP because GDK by default uses Anthropic hosted on Vertex. Access to this project should be available to all engineers at GitLab.
- If you do not have Vertex access for any reason, you should unset `DUO_WORKFLOW__VERTEX_PROJECT_ID` in the Duo Agent Platform Service and set `ANTHROPIC_API_KEY` to a regular Anthropic API key
- Various settings and feature flags, which are enabled for you by the [GDK setup script](#development-setup-for-backend-components)
## Set up local development for Agent Platform
Agent Platform consists of four separate services:
1. [GitLab instance](https://gitlab.com/gitlab-org/gitlab/)
1. GitLab Duo Agent Platform Service, which is part of [GitLab AI Gateway](https://gitlab.com/gitlab-org/modelops/applied-ml/code-suggestions/ai-assist/)
1. [GitLab Duo Agent Platform Executor](https://gitlab.com/gitlab-org/duo-workflow/duo-workflow-executor/)
1. [GitLab Duo Agent Platform Webview](https://gitlab.com/gitlab-org/editor-extensions/gitlab-lsp/-/blob/main/packages/webview_duo_workflow/README.md)
### Development Setup for Backend Components
You should [set up GitLab Duo Agent Platform with the GitLab Development Kit (GDK)](https://gitlab.com/gitlab-org/gitlab-development-kit/-/blob/main/doc/howto/duo_workflow.md)
to run local versions of GitLab, Duo Agent Platform Service, and Executor.
This setup can be used as-is with the [publicly available version of the VS Code Extension](https://marketplace.visualstudio.com/items?itemName=GitLab.gitlab-workflow).
### Development Setup for Frontend Components
There is no need to set up the backend components of the Agent Platform to test changes for the Agent Platform UI in the IDE.
A local build of the UI is required if you are making Duo Agent Platform UI changes that you need to view locally. A local build is also required if you want to use a version of the UI that has not been released yet.
Refer to the [GitLab Duo Agent Platform README](https://gitlab.com/gitlab-org/editor-extensions/gitlab-lsp/-/blob/main/packages/webview_duo_workflow/README.md) file in the Language Server project to get started with local development of GitLab Duo Agent Platform UI in the IDE.
## Development settings
Each of these settings can be turned on in your user settings in VS Code.
### Change view type
Enable the Duo Agent Platform as a sidepanel instead of fullview. This is going to be the default for public beta.
`"gitlab.featureFlags.duoWorkflowPanel": true,`
### Executor type
Allow to define which Duo Agent Platform executor is selected. Accepts:
- `shell` - Current default, runs the go binary directly on the user's machine
- `docker` - Runs the go binary inside a Docker container (deprecated)
- `node` - Runs a nodeJs/TypeScript executor directly inside the language server. Expected to become the default.
`"gitlab.duo.workflow.executor": "node",`
### Agent Platform flow
Experimental settings that allow Duo Agent Platform flow to be swapped. Includes:
- `software_development` - default
- `chat` - used by agentic chat
- `search_and_replace` - Used to scan large number of files and replace results with specific instructions
`"gitlab.duo.workflow.graph": "software_development",`
### Tool approval
Allow users to get access to tools that require approval such as running terminal commands.
`"gitlab.duo.workflow.toolApproval": true`
## Evaluate flow
### Running evals
To evaluate your local setup, please refer to [Duo Agent Platform Tests](https://gitlab.com/gitlab-org/duo-workflow/testing/duo-workflow-tests) repo.
### Comparing results
Once you finish a evaluation and have a experiment ID from LangSmith, compare results using [this notebook](https://gitlab.com/gitlab-org/duo-workflow/testing/notebooks/-/blob/main/notebooks/compare-swe-bench-evals.ipynb?ref_type=heads) from the [Duo Agent Platform Notebooks](https://gitlab.com/gitlab-org/duo-workflow/testing/notebooks) repo.
|
https://docs.gitlab.com/development/workhorse
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/_index.md
|
2025-08-13
|
doc/development/workhorse
|
[
"doc",
"development",
"workhorse"
] |
_index.md
|
Create
|
Source Code
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
GitLab Workhorse
| null |
GitLab Workhorse is a smart reverse proxy for GitLab intended to handle resource-intensive and long-running requests.
It sits in front of Puma and intercepts every HTTP request destined for and emitted from GitLab Rails.
Rails delegates requests to Workhorse and it takes responsibility for resource intensive HTTP requests
such as file downloads and uploads, `git` over HTTP push/pull and `git` over HTTP archive downloads,
which optimizes resource utilization and improves request handling efficiency.
## Role in the GitLab stack
Workhorse can have other reverse proxy servers in front of it but only NGINX is supported.
It is also possible (although unsupported) to use other reverse proxies such as Apache when installing
GitLab from source.
On many instances of GitLab, such as `gitlab.com`, a CDN like CloudFlare sits in front of NGINX.
Every Rails controller and other code that handles HTTP requests and returning HTTP responses is
proxied through GitLab Workhorse.
Workhorse is unlike other reverse proxies as it is tightly coupled to GitLab Rails, whereas most reverse
proxies are more generic.
When required, Workhorse makes modifications to HTTP headers which GitLab Rails depends on to offload work efficiently.
## Functionality and operations
### Request processing
- Workhorse primarily acts as a pass-through entity for incoming requests, forwarding them to Rails for processing.
In essence, it performs minimal intervention on most requests, thereby maintaining a streamlined
request handling pipeline.
- For specific types of requests, especially those that are resource-intensive or require specialized handling
(for example, large file uploads), Workhorse takes a more active role.
Upon receiving directives from Rails, Workhorse executes specialized tasks such as directly
interacting with [Gitaly](../../administration/gitaly/_index.md) or offloading processing file uploads from Rails.
### Specialized task handling
- Workhorse is capable of intercepting certain requests based on Rails' responses and executing
predefined operations.
This includes interacting with [Gitaly](../../administration/gitaly/_index.md), managing large data
blobs, and altering request handling logic as required.
- Workhorse can manage file uploads efficiently.
It can hijack the file upload process, perform necessary actions as dictated by Rails
(such as storing files temporarily or uploading them to object storage), and update Rails when the
process has completed.
### Integration with the Rails API
Workhorse serves as a proxy to the Rails API, especially in contexts requiring interaction with container
registry services.
This setup exemplifies Workhorse's handling of high-load services by acting as a reverse proxy,
thereby minimizing the direct load on Rails.
## Architectural considerations
### Expanding functionality
- Maintaining Simplicity: While expanding Workhorse's functionalities to include direct handling
of specific services (for example, container registry), it's crucial to maintain its simplicity and efficiency.
Workhorse should not encompass complex control logic but rather focus on executing tasks as directed
by Rails.
- Service Implementation and Data Migration: Implementing new functionalities in Workhorse
requires careful consideration of data migration strategies and service continuity.
### Data management and operational integrity
- Workhorse's architecture facilitates efficient data management strategies, including garbage
collection and data migration.
Workhorse's role is to support high-performance operations without directly involving complex data
manipulation or control logic, which remains the purview of Rails.
- For operations requiring background processing or long-running tasks, it is suggested to use
separate services or Sidekiq job queues, with Workhorse and Rails coordinating to manage task execution and data integrity.
Workhorse is contained in a subfolder of the Rails monorepo at
[`gitlab-org/gitlab/workhorse`](https://gitlab.com/gitlab-org/gitlab/tree/master/workhorse).
## Learning resources
- Workhorse documentation (this page)
- Video: [GitLab Workhorse Deep Dive: Dependency Proxy](https://www.youtube.com/watch?v=9cRd-k0TRqI)
- [How Dependency Proxy with Workhorse works](https://gitlab.com/gitlab-org/gitlab/-/issues/370235)
- [Workhorse overview for the Dependency Proxy](https://www.youtube.com/watch?v=WmBibT9oQms)
- [Workhorse architecture discussion](https://www.youtube.com/watch?v=QlHdh-yudtw)
## Install Workhorse
To install GitLab Workhorse you need [Go 1.18 or newer](https://go.dev/dl) and
[GNU Make](https://www.gnu.org/software/make/).
To install into `/usr/local/bin` run `make install`.
```plaintext
make install
```
To install into `/foo/bin` set the PREFIX variable.
```plaintext
make install PREFIX=/foo
```
On some operating systems, such as FreeBSD, you may have to use
`gmake` instead of `make`.
*NOTE*: Some features depends on build tags, make sure to check
[Workhorse configuration](configuration.md) to enable them.
### Run time dependencies
Workhorse uses [ExifTool](https://exiftool.org/) for
removing EXIF data (which may contain sensitive information) from uploaded
images. If you installed GitLab:
- Using the Linux package, you're all set.
If you are using CentOS Minimal, you may need to install `perl` package: `yum install perl`.
- From source, make sure `exiftool` is installed:
```shell
# Debian/Ubuntu
sudo apt-get install libimage-exiftool-perl
# RHEL/CentOS
sudo yum install perl-Image-ExifTool
```
## Testing your code
Run the tests with:
```plaintext
make clean test
```
Each feature in GitLab Workhorse should have an integration test that
verifies that the feature 'kicks in' on the right requests and leaves
other requests unaffected. It is better to also have package-level tests
for specific behavior but the high-level integration tests should have
the first priority during development.
It is OK if a feature is only covered by integration tests.
|
---
stage: Create
group: Source Code
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: GitLab Workhorse
breadcrumbs:
- doc
- development
- workhorse
---
GitLab Workhorse is a smart reverse proxy for GitLab intended to handle resource-intensive and long-running requests.
It sits in front of Puma and intercepts every HTTP request destined for and emitted from GitLab Rails.
Rails delegates requests to Workhorse and it takes responsibility for resource intensive HTTP requests
such as file downloads and uploads, `git` over HTTP push/pull and `git` over HTTP archive downloads,
which optimizes resource utilization and improves request handling efficiency.
## Role in the GitLab stack
Workhorse can have other reverse proxy servers in front of it but only NGINX is supported.
It is also possible (although unsupported) to use other reverse proxies such as Apache when installing
GitLab from source.
On many instances of GitLab, such as `gitlab.com`, a CDN like CloudFlare sits in front of NGINX.
Every Rails controller and other code that handles HTTP requests and returning HTTP responses is
proxied through GitLab Workhorse.
Workhorse is unlike other reverse proxies as it is tightly coupled to GitLab Rails, whereas most reverse
proxies are more generic.
When required, Workhorse makes modifications to HTTP headers which GitLab Rails depends on to offload work efficiently.
## Functionality and operations
### Request processing
- Workhorse primarily acts as a pass-through entity for incoming requests, forwarding them to Rails for processing.
In essence, it performs minimal intervention on most requests, thereby maintaining a streamlined
request handling pipeline.
- For specific types of requests, especially those that are resource-intensive or require specialized handling
(for example, large file uploads), Workhorse takes a more active role.
Upon receiving directives from Rails, Workhorse executes specialized tasks such as directly
interacting with [Gitaly](../../administration/gitaly/_index.md) or offloading processing file uploads from Rails.
### Specialized task handling
- Workhorse is capable of intercepting certain requests based on Rails' responses and executing
predefined operations.
This includes interacting with [Gitaly](../../administration/gitaly/_index.md), managing large data
blobs, and altering request handling logic as required.
- Workhorse can manage file uploads efficiently.
It can hijack the file upload process, perform necessary actions as dictated by Rails
(such as storing files temporarily or uploading them to object storage), and update Rails when the
process has completed.
### Integration with the Rails API
Workhorse serves as a proxy to the Rails API, especially in contexts requiring interaction with container
registry services.
This setup exemplifies Workhorse's handling of high-load services by acting as a reverse proxy,
thereby minimizing the direct load on Rails.
## Architectural considerations
### Expanding functionality
- Maintaining Simplicity: While expanding Workhorse's functionalities to include direct handling
of specific services (for example, container registry), it's crucial to maintain its simplicity and efficiency.
Workhorse should not encompass complex control logic but rather focus on executing tasks as directed
by Rails.
- Service Implementation and Data Migration: Implementing new functionalities in Workhorse
requires careful consideration of data migration strategies and service continuity.
### Data management and operational integrity
- Workhorse's architecture facilitates efficient data management strategies, including garbage
collection and data migration.
Workhorse's role is to support high-performance operations without directly involving complex data
manipulation or control logic, which remains the purview of Rails.
- For operations requiring background processing or long-running tasks, it is suggested to use
separate services or Sidekiq job queues, with Workhorse and Rails coordinating to manage task execution and data integrity.
Workhorse is contained in a subfolder of the Rails monorepo at
[`gitlab-org/gitlab/workhorse`](https://gitlab.com/gitlab-org/gitlab/tree/master/workhorse).
## Learning resources
- Workhorse documentation (this page)
- Video: [GitLab Workhorse Deep Dive: Dependency Proxy](https://www.youtube.com/watch?v=9cRd-k0TRqI)
- [How Dependency Proxy with Workhorse works](https://gitlab.com/gitlab-org/gitlab/-/issues/370235)
- [Workhorse overview for the Dependency Proxy](https://www.youtube.com/watch?v=WmBibT9oQms)
- [Workhorse architecture discussion](https://www.youtube.com/watch?v=QlHdh-yudtw)
## Install Workhorse
To install GitLab Workhorse you need [Go 1.18 or newer](https://go.dev/dl) and
[GNU Make](https://www.gnu.org/software/make/).
To install into `/usr/local/bin` run `make install`.
```plaintext
make install
```
To install into `/foo/bin` set the PREFIX variable.
```plaintext
make install PREFIX=/foo
```
On some operating systems, such as FreeBSD, you may have to use
`gmake` instead of `make`.
*NOTE*: Some features depends on build tags, make sure to check
[Workhorse configuration](configuration.md) to enable them.
### Run time dependencies
Workhorse uses [ExifTool](https://exiftool.org/) for
removing EXIF data (which may contain sensitive information) from uploaded
images. If you installed GitLab:
- Using the Linux package, you're all set.
If you are using CentOS Minimal, you may need to install `perl` package: `yum install perl`.
- From source, make sure `exiftool` is installed:
```shell
# Debian/Ubuntu
sudo apt-get install libimage-exiftool-perl
# RHEL/CentOS
sudo yum install perl-Image-ExifTool
```
## Testing your code
Run the tests with:
```plaintext
make clean test
```
Each feature in GitLab Workhorse should have an integration test that
verifies that the feature 'kicks in' on the right requests and leaves
other requests unaffected. It is better to also have package-level tests
for specific behavior but the high-level integration tests should have
the first priority during development.
It is OK if a feature is only covered by integration tests.
|
https://docs.gitlab.com/development/configuration
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/configuration.md
|
2025-08-13
|
doc/development/workhorse
|
[
"doc",
"development",
"workhorse"
] |
configuration.md
|
Create
|
Source Code
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Workhorse configuration
| null |
For historical reasons, Workhorse uses:
- Command line flags.
- A configuration file.
- Environment variables.
Add any new Workhorse configuration options into the configuration file.
## CLI options
```plaintext
gitlab-workhorse [OPTIONS]
Options:
-apiCiLongPollingDuration duration
Long polling duration for job requesting for runners (default 50ns)
-apiLimit uint
Number of API requests allowed at single time
-apiQueueDuration duration
Maximum queueing duration of requests (default 30s)
-apiQueueLimit uint
Number of API requests allowed to be queued
-authBackend string
Authentication/authorization backend (default "http://localhost:8080")
-authSocket string
Optional: Unix domain socket to dial authBackend at
-cableBackend string
ActionCable backend
-cableSocket string
Optional: Unix domain socket to dial cableBackend at
-config string
TOML file to load config from
-developmentMode
Allow the assets to be served from Rails app
-documentRoot string
Path to static files content (default "public")
-listenAddr string
Listen address for HTTP server (default "localhost:8181")
-listenNetwork string
Listen 'network' (tcp, tcp4, tcp6, unix) (default "tcp")
-listenUmask int
Umask for Unix socket
-logFile string
Log file location
-logFormat string
Log format to use defaults to text (text, json, structured, none) (default "text")
-pprofListenAddr string
pprof listening address, for example, 'localhost:6060'
-prometheusListenAddr string
Prometheus listening address, for example, 'localhost:9229'
-propagateCorrelationID X-Request-ID
Reuse existing Correlation-ID from the incoming request header X-Request-ID if present
-proxyHeadersTimeout duration
How long to wait for response headers when proxying the request (default 5m0s)
-secretPath string
File with secret key to authenticate with authBackend (default "./.gitlab_workhorse_secret")
-version
Print version and exit
```
The 'auth backend' refers to the GitLab Rails application. The name is
a holdover from when GitLab Workhorse only handled `git push` and `git pull` over
HTTP.
GitLab Workhorse can listen on either a TCP or a Unix domain socket. It
can also open a second listening TCP listening socket with the Go
[`net/http/pprof` profiler server](https://pkg.go.dev/net/http/pprof).
GitLab Workhorse can listen on Redis build and runner registration events if you
pass a valid TOML configuration file through the `-config` flag.
A regular setup it only requires the following (replacing the string
with the actual socket)
## Redis
GitLab Workhorse integrates with Redis to do long polling for CI build
requests. To configure it:
- Configure Redis settings in the TOML configuration file.
- Control polling behavior for CI build requests with the `-apiCiLongPollingDuration`
command-line flag.
You can enable Redis in the configuration file while leaving CI polling
disabled. This configuration results in an idle Redis Pub/Sub connection. The
opposite is not possible: CI long polling requires a correct Redis configuration.
For example, the `[redis]` section in the configuration file could contain:
```plaintext
[redis]
URL = "unix:///var/run/gitlab/redis.sock"
Password = "my_awesome_password"
```
- `URL` - A string in the format `unix://path/to/redis.sock` or `redis://host:port`.
- `Password` - Required only if your Redis instance is password-protected.
- `Sentinel` - Required if you use Sentinel.
If both `Sentinel` and `URL` are given, only `Sentinel` is used.
Optional fields:
```plaintext
[redis]
DB = 0
MaxIdle = 1
MaxActive = 1
```
- `DB` - The database to connect to. Defaults to `0`.
- `MaxIdle` - How many idle connections can be in the Redis pool at once. Defaults to `1`.
- `MaxActive` - How many connections the pool can keep. Defaults to `1`.
## Relative URL support
If you mount GitLab at a relative URL, like `example.com/gitlab`), use this
relative URL in the `authBackend` setting:
```plaintext
gitlab-workhorse -authBackend http://localhost:8080/gitlab
```
## TLS support
A listener with TLS can be configured to be used for incoming requests.
Paths to the files containing a certificate and matching private key for the server must be provided:
```toml
[[listeners]]
network = "tcp"
addr = "localhost:3443"
[listeners.tls]
certificate = "/path/to/certificate"
key = "/path/to/private/key"
min_version = "tls1.2"
max_version = "tls1.3"
```
The `certificate` file should contain the concatenation
of the server's certificate, any intermediates, and the certificate authority's certificate.
Metrics endpoints can be configured similarly:
```toml
[metrics_listener]
network = "tcp"
addr = "localhost:9229"
[metrics_listener.tls]
certificate = "/path/to/certificate"
key = "/path/to/private/key"
min_version = "tls1.2"
max_version = "tls1.3"
```
## Sentinel support
```plaintext
[redis]
Sentinel = [ "redis://sentinel1:23456", "redis://sentinel2:23456" ]
SentinelMaster = "mymaster"
```
## Sentinel TLS support
```plaintext
[redis]
Sentinel = [ "rediss://sentinel1:23456", "rediss://sentinel2:23456" ]
SentinelMaster = "mymaster"
[Sentinel.tls]
certificate = "/path/to/certificate"
key = "/path/to/private/key"
ca_certificate = "/path/to/ca_certificate" # optional
min_version = "tls1.2" # optional
max_version = "tls1.3" # optional
```
## Interaction of `authBackend` and `authSocket`
The interaction between `authBackend` and `authSocket` can be confusing.
If `authSocket` is set, it overrides the host portion of `authBackend`, but not
the relative path.
In table form:
| `authBackend` | `authSocket` | Workhorse connects to | Rails relative URL |
|--------------------------------|-------------------|-----------------------|--------------------|
| unset | unset | `localhost:8080` | `/` |
| `http://localhost:3000` | unset | `localhost:3000` | `/` |
| `http://localhost:3000/gitlab` | unset | `localhost:3000` | `/gitlab` |
| unset | `/path/to/socket` | `/path/to/socket` | `/` |
| `http://localhost:3000` | `/path/to/socket` | `/path/to/socket` | `/` |
| `http://localhost:3000/gitlab` | `/path/to/socket` | `/path/to/socket` | `/gitlab` |
The same applies to `cableBackend` and `cableSocket`.
## Metadata options
Include the following options in the `[metadata]` section:
| Setting | Type | Default value | Description |
| ------------------------ | ----- | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| `zip_reader_limit_bytes` | bytes | 104857600 (100 MB) | The optional number of bytes to limit the zip reader to. [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/439016) in GitLab 16.9. |
For example:
```toml
[metadata]
zip_reader_limit_bytes = 209715200 # 200 MB
```
## Error tracking
GitLab-Workhorse supports remote error tracking with [Sentry](https://sentry.io).
To enable this feature, set the `GITLAB_WORKHORSE_SENTRY_DSN` environment variable.
You can also set the `GITLAB_WORKHORSE_SENTRY_ENVIRONMENT` environment variable to
use the Sentry environment feature to separate staging, production and
development.
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
```ruby
gitlab_workhorse['env'] = {
'GITLAB_WORKHORSE_SENTRY_DSN' => 'https://foobar'
'GITLAB_WORKHORSE_SENTRY_ENVIRONMENT' => 'production'
}
```
{{< /tab >}}
{{< tab title="Self-compiled (source)" >}}
```plaintext
export GITLAB_WORKHORSE_SENTRY_DSN='https://foobar'
export GITLAB_WORKHORSE_SENTRY_ENVIRONMENT='production'
```
{{< /tab >}}
{{< /tabs >}}
## Distributed tracing
Workhorse supports distributed tracing through [LabKit](https://gitlab.com/gitlab-org/labkit/)
using [OpenTracing APIs](https://opentracing.io).
By default, no tracing implementation is linked into the binary. You can link in
different OpenTracing providers with [build tags](https://pkg.go.dev/go/build#hdr-Build_Constraints)
or build constraints by setting the `BUILD_TAGS` make variable.
For more details of the supported providers, refer to LabKit. For an example of
Jaeger tracing support, include the tags: `BUILD_TAGS="tracer_static tracer_static_jaeger"` like this:
```shell
make BUILD_TAGS="tracer_static tracer_static_jaeger"
```
After you compile Workhorse with an OpenTracing provider, configure the tracing
configuration with the `GITLAB_TRACING` environment variable, like this:
```shell
GITLAB_TRACING=opentracing://jaeger ./gitlab-workhorse
```
### Propagate correlation IDs
When a user makes an HTTP request, such as creating a new project, the
initial request is routed through Workhorse to another service, which
may in turn, make other requests. To help trace the request as it flows
across services, Workhorse generates a random value called a
[correlation ID](../../administration/logs/tracing_correlation_id.md).
Workhorse sends this correlation ID with the `X-Request-Id` HTTP header.
Some GitLab services, such as GitLab Shell, generate their own
correlation IDs. In addition, other services, such as Gitaly, make
internal API calls that pass along a correlation ID from the original
request. In either case, the correlation ID is also passed with the
`X-Request-Id` HTTP header.
By default, Workhorse ignores this header and always generates a new
correlation ID. This makes debugging harder and prevents distributed
tracing from working properly, because the new correlation ID is
completely unrelated to the original one.
Workhorse can be configured to propagate an incoming correlation ID with
the `-propagateCorrelationID` command-line flag. It is highly
recommended that this option be used with an IP allow list to ensure
arbitrary values cannot be generated by untrusted clients.
An IP allow list is specified with the `trusted_cidrs_for_propagation`
option in the Workhorse configuration file. Specify a list of CIDR blocks
that can be trusted. For example:
```toml
trusted_cidrs_for_propagation = ["10.0.0.0/8", "127.0.0.1/32"]
```
{{< alert type="note" >}}
The `-propagateCorrelationID` flag must be used for the `trusted_cidrs_for_propagation` option to work.
{{< /alert >}}
### Trusted proxies
If Workhorse is behind a reverse proxy such as NGINX, the
`trusted_cidrs_for_x_forwarded_for` option is needed to specify which
CIDR blocks can be used to trust to provide the originating IP address
with the `X-Forwarded-For` HTTP header. For example:
```toml
trusted_cidrs_for_x_forwarded_for = ["10.0.0.0/8", "127.0.0.1/32"]
```
## Continuous profiling
Workhorse supports continuous profiling through [LabKit](https://gitlab.com/gitlab-org/labkit/)
using [Stackdriver Profiler](https://cloud.google.com/products/operations). By default, the
Stackdriver Profiler implementation is linked in the binary using
[build tags](https://pkg.go.dev/go/build#hdr-Build_Constraints), though it's not
required and can be skipped. For example:
```shell
make BUILD_TAGS=""
```
After you compile Workhorse with continuous profiling, set the profiler configuration
with the `GITLAB_CONTINUOUS_PROFILING` environment variable. For example:
```shell
GITLAB_CONTINUOUS_PROFILING="stackdriver?service=workhorse&service_version=1.0.1&project_id=test-123 ./gitlab-workhorse"
```
## Related topics
- [LabKit monitoring documentation](https://gitlab.com/gitlab-org/labkit/-/blob/master/monitoring/doc.go)
|
---
stage: Create
group: Source Code
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: Workhorse configuration
breadcrumbs:
- doc
- development
- workhorse
---
For historical reasons, Workhorse uses:
- Command line flags.
- A configuration file.
- Environment variables.
Add any new Workhorse configuration options into the configuration file.
## CLI options
```plaintext
gitlab-workhorse [OPTIONS]
Options:
-apiCiLongPollingDuration duration
Long polling duration for job requesting for runners (default 50ns)
-apiLimit uint
Number of API requests allowed at single time
-apiQueueDuration duration
Maximum queueing duration of requests (default 30s)
-apiQueueLimit uint
Number of API requests allowed to be queued
-authBackend string
Authentication/authorization backend (default "http://localhost:8080")
-authSocket string
Optional: Unix domain socket to dial authBackend at
-cableBackend string
ActionCable backend
-cableSocket string
Optional: Unix domain socket to dial cableBackend at
-config string
TOML file to load config from
-developmentMode
Allow the assets to be served from Rails app
-documentRoot string
Path to static files content (default "public")
-listenAddr string
Listen address for HTTP server (default "localhost:8181")
-listenNetwork string
Listen 'network' (tcp, tcp4, tcp6, unix) (default "tcp")
-listenUmask int
Umask for Unix socket
-logFile string
Log file location
-logFormat string
Log format to use defaults to text (text, json, structured, none) (default "text")
-pprofListenAddr string
pprof listening address, for example, 'localhost:6060'
-prometheusListenAddr string
Prometheus listening address, for example, 'localhost:9229'
-propagateCorrelationID X-Request-ID
Reuse existing Correlation-ID from the incoming request header X-Request-ID if present
-proxyHeadersTimeout duration
How long to wait for response headers when proxying the request (default 5m0s)
-secretPath string
File with secret key to authenticate with authBackend (default "./.gitlab_workhorse_secret")
-version
Print version and exit
```
The 'auth backend' refers to the GitLab Rails application. The name is
a holdover from when GitLab Workhorse only handled `git push` and `git pull` over
HTTP.
GitLab Workhorse can listen on either a TCP or a Unix domain socket. It
can also open a second listening TCP listening socket with the Go
[`net/http/pprof` profiler server](https://pkg.go.dev/net/http/pprof).
GitLab Workhorse can listen on Redis build and runner registration events if you
pass a valid TOML configuration file through the `-config` flag.
A regular setup it only requires the following (replacing the string
with the actual socket)
## Redis
GitLab Workhorse integrates with Redis to do long polling for CI build
requests. To configure it:
- Configure Redis settings in the TOML configuration file.
- Control polling behavior for CI build requests with the `-apiCiLongPollingDuration`
command-line flag.
You can enable Redis in the configuration file while leaving CI polling
disabled. This configuration results in an idle Redis Pub/Sub connection. The
opposite is not possible: CI long polling requires a correct Redis configuration.
For example, the `[redis]` section in the configuration file could contain:
```plaintext
[redis]
URL = "unix:///var/run/gitlab/redis.sock"
Password = "my_awesome_password"
```
- `URL` - A string in the format `unix://path/to/redis.sock` or `redis://host:port`.
- `Password` - Required only if your Redis instance is password-protected.
- `Sentinel` - Required if you use Sentinel.
If both `Sentinel` and `URL` are given, only `Sentinel` is used.
Optional fields:
```plaintext
[redis]
DB = 0
MaxIdle = 1
MaxActive = 1
```
- `DB` - The database to connect to. Defaults to `0`.
- `MaxIdle` - How many idle connections can be in the Redis pool at once. Defaults to `1`.
- `MaxActive` - How many connections the pool can keep. Defaults to `1`.
## Relative URL support
If you mount GitLab at a relative URL, like `example.com/gitlab`), use this
relative URL in the `authBackend` setting:
```plaintext
gitlab-workhorse -authBackend http://localhost:8080/gitlab
```
## TLS support
A listener with TLS can be configured to be used for incoming requests.
Paths to the files containing a certificate and matching private key for the server must be provided:
```toml
[[listeners]]
network = "tcp"
addr = "localhost:3443"
[listeners.tls]
certificate = "/path/to/certificate"
key = "/path/to/private/key"
min_version = "tls1.2"
max_version = "tls1.3"
```
The `certificate` file should contain the concatenation
of the server's certificate, any intermediates, and the certificate authority's certificate.
Metrics endpoints can be configured similarly:
```toml
[metrics_listener]
network = "tcp"
addr = "localhost:9229"
[metrics_listener.tls]
certificate = "/path/to/certificate"
key = "/path/to/private/key"
min_version = "tls1.2"
max_version = "tls1.3"
```
## Sentinel support
```plaintext
[redis]
Sentinel = [ "redis://sentinel1:23456", "redis://sentinel2:23456" ]
SentinelMaster = "mymaster"
```
## Sentinel TLS support
```plaintext
[redis]
Sentinel = [ "rediss://sentinel1:23456", "rediss://sentinel2:23456" ]
SentinelMaster = "mymaster"
[Sentinel.tls]
certificate = "/path/to/certificate"
key = "/path/to/private/key"
ca_certificate = "/path/to/ca_certificate" # optional
min_version = "tls1.2" # optional
max_version = "tls1.3" # optional
```
## Interaction of `authBackend` and `authSocket`
The interaction between `authBackend` and `authSocket` can be confusing.
If `authSocket` is set, it overrides the host portion of `authBackend`, but not
the relative path.
In table form:
| `authBackend` | `authSocket` | Workhorse connects to | Rails relative URL |
|--------------------------------|-------------------|-----------------------|--------------------|
| unset | unset | `localhost:8080` | `/` |
| `http://localhost:3000` | unset | `localhost:3000` | `/` |
| `http://localhost:3000/gitlab` | unset | `localhost:3000` | `/gitlab` |
| unset | `/path/to/socket` | `/path/to/socket` | `/` |
| `http://localhost:3000` | `/path/to/socket` | `/path/to/socket` | `/` |
| `http://localhost:3000/gitlab` | `/path/to/socket` | `/path/to/socket` | `/gitlab` |
The same applies to `cableBackend` and `cableSocket`.
## Metadata options
Include the following options in the `[metadata]` section:
| Setting | Type | Default value | Description |
| ------------------------ | ----- | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| `zip_reader_limit_bytes` | bytes | 104857600 (100 MB) | The optional number of bytes to limit the zip reader to. [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/439016) in GitLab 16.9. |
For example:
```toml
[metadata]
zip_reader_limit_bytes = 209715200 # 200 MB
```
## Error tracking
GitLab-Workhorse supports remote error tracking with [Sentry](https://sentry.io).
To enable this feature, set the `GITLAB_WORKHORSE_SENTRY_DSN` environment variable.
You can also set the `GITLAB_WORKHORSE_SENTRY_ENVIRONMENT` environment variable to
use the Sentry environment feature to separate staging, production and
development.
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
```ruby
gitlab_workhorse['env'] = {
'GITLAB_WORKHORSE_SENTRY_DSN' => 'https://foobar'
'GITLAB_WORKHORSE_SENTRY_ENVIRONMENT' => 'production'
}
```
{{< /tab >}}
{{< tab title="Self-compiled (source)" >}}
```plaintext
export GITLAB_WORKHORSE_SENTRY_DSN='https://foobar'
export GITLAB_WORKHORSE_SENTRY_ENVIRONMENT='production'
```
{{< /tab >}}
{{< /tabs >}}
## Distributed tracing
Workhorse supports distributed tracing through [LabKit](https://gitlab.com/gitlab-org/labkit/)
using [OpenTracing APIs](https://opentracing.io).
By default, no tracing implementation is linked into the binary. You can link in
different OpenTracing providers with [build tags](https://pkg.go.dev/go/build#hdr-Build_Constraints)
or build constraints by setting the `BUILD_TAGS` make variable.
For more details of the supported providers, refer to LabKit. For an example of
Jaeger tracing support, include the tags: `BUILD_TAGS="tracer_static tracer_static_jaeger"` like this:
```shell
make BUILD_TAGS="tracer_static tracer_static_jaeger"
```
After you compile Workhorse with an OpenTracing provider, configure the tracing
configuration with the `GITLAB_TRACING` environment variable, like this:
```shell
GITLAB_TRACING=opentracing://jaeger ./gitlab-workhorse
```
### Propagate correlation IDs
When a user makes an HTTP request, such as creating a new project, the
initial request is routed through Workhorse to another service, which
may in turn, make other requests. To help trace the request as it flows
across services, Workhorse generates a random value called a
[correlation ID](../../administration/logs/tracing_correlation_id.md).
Workhorse sends this correlation ID with the `X-Request-Id` HTTP header.
Some GitLab services, such as GitLab Shell, generate their own
correlation IDs. In addition, other services, such as Gitaly, make
internal API calls that pass along a correlation ID from the original
request. In either case, the correlation ID is also passed with the
`X-Request-Id` HTTP header.
By default, Workhorse ignores this header and always generates a new
correlation ID. This makes debugging harder and prevents distributed
tracing from working properly, because the new correlation ID is
completely unrelated to the original one.
Workhorse can be configured to propagate an incoming correlation ID with
the `-propagateCorrelationID` command-line flag. It is highly
recommended that this option be used with an IP allow list to ensure
arbitrary values cannot be generated by untrusted clients.
An IP allow list is specified with the `trusted_cidrs_for_propagation`
option in the Workhorse configuration file. Specify a list of CIDR blocks
that can be trusted. For example:
```toml
trusted_cidrs_for_propagation = ["10.0.0.0/8", "127.0.0.1/32"]
```
{{< alert type="note" >}}
The `-propagateCorrelationID` flag must be used for the `trusted_cidrs_for_propagation` option to work.
{{< /alert >}}
### Trusted proxies
If Workhorse is behind a reverse proxy such as NGINX, the
`trusted_cidrs_for_x_forwarded_for` option is needed to specify which
CIDR blocks can be used to trust to provide the originating IP address
with the `X-Forwarded-For` HTTP header. For example:
```toml
trusted_cidrs_for_x_forwarded_for = ["10.0.0.0/8", "127.0.0.1/32"]
```
## Continuous profiling
Workhorse supports continuous profiling through [LabKit](https://gitlab.com/gitlab-org/labkit/)
using [Stackdriver Profiler](https://cloud.google.com/products/operations). By default, the
Stackdriver Profiler implementation is linked in the binary using
[build tags](https://pkg.go.dev/go/build#hdr-Build_Constraints), though it's not
required and can be skipped. For example:
```shell
make BUILD_TAGS=""
```
After you compile Workhorse with continuous profiling, set the profiler configuration
with the `GITLAB_CONTINUOUS_PROFILING` environment variable. For example:
```shell
GITLAB_CONTINUOUS_PROFILING="stackdriver?service=workhorse&service_version=1.0.1&project_id=test-123 ./gitlab-workhorse"
```
## Related topics
- [LabKit monitoring documentation](https://gitlab.com/gitlab-org/labkit/-/blob/master/monitoring/doc.go)
|
https://docs.gitlab.com/development/handlers
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/handlers.md
|
2025-08-13
|
doc/development/workhorse
|
[
"doc",
"development",
"workhorse"
] |
handlers.md
|
Create
|
Source Code
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://about.gitlab.com/handbook/engineering/ux/technical-writing/#assignments
|
Workhorse handlers
| null |
Long HTTP requests are hard to handle efficiently in Rails.
The requests are either memory-inefficient (file uploads) or impossible at all due to shorter timeouts
(for example, Puma server has 60-second timeout).
Workhorse can efficiently handle a large number of long HTTP requests.
Workhorse acts as a proxy that intercepts all HTTP requests and either propagates them without
changing or handles them itself by performing additional logic.
## Injectors
```mermaid
%%{init: { "fontFamily": "GitLab Sans" }}%%
sequenceDiagram
participant Client
participant Workhorse
participant Rails
Client->>+Workhorse: Request
Workhorse->>+Rails: Propagate the request as-is
Rails-->>-Workhorse: Respond with a special header that contains instructions for proceeding with the request
Workhorse-->>Client: Response
```
### Example: Send a Git blob
```mermaid
%%{init: { "fontFamily": "GitLab Sans" }}%%
sequenceDiagram
participant Client
participant Workhorse
participant Rails
participant Gitaly
Client->>+Workhorse: HTTP Request for a blob
Workhorse->>+Rails: Propagate the request as-is
Rails-->>-Workhorse: Respond with a git-blob:{encoded_data} header
Workhorse->>+Gitaly: BlobService.GetBlob gRPC request
Gitaly-->>-Workhorse: BlobService.GetBlob gRPC request
Workhorse-->>Client: Stream the data
```
### How GitLab Rails processes the request
- [`send_git_blob`](https://gitlab.com/gitlab-org/gitlab/blob/8ba71b1f2feec64aeec52ccac4a1e585ba8052d9/lib/api/files.rb#L161)
- [Send a header with a particular information](https://gitlab.com/gitlab-org/gitlab/blob/8ba71b1f2feec64aeec52ccac4a1e585ba8052d9/lib/gitlab/workhorse.rb#L49-63)
### How Workhorse processes the header
- [Specify a list of injectors](https://gitlab.com/gitlab-org/gitlab/blob/8ba71b1f2feec64aeec52ccac4a1e585ba8052d9/workhorse/internal/upstream/routes.go#L179)
- [Iterate over injectors to find a match](https://gitlab.com/gitlab-org/gitlab/blob/8ba71b1f2feec64aeec52ccac4a1e585ba8052d9/workhorse/internal/senddata/senddata.go#L88)
- [Process a particular request](https://gitlab.com/gitlab-org/gitlab/blob/8ba71b1f2feec64aeec52ccac4a1e585ba8052d9/workhorse/internal/git/blob.go#L23)
#### Example: Send a file
```mermaid
%%{init: { "fontFamily": "GitLab Sans" }}%%
sequenceDiagram
participant Client
participant Workhorse
participant Rails
participant Object Storage
Client->>+Workhorse: HTTP Request for a file
Workhorse->>+Rails: Propagate the request as-is
Rails-->>-Workhorse: Respond with a send-url:{encoded_data} header
Workhorse->>+Object Storage: Request for a file
Object Storage-->>-Workhorse: Stream the data
Workhorse-->>Client: Stream the data
```
## Pre-authorized requests
```mermaid
%%{init: { "fontFamily": "GitLab Sans" }}%%
sequenceDiagram
participant Client
participant Workhorse
participant Rails
participant Object Storage
Client->>+Workhorse: PUT /artifacts/uploads
Note right of Rails: Append `/authorize` to the original URL and call Rails for an Auth check
Workhorse->>+Rails: GET /artifacts/uploads/authorize
Rails-->>-Workhorse: Authorized successfully
Client->>+Workhorse: Stream the file content
Workhorse->>+Object Storage: Upload the file
Object Storage-->>-Workhorse: Success
Workhorse->>+Rails: Finalize the request
Note right of Rails: Workhorse calls the original URL to create a database record
Rails-->>-Workhorse: Finalized successfully
Workhorse-->>Client: Uploaded successfully
```
## Git over HTTP(S)
Workhorse accelerates Git over HTTP(S) by handling [Git HTTP protocol](https://www.git-scm.com/docs/http-protocol) requests. For example, Git push/pull may require serving large amounts of data. To avoid transferring it through GitLab Rails, Workhorse only performs authorization checks against GitLab Rails, then performs a Gitaly gRPC request directly, and streams the data from Gitaly to the Git client.
### Git pull
```mermaid
%%{init: { "fontFamily": "GitLab Sans" }}%%
sequenceDiagram
participant Git on client
participant Workhorse
participant Rails
participant Gitaly
Note left of Git on client: git clone/fetch
Git on client->>+Workhorse: GET /foo/bar.git/info/refs?service=git-upload-pack
Workhorse->>+Rails: GET Repositories::GitHttpController#info_refs
Note right of Rails: Access check/Log activity
Rails-->>Workhorse: 200 OK, Gitlab::Workhorse.git_http_ok
Workhorse->>+Gitaly: SmartHTTPService.InfoRefsUploadPack gRPC request
Gitaly -->>-Workhorse: SmartHTTPService.InfoRefsUploadPack gRPC response
Workhorse-->>-Git on client: send info-refs response
Git on client->>+Workhorse: GET /foo/bar.git/info/refs?service=git-upload-pack
Workhorse->>+Rails: GET Repositories::GitHttpController#git_receive_pack
Note right of Rails: Access check/Update statistics
Rails-->>Workhorse: 200 OK, Gitlab::Workhorse.git_http_ok
Workhorse->>+Gitaly: SmartHTTPService.PostUploadPackWithSidechannel gRPC request
Gitaly -->>-Workhorse: SmartHTTPService.PostUploadPackWithSidechannel gRPC response
Workhorse-->>-Git on client: send response
```
### Git push
```mermaid
%%{init: { "fontFamily": "GitLab Sans" }}%%
sequenceDiagram
participant Git on client
participant Workhorse
participant Rails
participant Gitaly
Note left of Git on client: git push
Git on client->>+Workhorse: GET /foo/bar.git/info/refs?service=git-receive-pack
Workhorse->>+Rails: GET Repositories::GitHttpController#info_refs
Note right of Rails: Access check/Log activity
Rails-->>Workhorse: 200 OK, Gitlab::Workhorse.git_http_ok
Workhorse->>+Gitaly: SmartHTTPService.InfoRefsReceivePack gRPC request
Gitaly -->>-Workhorse: SmartHTTPService.InfoRefsReceivePack gRPC response
Workhorse-->>-Git on client: send info-refs response
Git on client->>+Workhorse: GET /foo/bar.git/info/refs?service=git-receive-pack
Workhorse->>+Rails: GET Repositories::GitHttpController#git_receive_pack
Note right of Rails: Access check/Update statistics
Rails-->>Workhorse: 200 OK, Gitlab::Workhorse.git_http_ok
Workhorse->>+Gitaly: SmartHTTPService.PostReceivePackWithSidechannel gRPC request
Gitaly -->>-Workhorse: SmartHTTPService.PostReceivePackWithSidechannel gRPC response
Workhorse-->>-Git on client: send response
```
|
---
stage: Create
group: Source Code
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://about.gitlab.com/handbook/engineering/ux/technical-writing/#assignments
title: Workhorse handlers
breadcrumbs:
- doc
- development
- workhorse
---
Long HTTP requests are hard to handle efficiently in Rails.
The requests are either memory-inefficient (file uploads) or impossible at all due to shorter timeouts
(for example, Puma server has 60-second timeout).
Workhorse can efficiently handle a large number of long HTTP requests.
Workhorse acts as a proxy that intercepts all HTTP requests and either propagates them without
changing or handles them itself by performing additional logic.
## Injectors
```mermaid
%%{init: { "fontFamily": "GitLab Sans" }}%%
sequenceDiagram
participant Client
participant Workhorse
participant Rails
Client->>+Workhorse: Request
Workhorse->>+Rails: Propagate the request as-is
Rails-->>-Workhorse: Respond with a special header that contains instructions for proceeding with the request
Workhorse-->>Client: Response
```
### Example: Send a Git blob
```mermaid
%%{init: { "fontFamily": "GitLab Sans" }}%%
sequenceDiagram
participant Client
participant Workhorse
participant Rails
participant Gitaly
Client->>+Workhorse: HTTP Request for a blob
Workhorse->>+Rails: Propagate the request as-is
Rails-->>-Workhorse: Respond with a git-blob:{encoded_data} header
Workhorse->>+Gitaly: BlobService.GetBlob gRPC request
Gitaly-->>-Workhorse: BlobService.GetBlob gRPC request
Workhorse-->>Client: Stream the data
```
### How GitLab Rails processes the request
- [`send_git_blob`](https://gitlab.com/gitlab-org/gitlab/blob/8ba71b1f2feec64aeec52ccac4a1e585ba8052d9/lib/api/files.rb#L161)
- [Send a header with a particular information](https://gitlab.com/gitlab-org/gitlab/blob/8ba71b1f2feec64aeec52ccac4a1e585ba8052d9/lib/gitlab/workhorse.rb#L49-63)
### How Workhorse processes the header
- [Specify a list of injectors](https://gitlab.com/gitlab-org/gitlab/blob/8ba71b1f2feec64aeec52ccac4a1e585ba8052d9/workhorse/internal/upstream/routes.go#L179)
- [Iterate over injectors to find a match](https://gitlab.com/gitlab-org/gitlab/blob/8ba71b1f2feec64aeec52ccac4a1e585ba8052d9/workhorse/internal/senddata/senddata.go#L88)
- [Process a particular request](https://gitlab.com/gitlab-org/gitlab/blob/8ba71b1f2feec64aeec52ccac4a1e585ba8052d9/workhorse/internal/git/blob.go#L23)
#### Example: Send a file
```mermaid
%%{init: { "fontFamily": "GitLab Sans" }}%%
sequenceDiagram
participant Client
participant Workhorse
participant Rails
participant Object Storage
Client->>+Workhorse: HTTP Request for a file
Workhorse->>+Rails: Propagate the request as-is
Rails-->>-Workhorse: Respond with a send-url:{encoded_data} header
Workhorse->>+Object Storage: Request for a file
Object Storage-->>-Workhorse: Stream the data
Workhorse-->>Client: Stream the data
```
## Pre-authorized requests
```mermaid
%%{init: { "fontFamily": "GitLab Sans" }}%%
sequenceDiagram
participant Client
participant Workhorse
participant Rails
participant Object Storage
Client->>+Workhorse: PUT /artifacts/uploads
Note right of Rails: Append `/authorize` to the original URL and call Rails for an Auth check
Workhorse->>+Rails: GET /artifacts/uploads/authorize
Rails-->>-Workhorse: Authorized successfully
Client->>+Workhorse: Stream the file content
Workhorse->>+Object Storage: Upload the file
Object Storage-->>-Workhorse: Success
Workhorse->>+Rails: Finalize the request
Note right of Rails: Workhorse calls the original URL to create a database record
Rails-->>-Workhorse: Finalized successfully
Workhorse-->>Client: Uploaded successfully
```
## Git over HTTP(S)
Workhorse accelerates Git over HTTP(S) by handling [Git HTTP protocol](https://www.git-scm.com/docs/http-protocol) requests. For example, Git push/pull may require serving large amounts of data. To avoid transferring it through GitLab Rails, Workhorse only performs authorization checks against GitLab Rails, then performs a Gitaly gRPC request directly, and streams the data from Gitaly to the Git client.
### Git pull
```mermaid
%%{init: { "fontFamily": "GitLab Sans" }}%%
sequenceDiagram
participant Git on client
participant Workhorse
participant Rails
participant Gitaly
Note left of Git on client: git clone/fetch
Git on client->>+Workhorse: GET /foo/bar.git/info/refs?service=git-upload-pack
Workhorse->>+Rails: GET Repositories::GitHttpController#info_refs
Note right of Rails: Access check/Log activity
Rails-->>Workhorse: 200 OK, Gitlab::Workhorse.git_http_ok
Workhorse->>+Gitaly: SmartHTTPService.InfoRefsUploadPack gRPC request
Gitaly -->>-Workhorse: SmartHTTPService.InfoRefsUploadPack gRPC response
Workhorse-->>-Git on client: send info-refs response
Git on client->>+Workhorse: GET /foo/bar.git/info/refs?service=git-upload-pack
Workhorse->>+Rails: GET Repositories::GitHttpController#git_receive_pack
Note right of Rails: Access check/Update statistics
Rails-->>Workhorse: 200 OK, Gitlab::Workhorse.git_http_ok
Workhorse->>+Gitaly: SmartHTTPService.PostUploadPackWithSidechannel gRPC request
Gitaly -->>-Workhorse: SmartHTTPService.PostUploadPackWithSidechannel gRPC response
Workhorse-->>-Git on client: send response
```
### Git push
```mermaid
%%{init: { "fontFamily": "GitLab Sans" }}%%
sequenceDiagram
participant Git on client
participant Workhorse
participant Rails
participant Gitaly
Note left of Git on client: git push
Git on client->>+Workhorse: GET /foo/bar.git/info/refs?service=git-receive-pack
Workhorse->>+Rails: GET Repositories::GitHttpController#info_refs
Note right of Rails: Access check/Log activity
Rails-->>Workhorse: 200 OK, Gitlab::Workhorse.git_http_ok
Workhorse->>+Gitaly: SmartHTTPService.InfoRefsReceivePack gRPC request
Gitaly -->>-Workhorse: SmartHTTPService.InfoRefsReceivePack gRPC response
Workhorse-->>-Git on client: send info-refs response
Git on client->>+Workhorse: GET /foo/bar.git/info/refs?service=git-receive-pack
Workhorse->>+Rails: GET Repositories::GitHttpController#git_receive_pack
Note right of Rails: Access check/Update statistics
Rails-->>Workhorse: 200 OK, Gitlab::Workhorse.git_http_ok
Workhorse->>+Gitaly: SmartHTTPService.PostReceivePackWithSidechannel gRPC request
Gitaly -->>-Workhorse: SmartHTTPService.PostReceivePackWithSidechannel gRPC response
Workhorse-->>-Git on client: send response
```
|
https://docs.gitlab.com/development/gitlab_features
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/gitlab_features.md
|
2025-08-13
|
doc/development/workhorse
|
[
"doc",
"development",
"workhorse"
] |
gitlab_features.md
|
Create
|
Source Code
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Features that rely on Workhorse
| null |
Workhorse itself is not a feature, but there are several features in
GitLab that would not work efficiently without Workhorse.
To put the efficiency benefit in context, consider that in 2020Q3 on
GitLab.com [we see](https://dashboards.gitlab.net/explore?schemaVersion=1&panes=%7B%22m95%22:%7B%22datasource%22:%22e58c2f51-20f8-4f4b-ad48-2968782ca7d6%22,%22queries%22:%5B%7B%22refId%22:%22A%22,%22expr%22:%22sum%28ruby_process_resident_memory_bytes%7Bapp%3D%5C%22webservice%5C%22,env%3D%5C%22gprd%5C%22,release%3D%5C%22gitlab%5C%22%7D%29%20%2F%20sum%28puma_max_threads%7Bapp%3D%5C%22webservice%5C%22,env%3D%5C%22gprd%5C%22,release%3D%5C%22gitlab%5C%22%7D%29%22,%22range%22:true,%22instant%22:true,%22datasource%22:%7B%22type%22:%22prometheus%22,%22uid%22:%22e58c2f51-20f8-4f4b-ad48-2968782ca7d6%22%7D,%22editorMode%22:%22code%22,%22legendFormat%22:%22__auto%22%7D,%7B%22refId%22:%22B%22,%22expr%22:%22sum%28go_memstats_sys_bytes%7Bapp%3D%5C%22webservice%5C%22,env%3D%5C%22gprd%5C%22,release%3D%5C%22gitlab%5C%22%7D%29%2Fsum%28go_goroutines%7Bapp%3D%5C%22webservice%5C%22,env%3D%5C%22gprd%5C%22,release%3D%5C%22gitlab%5C%22%7D%29%22,%22range%22:true,%22instant%22:true,%22datasource%22:%7B%22type%22:%22prometheus%22,%22uid%22:%22e58c2f51-20f8-4f4b-ad48-2968782ca7d6%22%7D,%22editorMode%22:%22code%22,%22legendFormat%22:%22__auto%22%7D%5D,%22range%22:%7B%22from%22:%22now-1h%22,%22to%22:%22now%22%7D%7D%7D&orgId=1)
Rails application threads using on average
about 200 MB of RSS vs about 200 KB for Workhorse goroutines.
Examples of features that rely on Workhorse:
## 1. `git clone` and `git push` over HTTP
Git clone, pull and push are slow because they transfer large amounts
of data and because each is CPU intensive on the GitLab side. Without
Workhorse, HTTP access to Git repositories would compete with regular
web access to the application, requiring us to run way more Rails
application servers.
## 2. CI runner long polling
GitLab CI runners fetch new CI jobs by polling the GitLab server.
Workhorse acts as a kind of "waiting room" where CI runners can sit
and wait for new CI jobs. Because of Go's efficiency we can fit a lot
of runners in the waiting room at little cost. Without this waiting
room mechanism we would have to add a lot more Rails server capacity.
See [the long polling documentation](../../ci/runners/long_polling.md)
for more details.
## 3. File uploads and downloads
File uploads and downloads may be slow either because the file is
large or because the user's connection is slow. Workhorse can handle
the slow part for Rails. This improves the efficiency of features such
as CI artifacts, package repositories, LFS objects, etc.
## 4. Websocket proxying
Features such as the web terminal require a long lived connection
between the user's web browser and a container inside GitLab that is
not directly accessible from the internet. Dedicating a Rails
application thread to proxying such a connection would cost much more
memory than it costs to have Workhorse look after it.
## 5. Web IDE
For security, some parts of the Web IDE must run in a separate origin.
To support this approach, the Web IDE relies on Workhorse to appropriately
route and decorate certain requests to and from Web IDE assets.
Because the Web IDE assets are static frontend assets, it's unnecessary
overhead to rely on Rails for this effort.
## Quick facts (how does Workhorse work)
- Workhorse can handle some requests without involving Rails at all:
for example, JavaScript files and CSS files are served straight
from disk.
- Workhorse can modify responses sent by Rails: for example if you use
`send_file` in Rails then GitLab Workhorse opens the file on
disk and send its contents as the response body to the client.
- Workhorse can take over requests after asking permission from Rails.
Example: handling `git clone`.
- Workhorse can modify requests before passing them to Rails. Example:
when handling a Git LFS upload Workhorse first asks permission from
Rails, then it stores the request body in a temporary file, then it sends
a modified request containing the file path to Rails.
- Workhorse can manage long-lived WebSocket connections for Rails.
Example: handling the terminal websocket for environments.
- Workhorse does not connect to PostgreSQL, only to Rails and (optionally) Redis.
- We assume that all requests that reach Workhorse pass through an
upstream proxy such as NGINX or Apache first.
- Workhorse does not clean up idle client connections.
- We assume that all requests to Rails pass through Workhorse.
For more information see ['A brief history of GitLab Workhorse'](https://about.gitlab.com/blog/2016/04/12/a-brief-history-of-gitlab-workhorse/).
|
---
stage: Create
group: Source Code
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: Features that rely on Workhorse
breadcrumbs:
- doc
- development
- workhorse
---
Workhorse itself is not a feature, but there are several features in
GitLab that would not work efficiently without Workhorse.
To put the efficiency benefit in context, consider that in 2020Q3 on
GitLab.com [we see](https://dashboards.gitlab.net/explore?schemaVersion=1&panes=%7B%22m95%22:%7B%22datasource%22:%22e58c2f51-20f8-4f4b-ad48-2968782ca7d6%22,%22queries%22:%5B%7B%22refId%22:%22A%22,%22expr%22:%22sum%28ruby_process_resident_memory_bytes%7Bapp%3D%5C%22webservice%5C%22,env%3D%5C%22gprd%5C%22,release%3D%5C%22gitlab%5C%22%7D%29%20%2F%20sum%28puma_max_threads%7Bapp%3D%5C%22webservice%5C%22,env%3D%5C%22gprd%5C%22,release%3D%5C%22gitlab%5C%22%7D%29%22,%22range%22:true,%22instant%22:true,%22datasource%22:%7B%22type%22:%22prometheus%22,%22uid%22:%22e58c2f51-20f8-4f4b-ad48-2968782ca7d6%22%7D,%22editorMode%22:%22code%22,%22legendFormat%22:%22__auto%22%7D,%7B%22refId%22:%22B%22,%22expr%22:%22sum%28go_memstats_sys_bytes%7Bapp%3D%5C%22webservice%5C%22,env%3D%5C%22gprd%5C%22,release%3D%5C%22gitlab%5C%22%7D%29%2Fsum%28go_goroutines%7Bapp%3D%5C%22webservice%5C%22,env%3D%5C%22gprd%5C%22,release%3D%5C%22gitlab%5C%22%7D%29%22,%22range%22:true,%22instant%22:true,%22datasource%22:%7B%22type%22:%22prometheus%22,%22uid%22:%22e58c2f51-20f8-4f4b-ad48-2968782ca7d6%22%7D,%22editorMode%22:%22code%22,%22legendFormat%22:%22__auto%22%7D%5D,%22range%22:%7B%22from%22:%22now-1h%22,%22to%22:%22now%22%7D%7D%7D&orgId=1)
Rails application threads using on average
about 200 MB of RSS vs about 200 KB for Workhorse goroutines.
Examples of features that rely on Workhorse:
## 1. `git clone` and `git push` over HTTP
Git clone, pull and push are slow because they transfer large amounts
of data and because each is CPU intensive on the GitLab side. Without
Workhorse, HTTP access to Git repositories would compete with regular
web access to the application, requiring us to run way more Rails
application servers.
## 2. CI runner long polling
GitLab CI runners fetch new CI jobs by polling the GitLab server.
Workhorse acts as a kind of "waiting room" where CI runners can sit
and wait for new CI jobs. Because of Go's efficiency we can fit a lot
of runners in the waiting room at little cost. Without this waiting
room mechanism we would have to add a lot more Rails server capacity.
See [the long polling documentation](../../ci/runners/long_polling.md)
for more details.
## 3. File uploads and downloads
File uploads and downloads may be slow either because the file is
large or because the user's connection is slow. Workhorse can handle
the slow part for Rails. This improves the efficiency of features such
as CI artifacts, package repositories, LFS objects, etc.
## 4. Websocket proxying
Features such as the web terminal require a long lived connection
between the user's web browser and a container inside GitLab that is
not directly accessible from the internet. Dedicating a Rails
application thread to proxying such a connection would cost much more
memory than it costs to have Workhorse look after it.
## 5. Web IDE
For security, some parts of the Web IDE must run in a separate origin.
To support this approach, the Web IDE relies on Workhorse to appropriately
route and decorate certain requests to and from Web IDE assets.
Because the Web IDE assets are static frontend assets, it's unnecessary
overhead to rely on Rails for this effort.
## Quick facts (how does Workhorse work)
- Workhorse can handle some requests without involving Rails at all:
for example, JavaScript files and CSS files are served straight
from disk.
- Workhorse can modify responses sent by Rails: for example if you use
`send_file` in Rails then GitLab Workhorse opens the file on
disk and send its contents as the response body to the client.
- Workhorse can take over requests after asking permission from Rails.
Example: handling `git clone`.
- Workhorse can modify requests before passing them to Rails. Example:
when handling a Git LFS upload Workhorse first asks permission from
Rails, then it stores the request body in a temporary file, then it sends
a modified request containing the file path to Rails.
- Workhorse can manage long-lived WebSocket connections for Rails.
Example: handling the terminal websocket for environments.
- Workhorse does not connect to PostgreSQL, only to Rails and (optionally) Redis.
- We assume that all requests that reach Workhorse pass through an
upstream proxy such as NGINX or Apache first.
- Workhorse does not clean up idle client connections.
- We assume that all requests to Rails pass through Workhorse.
For more information see ['A brief history of GitLab Workhorse'](https://about.gitlab.com/blog/2016/04/12/a-brief-history-of-gitlab-workhorse/).
|
https://docs.gitlab.com/development/new_features
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/new_features.md
|
2025-08-13
|
doc/development/workhorse
|
[
"doc",
"development",
"workhorse"
] |
new_features.md
|
Create
|
Source Code
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Adding new features to Workhorse
| null |
GitLab Workhorse is a smart reverse proxy for GitLab. It handles
[long HTTP requests](#what-are-long-requests), such as:
- File downloads.
- File uploads.
- Git pushes and pulls.
- Git archive downloads.
Workhorse itself is not a feature, but [several features in GitLab](gitlab_features.md)
would not work efficiently without Workhorse.
At a first glance, Workhorse appears to be just a pipeline for processing HTTP
streams to reduce the amount of logic in your Ruby on Rails controller. However,
don't treat it that way. Engineers trying to offload a feature to Workhorse often
find it takes more work than originally anticipated:
- It's a new programming language, and only a few engineers at GitLab are Go developers.
- Workhorse has demanding requirements:
- It's stateless.
- Memory and disk usage must be kept under tight control.
- The request should not be slowed down in the process.
## Avoid adding new features
We suggest adding new features only if absolutely necessary and no other options exist.
Splitting a feature between the Rails codebase and Workhorse is a deliberate choice
to introduce technical debt. It adds complexity to the system, and coupling between
the two components:
- Building features using Workhorse has a considerable complexity cost, so you should
prefer designs based on Rails requests and Sidekiq jobs.
- Even when using Rails-and-Sidekiq is more work than using Rails-and-Workhorse,
Rails-and-Sidekiq is easier to maintain in the long term. Workhorse is unique
to GitLab, while Rails-and-Sidekiq is an industry standard.
- For global behaviors around web requests, consider using a Rack middleware
instead of Workhorse.
- Generally speaking, use Rails-and-Workhorse only if the HTTP client expects
behavior reasonable to implement in Rails, like long requests.
## What are long requests?
One order of magnitude exists between Workhorse and Puma RAM usage. Having a connection
open for longer than milliseconds is problematic due to the amount of RAM
it monopolizes after it reaches the Ruby on Rails controller. We've identified two classes
of long requests: data transfers and HTTP long polling. Some examples:
- `git push`.
- `git pull`.
- Uploading or downloading an artifact.
- A CI runner waiting for a new job.
With the rise of cloud-native installations, Workhorse's feature set was extended
to add object storage direct-upload. This change removed the need for the shared
Network File System (NFS) drives.
If you still think we should add a new feature to Workhorse, open an issue for the
Workhorse maintainers and explain:
1. What you want to implement.
1. Why it can't be implemented in our Ruby codebase.
The Workhorse maintainers can help you assess the situation.
## Related topics
- In 2020, `@nolith` presented the talk
["Speed up the monolith. Building a smart reverse proxy in Go"](https://archive.fosdem.org/2020/schedule/event/speedupmonolith/)
at FOSDEM. The talk includes more details on the history of Workhorse and the NFS removal.
- The [uploads development documentation](../uploads/_index.md) contains the most common
use cases for adding a new type of upload.
|
---
stage: Create
group: Source Code
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: Adding new features to Workhorse
breadcrumbs:
- doc
- development
- workhorse
---
GitLab Workhorse is a smart reverse proxy for GitLab. It handles
[long HTTP requests](#what-are-long-requests), such as:
- File downloads.
- File uploads.
- Git pushes and pulls.
- Git archive downloads.
Workhorse itself is not a feature, but [several features in GitLab](gitlab_features.md)
would not work efficiently without Workhorse.
At a first glance, Workhorse appears to be just a pipeline for processing HTTP
streams to reduce the amount of logic in your Ruby on Rails controller. However,
don't treat it that way. Engineers trying to offload a feature to Workhorse often
find it takes more work than originally anticipated:
- It's a new programming language, and only a few engineers at GitLab are Go developers.
- Workhorse has demanding requirements:
- It's stateless.
- Memory and disk usage must be kept under tight control.
- The request should not be slowed down in the process.
## Avoid adding new features
We suggest adding new features only if absolutely necessary and no other options exist.
Splitting a feature between the Rails codebase and Workhorse is a deliberate choice
to introduce technical debt. It adds complexity to the system, and coupling between
the two components:
- Building features using Workhorse has a considerable complexity cost, so you should
prefer designs based on Rails requests and Sidekiq jobs.
- Even when using Rails-and-Sidekiq is more work than using Rails-and-Workhorse,
Rails-and-Sidekiq is easier to maintain in the long term. Workhorse is unique
to GitLab, while Rails-and-Sidekiq is an industry standard.
- For global behaviors around web requests, consider using a Rack middleware
instead of Workhorse.
- Generally speaking, use Rails-and-Workhorse only if the HTTP client expects
behavior reasonable to implement in Rails, like long requests.
## What are long requests?
One order of magnitude exists between Workhorse and Puma RAM usage. Having a connection
open for longer than milliseconds is problematic due to the amount of RAM
it monopolizes after it reaches the Ruby on Rails controller. We've identified two classes
of long requests: data transfers and HTTP long polling. Some examples:
- `git push`.
- `git pull`.
- Uploading or downloading an artifact.
- A CI runner waiting for a new job.
With the rise of cloud-native installations, Workhorse's feature set was extended
to add object storage direct-upload. This change removed the need for the shared
Network File System (NFS) drives.
If you still think we should add a new feature to Workhorse, open an issue for the
Workhorse maintainers and explain:
1. What you want to implement.
1. Why it can't be implemented in our Ruby codebase.
The Workhorse maintainers can help you assess the situation.
## Related topics
- In 2020, `@nolith` presented the talk
["Speed up the monolith. Building a smart reverse proxy in Go"](https://archive.fosdem.org/2020/schedule/event/speedupmonolith/)
at FOSDEM. The talk includes more details on the history of Workhorse and the NFS removal.
- The [uploads development documentation](../uploads/_index.md) contains the most common
use cases for adding a new type of upload.
|
https://docs.gitlab.com/development/channel
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/channel.md
|
2025-08-13
|
doc/development/workhorse
|
[
"doc",
"development",
"workhorse"
] |
channel.md
|
Create
|
Source Code
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Websocket channel support for Workhorse
| null |
In some cases, GitLab can provide the following through a WebSocket:
- In-browser terminal access to an environment: a running server or container,
onto which a project has been deployed.
- Access to services running in CI.
Workhorse manages the WebSocket upgrade and long-lived connection to the websocket
connection, which frees up GitLab to process other requests. This document outlines
the architecture of these connections.
## Introduction to WebSockets
Websockets are an "upgraded" `HTTP/1.1` request. They permit bidirectional
communication between a client and a server. Websockets are not HTTP.
Clients can send messages (known as frames) to the server at any time, and
vice versa. Client messages are not necessarily requests, and server messages are
not necessarily responses. WebSocket URLs have schemes like `ws://` (unencrypted) or
`wss://` (TLS-secured).
When requesting an upgrade to WebSocket, the browser sends a `HTTP/1.1`
request like this:
```plaintext
GET /path.ws HTTP/1.1
Connection: upgrade
Upgrade: websocket
Sec-WebSocket-Protocol: terminal.gitlab.com
# More headers, including security measures
```
At this point, the connection is still HTTP, so this is a request.
The server can send a standard HTTP response, such as `404 Not Found` or
`500 Internal Server Error`.
If the server decides to permit the upgrade, it sends an HTTP
`101 Switching Protocols` response. From this point, the connection is no longer
HTTP. It is now a WebSocket and frames, not HTTP requests, flow over it. The connection
persists until the client or server closes the connection.
In addition to the sub-protocol, individual websocket frames may
also specify a message type, such as:
- `BinaryMessage`
- `TextMessage`
- `Ping`
- `Pong`
- `Close`
Only binary frames can contain arbitrary data. The frames are expected to be valid
UTF-8 strings, in addition to any sub-protocol expectations.
## Browser to Workhorse
Using the terminal as an example:
1. GitLab serves a JavaScript terminal emulator to the browser on a URL like
`https://gitlab.com/group/project/-/environments/1/terminal`.
1. This URL opens a websocket connection to
`wss://gitlab.com/group/project/-/environments/1/terminal.ws`.
This endpoint exists only in Workhorse, and doesn't exist in GitLab.
1. When receiving the connection, Workhorse first performs a `preauthentication`
request to GitLab to confirm the client is authorized to access the requested terminal:
- If the client has the appropriate permissions and the terminal exists, GitLab
responds with a successful response that includes details of the terminal
the client should be connected to.
- Otherwise, Workhorse returns an appropriate HTTP error response.
1. If GitLab returns valid terminal details to Workhorse, it:
1. Connects to the specified terminal.
1. Upgrades the browser to a WebSocket.
1. Proxies between the two connections for as long as the browser's credentials are valid.
1. Send regular `PingMessage` control frames to the browser, to prevent intervening
proxies from terminating the connection while the browser is present.
The browser must request an upgrade with a specific sub-protocol:
- [`terminal.gitlab.com`](#terminalgitlabcom)
- [`base64.terminal.gitlab.com`](#base64terminalgitlabcom)
### `terminal.gitlab.com`
This sub-protocol considers `TextMessage` frames to be invalid. Control frames,
such as `PingMessage` or `CloseMessage`, have their usual meanings.
- `BinaryMessage` frames sent from the browser to the server are
arbitrary text input.
- `BinaryMessage` frames sent from the server to the browser are
arbitrary text output.
These frames are expected to contain ANSI text control codes
and may be in any encoding.
### `base64.terminal.gitlab.com`
This sub-protocol considers `BinaryMessage` frames to be invalid.
Control frames, such as `PingMessage` or `CloseMessage`, have
their usual meanings.
- `TextMessage` frames sent from the browser to the server are
base64-encoded arbitrary text input. The server must
base64-decode them before inputting them.
- `TextMessage` frames sent from the server to the browser are
base64-encoded arbitrary text output. The browser must
base64-decode them before outputting them.
In their base64-encoded form, these frames are expected to
contain ANSI terminal control codes, and may be in any encoding.
## Workhorse to GitLab
Using the terminal as an example, before upgrading the browser,
Workhorse sends a standard HTTP request to GitLab on a URL like
`https://gitlab.com/group/project/environments/1/terminal.ws/authorize`.
This returns a JSON response containing details of where the
terminal can be found, and how to connect it. In particular,
the following details are returned in case of success:
- WebSocket URL to connect to, such as `wss://example.com/terminals/1.ws?tty=1`.
- WebSocket sub-protocols to support, such as `["channel.k8s.io"]`.
- Headers to send, such as `Authorization: Token xxyyz`.
- Optional. Certificate authority to verify `wss` connections with.
Workhorse periodically rechecks this endpoint. If it receives an error response,
or the details of the terminal change, it terminates the websocket session.
## Workhorse to the WebSocket server
In GitLab, environments or CI jobs may have a deployment service (like
`KubernetesService`) associated with them. This service knows
where the terminals or the service for an environment may be found, and GitLab
returns these details to Workhorse.
These URLs are also WebSocket URLs. GitLab tells Workhorse which sub-protocols to
speak over the connection, along with any authentication details required by the
remote end.
Before upgrading the browser's connection to a websocket, Workhorse:
1. Opens an HTTP client connection, according to the details given to it by Workhorse.
1. Attempts to upgrade that connection to a websocket.
- If it fails, an error response is sent to the browser.
- If it succeeds, the browser is also upgraded.
Workhorse now has two websocket connections, albeit with differing sub-protocols,
and then:
- Decodes incoming frames from the browser, re-encodes them to the channel's
sub-protocol, and sends them to the channel.
- Decodes incoming frames from the channel, re-encodes them to the browser's
sub-protocol, and sends them to the browser.
When either connection closes or enters an error state, Workhorse detects the error
and closes the other connection, terminating the channel session. If the browser
is the connection that has disconnected, Workhorse sends an ANSI `End of Transmission`
control code (the `0x04` byte) to the channel, encoded according to the appropriate
sub-protocol. To avoid being disconnected, Workhorse replies to any websocket ping
frame sent by the channel.
Workhorse only supports the following sub-protocols:
- [`channel.k8s.io`](#channelk8sio)
- [`base64.channel.k8s.io`](#base64channelk8sio)
Supporting new deployment services requires new sub-protocols to be supported.
### `channel.k8s.io`
Used by Kubernetes, this sub-protocol defines a multiplexed channel.
Control frames have their usual meanings. `TextMessage` frames are
invalid. `BinaryMessage` frames represent I/O to a specific file
descriptor.
The first byte of each `BinaryMessage` frame represents the file
descriptor (`fd`) number, as a `uint8`. For example:
- `0x00` corresponds to `fd 0`, `STDIN`.
- `0x01` corresponds to `fd 1`, `STDOUT`.
The remaining bytes represent arbitrary data. For frames received
from the server, they are bytes that have been received from that
`fd`. For frames sent to the server, they are bytes that should be
written to that `fd`.
### `base64.channel.k8s.io`
Also used by Kubernetes, this sub-protocol defines a similar multiplexed
channel to `channel.k8s.io`. The main differences are:
- `TextMessage` frames are valid, rather than `BinaryMessage` frames.
- The first byte of each `TextMessage` frame represents the file
descriptor as a numeric UTF-8 character, so the character `U+0030`,
or "0", is `fd 0`, `STDIN`.
- The remaining bytes represent base64-encoded arbitrary data.
|
---
stage: Create
group: Source Code
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: Websocket channel support for Workhorse
breadcrumbs:
- doc
- development
- workhorse
---
In some cases, GitLab can provide the following through a WebSocket:
- In-browser terminal access to an environment: a running server or container,
onto which a project has been deployed.
- Access to services running in CI.
Workhorse manages the WebSocket upgrade and long-lived connection to the websocket
connection, which frees up GitLab to process other requests. This document outlines
the architecture of these connections.
## Introduction to WebSockets
Websockets are an "upgraded" `HTTP/1.1` request. They permit bidirectional
communication between a client and a server. Websockets are not HTTP.
Clients can send messages (known as frames) to the server at any time, and
vice versa. Client messages are not necessarily requests, and server messages are
not necessarily responses. WebSocket URLs have schemes like `ws://` (unencrypted) or
`wss://` (TLS-secured).
When requesting an upgrade to WebSocket, the browser sends a `HTTP/1.1`
request like this:
```plaintext
GET /path.ws HTTP/1.1
Connection: upgrade
Upgrade: websocket
Sec-WebSocket-Protocol: terminal.gitlab.com
# More headers, including security measures
```
At this point, the connection is still HTTP, so this is a request.
The server can send a standard HTTP response, such as `404 Not Found` or
`500 Internal Server Error`.
If the server decides to permit the upgrade, it sends an HTTP
`101 Switching Protocols` response. From this point, the connection is no longer
HTTP. It is now a WebSocket and frames, not HTTP requests, flow over it. The connection
persists until the client or server closes the connection.
In addition to the sub-protocol, individual websocket frames may
also specify a message type, such as:
- `BinaryMessage`
- `TextMessage`
- `Ping`
- `Pong`
- `Close`
Only binary frames can contain arbitrary data. The frames are expected to be valid
UTF-8 strings, in addition to any sub-protocol expectations.
## Browser to Workhorse
Using the terminal as an example:
1. GitLab serves a JavaScript terminal emulator to the browser on a URL like
`https://gitlab.com/group/project/-/environments/1/terminal`.
1. This URL opens a websocket connection to
`wss://gitlab.com/group/project/-/environments/1/terminal.ws`.
This endpoint exists only in Workhorse, and doesn't exist in GitLab.
1. When receiving the connection, Workhorse first performs a `preauthentication`
request to GitLab to confirm the client is authorized to access the requested terminal:
- If the client has the appropriate permissions and the terminal exists, GitLab
responds with a successful response that includes details of the terminal
the client should be connected to.
- Otherwise, Workhorse returns an appropriate HTTP error response.
1. If GitLab returns valid terminal details to Workhorse, it:
1. Connects to the specified terminal.
1. Upgrades the browser to a WebSocket.
1. Proxies between the two connections for as long as the browser's credentials are valid.
1. Send regular `PingMessage` control frames to the browser, to prevent intervening
proxies from terminating the connection while the browser is present.
The browser must request an upgrade with a specific sub-protocol:
- [`terminal.gitlab.com`](#terminalgitlabcom)
- [`base64.terminal.gitlab.com`](#base64terminalgitlabcom)
### `terminal.gitlab.com`
This sub-protocol considers `TextMessage` frames to be invalid. Control frames,
such as `PingMessage` or `CloseMessage`, have their usual meanings.
- `BinaryMessage` frames sent from the browser to the server are
arbitrary text input.
- `BinaryMessage` frames sent from the server to the browser are
arbitrary text output.
These frames are expected to contain ANSI text control codes
and may be in any encoding.
### `base64.terminal.gitlab.com`
This sub-protocol considers `BinaryMessage` frames to be invalid.
Control frames, such as `PingMessage` or `CloseMessage`, have
their usual meanings.
- `TextMessage` frames sent from the browser to the server are
base64-encoded arbitrary text input. The server must
base64-decode them before inputting them.
- `TextMessage` frames sent from the server to the browser are
base64-encoded arbitrary text output. The browser must
base64-decode them before outputting them.
In their base64-encoded form, these frames are expected to
contain ANSI terminal control codes, and may be in any encoding.
## Workhorse to GitLab
Using the terminal as an example, before upgrading the browser,
Workhorse sends a standard HTTP request to GitLab on a URL like
`https://gitlab.com/group/project/environments/1/terminal.ws/authorize`.
This returns a JSON response containing details of where the
terminal can be found, and how to connect it. In particular,
the following details are returned in case of success:
- WebSocket URL to connect to, such as `wss://example.com/terminals/1.ws?tty=1`.
- WebSocket sub-protocols to support, such as `["channel.k8s.io"]`.
- Headers to send, such as `Authorization: Token xxyyz`.
- Optional. Certificate authority to verify `wss` connections with.
Workhorse periodically rechecks this endpoint. If it receives an error response,
or the details of the terminal change, it terminates the websocket session.
## Workhorse to the WebSocket server
In GitLab, environments or CI jobs may have a deployment service (like
`KubernetesService`) associated with them. This service knows
where the terminals or the service for an environment may be found, and GitLab
returns these details to Workhorse.
These URLs are also WebSocket URLs. GitLab tells Workhorse which sub-protocols to
speak over the connection, along with any authentication details required by the
remote end.
Before upgrading the browser's connection to a websocket, Workhorse:
1. Opens an HTTP client connection, according to the details given to it by Workhorse.
1. Attempts to upgrade that connection to a websocket.
- If it fails, an error response is sent to the browser.
- If it succeeds, the browser is also upgraded.
Workhorse now has two websocket connections, albeit with differing sub-protocols,
and then:
- Decodes incoming frames from the browser, re-encodes them to the channel's
sub-protocol, and sends them to the channel.
- Decodes incoming frames from the channel, re-encodes them to the browser's
sub-protocol, and sends them to the browser.
When either connection closes or enters an error state, Workhorse detects the error
and closes the other connection, terminating the channel session. If the browser
is the connection that has disconnected, Workhorse sends an ANSI `End of Transmission`
control code (the `0x04` byte) to the channel, encoded according to the appropriate
sub-protocol. To avoid being disconnected, Workhorse replies to any websocket ping
frame sent by the channel.
Workhorse only supports the following sub-protocols:
- [`channel.k8s.io`](#channelk8sio)
- [`base64.channel.k8s.io`](#base64channelk8sio)
Supporting new deployment services requires new sub-protocols to be supported.
### `channel.k8s.io`
Used by Kubernetes, this sub-protocol defines a multiplexed channel.
Control frames have their usual meanings. `TextMessage` frames are
invalid. `BinaryMessage` frames represent I/O to a specific file
descriptor.
The first byte of each `BinaryMessage` frame represents the file
descriptor (`fd`) number, as a `uint8`. For example:
- `0x00` corresponds to `fd 0`, `STDIN`.
- `0x01` corresponds to `fd 1`, `STDOUT`.
The remaining bytes represent arbitrary data. For frames received
from the server, they are bytes that have been received from that
`fd`. For frames sent to the server, they are bytes that should be
written to that `fd`.
### `base64.channel.k8s.io`
Also used by Kubernetes, this sub-protocol defines a similar multiplexed
channel to `channel.k8s.io`. The main differences are:
- `TextMessage` frames are valid, rather than `BinaryMessage` frames.
- The first byte of each `TextMessage` frame represents the file
descriptor as a numeric UTF-8 character, so the character `U+0030`,
or "0", is `fd 0`, `STDIN`.
- The remaining bytes represent base64-encoded arbitrary data.
|
https://docs.gitlab.com/development/gitlab_subscriptions
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/gitlab_subscriptions.md
|
2025-08-13
|
doc/development/internal_api
|
[
"doc",
"development",
"internal_api"
] |
gitlab_subscriptions.md
|
Fulfillment
|
Provision
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
GitLab Subscriptions Internal API
| null |
The GitLab Subscriptions internal API is used by the CustomersDot application,
it cannot be used by other consumers. This documentation is intended for people
working on the GitLab and CustomersDot codebases.
## Add new endpoints
API endpoints should be externally accessible by default, with proper authentication and authorization.
Before adding a new internal endpoint, consider if the API would benefit the wider GitLab community and
can be made externally accessible.
For the GitLab Subscription portal, we might chose to use an internal API when we need to make updates
to GitLab without the context of a user. This means we don't have access to a user's access token, and
instead make updates as the CustomersDot application in general.
## Authentication
### CustomersDot JWT
These endpoints are all authenticated using JWT authentication from CustomersDot.
To authenticate using the JWT, clients:
1. Read the contents of the signing key from the credentials.
1. Use the signing key to generate a JSON Web Token (`JWT`).
1. Pass the JWT in the `X-CUSTOMERS-DOT-INTERNAL-TOKEN` header.
### Admin personal access token (PAT)
This authentication method is deprecated as it is not supported in the Cells architecture. It will be
[removed in a future milestone](https://gitlab.com/gitlab-org/gitlab/-/issues/473625). Use JWT authentication instead.
To authenticate as an administrator, generate a personal access token for an administrator with the
`api` and `admin_mode` scopes. This token can then be supplied in the `PRIVATE-TOKEN` header.
## Internal Endpoints
### Namespaces
#### Fetch group owners
Use a GET command to get direct owners of the namespace. CustomersDot uses this endpoint to find users to notify about
billing events.
```plaintext
GET /internal/gitlab_subscriptions/namespaces/:id/owners
```
Example request:
```shell
curl --header "X-CUSTOMERS-DOT-INTERNAL-TOKEN: <json-web-token>" "https://gitlab.com/api/v4/internal/gitlab_subscriptions/namespaces/1234/owners"
```
Example response:
```json
[
{
"user": {
"id": 1,
"username": "john_smith",
"name": "John Smith"
},
"access_level": 50,
"notification_email": "name@example.com"
}
]
```
#### Fetch a namespace by ID
Used to fetch information about a namespace.
```plaintext
GET /internal/gitlab_subscriptions/namespaces/:id
```
Parameters:
| Attribute | Type | Required | Description |
| --------- | -------------- | -------- | ----------- |
| `id` | integer/string | yes | ID or [URL-encoded path of the namespace](../../api/rest/_index.md#namespaced-paths) |
Example request:
```shell
curl --request GET --header "X-CUSTOMERS-DOT-INTERNAL-TOKEN: <json-web-token>" "https://gitlab.com/api/v4/internal/gitlab_subscriptions/namespaces/1"
```
Example response:
```json
{
"id": 1,
"name": "group1",
"path": "group1",
"kind": "group",
"full_path": "group1",
"parent_id": null,
"avatar_url": null,
"web_url": "https://gitlab.example.com/groups/group1",
"members_count_with_descendants": 2,
"billable_members_count": 2,
"max_seats_used": 0,
"seats_in_use": 0,
"plan": "default",
"end_date": null,
"trial_ends_on": null,
"trial": false,
"root_repository_size": 100,
"projects_count": 3
}
```
#### Update a namespace
Use a PUT command to update an existing namespace.
```plaintext
PUT /internal/gitlab_subscriptions/namespaces/:id
```
Parameters:
| Attribute | Type | Required | Description |
| --------- | -------------- | -------- | ----------- |
| `id` | integer/string | yes | ID or [URL-encoded path of the namespace](../../api/rest/_index.md#namespaced-paths) |
| `shared_runners_minutes_limit` | integer | no | Compute minutes quota |
| `extra_shared_runners_minutes_limit` | integer | no | Extra compute minutes |
| `additional_purchased_storage_size` | integer | no | Additional storage size |
| `additional_purchased_storage_ends_on` | date | no | Additional purchased storage Ends on |
| `gitlab_subscription_attributes` | hash | no | Hash object containing GitLab Subscription attributes. Accepts `seats`,`max_seats_used`,`plan_code`,`end_date`,`auto_renew`,`trial`,`trial_ends_on`,`trial_starts_on`,`trial_extension_type` |
Example request:
```shell
curl --request PUT --header "X-CUSTOMERS-DOT-INTERNAL-TOKEN: <json-web-token>" "https://gitlab.com/api/v4/internal/gitlab_subscriptions/namespaces/1 --data '{"shared_runners_minutes_limit":1000}'"
```
Example response:
```json
{
"id": 1,
"name": "group1",
"path": "group1",
"kind": "group",
"full_path": "group1",
"parent_id": null,
"avatar_url": null,
"web_url": "https://gitlab.example.com/groups/group1",
"members_count_with_descendants": 2,
"billable_members_count": 2,
"max_seats_used": 0,
"seats_in_use": 0,
"plan": "default",
"end_date": null,
"trial_ends_on": null,
"trial": false,
"root_repository_size": 100,
"projects_count": 3
}
```
#### Provision a namespace
Use to provision subscription related resources for a root namespace. This includes base product, storage, compute minutes, and add-on purchases.
The endpoint processes resources independently - if one resource fails to provision, others continue to be provisioned.
You can provision one or more resources in a single request based on the parameters provided.
```plaintext
POST /internal/gitlab_subscriptions/namespaces/:id/provision
```
Parameters:
| Attribute | Type | Required | Description |
| :------------ | :-------- | :--------- | :------------ |
| `id` | integer | yes | ID of the namespace to provision |
The endpoint supports parameters for each resource nested under the `provision` root key:
| Attribute | Type | Required | Description |
| :------------ | :-------- | :--------- | :------------ |
| `base_product` | hash | no | Hash object containing GitLab Subscription attributes |
| `storage` | hash | no | Hash object containing Storage attributes |
| `compute_minutes` | hash | no | Hash object containing Compute Minutes attributes |
| `add_on_purchases` | hash | no | Hash object containing Add-on Purchases attributes |
Base product supported attributes:
| Attribute | Type | Required | Description |
| :------------ | :-------- | :--------- | :------------ |
| `plan_code` | string | no | Subscription tier code |
| `start_date` | date | no | Start date of subscription |
| `end_date` | date | no | End date of subscription |
| `seats` | integer | no | Number of seats in subscription |
| `max_seats_used` | integer | no | Highest number of billable users in the current subscription term |
| `auto_renew` | boolean | no | Whether subscription auto-renews on end date |
| `trial` | boolean | no | Whether subscription is a trial |
| `trial_starts_on` | date | no | Start date of trial. Required if trial is true |
| `trial_ends_on` | date | no | End date of trial |
Storage supported attributes:
| Attribute | Type | Required | Description |
| :------------ | :-------- | :--------- | :------------ |
| `additional_purchased_storage_size` | integer | no | Additional storage size |
| `additional_purchased_storage_ends_on` | date | no | Additional purchased storage ends on |
Compute Minutes supported attributes:
| Attribute | Type | Required | Description |
| :------------ | :-------- | :--------- | :------------ |
| `shared_runners_minutes_limit` | integer | no | Compute minutes quota |
| `extra_shared_runners_minutes_limit` | integer | no | Extra compute minutes |
Add-on Purchases Supported attributes:
| Attribute | Type | Required | Description |
| :------------ | :-------- | :--------- | :------------ |
| `quantity` | integer | No | Amount of units in the subscription add-on purchase. Must be a non-negative integer. (Example: Number of seats for Duo Pro add-on) |
| `started_on` | date | Yes | Date the subscription add-on purchase became available |
| `expires_on` | date | Yes | Expiration date of the subscription add-on purchase |
| `purchase_xid` | string | No | Identifier for the subscription add-on purchase (Example: Subscription name for a Duo Pro add-on) |
| `trial` | boolean | No | Whether the add-on is a trial |
Example request:
```shell
curl --request POST --header "X-CUSTOMERS-DOT-INTERNAL-TOKEN: <json-web-token>" "https://gitlab.com/api/v4/internal/gitlab_subscriptions/namespaces/1/provision" \
--data '{
"provision": {
"base_product": {
"plan_code": "ultimate",
"seats": 30,
"start_date": "2024-01-01",
"end_date": "2025-01-01",
"max_seats_used": 10,
"auto_renew": true,
"trial": false,
"trial_starts_on": null,
"trial_ends_on": null
},
"storage": {
"additional_purchased_storage_size": 100,
"additional_purchased_storage_ends_on": "2025-01-01"
},
"compute_minutes": {
"extra_shared_runners_minutes_limit": 90,
"shared_runners_minutes_limit": 100
},
"add_on_purchases": {
"duo_enterprise": [{
"started_on": "2024-01-01",
"expires_on": "2025-01-01",
"purchase_xid": "A-S00001",
"quantity": 1,
"trial": false
}]
}
}
}'
```
Response Status Codes:
- 200 OK - Namespace provisioned successfully (empty response)
- 400 Bad Request - Invalid parameters or non-root namespace
- 401 Unauthorized - Invalid token
- 404 Not Found - Namespace doesn't exist
- 422 Unprocessable Entity - Validation errors during provisioning
### Subscriptions
The subscription endpoints are used by
[CustomersDot](https://gitlab.com/gitlab-org/customers-gitlab-com) (`customers.gitlab.com`) to
apply subscriptions (including trials, and add-on purchases) to personal namespaces, or top-level
groups on GitLab.com.
#### Fetch a subscription
Use a GET command to view an existing subscription.
```plaintext
GET /internal/gitlab_subscriptions/namespaces/:id/gitlab_subscription
```
Example request:
```shell
curl --header "X-CUSTOMERS-DOT-INTERNAL-TOKEN: <json-web-token>" "https://gitlab.com/api/v4/internal/gitlab_subscriptions/namespaces/1234/gitlab_subscription"
```
Example response:
```json
{
"plan": {
"code": "premium",
"name": "premium",
"trial": false,
"auto_renew": null,
"upgradable": false,
"exclude_guests": false
},
"usage": {
"seats_in_subscription": 80,
"seats_in_use": 82,
"max_seats_used": 82,
"seats_owed": 2
},
"billing": {
"subscription_start_date": "2020-07-15",
"subscription_end_date": "2021-07-15",
"trial_ends_on": null
}
}
```
#### Create a subscription
Use a POST command to create a subscription.
```plaintext
POST /internal/gitlab_subscriptions/namespaces/:id/gitlab_subscription
```
| Attribute | Type | Required | Description |
|:------------|:--------|:---------|:------------|
| `start_date` | date | yes | Start date of subscription |
| `end_date` | date | no | End date of subscription |
| `plan_code` | string | no | Subscription tier code |
| `seats` | integer | no | Number of seats in subscription |
| `max_seats_used` | integer | no | Highest number of billable users in the current subscription term |
| `auto_renew` | boolean | no | Whether subscription auto-renews on end date |
| `trial` | boolean | no | Whether subscription is a trial |
| `trial_starts_on` | date | no | Start date of trial |
| `trial_ends_on` | date | no | End date of trial |
Example request:
```shell
curl --request POST --header "X-CUSTOMERS-DOT-INTERNAL-TOKEN: <json-web-token>" "https://gitlab.com/api/v4/internal/gitlab_subscriptions/namespaces/1234/gitlab_subscription?start_date="2020-07-15"&plan="premium"&seats=10"
```
Example response:
```json
{
"plan": {
"code":"premium",
"name":"premium",
"trial":false,
"auto_renew":null,
"upgradable":false
},
"usage": {
"seats_in_subscription":10,
"seats_in_use":1,
"max_seats_used":0,
"seats_owed":0
},
"billing": {
"subscription_start_date":"2020-07-15",
"subscription_end_date":null,
"trial_ends_on":null
}
}
```
#### Update a subscription
Use a PUT command to update an existing subscription.
```plaintext
PUT /internal/gitlab_subscriptions/namespaces/:id/gitlab_subscription
```
| Attribute | Type | Required | Description |
|:------------|:--------|:---------|:------------|
| `start_date` | date | no | Start date of subscription |
| `end_date` | date | no | End date of subscription |
| `plan_code` | string | no | Subscription tier code |
| `seats` | integer | no | Number of seats in subscription |
| `max_seats_used` | integer | no | Highest number of billable users in the current subscription term |
| `auto_renew` | boolean | no | Whether subscription auto-renews on end date |
| `trial` | boolean | no | Whether subscription is a trial |
| `trial_starts_on` | date | no | Start date of trial. Required if trial is true. |
| `trial_ends_on` | date | no | End date of trial |
Example request:
```shell
curl --request PUT --header "X-CUSTOMERS-DOT-INTERNAL-TOKEN: <json-web-token>" "https://gitlab.com/api/v4/internal/gitlab_subscriptions/namespaces/1234/gitlab_subscription?max_seats_used=0"
```
Example response:
```json
{
"plan": {
"code":"premium",
"name":"premium",
"trial":false,
"auto_renew":null,
"upgradable":false
},
"usage": {
"seats_in_subscription":80,
"seats_in_use":82,
"max_seats_used":0,
"seats_owed":2
},
"billing": {
"subscription_start_date":"2020-07-15",
"subscription_end_date":"2021-07-15",
"trial_ends_on":null
}
}
```
### Upcoming Reconciliations
The `upcoming_reconciliations` endpoint is used by [CustomersDot](https://gitlab.com/gitlab-org/customers-gitlab-com) (`customers.gitlab.com`)
to update upcoming reconciliations for namespaces.
#### Update an upcoming reconciliation
```plaintext
PUT /internal/gitlab_subscriptions/namespaces/:namespace_id/upcoming_reconciliations
```
| Attribute | Type | Required | Description |
|:---------------------------|:-----|:---------|:--------------------------------------------------------|
| `namespace_id` | ID | yes | ID of the namespace with the upcoming reconciliation |
| `next_reconciliation_date` | date | yes | Date the reconciliation will occur on |
| `display_alert_from` | date | yes | Date to start display the upcoming reconciliation alert |
Example request:
```shell
curl --request PUT --header "X-CUSTOMERS-DOT-INTERNAL-TOKEN: <json-web-token>" --header "Content-Type: application/json" \
--data '{"upcoming_reconciliations": [{"next_reconciliation_date": "12 Jun 2021", "display_alert_from": "05 Jun 2021"}]}' \
"https://gitlab.com/api/v4/internal/gitlab_subscriptions/129/upcoming_reconciliations"
```
Example response:
```plaintext
200
```
#### Delete an upcoming reconciliation
Use a DELETE command to delete an `upcoming_reconciliation`.
```plaintext
DELETE /internal/gitlab_subscriptions/namespaces/:namespace_id/upcoming_reconciliations
```
Example request:
```shell
curl --request DELETE \
--url "http://localhost:3000/api/v4/internal/gitlab_subscriptions/namespaces/22/upcoming_reconciliations" \
--header "X-CUSTOMERS-DOT-INTERNAL-TOKEN: <json-web-token>"
```
Example response:
```plaintext
204
```
### Users
#### Retrieve a user
Use a GET command to get the User object based on user ID.
```plaintext
GET /internal/gitlab_subscriptions/users/:id
```
Example request:
```shell
curl --header "X-CUSTOMERS-DOT-INTERNAL-TOKEN: <json-web-token>" "https://gitlab.com/api/v4/internal/gitlab_subscriptions/users/:id"
```
Example response:
```json
{
"id": 1,
"username": "john_smith",
"name": "John Smith",
"web_url": "http://localhost:3000/john_smith"
}
```
#### Fetch user permissions in a namespace
Use a GET command to fetch the permissions a user has in a namespace.
```plaintext
GET /internal/gitlab_subscriptions/namespaces/:namespace_id/user_permissions/:user_id
```
Example request:
```shell
curl --header "X-CUSTOMERS-DOT-INTERNAL-TOKEN: <json-web-token>" "https://gitlab.com/api/v4/internal/gitlab_subscriptions/namespaces/:namespace_id/user_permissions/:user_id"
```
Example response:
```json
{
"edit_billing": true
}
```
#### Update credit card validation
Use a PUT command to update the User's credit card validation
```plaintext
PUT /internal/gitlab_subscriptions/users/:user_id/credit_card_validation
```
Example request:
```shell
curl --request PUT --header "X-CUSTOMERS-DOT-INTERNAL-TOKEN: <json-web-token>" \
--data '{"credit_card_validated_at": "2020-01-01 00:00:00 UTC", "credit_card_expiration_year": "2010", "credit_card_expiration_month": "12", "credit_card_holder_name": "John Smith", "credit_card_type": "American Express", "credit_card_mask_number": "1111", "zuora_payment_method_xid": "abc123", "stripe_setup_intent_xid": "seti_abc123", "stripe_payment_method_xid": "pm_abc123", "stripe_card_fingerprint": "card123"}' \
"https://gitlab.com/api/v4/internal/gitlab_subscriptions/users/:user_id/credit_card_validation"
```
Example response:
```json
{
"success": {}
}
```
### Add-On Purchases
This API is used by CustomersDot to manage add-on purchases, excluding Compute Minutes
and Storage packs.
#### Create multiple subscription add-on purchases (Internal)
Use a POST command to create, update, and deprovision multiple subscription add-on purchases. Possible add-on types are `duo_pro`, `duo_enterprise`, and `product_analytics`.
```plaintext
POST /internal/gitlab_subscriptions/namespaces/:id/subscription_add_on_purchases
```
Supported attributes:
| Attribute | Type | Required | Description |
|:------------|:--------|:---------|:------------|
| `quantity` | integer | No | Amount of units in the subscription add-on purchase. Must be a non-negative integer. (Example: Number of seats for Duo Pro add-on) |
| `started_on` | date | Yes | Date the subscription add-on purchase became available |
| `expires_on` | date | Yes | Expiration date of the subscription add-on purchase |
| `purchase_xid` | string | No | Identifier for the subscription add-on purchase (Example: Subscription name for a Code Suggestions add-on) |
| `trial` | boolean | No | Whether the add-on is a trial |
If successful, returns [`201`](../../api/rest/troubleshooting.md#status-codes) and the following response attributes:
| Attribute | Type | Description |
|:----------------|:--------|:------------|
| `namespace_id` | integer | Unique identifier for the namespace associated with the purchase |
| `namespace_name`| string | Name of the namespace linked to the purchase |
| `add_on` | integer | Type of add-on related to the purchase. Possible add-on types are `Code Suggestions` alias Duo Pro, `Duo Enterprise` and `Product Analytics` |
| `quantity` | integer | Number of units purchased for the subscription add-on |
| `started_on` | date | Date the subscription add-on became active |
| `expires_on` | date | Date the subscription add-on will expire |
| `purchase_xid` | string | Unique identifier for the subscription add-on purchase |
| `trial` | boolean | Indicates whether the add-on is part of a trial |
Example request for create/update:
```shell
curl --request POST \
--header --header "X-CUSTOMERS-DOT-INTERNAL-TOKEN: <json-web-token>" \
--header "Content-Type: application/json" \
--data '{ "add_on_purchases": { "duo_pro": [{ "quantity": 1, "started_on": "<YYYY-MM-DD>", "expires_on": "<YYYY-MM-DD>", "purchase_xid": "C-00123456", "trial": false }] } }' \
"https://gitlab.com/api/v4/internal/gitlab_subscriptions/namespaces/1234/subscription_add_on_purchases"
```
Example request for deprovision:
```shell
curl --request POST \
--header --header "X-CUSTOMERS-DOT-INTERNAL-TOKEN: <json-web-token>" \
--header "Content-Type: application/json" \
--data '{ "add_on_purchases": { "duo_pro": [{ "started_on": "<YYYY-MM-DD>", "expires_on": "<YYYY-MM-DD>" }] } }' \
"https://gitlab.com/api/v4/internal/gitlab_subscriptions/namespaces/1234/subscription_add_on_purchases"
```
The dates should reflect the day prior to the request (that is, yesterday).
Example response:
```json
[
{
"namespace_id": 1234,
"namespace_name": "namespace-name",
"add_on": "Code Suggestions",
"quantity": 1,
"started_on": "2024-01-01",
"expires_on": "2024-12-31",
"purchase_xid": "C-00123456",
"trial": false
}
]
```
#### Fetch a subscription add-on purchases
Use a GET command to view an existing subscription add-on purchase.
```plaintext
GET /internal/gitlab_subscriptions/namespaces/:id/subscription_add_on_purchases/:add_on_name
```
Example request:
```shell
curl --header "X-CUSTOMERS-DOT-INTERNAL-TOKEN: <json-web-token>" "https://gitlab.com/api/v4/internal/gitlab_subscriptions/namespaces/1234/subscription_add_on_purchases/code_suggestions"
```
Example response:
```json
{
"namespace_id":1234,
"namespace_name":"A Namespace Name",
"add_on":"Code Suggestions",
"quantity":15,
"started_on":"2024-06-15",
"expires_on":"2024-07-15",
"purchase_xid":"C-00123456",
"trial":true
}
```
### Compute Minutes provisioning
The compute minutes endpoints are used by [CustomersDot](https://gitlab.com/gitlab-org/customers-gitlab-com) (`customers.gitlab.com`)
to apply additional packs of compute minutes, for personal namespaces or top-level groups in GitLab.com.
#### Create an additional pack
Use a POST command to create additional packs.
```plaintext
POST /internal/gitlab_subscriptions/namespaces/:id/minutes
```
| Attribute | Type | Required | Description |
|:------------|:--------|:---------|:------------|
| `packs` | array | yes | An array of purchased compute packs |
| `packs[expires_at]` | date | yes | Expiry date of the purchased pack|
| `packs[number_of_minutes]` | integer | yes | Number of additional compute minutes |
| `packs[purchase_xid]` | string | yes | The unique ID of the purchase |
Example request:
```shell
curl --request POST \
--url "http://localhost:3000/api/v4/internal/gitlab_subscriptions/namespaces/123/minutes" \
--header 'Content-Type: application/json' \
--header 'X-CUSTOMERS-DOT-INTERNAL-TOKEN: <json-web-token>' \
--data '{
"packs": [
{
"number_of_minutes": 10000,
"expires_at": "2022-01-01",
"purchase_xid": "C-00123456"
}
]
}'
```
Example response:
```json
[
{
"namespace_id": 123,
"expires_at": "2022-01-01",
"number_of_minutes": 10000,
"purchase_xid": "C-00123456"
}
]
```
#### Move additional packs
Use a `PATCH` command to move additional packs from one namespace to another.
```plaintext
PATCH /internal/gitlab_subscriptions/namespaces/:id/minutes/move/:target_id
```
| Attribute | Type | Required | Description |
|:------------|:--------|:---------|:------------|
| `id` | string | yes | The ID of the namespace to transfer packs from |
| `target_id` | string | yes | The ID of the target namespace to transfer the packs to |
Example request:
```shell
curl --request PATCH \
--url "http://localhost:3000/api/v4/internal/gitlab_subscriptions/namespaces/123/minutes/move/321" \
--header "X-CUSTOMERS-DOT-INTERNAL-TOKEN: <json-web-token>"
```
Example response:
```json
{
"message": "202 Accepted"
}
```
## Deprecated Endpoints
These endpoints have been [migrated to internal endpoints](https://gitlab.com/gitlab-org/gitlab/-/issues/463741). Now, they are
deprecated and will be [removed in a future milestone](https://gitlab.com/gitlab-org/gitlab/-/issues/473625).
### Add-On Purchases (deprecated)
This API is used by CustomersDot to manage add-on purchases, excluding Compute Minutes
and Storage packs.
#### Create a subscription add-on purchase (deprecated)
Use a POST command to create a subscription add-on purchase.
```plaintext
POST /namespaces/:id/subscription_add_on_purchase/:add_on_name
```
| Attribute | Type | Required | Description |
|:------------|:--------|:---------|:------------|
| `quantity` | integer | yes | Amount of units in the subscription add-on purchase (Example: Number of seats for a Code Suggestions add-on) |
| `started_on` | date | yes | Date the subscription add-on purchase became available |
| `expires_on` | date | yes | Expiration date of the subscription add-on purchase |
| `purchase_xid` | string | yes | Identifier for the subscription add-on purchase (Example: Subscription name for a Code Suggestions add-on) |
| `trial` | boolean | no | Whether the add-on is a trial |
Example request:
```shell
curl --request POST --header "X-CUSTOMERS-DOT-INTERNAL-TOKEN: <json-web-token>" "https://gitlab.com/api/v4/namespaces/1234/subscription_add_on_purchase/code_suggestions?&quantity=10&started_on="2024-06-15"&expires_on="2024-07-15"&purchase_xid="C-00123456"&trial=true"
```
Example response:
```json
{
"namespace_id":1234,
"namespace_name":"A Namespace Name",
"add_on":"Code Suggestions",
"quantity":10,
"started_on":"2024-06-15",
"expires_on":"2024-07-15",
"purchase_xid":"C-00123456",
"trial":true
}
```
#### Update a subscription add-on purchase (deprecated)
Use a PUT command to update an existing subscription add-on purchase.
```plaintext
PUT /namespaces/:id/subscription_add_on_purchase/:add_on_name
```
| Attribute | Type | Required | Description |
|:------------|:--------|:---------|:------------|
| `quantity` | integer | no | Amount of units in the subscription add-on purchase (Example: Number of seats for a Code Suggestions add-on) |
| `started_on` | date | yes | Date the subscription add-on purchase became available |
| `expires_on` | date | yes | Expiration date of the subscription add-on purchase |
| `purchase_xid` | string | no | Identifier for the subscription add-on purchase (Example: Subscription name for a Code Suggestions add-on) |
| `trial` | boolean | no | Whether the add-on is a trial |
Example request:
```shell
curl --request PUT --header "X-CUSTOMERS-DOT-INTERNAL-TOKEN: <json-web-token>" "https://gitlab.com/api/v4/namespaces/1234/subscription_add_on_purchase/code_suggestions?&quantity=15&started_on="2024-06-15"&expires_on="2024-07-15"&purchase_xid="C-00123456"&trial=true"
```
Example response:
```json
{
"namespace_id":1234,
"namespace_name":"A Namespace Name",
"add_on":"Code Suggestions",
"quantity":15,
"started_on":"2024-06-15",
"expires_on":"2024-07-15",
"purchase_xid":"C-00123456",
"trial":true
}
```
#### Fetch a subscription add-on purchases (deprecated)
Use a GET command to view an existing subscription add-on purchase.
```plaintext
GET /namespaces/:id/subscription_add_on_purchase/:add_on_name
```
Example request:
```shell
curl --header "X-CUSTOMERS-DOT-INTERNAL-TOKEN: <json-web-token>" "https://gitlab.com/api/v4/namespaces/1234/subscription_add_on_purchase/code_suggestions"
```
Example response:
```json
{
"namespace_id":1234,
"namespace_name":"A Namespace Name",
"add_on":"Code Suggestions",
"quantity":15,
"started_on":"2024-06-15",
"expires_on":"2024-07-15",
"purchase_xid":"C-00123456",
"trial":true
}
```
### Compute quota provisioning (deprecated)
{{< history >}}
- [Renamed](https://gitlab.com/groups/gitlab-com/-/epics/2150) from "CI/CD minutes" to "compute quota" and "compute minutes" in GitLab 16.1.
{{< /history >}}
The compute quota endpoints are used by [CustomersDot](https://gitlab.com/gitlab-org/customers-gitlab-com) (`customers.gitlab.com`)
to apply additional packs of compute minutes, for personal namespaces or top-level groups in GitLab.com.
#### Create an additional pack (deprecated)
Use a POST command to create additional packs.
```plaintext
POST /namespaces/:id/minutes
```
| Attribute | Type | Required | Description |
|:------------|:--------|:---------|:------------|
| `packs` | array | yes | An array of purchased compute packs |
| `packs[expires_at]` | date | yes | Expiry date of the purchased pack|
| `packs[number_of_minutes]` | integer | yes | Number of additional compute minutes |
| `packs[purchase_xid]` | string | yes | The unique ID of the purchase |
Example request:
```shell
curl --request POST \
--url "http://localhost:3000/api/v4/namespaces/123/minutes" \
--header 'Content-Type: application/json' \
--header 'X-CUSTOMERS-DOT-INTERNAL-TOKEN: <json-web-token>' \
--data '{
"packs": [
{
"number_of_minutes": 10000,
"expires_at": "2022-01-01",
"purchase_xid": "C-00123456"
}
]
}'
```
Example response:
```json
[
{
"namespace_id": 123,
"expires_at": "2022-01-01",
"number_of_minutes": 10000,
"purchase_xid": "C-00123456"
}
]
```
#### Move additional packs (deprecated)
Use a `PATCH` command to move additional packs from one namespace to another.
```plaintext
PATCH /namespaces/:id/minutes/move/:target_id
```
| Attribute | Type | Required | Description |
|:------------|:--------|:---------|:------------|
| `id` | string | yes | The ID of the namespace to transfer packs from |
| `target_id` | string | yes | The ID of the target namespace to transfer the packs to |
Example request:
```shell
curl --request PATCH \
--url "http://localhost:3000/api/v4/namespaces/123/minutes/move/321" \
--header "X-CUSTOMERS-DOT-INTERNAL-TOKEN: <json-web-token>"
```
Example response:
```json
{
"message": "202 Accepted"
}
```
### Subscriptions (deprecated)
The subscription endpoints are used by
[CustomersDot](https://gitlab.com/gitlab-org/customers-gitlab-com) (`customers.gitlab.com`) to
apply subscriptions (including trials) to personal namespaces, or top-level groups on GitLab.com.
#### Create a subscription (deprecated)
Use a POST command to create a subscription.
```plaintext
POST /namespaces/:id/gitlab_subscription
```
| Attribute | Type | Required | Description |
|:------------|:--------|:---------|:------------|
| `start_date` | date | yes | Start date of subscription |
| `end_date` | date | no | End date of subscription |
| `plan_code` | string | no | Subscription tier code |
| `seats` | integer | no | Number of seats in subscription |
| `max_seats_used` | integer | no | Highest number of active users in the last month |
| `auto_renew` | boolean | no | Whether subscription auto-renews on end date |
| `trial` | boolean | no | Whether subscription is a trial |
| `trial_starts_on` | date | no | Start date of trial |
| `trial_ends_on` | date | no | End date of trial |
Example request:
```shell
curl --request POST --header "X-CUSTOMERS-DOT-INTERNAL-TOKEN: <json-web-token>" "https://gitlab.com/api/v4/namespaces/1234/gitlab_subscription?start_date="2020-07-15"&plan="premium"&seats=10"
```
Example response:
```json
{
"plan": {
"code":"premium",
"name":"premium",
"trial":false,
"auto_renew":null,
"upgradable":false
},
"usage": {
"seats_in_subscription":10,
"seats_in_use":1,
"max_seats_used":0,
"seats_owed":0
},
"billing": {
"subscription_start_date":"2020-07-15",
"subscription_end_date":null,
"trial_ends_on":null
}
}
```
#### Update a subscription (deprecated)
Use a PUT command to update an existing subscription.
```plaintext
PUT /namespaces/:id/gitlab_subscription
```
| Attribute | Type | Required | Description |
|:------------|:--------|:---------|:------------|
| `start_date` | date | no | Start date of subscription |
| `end_date` | date | no | End date of subscription |
| `plan_code` | string | no | Subscription tier code |
| `seats` | integer | no | Number of seats in subscription |
| `max_seats_used` | integer | no | Highest number of active users in the last month |
| `auto_renew` | boolean | no | Whether subscription auto-renews on end date |
| `trial` | boolean | no | Whether subscription is a trial |
| `trial_starts_on` | date | no | Start date of trial. Required if trial is true. |
| `trial_ends_on` | date | no | End date of trial |
Example request:
```shell
curl --request PUT --header "X-CUSTOMERS-DOT-INTERNAL-TOKEN: <json-web-token>" "https://gitlab.com/api/v4/namespaces/1234/gitlab_subscription?max_seats_used=0"
```
Example response:
```json
{
"plan": {
"code":"premium",
"name":"premium",
"trial":false,
"auto_renew":null,
"upgradable":false
},
"usage": {
"seats_in_subscription":80,
"seats_in_use":82,
"max_seats_used":0,
"seats_owed":2
},
"billing": {
"subscription_start_date":"2020-07-15",
"subscription_end_date":"2021-07-15",
"trial_ends_on":null
}
}
```
#### Fetch a subscription (deprecated)
Use a GET command to view an existing subscription.
```plaintext
GET /namespaces/:id/gitlab_subscription
```
Example request:
```shell
curl --header "TOKEN: <admin_access_token>" "https://gitlab.com/api/v4/namespaces/1234/gitlab_subscription"
```
Example response:
```json
{
"plan": {
"code":"premium",
"name":"premium",
"trial":false,
"auto_renew":null,
"upgradable":false,
"exclude_guests":false
},
"usage": {
"seats_in_subscription":80,
"seats_in_use":82,
"max_seats_used":82,
"seats_owed":2
},
"billing": {
"subscription_start_date":"2020-07-15",
"subscription_end_date":"2021-07-15",
"trial_ends_on":null
}
}
```
|
---
stage: Fulfillment
group: Provision
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: GitLab Subscriptions Internal API
breadcrumbs:
- doc
- development
- internal_api
---
The GitLab Subscriptions internal API is used by the CustomersDot application,
it cannot be used by other consumers. This documentation is intended for people
working on the GitLab and CustomersDot codebases.
## Add new endpoints
API endpoints should be externally accessible by default, with proper authentication and authorization.
Before adding a new internal endpoint, consider if the API would benefit the wider GitLab community and
can be made externally accessible.
For the GitLab Subscription portal, we might chose to use an internal API when we need to make updates
to GitLab without the context of a user. This means we don't have access to a user's access token, and
instead make updates as the CustomersDot application in general.
## Authentication
### CustomersDot JWT
These endpoints are all authenticated using JWT authentication from CustomersDot.
To authenticate using the JWT, clients:
1. Read the contents of the signing key from the credentials.
1. Use the signing key to generate a JSON Web Token (`JWT`).
1. Pass the JWT in the `X-CUSTOMERS-DOT-INTERNAL-TOKEN` header.
### Admin personal access token (PAT)
This authentication method is deprecated as it is not supported in the Cells architecture. It will be
[removed in a future milestone](https://gitlab.com/gitlab-org/gitlab/-/issues/473625). Use JWT authentication instead.
To authenticate as an administrator, generate a personal access token for an administrator with the
`api` and `admin_mode` scopes. This token can then be supplied in the `PRIVATE-TOKEN` header.
## Internal Endpoints
### Namespaces
#### Fetch group owners
Use a GET command to get direct owners of the namespace. CustomersDot uses this endpoint to find users to notify about
billing events.
```plaintext
GET /internal/gitlab_subscriptions/namespaces/:id/owners
```
Example request:
```shell
curl --header "X-CUSTOMERS-DOT-INTERNAL-TOKEN: <json-web-token>" "https://gitlab.com/api/v4/internal/gitlab_subscriptions/namespaces/1234/owners"
```
Example response:
```json
[
{
"user": {
"id": 1,
"username": "john_smith",
"name": "John Smith"
},
"access_level": 50,
"notification_email": "name@example.com"
}
]
```
#### Fetch a namespace by ID
Used to fetch information about a namespace.
```plaintext
GET /internal/gitlab_subscriptions/namespaces/:id
```
Parameters:
| Attribute | Type | Required | Description |
| --------- | -------------- | -------- | ----------- |
| `id` | integer/string | yes | ID or [URL-encoded path of the namespace](../../api/rest/_index.md#namespaced-paths) |
Example request:
```shell
curl --request GET --header "X-CUSTOMERS-DOT-INTERNAL-TOKEN: <json-web-token>" "https://gitlab.com/api/v4/internal/gitlab_subscriptions/namespaces/1"
```
Example response:
```json
{
"id": 1,
"name": "group1",
"path": "group1",
"kind": "group",
"full_path": "group1",
"parent_id": null,
"avatar_url": null,
"web_url": "https://gitlab.example.com/groups/group1",
"members_count_with_descendants": 2,
"billable_members_count": 2,
"max_seats_used": 0,
"seats_in_use": 0,
"plan": "default",
"end_date": null,
"trial_ends_on": null,
"trial": false,
"root_repository_size": 100,
"projects_count": 3
}
```
#### Update a namespace
Use a PUT command to update an existing namespace.
```plaintext
PUT /internal/gitlab_subscriptions/namespaces/:id
```
Parameters:
| Attribute | Type | Required | Description |
| --------- | -------------- | -------- | ----------- |
| `id` | integer/string | yes | ID or [URL-encoded path of the namespace](../../api/rest/_index.md#namespaced-paths) |
| `shared_runners_minutes_limit` | integer | no | Compute minutes quota |
| `extra_shared_runners_minutes_limit` | integer | no | Extra compute minutes |
| `additional_purchased_storage_size` | integer | no | Additional storage size |
| `additional_purchased_storage_ends_on` | date | no | Additional purchased storage Ends on |
| `gitlab_subscription_attributes` | hash | no | Hash object containing GitLab Subscription attributes. Accepts `seats`,`max_seats_used`,`plan_code`,`end_date`,`auto_renew`,`trial`,`trial_ends_on`,`trial_starts_on`,`trial_extension_type` |
Example request:
```shell
curl --request PUT --header "X-CUSTOMERS-DOT-INTERNAL-TOKEN: <json-web-token>" "https://gitlab.com/api/v4/internal/gitlab_subscriptions/namespaces/1 --data '{"shared_runners_minutes_limit":1000}'"
```
Example response:
```json
{
"id": 1,
"name": "group1",
"path": "group1",
"kind": "group",
"full_path": "group1",
"parent_id": null,
"avatar_url": null,
"web_url": "https://gitlab.example.com/groups/group1",
"members_count_with_descendants": 2,
"billable_members_count": 2,
"max_seats_used": 0,
"seats_in_use": 0,
"plan": "default",
"end_date": null,
"trial_ends_on": null,
"trial": false,
"root_repository_size": 100,
"projects_count": 3
}
```
#### Provision a namespace
Use to provision subscription related resources for a root namespace. This includes base product, storage, compute minutes, and add-on purchases.
The endpoint processes resources independently - if one resource fails to provision, others continue to be provisioned.
You can provision one or more resources in a single request based on the parameters provided.
```plaintext
POST /internal/gitlab_subscriptions/namespaces/:id/provision
```
Parameters:
| Attribute | Type | Required | Description |
| :------------ | :-------- | :--------- | :------------ |
| `id` | integer | yes | ID of the namespace to provision |
The endpoint supports parameters for each resource nested under the `provision` root key:
| Attribute | Type | Required | Description |
| :------------ | :-------- | :--------- | :------------ |
| `base_product` | hash | no | Hash object containing GitLab Subscription attributes |
| `storage` | hash | no | Hash object containing Storage attributes |
| `compute_minutes` | hash | no | Hash object containing Compute Minutes attributes |
| `add_on_purchases` | hash | no | Hash object containing Add-on Purchases attributes |
Base product supported attributes:
| Attribute | Type | Required | Description |
| :------------ | :-------- | :--------- | :------------ |
| `plan_code` | string | no | Subscription tier code |
| `start_date` | date | no | Start date of subscription |
| `end_date` | date | no | End date of subscription |
| `seats` | integer | no | Number of seats in subscription |
| `max_seats_used` | integer | no | Highest number of billable users in the current subscription term |
| `auto_renew` | boolean | no | Whether subscription auto-renews on end date |
| `trial` | boolean | no | Whether subscription is a trial |
| `trial_starts_on` | date | no | Start date of trial. Required if trial is true |
| `trial_ends_on` | date | no | End date of trial |
Storage supported attributes:
| Attribute | Type | Required | Description |
| :------------ | :-------- | :--------- | :------------ |
| `additional_purchased_storage_size` | integer | no | Additional storage size |
| `additional_purchased_storage_ends_on` | date | no | Additional purchased storage ends on |
Compute Minutes supported attributes:
| Attribute | Type | Required | Description |
| :------------ | :-------- | :--------- | :------------ |
| `shared_runners_minutes_limit` | integer | no | Compute minutes quota |
| `extra_shared_runners_minutes_limit` | integer | no | Extra compute minutes |
Add-on Purchases Supported attributes:
| Attribute | Type | Required | Description |
| :------------ | :-------- | :--------- | :------------ |
| `quantity` | integer | No | Amount of units in the subscription add-on purchase. Must be a non-negative integer. (Example: Number of seats for Duo Pro add-on) |
| `started_on` | date | Yes | Date the subscription add-on purchase became available |
| `expires_on` | date | Yes | Expiration date of the subscription add-on purchase |
| `purchase_xid` | string | No | Identifier for the subscription add-on purchase (Example: Subscription name for a Duo Pro add-on) |
| `trial` | boolean | No | Whether the add-on is a trial |
Example request:
```shell
curl --request POST --header "X-CUSTOMERS-DOT-INTERNAL-TOKEN: <json-web-token>" "https://gitlab.com/api/v4/internal/gitlab_subscriptions/namespaces/1/provision" \
--data '{
"provision": {
"base_product": {
"plan_code": "ultimate",
"seats": 30,
"start_date": "2024-01-01",
"end_date": "2025-01-01",
"max_seats_used": 10,
"auto_renew": true,
"trial": false,
"trial_starts_on": null,
"trial_ends_on": null
},
"storage": {
"additional_purchased_storage_size": 100,
"additional_purchased_storage_ends_on": "2025-01-01"
},
"compute_minutes": {
"extra_shared_runners_minutes_limit": 90,
"shared_runners_minutes_limit": 100
},
"add_on_purchases": {
"duo_enterprise": [{
"started_on": "2024-01-01",
"expires_on": "2025-01-01",
"purchase_xid": "A-S00001",
"quantity": 1,
"trial": false
}]
}
}
}'
```
Response Status Codes:
- 200 OK - Namespace provisioned successfully (empty response)
- 400 Bad Request - Invalid parameters or non-root namespace
- 401 Unauthorized - Invalid token
- 404 Not Found - Namespace doesn't exist
- 422 Unprocessable Entity - Validation errors during provisioning
### Subscriptions
The subscription endpoints are used by
[CustomersDot](https://gitlab.com/gitlab-org/customers-gitlab-com) (`customers.gitlab.com`) to
apply subscriptions (including trials, and add-on purchases) to personal namespaces, or top-level
groups on GitLab.com.
#### Fetch a subscription
Use a GET command to view an existing subscription.
```plaintext
GET /internal/gitlab_subscriptions/namespaces/:id/gitlab_subscription
```
Example request:
```shell
curl --header "X-CUSTOMERS-DOT-INTERNAL-TOKEN: <json-web-token>" "https://gitlab.com/api/v4/internal/gitlab_subscriptions/namespaces/1234/gitlab_subscription"
```
Example response:
```json
{
"plan": {
"code": "premium",
"name": "premium",
"trial": false,
"auto_renew": null,
"upgradable": false,
"exclude_guests": false
},
"usage": {
"seats_in_subscription": 80,
"seats_in_use": 82,
"max_seats_used": 82,
"seats_owed": 2
},
"billing": {
"subscription_start_date": "2020-07-15",
"subscription_end_date": "2021-07-15",
"trial_ends_on": null
}
}
```
#### Create a subscription
Use a POST command to create a subscription.
```plaintext
POST /internal/gitlab_subscriptions/namespaces/:id/gitlab_subscription
```
| Attribute | Type | Required | Description |
|:------------|:--------|:---------|:------------|
| `start_date` | date | yes | Start date of subscription |
| `end_date` | date | no | End date of subscription |
| `plan_code` | string | no | Subscription tier code |
| `seats` | integer | no | Number of seats in subscription |
| `max_seats_used` | integer | no | Highest number of billable users in the current subscription term |
| `auto_renew` | boolean | no | Whether subscription auto-renews on end date |
| `trial` | boolean | no | Whether subscription is a trial |
| `trial_starts_on` | date | no | Start date of trial |
| `trial_ends_on` | date | no | End date of trial |
Example request:
```shell
curl --request POST --header "X-CUSTOMERS-DOT-INTERNAL-TOKEN: <json-web-token>" "https://gitlab.com/api/v4/internal/gitlab_subscriptions/namespaces/1234/gitlab_subscription?start_date="2020-07-15"&plan="premium"&seats=10"
```
Example response:
```json
{
"plan": {
"code":"premium",
"name":"premium",
"trial":false,
"auto_renew":null,
"upgradable":false
},
"usage": {
"seats_in_subscription":10,
"seats_in_use":1,
"max_seats_used":0,
"seats_owed":0
},
"billing": {
"subscription_start_date":"2020-07-15",
"subscription_end_date":null,
"trial_ends_on":null
}
}
```
#### Update a subscription
Use a PUT command to update an existing subscription.
```plaintext
PUT /internal/gitlab_subscriptions/namespaces/:id/gitlab_subscription
```
| Attribute | Type | Required | Description |
|:------------|:--------|:---------|:------------|
| `start_date` | date | no | Start date of subscription |
| `end_date` | date | no | End date of subscription |
| `plan_code` | string | no | Subscription tier code |
| `seats` | integer | no | Number of seats in subscription |
| `max_seats_used` | integer | no | Highest number of billable users in the current subscription term |
| `auto_renew` | boolean | no | Whether subscription auto-renews on end date |
| `trial` | boolean | no | Whether subscription is a trial |
| `trial_starts_on` | date | no | Start date of trial. Required if trial is true. |
| `trial_ends_on` | date | no | End date of trial |
Example request:
```shell
curl --request PUT --header "X-CUSTOMERS-DOT-INTERNAL-TOKEN: <json-web-token>" "https://gitlab.com/api/v4/internal/gitlab_subscriptions/namespaces/1234/gitlab_subscription?max_seats_used=0"
```
Example response:
```json
{
"plan": {
"code":"premium",
"name":"premium",
"trial":false,
"auto_renew":null,
"upgradable":false
},
"usage": {
"seats_in_subscription":80,
"seats_in_use":82,
"max_seats_used":0,
"seats_owed":2
},
"billing": {
"subscription_start_date":"2020-07-15",
"subscription_end_date":"2021-07-15",
"trial_ends_on":null
}
}
```
### Upcoming Reconciliations
The `upcoming_reconciliations` endpoint is used by [CustomersDot](https://gitlab.com/gitlab-org/customers-gitlab-com) (`customers.gitlab.com`)
to update upcoming reconciliations for namespaces.
#### Update an upcoming reconciliation
```plaintext
PUT /internal/gitlab_subscriptions/namespaces/:namespace_id/upcoming_reconciliations
```
| Attribute | Type | Required | Description |
|:---------------------------|:-----|:---------|:--------------------------------------------------------|
| `namespace_id` | ID | yes | ID of the namespace with the upcoming reconciliation |
| `next_reconciliation_date` | date | yes | Date the reconciliation will occur on |
| `display_alert_from` | date | yes | Date to start display the upcoming reconciliation alert |
Example request:
```shell
curl --request PUT --header "X-CUSTOMERS-DOT-INTERNAL-TOKEN: <json-web-token>" --header "Content-Type: application/json" \
--data '{"upcoming_reconciliations": [{"next_reconciliation_date": "12 Jun 2021", "display_alert_from": "05 Jun 2021"}]}' \
"https://gitlab.com/api/v4/internal/gitlab_subscriptions/129/upcoming_reconciliations"
```
Example response:
```plaintext
200
```
#### Delete an upcoming reconciliation
Use a DELETE command to delete an `upcoming_reconciliation`.
```plaintext
DELETE /internal/gitlab_subscriptions/namespaces/:namespace_id/upcoming_reconciliations
```
Example request:
```shell
curl --request DELETE \
--url "http://localhost:3000/api/v4/internal/gitlab_subscriptions/namespaces/22/upcoming_reconciliations" \
--header "X-CUSTOMERS-DOT-INTERNAL-TOKEN: <json-web-token>"
```
Example response:
```plaintext
204
```
### Users
#### Retrieve a user
Use a GET command to get the User object based on user ID.
```plaintext
GET /internal/gitlab_subscriptions/users/:id
```
Example request:
```shell
curl --header "X-CUSTOMERS-DOT-INTERNAL-TOKEN: <json-web-token>" "https://gitlab.com/api/v4/internal/gitlab_subscriptions/users/:id"
```
Example response:
```json
{
"id": 1,
"username": "john_smith",
"name": "John Smith",
"web_url": "http://localhost:3000/john_smith"
}
```
#### Fetch user permissions in a namespace
Use a GET command to fetch the permissions a user has in a namespace.
```plaintext
GET /internal/gitlab_subscriptions/namespaces/:namespace_id/user_permissions/:user_id
```
Example request:
```shell
curl --header "X-CUSTOMERS-DOT-INTERNAL-TOKEN: <json-web-token>" "https://gitlab.com/api/v4/internal/gitlab_subscriptions/namespaces/:namespace_id/user_permissions/:user_id"
```
Example response:
```json
{
"edit_billing": true
}
```
#### Update credit card validation
Use a PUT command to update the User's credit card validation
```plaintext
PUT /internal/gitlab_subscriptions/users/:user_id/credit_card_validation
```
Example request:
```shell
curl --request PUT --header "X-CUSTOMERS-DOT-INTERNAL-TOKEN: <json-web-token>" \
--data '{"credit_card_validated_at": "2020-01-01 00:00:00 UTC", "credit_card_expiration_year": "2010", "credit_card_expiration_month": "12", "credit_card_holder_name": "John Smith", "credit_card_type": "American Express", "credit_card_mask_number": "1111", "zuora_payment_method_xid": "abc123", "stripe_setup_intent_xid": "seti_abc123", "stripe_payment_method_xid": "pm_abc123", "stripe_card_fingerprint": "card123"}' \
"https://gitlab.com/api/v4/internal/gitlab_subscriptions/users/:user_id/credit_card_validation"
```
Example response:
```json
{
"success": {}
}
```
### Add-On Purchases
This API is used by CustomersDot to manage add-on purchases, excluding Compute Minutes
and Storage packs.
#### Create multiple subscription add-on purchases (Internal)
Use a POST command to create, update, and deprovision multiple subscription add-on purchases. Possible add-on types are `duo_pro`, `duo_enterprise`, and `product_analytics`.
```plaintext
POST /internal/gitlab_subscriptions/namespaces/:id/subscription_add_on_purchases
```
Supported attributes:
| Attribute | Type | Required | Description |
|:------------|:--------|:---------|:------------|
| `quantity` | integer | No | Amount of units in the subscription add-on purchase. Must be a non-negative integer. (Example: Number of seats for Duo Pro add-on) |
| `started_on` | date | Yes | Date the subscription add-on purchase became available |
| `expires_on` | date | Yes | Expiration date of the subscription add-on purchase |
| `purchase_xid` | string | No | Identifier for the subscription add-on purchase (Example: Subscription name for a Code Suggestions add-on) |
| `trial` | boolean | No | Whether the add-on is a trial |
If successful, returns [`201`](../../api/rest/troubleshooting.md#status-codes) and the following response attributes:
| Attribute | Type | Description |
|:----------------|:--------|:------------|
| `namespace_id` | integer | Unique identifier for the namespace associated with the purchase |
| `namespace_name`| string | Name of the namespace linked to the purchase |
| `add_on` | integer | Type of add-on related to the purchase. Possible add-on types are `Code Suggestions` alias Duo Pro, `Duo Enterprise` and `Product Analytics` |
| `quantity` | integer | Number of units purchased for the subscription add-on |
| `started_on` | date | Date the subscription add-on became active |
| `expires_on` | date | Date the subscription add-on will expire |
| `purchase_xid` | string | Unique identifier for the subscription add-on purchase |
| `trial` | boolean | Indicates whether the add-on is part of a trial |
Example request for create/update:
```shell
curl --request POST \
--header --header "X-CUSTOMERS-DOT-INTERNAL-TOKEN: <json-web-token>" \
--header "Content-Type: application/json" \
--data '{ "add_on_purchases": { "duo_pro": [{ "quantity": 1, "started_on": "<YYYY-MM-DD>", "expires_on": "<YYYY-MM-DD>", "purchase_xid": "C-00123456", "trial": false }] } }' \
"https://gitlab.com/api/v4/internal/gitlab_subscriptions/namespaces/1234/subscription_add_on_purchases"
```
Example request for deprovision:
```shell
curl --request POST \
--header --header "X-CUSTOMERS-DOT-INTERNAL-TOKEN: <json-web-token>" \
--header "Content-Type: application/json" \
--data '{ "add_on_purchases": { "duo_pro": [{ "started_on": "<YYYY-MM-DD>", "expires_on": "<YYYY-MM-DD>" }] } }' \
"https://gitlab.com/api/v4/internal/gitlab_subscriptions/namespaces/1234/subscription_add_on_purchases"
```
The dates should reflect the day prior to the request (that is, yesterday).
Example response:
```json
[
{
"namespace_id": 1234,
"namespace_name": "namespace-name",
"add_on": "Code Suggestions",
"quantity": 1,
"started_on": "2024-01-01",
"expires_on": "2024-12-31",
"purchase_xid": "C-00123456",
"trial": false
}
]
```
#### Fetch a subscription add-on purchases
Use a GET command to view an existing subscription add-on purchase.
```plaintext
GET /internal/gitlab_subscriptions/namespaces/:id/subscription_add_on_purchases/:add_on_name
```
Example request:
```shell
curl --header "X-CUSTOMERS-DOT-INTERNAL-TOKEN: <json-web-token>" "https://gitlab.com/api/v4/internal/gitlab_subscriptions/namespaces/1234/subscription_add_on_purchases/code_suggestions"
```
Example response:
```json
{
"namespace_id":1234,
"namespace_name":"A Namespace Name",
"add_on":"Code Suggestions",
"quantity":15,
"started_on":"2024-06-15",
"expires_on":"2024-07-15",
"purchase_xid":"C-00123456",
"trial":true
}
```
### Compute Minutes provisioning
The compute minutes endpoints are used by [CustomersDot](https://gitlab.com/gitlab-org/customers-gitlab-com) (`customers.gitlab.com`)
to apply additional packs of compute minutes, for personal namespaces or top-level groups in GitLab.com.
#### Create an additional pack
Use a POST command to create additional packs.
```plaintext
POST /internal/gitlab_subscriptions/namespaces/:id/minutes
```
| Attribute | Type | Required | Description |
|:------------|:--------|:---------|:------------|
| `packs` | array | yes | An array of purchased compute packs |
| `packs[expires_at]` | date | yes | Expiry date of the purchased pack|
| `packs[number_of_minutes]` | integer | yes | Number of additional compute minutes |
| `packs[purchase_xid]` | string | yes | The unique ID of the purchase |
Example request:
```shell
curl --request POST \
--url "http://localhost:3000/api/v4/internal/gitlab_subscriptions/namespaces/123/minutes" \
--header 'Content-Type: application/json' \
--header 'X-CUSTOMERS-DOT-INTERNAL-TOKEN: <json-web-token>' \
--data '{
"packs": [
{
"number_of_minutes": 10000,
"expires_at": "2022-01-01",
"purchase_xid": "C-00123456"
}
]
}'
```
Example response:
```json
[
{
"namespace_id": 123,
"expires_at": "2022-01-01",
"number_of_minutes": 10000,
"purchase_xid": "C-00123456"
}
]
```
#### Move additional packs
Use a `PATCH` command to move additional packs from one namespace to another.
```plaintext
PATCH /internal/gitlab_subscriptions/namespaces/:id/minutes/move/:target_id
```
| Attribute | Type | Required | Description |
|:------------|:--------|:---------|:------------|
| `id` | string | yes | The ID of the namespace to transfer packs from |
| `target_id` | string | yes | The ID of the target namespace to transfer the packs to |
Example request:
```shell
curl --request PATCH \
--url "http://localhost:3000/api/v4/internal/gitlab_subscriptions/namespaces/123/minutes/move/321" \
--header "X-CUSTOMERS-DOT-INTERNAL-TOKEN: <json-web-token>"
```
Example response:
```json
{
"message": "202 Accepted"
}
```
## Deprecated Endpoints
These endpoints have been [migrated to internal endpoints](https://gitlab.com/gitlab-org/gitlab/-/issues/463741). Now, they are
deprecated and will be [removed in a future milestone](https://gitlab.com/gitlab-org/gitlab/-/issues/473625).
### Add-On Purchases (deprecated)
This API is used by CustomersDot to manage add-on purchases, excluding Compute Minutes
and Storage packs.
#### Create a subscription add-on purchase (deprecated)
Use a POST command to create a subscription add-on purchase.
```plaintext
POST /namespaces/:id/subscription_add_on_purchase/:add_on_name
```
| Attribute | Type | Required | Description |
|:------------|:--------|:---------|:------------|
| `quantity` | integer | yes | Amount of units in the subscription add-on purchase (Example: Number of seats for a Code Suggestions add-on) |
| `started_on` | date | yes | Date the subscription add-on purchase became available |
| `expires_on` | date | yes | Expiration date of the subscription add-on purchase |
| `purchase_xid` | string | yes | Identifier for the subscription add-on purchase (Example: Subscription name for a Code Suggestions add-on) |
| `trial` | boolean | no | Whether the add-on is a trial |
Example request:
```shell
curl --request POST --header "X-CUSTOMERS-DOT-INTERNAL-TOKEN: <json-web-token>" "https://gitlab.com/api/v4/namespaces/1234/subscription_add_on_purchase/code_suggestions?&quantity=10&started_on="2024-06-15"&expires_on="2024-07-15"&purchase_xid="C-00123456"&trial=true"
```
Example response:
```json
{
"namespace_id":1234,
"namespace_name":"A Namespace Name",
"add_on":"Code Suggestions",
"quantity":10,
"started_on":"2024-06-15",
"expires_on":"2024-07-15",
"purchase_xid":"C-00123456",
"trial":true
}
```
#### Update a subscription add-on purchase (deprecated)
Use a PUT command to update an existing subscription add-on purchase.
```plaintext
PUT /namespaces/:id/subscription_add_on_purchase/:add_on_name
```
| Attribute | Type | Required | Description |
|:------------|:--------|:---------|:------------|
| `quantity` | integer | no | Amount of units in the subscription add-on purchase (Example: Number of seats for a Code Suggestions add-on) |
| `started_on` | date | yes | Date the subscription add-on purchase became available |
| `expires_on` | date | yes | Expiration date of the subscription add-on purchase |
| `purchase_xid` | string | no | Identifier for the subscription add-on purchase (Example: Subscription name for a Code Suggestions add-on) |
| `trial` | boolean | no | Whether the add-on is a trial |
Example request:
```shell
curl --request PUT --header "X-CUSTOMERS-DOT-INTERNAL-TOKEN: <json-web-token>" "https://gitlab.com/api/v4/namespaces/1234/subscription_add_on_purchase/code_suggestions?&quantity=15&started_on="2024-06-15"&expires_on="2024-07-15"&purchase_xid="C-00123456"&trial=true"
```
Example response:
```json
{
"namespace_id":1234,
"namespace_name":"A Namespace Name",
"add_on":"Code Suggestions",
"quantity":15,
"started_on":"2024-06-15",
"expires_on":"2024-07-15",
"purchase_xid":"C-00123456",
"trial":true
}
```
#### Fetch a subscription add-on purchases (deprecated)
Use a GET command to view an existing subscription add-on purchase.
```plaintext
GET /namespaces/:id/subscription_add_on_purchase/:add_on_name
```
Example request:
```shell
curl --header "X-CUSTOMERS-DOT-INTERNAL-TOKEN: <json-web-token>" "https://gitlab.com/api/v4/namespaces/1234/subscription_add_on_purchase/code_suggestions"
```
Example response:
```json
{
"namespace_id":1234,
"namespace_name":"A Namespace Name",
"add_on":"Code Suggestions",
"quantity":15,
"started_on":"2024-06-15",
"expires_on":"2024-07-15",
"purchase_xid":"C-00123456",
"trial":true
}
```
### Compute quota provisioning (deprecated)
{{< history >}}
- [Renamed](https://gitlab.com/groups/gitlab-com/-/epics/2150) from "CI/CD minutes" to "compute quota" and "compute minutes" in GitLab 16.1.
{{< /history >}}
The compute quota endpoints are used by [CustomersDot](https://gitlab.com/gitlab-org/customers-gitlab-com) (`customers.gitlab.com`)
to apply additional packs of compute minutes, for personal namespaces or top-level groups in GitLab.com.
#### Create an additional pack (deprecated)
Use a POST command to create additional packs.
```plaintext
POST /namespaces/:id/minutes
```
| Attribute | Type | Required | Description |
|:------------|:--------|:---------|:------------|
| `packs` | array | yes | An array of purchased compute packs |
| `packs[expires_at]` | date | yes | Expiry date of the purchased pack|
| `packs[number_of_minutes]` | integer | yes | Number of additional compute minutes |
| `packs[purchase_xid]` | string | yes | The unique ID of the purchase |
Example request:
```shell
curl --request POST \
--url "http://localhost:3000/api/v4/namespaces/123/minutes" \
--header 'Content-Type: application/json' \
--header 'X-CUSTOMERS-DOT-INTERNAL-TOKEN: <json-web-token>' \
--data '{
"packs": [
{
"number_of_minutes": 10000,
"expires_at": "2022-01-01",
"purchase_xid": "C-00123456"
}
]
}'
```
Example response:
```json
[
{
"namespace_id": 123,
"expires_at": "2022-01-01",
"number_of_minutes": 10000,
"purchase_xid": "C-00123456"
}
]
```
#### Move additional packs (deprecated)
Use a `PATCH` command to move additional packs from one namespace to another.
```plaintext
PATCH /namespaces/:id/minutes/move/:target_id
```
| Attribute | Type | Required | Description |
|:------------|:--------|:---------|:------------|
| `id` | string | yes | The ID of the namespace to transfer packs from |
| `target_id` | string | yes | The ID of the target namespace to transfer the packs to |
Example request:
```shell
curl --request PATCH \
--url "http://localhost:3000/api/v4/namespaces/123/minutes/move/321" \
--header "X-CUSTOMERS-DOT-INTERNAL-TOKEN: <json-web-token>"
```
Example response:
```json
{
"message": "202 Accepted"
}
```
### Subscriptions (deprecated)
The subscription endpoints are used by
[CustomersDot](https://gitlab.com/gitlab-org/customers-gitlab-com) (`customers.gitlab.com`) to
apply subscriptions (including trials) to personal namespaces, or top-level groups on GitLab.com.
#### Create a subscription (deprecated)
Use a POST command to create a subscription.
```plaintext
POST /namespaces/:id/gitlab_subscription
```
| Attribute | Type | Required | Description |
|:------------|:--------|:---------|:------------|
| `start_date` | date | yes | Start date of subscription |
| `end_date` | date | no | End date of subscription |
| `plan_code` | string | no | Subscription tier code |
| `seats` | integer | no | Number of seats in subscription |
| `max_seats_used` | integer | no | Highest number of active users in the last month |
| `auto_renew` | boolean | no | Whether subscription auto-renews on end date |
| `trial` | boolean | no | Whether subscription is a trial |
| `trial_starts_on` | date | no | Start date of trial |
| `trial_ends_on` | date | no | End date of trial |
Example request:
```shell
curl --request POST --header "X-CUSTOMERS-DOT-INTERNAL-TOKEN: <json-web-token>" "https://gitlab.com/api/v4/namespaces/1234/gitlab_subscription?start_date="2020-07-15"&plan="premium"&seats=10"
```
Example response:
```json
{
"plan": {
"code":"premium",
"name":"premium",
"trial":false,
"auto_renew":null,
"upgradable":false
},
"usage": {
"seats_in_subscription":10,
"seats_in_use":1,
"max_seats_used":0,
"seats_owed":0
},
"billing": {
"subscription_start_date":"2020-07-15",
"subscription_end_date":null,
"trial_ends_on":null
}
}
```
#### Update a subscription (deprecated)
Use a PUT command to update an existing subscription.
```plaintext
PUT /namespaces/:id/gitlab_subscription
```
| Attribute | Type | Required | Description |
|:------------|:--------|:---------|:------------|
| `start_date` | date | no | Start date of subscription |
| `end_date` | date | no | End date of subscription |
| `plan_code` | string | no | Subscription tier code |
| `seats` | integer | no | Number of seats in subscription |
| `max_seats_used` | integer | no | Highest number of active users in the last month |
| `auto_renew` | boolean | no | Whether subscription auto-renews on end date |
| `trial` | boolean | no | Whether subscription is a trial |
| `trial_starts_on` | date | no | Start date of trial. Required if trial is true. |
| `trial_ends_on` | date | no | End date of trial |
Example request:
```shell
curl --request PUT --header "X-CUSTOMERS-DOT-INTERNAL-TOKEN: <json-web-token>" "https://gitlab.com/api/v4/namespaces/1234/gitlab_subscription?max_seats_used=0"
```
Example response:
```json
{
"plan": {
"code":"premium",
"name":"premium",
"trial":false,
"auto_renew":null,
"upgradable":false
},
"usage": {
"seats_in_subscription":80,
"seats_in_use":82,
"max_seats_used":0,
"seats_owed":2
},
"billing": {
"subscription_start_date":"2020-07-15",
"subscription_end_date":"2021-07-15",
"trial_ends_on":null
}
}
```
#### Fetch a subscription (deprecated)
Use a GET command to view an existing subscription.
```plaintext
GET /namespaces/:id/gitlab_subscription
```
Example request:
```shell
curl --header "TOKEN: <admin_access_token>" "https://gitlab.com/api/v4/namespaces/1234/gitlab_subscription"
```
Example response:
```json
{
"plan": {
"code":"premium",
"name":"premium",
"trial":false,
"auto_renew":null,
"upgradable":false,
"exclude_guests":false
},
"usage": {
"seats_in_subscription":80,
"seats_in_use":82,
"max_seats_used":82,
"seats_owed":2
},
"billing": {
"subscription_start_date":"2020-07-15",
"subscription_end_date":"2021-07-15",
"trial_ends_on":null
}
}
```
|
https://docs.gitlab.com/development/internal_api_allowed
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/internal_api_allowed.md
|
2025-08-13
|
doc/development/internal_api
|
[
"doc",
"development",
"internal_api"
] |
internal_api_allowed.md
|
Create
|
Source Code
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Internal allowed API
| null |
The `internal/allowed` endpoint assesses whether a user has permission to perform
certain operations on the Git repository. It performs multiple checks, such as:
- Ensuring the branch or tag name is acceptable.
- Whether or not the user has the authority to perform that action.
## Endpoint definition
The internal API endpoints are defined under
[`lib/api/internal`](https://gitlab.com/gitlab-org/gitlab/-/tree/master/lib/api/internal),
and the `/allowed` path is in
[`lib/api/internal/base.rb`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/lib/api/internal/base.rb).
## Use the endpoint
`internal/allowed` is called when you:
- Push to the repository.
- Perform actions on the repository through the GitLab user interface, such as
applying suggestions or using the GitLab IDE.
Gitaly typically calls this endpoint. It is only called internally (by other parts
of the application) rather than by external users of the API.
## Push checks
A key part of the `internal/allowed` flow is the call to
`EE::Gitlab::Checks::PushRuleCheck`, which can perform the following checks:
- `EE::Gitlab::Checks::PushRules::CommitCheck`
- `EE::Gitlab::Checks::PushRules::TagCheck`
- `EE::Gitlab::Checks::PushRules::BranchCheck`
## Recursion
Some of the Gitaly RPCs called by `internal/allowed` then, themselves, make calls
back to `internal/allowed`. These calls are now correlated with the original request.
Gitaly relies on the Rails application for authorization, and maintains no permissions model itself.
These calls show up in the logs differently to the initial requests. {example}
Because this endpoint can be called recursively, slow performance on this endpoint can result in an exponential performance impact. This documentation is in fact adapted from [the investigation into its performance](https://gitlab.com/gitlab-org/gitlab/-/issues/222247).
## Known performance issues
### Refs
The number of [`refs`](https://git-scm.com/book/en/v2/Git-Internals-Git-References)
on the Git repository have a notable effect on the performance of `git` commands
called upon it. Gitaly RPCs are similarly affected. Certain `git` commands scan
through all refs, causing a notable impact on the speed of those commands.
On the `internal/allowed` endpoint, the recursive nature of RPC calls mean the
ref counts have an exponential effect on performance.
#### Environment refs
[Stale environment refs](https://gitlab.com/gitlab-org/gitlab/-/issues/296625)
are a common example of excessive refs causing performance issues. Stale environment
refs can number into the tens of thousands on busy repositories, as they aren't
cleared up automatically.
#### Dangling refs
Dangling refs are created to prevent accidental deletion of objects from object pools.
Large numbers of these refs can exist, which may have potential performance implications.
For existing discussion around this issue, read
[`gitaly#1900`](https://gitlab.com/gitlab-org/gitaly/-/issues/1900). This issue
appears to have less effect than stale environment refs.
### Pool repositories
When a fork is created on GitLab, a central pool repository is created and the forks
are linked to it. This pool repository prevents duplication of data by storing
data common to other forks. However, the pool repository is not cleaned up in the
same manner as the standard repositories, and is more prone to the refs issue.
## Feature flags
### Parallel push checks
{{< alert type="flag" >}}
On GitLab Self-Managed, by default this feature is not available. To make it available,
an administrator can [enable the feature flag](../../administration/feature_flags/_index.md) named `parallel_push_checks`.
On GitLab.com, by default this feature is not available. To make it available
per project, ask GitLab.com administrator to
[enable the feature flag](../../administration/feature_flags/_index.md) named `parallel_push_checks`.
You should not use this feature for production environments. On GitLab Dedicated, this feature is
not available.
{{< /alert >}}
This experimental feature flag enables the endpoint to run multiple RPCs simultaneously,
reducing the overall time taken by roughly half. This time savings is achieved through
threading, and has potential side effects at large scale. On GitLab.com, this feature flag
is enabled only for `gitlab-org/gitlab` and `gitlab-com/www-gitlab-com` projects.
Without it, those projects routinely time out requests to the endpoint. When this
feature was deployed to all of GitLab.com, some pushes failed, presumably due to
exhausting resources like database connection pools.
You should enable this feature flag only if you are experiencing timeouts, and
only enable it for that specific project.
|
---
stage: Create
group: Source Code
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Internal allowed API
breadcrumbs:
- doc
- development
- internal_api
---
The `internal/allowed` endpoint assesses whether a user has permission to perform
certain operations on the Git repository. It performs multiple checks, such as:
- Ensuring the branch or tag name is acceptable.
- Whether or not the user has the authority to perform that action.
## Endpoint definition
The internal API endpoints are defined under
[`lib/api/internal`](https://gitlab.com/gitlab-org/gitlab/-/tree/master/lib/api/internal),
and the `/allowed` path is in
[`lib/api/internal/base.rb`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/lib/api/internal/base.rb).
## Use the endpoint
`internal/allowed` is called when you:
- Push to the repository.
- Perform actions on the repository through the GitLab user interface, such as
applying suggestions or using the GitLab IDE.
Gitaly typically calls this endpoint. It is only called internally (by other parts
of the application) rather than by external users of the API.
## Push checks
A key part of the `internal/allowed` flow is the call to
`EE::Gitlab::Checks::PushRuleCheck`, which can perform the following checks:
- `EE::Gitlab::Checks::PushRules::CommitCheck`
- `EE::Gitlab::Checks::PushRules::TagCheck`
- `EE::Gitlab::Checks::PushRules::BranchCheck`
## Recursion
Some of the Gitaly RPCs called by `internal/allowed` then, themselves, make calls
back to `internal/allowed`. These calls are now correlated with the original request.
Gitaly relies on the Rails application for authorization, and maintains no permissions model itself.
These calls show up in the logs differently to the initial requests. {example}
Because this endpoint can be called recursively, slow performance on this endpoint can result in an exponential performance impact. This documentation is in fact adapted from [the investigation into its performance](https://gitlab.com/gitlab-org/gitlab/-/issues/222247).
## Known performance issues
### Refs
The number of [`refs`](https://git-scm.com/book/en/v2/Git-Internals-Git-References)
on the Git repository have a notable effect on the performance of `git` commands
called upon it. Gitaly RPCs are similarly affected. Certain `git` commands scan
through all refs, causing a notable impact on the speed of those commands.
On the `internal/allowed` endpoint, the recursive nature of RPC calls mean the
ref counts have an exponential effect on performance.
#### Environment refs
[Stale environment refs](https://gitlab.com/gitlab-org/gitlab/-/issues/296625)
are a common example of excessive refs causing performance issues. Stale environment
refs can number into the tens of thousands on busy repositories, as they aren't
cleared up automatically.
#### Dangling refs
Dangling refs are created to prevent accidental deletion of objects from object pools.
Large numbers of these refs can exist, which may have potential performance implications.
For existing discussion around this issue, read
[`gitaly#1900`](https://gitlab.com/gitlab-org/gitaly/-/issues/1900). This issue
appears to have less effect than stale environment refs.
### Pool repositories
When a fork is created on GitLab, a central pool repository is created and the forks
are linked to it. This pool repository prevents duplication of data by storing
data common to other forks. However, the pool repository is not cleaned up in the
same manner as the standard repositories, and is more prone to the refs issue.
## Feature flags
### Parallel push checks
{{< alert type="flag" >}}
On GitLab Self-Managed, by default this feature is not available. To make it available,
an administrator can [enable the feature flag](../../administration/feature_flags/_index.md) named `parallel_push_checks`.
On GitLab.com, by default this feature is not available. To make it available
per project, ask GitLab.com administrator to
[enable the feature flag](../../administration/feature_flags/_index.md) named `parallel_push_checks`.
You should not use this feature for production environments. On GitLab Dedicated, this feature is
not available.
{{< /alert >}}
This experimental feature flag enables the endpoint to run multiple RPCs simultaneously,
reducing the overall time taken by roughly half. This time savings is achieved through
threading, and has potential side effects at large scale. On GitLab.com, this feature flag
is enabled only for `gitlab-org/gitlab` and `gitlab-com/www-gitlab-com` projects.
Without it, those projects routinely time out requests to the endpoint. When this
feature was deployed to all of GitLab.com, some pushes failed, presumably due to
exhausting resources like database connection pools.
You should enable this feature flag only if you are experiencing timeouts, and
only enable it for that specific project.
|
https://docs.gitlab.com/development/internal_api
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/_index.md
|
2025-08-13
|
doc/development/internal_api
|
[
"doc",
"development",
"internal_api"
] |
_index.md
|
Create
|
Source Code
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Internal API
| null |
The internal API is used by different GitLab components, it cannot be
used by other consumers. This documentation is intended for people
working on the GitLab codebase.
This documentation does not yet include the internal API used by
GitLab Pages.
For information on the GitLab Subscriptions internal API, see [the dedicated page](gitlab_subscriptions.md).
## Add new endpoints
API endpoints should be externally accessible by default, with proper authentication and authorization.
Before adding a new internal endpoint, consider if the API would benefit the wider GitLab community and can be made externally accessible.
One reason we might favor internal API endpoints sometimes is when using such an endpoint requires
internal data that external actors cannot have. For example, in the internal Pages API we might use
a secret token that identifies a request as internal or sign a request with a public key that is
not available to a wider community.
Another reason to separate something into an internal API is when request to such API endpoint
should never go through an edge (public) load balancer. This way we can configure different rate
limiting rules and policies around how the endpoint is being accessed, because we know that only
internal requests can be made to that endpoint going through an internal load balancer.
## Authentication
These methods are all authenticated using a shared secret. This secret
is stored in a file at the path configured in `config/gitlab.yml` by
default this is in the root of the rails app named
`.gitlab_shell_secret`
To authenticate using that token, clients:
1. Read the contents of that file.
1. Use the file contents to generate a JSON Web Token (`JWT`).
1. Pass the JWT in the `Gitlab-Shell-Api-Request` header.
## Git Authentication
Called by [Gitaly](https://gitlab.com/gitlab-org/gitaly) and
[GitLab Shell](https://gitlab.com/gitlab-org/gitlab-shell) to check access to a
repository.
- When called from GitLab Shell: No changes are passed, and the internal
API replies with the information needed to pass the request on to Gitaly.
- When called from Gitaly in a `pre-receive` hook: The changes are passed
and validated to determine if the push is allowed.
Calls are limited to 50 seconds each.
This endpoint is covered in more detail on [its own page](internal_api_allowed.md), due to the scope of what it covers.
```plaintext
POST /internal/allowed
```
| Attribute | Type | Required | Description |
|:----------|:-------|:---------|:------------|
| `key_id` | string | no | ID of the SSH-key used to connect to GitLab Shell |
| `username` | string | no | Username from the certificate used to connect to GitLab Shell |
| `project` | string | no (if `gl_repository` is passed) | Path to the project |
| `gl_repository` | string | no (if `project` is passed) | Repository identifier, such as `project-7` |
| `protocol` | string | yes | SSH when called from GitLab Shell, HTTP or SSH when called from Gitaly |
| `action` | string | yes | Git command being run (`git-upload-pack`, `git-receive-pack`, `git-upload-archive`) |
| `changes` | string | yes | `<oldrev> <newrev> <refname>` when called from Gitaly, the magic string `_any` when called from GitLab Shell |
| `check_ip` | string | no | IP address from which call to GitLab Shell was made |
Example request:
```shell
curl --request POST --header "Gitlab-Shell-Api-Request: <JWT token>" \
--data "key_id=11&project=gnuwget/wget2&action=git-upload-pack&protocol=ssh" \
"http://localhost:3001/api/v4/internal/allowed"
```
Example response:
```json
{
"status": true,
"gl_repository": "project-3",
"gl_project_path": "gnuwget/wget2",
"gl_id": "user-1",
"gl_username": "root",
"git_config_options": [],
"gitaly": {
"repository": {
"storage_name": "default",
"relative_path": "@hashed/4e/07/4e07408562bedb8b60ce05c1decfe3ad16b72230967de01f640b7e4729b49fce.git",
"git_object_directory": "",
"git_alternate_object_directories": [],
"gl_repository": "project-3",
"gl_project_path": "gnuwget/wget2"
},
"address": "unix:/Users/bvl/repos/gitlab/gitaly.socket",
"token": null
},
"gl_console_messages": []
}
```
### Known consumers
- Gitaly
- GitLab Shell
## LFS Authentication
This is the endpoint that gets called from GitLab Shell to provide
information for LFS clients when the repository is accessed over SSH.
| Attribute | Type | Required | Description |
|:----------|:-------|:---------|:------------|
| `key_id` | string | no | ID of the SSH-key used to connect to GitLab Shell |
| `username`| string | no | Username from the certificate used to connect to GitLab Shell |
| `project` | string | no | Path to the project |
Example request:
```shell
curl --request POST --header "Gitlab-Shell-Api-Request: <JWT token>" \
--data "key_id=11&project=gnuwget/wget2" "http://localhost:3001/api/v4/internal/lfs_authenticate"
```
```json
{
"username": "root",
"lfs_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjp7ImFjdG9yIjoicm9vdCJ9LCJqdGkiOiIyYWJhZDcxZC0xNDFlLTQ2NGUtOTZlMi1mODllYWRiMGVmZTYiLCJpYXQiOjE1NzAxMTc2NzYsIm5iZiI6MTU3MDExNzY3MSwiZXhwIjoxNTcwMTE5NDc2fQ.g7atlBw1QMY7QEBVPE0LZ8ZlKtaRzaMRmNn41r2YITM",
"repository_http_path": "http://localhost:3001/gnuwget/wget2.git",
"expires_in": 1800
}
```
### Known consumers
- GitLab Shell
## Authorized Keys Check
This endpoint is called by the GitLab Shell authorized keys
check. Which is called by OpenSSH or GitLab SSHD for
[fast SSH key lookup](../../administration/operations/fast_ssh_key_lookup.md).
| Attribute | Type | Required | Description |
|:----------|:-------|:---------|:------------|
| `key` | string | yes | An authorized key used for public key authentication. |
```plaintext
GET /internal/authorized_keys
```
Example request:
```shell
curl --request GET --header "Gitlab-Shell-Api-Request: <JWT token>" "http://localhost:3001/api/v4/internal/authorized_keys?key=<key>"
```
Example response:
```json
{
"id": 11,
"title": "admin@example.com",
"key": "ssh-rsa ...",
"created_at": "2019-06-27T15:29:02.219Z"
}
```
### Known consumers
- GitLab Shell
## Authorized Certs
This endpoint is called by the GitLab Shell to get the namespace that has a particular CA SSH certificate
configured. It also accepts `user_identifier` to return a GitLab user for specified identifier.
| Attribute | Type | Required | Description |
|:----------------------|:-------|:---------|:------------|
| `key` | string | yes | The fingerprint of the SSH certificate. |
| `user_identifier` | string | yes | The identifier of the user to whom the SSH certificate has been issued (username or primary email). |
```plaintext
GET /internal/authorized_certs
```
Example request:
```shell
curl --request GET --header "Gitlab-Shell-Api-Request: <JWT token>" "http://localhost:3001/api/v4/internal/authorized_certs?key=<key>&user_identifier=<user_identifier>"
```
Example response:
```json
{
"success": true,
"namespace": "gitlab-org",
"username": "root"
}
```
### Known consumers
- GitLab Shell
## Get user for user ID or key
This endpoint is used when a user performs `ssh git@gitlab.com`. It
discovers the user associated with an SSH key.
| Attribute | Type | Required | Description |
|:----------|:-------|:---------|:------------|
| `key_id` | integer | no | The ID of the SSH key used as found in the authorized-keys file or through the `/authorized_keys` check |
| `username` | string | no | Username of the user being looked up, used by GitLab Shell when authenticating using a certificate |
```plaintext
GET /internal/discover
```
Example request:
```shell
curl --request GET --header "Gitlab-Shell-Api-Request: <JWT token>" "http://localhost:3001/api/v4/internal/discover?key_id=7"
```
Example response:
```json
{
"id": 7,
"name": "Dede Eichmann",
"username": "rubi"
}
```
### Known consumers
- GitLab Shell
## Instance information
This gets some generic information about the instance. It's used
by Geo nodes to get information about each other.
```plaintext
GET /internal/check
```
Example request:
```shell
curl --request GET --header "Gitlab-Shell-Api-Request: <JWT token>" "http://localhost:3001/api/v4/internal/check"
```
Example response:
```json
{
"api_version": "v4",
"gitlab_version": "12.3.0-pre",
"gitlab_rev": "d69c988e6a6",
"redis": true
}
```
### Known consumers
- GitLab Geo
- GitLab Shell's `bin/check`
- Gitaly
## Get new 2FA recovery codes using an SSH key
This is called from GitLab Shell and allows users to get new 2FA
recovery codes based on their SSH key.
| Attribute | Type | Required | Description |
|:----------|:-------|:---------|:------------|
| `key_id` | integer | no | The ID of the SSH key used as found in the authorized-keys file or through the `/authorized_keys` check |
| `user_id` | integer | no | Deprecated. User ID for which to generate new recovery codes |
```plaintext
GET /internal/two_factor_recovery_codes
```
Example request:
```shell
curl --request POST --header "Gitlab-Shell-Api-Request: <JWT token>" \
--data "key_id=7" "http://localhost:3001/api/v4/internal/two_factor_recovery_codes"
```
Example response:
```json
{
"success": true,
"recovery_codes": [
"d93ee7037944afd5",
"19d7b84862de93dd",
"1e8c52169195bf71",
"be50444dddb7ca84",
"26048c77d161d5b7",
"482d5c03d1628c47",
"d2c695e309ce7679",
"dfb4748afc4f12a7",
"0e5f53d1399d7979",
"af04d5622153b020"
]
}
```
### Known consumers
- GitLab Shell
## Get new personal access-token
Called from GitLab Shell and allows users to generate a new
personal access token.
| Attribute | Type | Required | Description |
|:----------|:-------|:---------|:------------|
| `name` | string | yes | The name of the new token |
| `scopes` | string array | yes | The authorization scopes for the new token, these must be valid token scopes |
| `expires_at` | string | no | Expiration date of the access token in ISO format (`YYYY-MM-DD`). |
| `key_id` | integer | no | The ID of the SSH key used as found in the authorized-keys file or through the `/authorized_keys` check |
| `user_id` | integer | no | User ID for which to generate the new token |
```plaintext
POST /internal/personal_access_token
```
Example request:
```shell
curl --request POST --header "Gitlab-Shell-Api-Request: <JWT token>" \
--data "user_id=29&name=mytokenname&scopes[]=read_user&scopes[]=read_repository&expires_at=2020-07-24" \
"http://localhost:3001/api/v4/internal/personal_access_token"
```
Example response:
```json
{
"success": true,
"token": "Hf_79B288hRv_3-TSD1R",
"scopes": ["read_user","read_repository"],
"expires_at": "2020-07-24"
}
```
### Known consumers
- GitLab Shell
## Authenticate Error Tracking requests
This endpoint is called by the error tracking Go REST API application to authenticate a project.
| Attribute | Type | Required | Description |
|:-------------|:--------|:---------|:-------------------------------------------------------------------|
| `project_id` | integer | yes | The ID of the project which has the associated key. |
| `public_key` | string | yes | The [public key](../../api/error_tracking.md#create-a-client-key) generated by the integrated Error Tracking feature. |
```plaintext
POST /internal/error_tracking/allowed
```
Example request:
```shell
curl --request POST --header "Gitlab-Shell-Api-Request: <JWT token>" \
--data "project_id=111&public_key=generated-error-tracking-key" \
"http://localhost:3001/api/v4/internal/error_tracking/allowed"
```
Example response:
```json
{ "enabled": true }
```
### Known consumers
- OpsTrace
## Incrementing counter on pre-receive
This is called from the Gitaly hooks increasing the reference counter
for a push that might be accepted.
| Attribute | Type | Required | Description |
|:----------|:-------|:---------|:------------|
| `gl_repository` | string | yes | repository identifier for the repository receiving the push |
```plaintext
POST /internal/pre_receive
```
Example request:
```shell
curl --request POST --header "Gitlab-Shell-Api-Request: <JWT token>" \
--data "gl_repository=project-7" "http://localhost:3001/api/v4/internal/pre_receive"
```
Example response:
```json
{
"reference_counter_increased": true
}
```
## PostReceive
Called from Gitaly after a receiving a push. This triggers the
`PostReceive`-worker in Sidekiq, processes the passed push options and
builds the response including messages that need to be displayed to
the user.
| Attribute | Type | Required | Description |
|:----------|:-------|:---------|:------------|
| `identifier` | string | yes | `user-[id]` or `key-[id]` Identifying the user performing the push |
| `gl_repository` | string | yes | identifier of the repository being pushed to |
| `push_options` | string array | no | array of push options |
| `changes` | string | no | refs to be updated in the push in the format `oldrev newrev refname\n`. |
```plaintext
POST /internal/post_receive
```
Example Request:
```shell
curl --request POST --header "Gitlab-Shell-Api-Request: <JWT token>" \
--data "gl_repository=project-7" --data "identifier=user-1" \
--data "changes=0000000000000000000000000000000000000000 fd9e76b9136bdd9fe217061b497745792fe5a5ee gh-pages\n" \
"http://localhost:3001/api/v4/internal/post_receive"
```
Example response:
```json
{
"messages": [
{
"message": "Hello from post-receive",
"type": "alert"
}
],
"reference_counter_decreased": true
}
```
## GitLab agent for Kubernetes endpoints
{{< history >}}
- [Feature flag removed](https://gitlab.com/gitlab-org/gitlab/-/issues/432773) in GitLab 16.7.
{{< /history >}}
The following endpoints are used by the GitLab agent server for Kubernetes (`kas`)
for various purposes.
These endpoints are all authenticated using JWT. The JWT secret is stored in a file
specified in `config/gitlab.yml`. By default, the location is in the root of the
GitLab Rails app in a file called `.gitlab_kas_secret`.
### GitLab agent for Kubernetes information
Called from the GitLab agent server for Kubernetes (`kas`) to retrieve agent
information for the given agent token. This returns the Gitaly connection
information for the agent's project in order for `kas` to fetch and update
the agent's configuration.
```plaintext
GET /internal/kubernetes/agent_info
```
Example Request:
```shell
curl --request GET --header "Gitlab-Kas-Api-Request: <JWT token>" \
--header "Authorization: Bearer <agent token>" "http://localhost:3000/api/v4/internal/kubernetes/agent_info"
```
### GitLab agent for Kubernetes project information
Called from the GitLab agent server for Kubernetes (`kas`) to retrieve project
information for the given agent token. This returns the Gitaly
connection for the requested project. GitLab `kas` uses this to configure
the agent to fetch Kubernetes resources from the project repository to
sync.
Only public projects are supported. For private projects, the ability for the
agent to be authorized is [not yet implemented](https://gitlab.com/gitlab-org/gitlab/-/issues/220912).
| Attribute | Type | Required | Description |
|:----------|:-------|:---------|:------------|
| `id` | integer/string | yes | The ID or [URL-encoded path of the project](../../api/rest/_index.md#namespaced-paths) |
```plaintext
GET /internal/kubernetes/project_info
```
Example Request:
```shell
curl --request GET --header "Gitlab-Kas-Api-Request: <JWT token>" \
--header "Authorization: Bearer <agent token>" "http://localhost:3000/api/v4/internal/kubernetes/project_info?id=7"
```
### GitLab agent for Kubernetes usage metrics
Called from the GitLab agent server for Kubernetes (`kas`) to increase the usage
metric counters.
| Attribute | Type | Required | Description |
|:--------------------------------------------------------------------------|:--------------|:---------|:----------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `counters` | hash | no | Hash of counters |
| `counters["k8s_api_proxy_request"]` | integer | no | The number to increase the `k8s_api_proxy_request` counter by |
| `counters["flux_git_push_notifications_total"]` | integer | no | The number to increase the `flux_git_push_notifications_total` counter by |
| `counters["k8s_api_proxy_requests_via_ci_access"]` | integer | no | The number to increase the `k8s_api_proxy_requests_via_ci_access` counter by |
| `counters["k8s_api_proxy_requests_via_user_access"]` | integer | no | The number to increase the `k8s_api_proxy_requests_via_user_access` counter by |
| `counters["k8s_api_proxy_requests_via_pat_access"]` | integer | no | The number to increase the `k8s_api_proxy_requests_via_pat_access` counter by |
| `unique_counters` | hash | no | Array of unique numbers |
| `unique_counters["k8s_api_proxy_requests_unique_users_via_ci_access"]` | integer array | no | The set of unique user ids that have interacted a CI Tunnel via `ci_access` to track the `k8s_api_proxy_requests_unique_users_via_ci_access` metric event |
| `unique_counters["k8s_api_proxy_requests_unique_agents_via_ci_access"]` | integer array | no | The set of unique agent ids that have interacted a CI Tunnel via `ci_access` to track the `k8s_api_proxy_requests_unique_agents_via_ci_access` metric event |
| `unique_counters["k8s_api_proxy_requests_unique_users_via_user_access"]` | integer array | no | The set of unique user ids that have interacted a CI Tunnel via `user_access` to track the `k8s_api_proxy_requests_unique_users_via_user_access` metric event |
| `unique_counters["k8s_api_proxy_requests_unique_agents_via_user_access"]` | integer array | no | The set of unique agent ids that have interacted a CI Tunnel via `user_access` to track the `k8s_api_proxy_requests_unique_agents_via_user_access` metric event |
| `unique_counters["k8s_api_proxy_requests_unique_users_via_pat_access"]` | integer array | no | The set of unique user ids that have used the KAS Kubernetes API proxy with PAT to track the `k8s_api_proxy_requests_unique_users_via_pat_access` metric event |
| `unique_counters["k8s_api_proxy_requests_unique_agents_via_pat_access"]` | integer array | no | The set of unique agent ids that have used the KAS Kubernetes API proxy with PAT to track the `k8s_api_proxy_requests_unique_agents_via_pat_access` metric event |
| `unique_counters["flux_git_push_notified_unique_projects"]` | integer array | no | The set of unique projects ids that have been notified to reconcile their Flux workloads to track the `flux_git_push_notified_unique_projects` metric event |
```plaintext
POST /internal/kubernetes/usage_metrics
```
Example Request:
```shell
curl --request POST --header "Gitlab-Kas-Api-Request: <JWT token>" --header "Content-Type: application/json" \
--data '{"counters": {"k8s_api_proxy_request":1}}' "http://localhost:3000/api/v4/internal/kubernetes/usage_metrics"
```
### GitLab agent for Kubernetes events
Called from the GitLab agent server for Kubernetes (`kas`) to track events.
| Attribute | Type | Required | Description |
|:------------------------------------------------------------------------------|:--------------|:---------|:--------------------------------------------------------------------------|
| `events` | hash | no | Hash of events |
| `events["k8s_api_proxy_requests_unique_users_via_ci_access"]` | hash array | no | Array of events for `k8s_api_proxy_requests_unique_users_via_ci_access` |
| `events["k8s_api_proxy_requests_unique_users_via_ci_access"]["user_id"]` | integer | no | The user ID for the event |
| `events["k8s_api_proxy_requests_unique_users_via_ci_access"]["project_id"]` | integer | no | The project ID for the event |
| `events["k8s_api_proxy_requests_unique_users_via_user_access"]` | hash array | no | Array of events for `k8s_api_proxy_requests_unique_users_via_user_access` |
| `events["k8s_api_proxy_requests_unique_users_via_user_access"]["user_id"]` | integer | no | The user ID for the event |
| `events["k8s_api_proxy_requests_unique_users_via_user_access"]["project_id"]` | integer | no | The project ID for the event |
| `events["k8s_api_proxy_requests_unique_users_via_pat_access"]` | hash array | no | Array of events for `k8s_api_proxy_requests_unique_users_via_pat_access` |
| `events["k8s_api_proxy_requests_unique_users_via_pat_access"]["user_id"]` | integer | no | The user ID for the event |
| `events["k8s_api_proxy_requests_unique_users_via_pat_access"]["project_id"]` | integer | no | The project ID for the event |
```plaintext
POST /internal/kubernetes/agent_events
```
Example Request:
```shell
curl --request POST \
--url "http://localhost:3000/api/v4/internal/kubernetes/agent_events" \
--header "Gitlab-Kas-Api-Request: <JWT token>" \
--header "Content-Type: application/json" \
--data '{
"events": {
"k8s_api_proxy_requests_unique_users_via_ci_access": [
{
"user_id": 1,
"project_id": 1
}
]
}
}'
```
### Create Starboard vulnerability
Called from the GitLab agent server for Kubernetes (`kas`) to create a security vulnerability
from a Starboard vulnerability report. This request is idempotent. Multiple requests with the same data
create a single vulnerability. The response contains the UUID of the created vulnerability finding.
| Attribute | Type | Required | Description |
|:----------------|:-------|:---------|:------------|
| `vulnerability` | Hash | yes | Vulnerability data matching the security report schema [`vulnerability` field](https://gitlab.com/gitlab-org/security-products/security-report-schemas/-/blob/master/src/security-report-format.json). |
| `scanner` | Hash | yes | Scanner data matching the security report schema [`scanner` field](https://gitlab.com/gitlab-org/security-products/security-report-schemas/-/blob/master/src/security-report-format.json). |
```plaintext
PUT internal/kubernetes/modules/starboard_vulnerability
```
Example Request:
```shell
curl --request PUT --header "Gitlab-Kas-Api-Request: <JWT token>" \
--header "Authorization: Bearer <agent token>" --header "Content-Type: application/json" \
--url "http://localhost:3000/api/v4/internal/kubernetes/modules/starboard_vulnerability" \
--data '{
"vulnerability": {
"name": "CVE-123-4567 in libc",
"severity": "high",
"confidence": "unknown",
"location": {
"kubernetes_resource": {
"namespace": "production",
"kind": "deployment",
"name": "nginx",
"container": "nginx"
}
},
"identifiers": [
{
"type": "cve",
"name": "CVE-123-4567",
"value": "CVE-123-4567"
}
]
},
"scanner": {
"id": "starboard_trivy",
"name": "Trivy (via Starboard Operator)",
"vendor": "GitLab"
}
}'
```
Example response:
```json
{
"uuid": "4773b2ee-5ba5-5e9f-b48c-5f7a17f0faac"
}
```
### Resolve Starboard vulnerabilities
Called from the GitLab agent server for Kubernetes (`kas`) to resolve Starboard security vulnerabilities.
Accepts a list of finding UUIDs and marks all Starboard vulnerabilities not identified by
the list as resolved.
| Attribute | Type | Required | Description |
|:----------|:-------------|:---------|:----------------------------------------------------------------------------------------------------------------------------------|
| `uuids` | string array | yes | UUIDs of detected vulnerabilities, as collected from [Create Starboard vulnerability](#create-starboard-vulnerability) responses. |
```plaintext
POST internal/kubernetes/modules/starboard_vulnerability/scan_result
```
Example Request:
```shell
curl --request POST --header "Gitlab-Kas-Api-Request: <JWT token>" \
--header "Authorization: Bearer <agent token>" --header "Content-Type: application/json" \
--url "http://localhost:3000/api/v4/internal/kubernetes/modules/starboard_vulnerability/scan_result" \
--data '{ "uuids": ["102e8a0a-fe29-59bd-b46c-57c3e9bc6411", "5eb12985-0ed5-51f4-b545-fd8871dc2870"] }'
```
### Scan Execution Policies
Called from GitLab agent server for Kubernetes (`kas`) to retrieve `scan_execution_policies`
configured for the project belonging to the agent token. GitLab `kas` uses
this to configure the agent to scan images in the Kubernetes cluster based on the policy.
```plaintext
GET /internal/kubernetes/modules/starboard_vulnerability/scan_execution_policies
```
Example Request:
```shell
curl --request GET --header "Gitlab-Kas-Api-Request: <JWT token>" \
--header "Authorization: Bearer <agent token>" "http://localhost:3000/api/v4/internal/kubernetes/modules/starboard_vulnerability/scan_execution_policies"
```
Example response:
```json
{
"policies": [
{
"name": "Policy",
"description": "Policy description",
"enabled": true,
"yaml": "---\nname: Policy\ndescription: 'Policy description'\nenabled: true\nactions:\n- scan: container_scanning\nrules:\n- type: pipeline\n branches:\n - main\n",
"updated_at": "2022-06-02T05:36:26+00:00"
}
]
}
```
### Policy Configuration
Called from GitLab agent server for Kubernetes (`kas`) to retrieve `policies_configuration`
configured for the project belonging to the agent token. GitLab `kas` uses
this to configure the agent to scan images in the Kubernetes cluster based on the configuration.
```plaintext
GET /internal/kubernetes/modules/starboard_vulnerability/policies_configuration
```
Example Request:
```shell
curl --request GET --header "Gitlab-Kas-Api-Request: <JWT token>" \
--header "Authorization: Bearer <agent token>" "http://localhost:3000/api/v4/internal/kubernetes/modules/starboard_vulnerability/policies_configuration"
```
Example response:
```json
{
"configurations": [
{
"cadence": "30 2 * * *",
"namespaces": [
"namespace-a",
"namespace-b"
],
"updated_at": "2022-06-02T05:36:26+00:00"
}
]
}
```
## Storage limit exclusions
The namespace storage limit exclusion endpoints manage storage limit exclusions on top-level namespaces on GitLab.com.
These endpoints can only be consumed in the **Admin** area of GitLab.com.
### Retrieve storage limit exclusions
Use a GET request to retrieve all `Namespaces::Storage::LimitExclusion` records.
```plaintext
GET /namespaces/storage/limit_exclusions
```
Example request:
```shell
curl --request GET \
--url "https://gitlab.com/v4/namespaces/storage/limit_exclusions" \
--header 'PRIVATE-TOKEN: <admin access token>'
```
Example response:
```json
[
{
"id": 1,
"namespace_id": 1234,
"namespace_name": "A Namespace Name",
"reason": "a reason to exclude the Namespace"
},
{
"id": 2,
"namespace_id": 4321,
"namespace_name": "Another Namespace Name",
"reason": "another reason to exclude the Namespace"
},
]
```
### Create a storage limit exclusion
Use a POST request to create an `Namespaces::Storage::LimitExclusion`.
```plaintext
POST /namespaces/:id/storage/limit_exclusion
```
| Attribute | Type | Required | Description |
|:------------|:--------|:---------|:------------|
| `reason` | string | yes | The reason to exclude the namespace. |
Example request:
```shell
curl --request POST \
--url "https://gitlab.com/v4/namespaces/123/storage/limit_exclusion" \
--header 'Content-Type: application/json' \
--header 'PRIVATE-TOKEN: <admin access token>' \
--data '{
"reason": "a reason to exclude the Namespace"
}'
```
Example response:
```json
{
"id": 1,
"namespace_id": 1234,
"namespace_name": "A Namespace Name",
"reason": "a reason to exclude the Namespace"
}
```
### Delete a storage limit exclusion
Use a DELETE request to delete a `Namespaces::Storage::LimitExclusion` for a namespace.
```plaintext
DELETE /namespaces/:id/storage/limit_exclusion
```
Example request:
```shell
curl --request DELETE \
--url "https://gitlab.com/v4/namespaces/123/storage/limit_exclusion" \
--header 'PRIVATE-TOKEN: <admin access token>'
```
Example response:
```plaintext
204
```
### Known consumers
- GitLab.com **Admin** area
## Group SCIM API
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab.com
{{< /details >}}
The group SCIM API partially implements the [RFC7644 protocol](https://www.rfc-editor.org/rfc/rfc7644). This API provides the `/groups/:group_path/Users` and `/groups/:group_path/Users/:id` endpoints. The base URL is `<http|https>://<GitLab host>/api/scim/v2`. Because this API is for
system use for SCIM provider integration, it is subject to change without notice.
To use this API, enable [Group SSO](../../user/group/saml_sso/_index.md) for the group.
This API is only in use where [SCIM for Group SSO](../../user/group/saml_sso/scim_setup.md) is enabled. It's a prerequisite to the creation of SCIM identities.
This group SCIM API:
- Is for system use for SCIM provider integration.
- Implements the [RFC7644 protocol](https://www.rfc-editor.org/rfc/rfc7644).
- Gets a list of SCIM provisioned users for the group.
- Creates, deletes and updates SCIM provisioned users for the group.
The [instance SCIM API](#instance-scim-api) does the same for instances.
This group SCIM API is different to the [SCIM API](../../api/scim.md). The SCIM API:
- Is not an internal API.
- Does not implement the [RFC7644 protocol](https://www.rfc-editor.org/rfc/rfc7644).
- Gets, checks, updates, and deletes SCIM identities in groups.
{{< alert type="note" >}}
This API does not require the `Gitlab-Shell-Api-Request` header.
{{< /alert >}}
### Get a list of SCIM provisioned users
This endpoint is used as part of the SCIM syncing mechanism. It returns a list of users depending on the filter used.
```plaintext
GET /api/scim/v2/groups/:group_path/Users
```
Parameters:
| Attribute | Type | Required | Description |
|:----------|:--------|:---------|:----------------------------------------------------------------------------------------------------------------------------------------|
| `filter` | string | no | A [filter](#available-filters) expression. |
| `group_path` | string | yes | Full path to the group. |
| `startIndex` | integer | no | The 1-based index indicating where to start returning results from. A value of less than one is interpreted as 1. |
| `count` | integer | no | Desired maximum number of query results. |
{{< alert type="note" >}}
Pagination follows the [SCIM spec](https://www.rfc-editor.org/rfc/rfc7644#section-3.4.2.4) rather than GitLab pagination as used elsewhere. If records change between requests it is possible for a page to either be missing records that have moved to a different page or repeat records from a previous request.
{{< /alert >}}
Example request filtering on a specific identifier:
```shell
curl "https://gitlab.example.com/api/scim/v2/groups/test_group/Users?filter=id%20eq%20%220b1d561c-21ff-4092-beab-8154b17f82f2%22" \
--header "Authorization: Bearer <your_scim_token>" \
--header "Content-Type: application/scim+json"
```
Example response:
```json
{
"schemas": [
"urn:ietf:params:scim:api:messages:2.0:ListResponse"
],
"totalResults": 1,
"itemsPerPage": 20,
"startIndex": 1,
"Resources": [
{
"schemas": [
"urn:ietf:params:scim:schemas:core:2.0:User"
],
"id": "0b1d561c-21ff-4092-beab-8154b17f82f2",
"active": true,
"name.formatted": "Test User",
"userName": "username",
"meta": { "resourceType":"User" },
"emails": [
{
"type": "work",
"value": "name@example.com",
"primary": true
}
]
}
]
}
```
### Get a single SCIM provisioned user
```plaintext
GET /api/scim/v2/groups/:group_path/Users/:id
```
Parameters:
| Attribute | Type | Required | Description |
|:----------|:--------|:---------|:----------------------------------------------------------------------------------------------------------------------------------------|
| `id` | string | yes | External UID of the user. |
| `group_path` | string | yes | Full path to the group. |
Example request:
```shell
curl "https://gitlab.example.com/api/scim/v2/groups/test_group/Users/f0b1d561c-21ff-4092-beab-8154b17f82f2" \
--header "Authorization: Bearer <your_scim_token>" --header "Content-Type: application/scim+json"
```
Example response:
```json
{
"schemas": [
"urn:ietf:params:scim:schemas:core:2.0:User"
],
"id": "0b1d561c-21ff-4092-beab-8154b17f82f2",
"active": true,
"name.formatted": "Test User",
"userName": "username",
"meta": { "resourceType":"User" },
"emails": [
{
"type": "work",
"value": "name@example.com",
"primary": true
}
]
}
```
### Create a SCIM provisioned user
```plaintext
POST /api/scim/v2/groups/:group_path/Users/
```
Parameters:
| Attribute | Type | Required | Description |
|:---------------|:----------|:----|:--------------------------|
| `externalId` | string | yes | External UID of the user. |
| `userName` | string | yes | Username of the user. |
| `emails` | JSON string | yes | Work email. |
| `name` | JSON string | yes | Name of the user. |
| `meta` | string | no | Resource type (`User`). |
Example request:
```shell
curl --verbose --request POST "https://gitlab.example.com/api/scim/v2/groups/test_group/Users" \
--data '{"externalId":"test_uid","active":null,"userName":"username","emails":[{"primary":true,"type":"work","value":"name@example.com"}],"name":{"formatted":"Test User","familyName":"User","givenName":"Test"},"schemas":["urn:ietf:params:scim:schemas:core:2.0:User"],"meta":{"resourceType":"User"}}' \
--header "Authorization: Bearer <your_scim_token>" --header "Content-Type: application/scim+json"
```
Example response:
```json
{
"schemas": [
"urn:ietf:params:scim:schemas:core:2.0:User"
],
"id": "0b1d561c-21ff-4092-beab-8154b17f82f2",
"active": true,
"name.formatted": "Test User",
"userName": "username",
"meta": { "resourceType":"User" },
"emails": [
{
"type": "work",
"value": "name@example.com",
"primary": true
}
]
}
```
Returns a `201` status code if successful.
{{< alert type="note" >}}
After you create a group SCIM identity for a user, you can see that SCIM identity in the **Admin** area.
{{< /alert >}}
### Update a single SCIM provisioned user
Fields that can be updated are:
| SCIM/IdP field | GitLab field |
|:---------------------------------|:-----------------------------------------------------------------------------|
| `id/externalId` | `extern_uid` |
| `name.formatted` | `name` ([Removed](https://gitlab.com/gitlab-org/gitlab/-/issues/363058)) |
| `emails\[type eq "work"\].value` | `email` ([Removed](https://gitlab.com/gitlab-org/gitlab/-/issues/363058)) |
| `active` | Identity removal if `active` = `false` |
| `userName` | `username` ([Removed](https://gitlab.com/gitlab-org/gitlab/-/issues/363058)) |
```plaintext
PATCH /api/scim/v2/groups/:group_path/Users/:id
```
Parameters:
| Attribute | Type | Required | Description |
|:----------|:--------|:---------|:----------------------------------------------------------------------------------------------------------------------------------------|
| `id` | string | yes | External UID of the user. |
| `group_path` | string | yes | Full path to the group. |
| `Operations` | JSON string | yes | An [operations](#available-operations) expression. |
Example request to update the user's `id`:
```shell
curl --verbose --request PATCH "https://gitlab.example.com/api/scim/v2/groups/test_group/Users/f0b1d561c-21ff-4092-beab-8154b17f82f2" \
--data '{ "Operations": [{"op":"replace","path":"id","value":"1234abcd"}] }' \
--header "Authorization: Bearer <your_scim_token>" --header "Content-Type: application/scim+json"
```
Returns an empty response with a `204` status code if successful.
Example request to set the user's `active` state:
```shell
curl --verbose --request PATCH "https://gitlab.example.com/api/scim/v2/groups/test_group/Users/f0b1d561c-21ff-4092-beab-8154b17f82f2" \
--data '{ "Operations": [{"op":"replace","path":"active","value":"true"}] }' \
--header "Authorization: Bearer <your_scim_token>" --header "Content-Type: application/scim+json"
```
Returns an empty response with a `204` status code if successful.
### Remove a single SCIM provisioned user
Removes the user's SSO identity and group membership.
```plaintext
DELETE /api/scim/v2/groups/:group_path/Users/:id
```
Parameters:
| Attribute | Type | Required | Description |
| ------------ | ------ | -------- | ------------------------- |
| `id` | string | yes | External UID of the user. |
| `group_path` | string | yes | Full path to the group. |
Example request:
```shell
curl --verbose --request DELETE "https://gitlab.example.com/api/scim/v2/groups/test_group/Users/f0b1d561c-21ff-4092-beab-8154b17f82f2" \
--header "Authorization: Bearer <your_scim_token>" --header "Content-Type: application/scim+json"
```
Returns an empty response with a `204` status code if successful.
## Instance SCIM API
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
{{< history >}}
- Group sync support [added](https://gitlab.com/groups/gitlab-org/-/epics/15990) in GitLab 18.0.
{{< /history >}}
The instance SCIM API partially implements the [RFC7644 protocol](https://www.rfc-editor.org/rfc/rfc7644). This API provides endpoints for managing users and groups. The base URL is `<http|https>://<GitLab host>/api/scim/v2`. Because this API is for system use for SCIM provider integration, it is subject to change without notice.
To use this API, enable [SAML SSO](../../integration/saml.md) for the instance.
This instance SCIM API:
- Is for system use for SCIM provider integration.
- Implements the [RFC7644 protocol](https://www.rfc-editor.org/rfc/rfc7644).
- Gets a list of SCIM provisioned users.
- Creates, deletes, and updates SCIM provisioned users.
- Manages group memberships through [SAML group links](../../user/group/saml_sso/group_sync.md#configure-saml-group-links).
The [group SCIM API](#group-scim-api) does the same for groups.
This instance SCIM API is different to the [SCIM API](../../api/scim.md). The SCIM API:
- Is not an internal API.
- Does not implement the [RFC7644 protocol](https://www.rfc-editor.org/rfc/rfc7644).
- Gets, checks, updates, and deletes SCIM identities within groups.
{{< alert type="note" >}}
This API does not require the `Gitlab-Shell-Api-Request` header.
{{< /alert >}}
### User endpoints
Use user endpoints to manage SCIM provisioned users.
#### Get a list of SCIM provisioned users
This endpoint is used as part of the SCIM syncing mechanism. It returns a list of users depending on the filter used.
```plaintext
GET /api/scim/v2/application/Users
```
Parameters:
| Attribute | Type | Required | Description |
|:----------|:--------|:---------|:----------------------------------------------------------------------------------------------------------------------------------------|
| `filter` | string | no | A [filter](#available-filters) expression. |
| `startIndex` | integer | no | The 1-based index indicating where to start returning results from. A value of less than one is interpreted as 1. |
| `count` | integer | no | Desired maximum number of query results. |
{{< alert type="note" >}}
Pagination follows the [SCIM spec](https://www.rfc-editor.org/rfc/rfc7644#section-3.4.2.4) rather than GitLab pagination as used elsewhere. If records change between requests it is possible for a page to either be missing records that have moved to a different page or repeat records from a previous request.
{{< /alert >}}
Example request:
```shell
curl "https://gitlab.example.com/api/scim/v2/application/Users?filter=id%20eq%20%220b1d561c-21ff-4092-beab-8154b17f82f2%22" \
--header "Authorization: Bearer <your_scim_token>" \
--header "Content-Type: application/scim+json"
```
Example response:
```json
{
"schemas": [
"urn:ietf:params:scim:api:messages:2.0:ListResponse"
],
"totalResults": 1,
"itemsPerPage": 20,
"startIndex": 1,
"Resources": [
{
"schemas": [
"urn:ietf:params:scim:schemas:core:2.0:User"
],
"id": "0b1d561c-21ff-4092-beab-8154b17f82f2",
"active": true,
"name.formatted": "Test User",
"userName": "username",
"meta": { "resourceType":"User" },
"emails": [
{
"type": "work",
"value": "name@example.com",
"primary": true
}
]
}
]
}
```
#### Get a single SCIM provisioned user
```plaintext
GET /api/scim/v2/application/Users/:id
```
Parameters:
| Attribute | Type | Required | Description |
|:----------|:--------|:---------|:----------------------------------------------------------------------------------------------------------------------------------------|
| `id` | string | yes | External UID of the user. |
Example request:
```shell
curl "https://gitlab.example.com/api/scim/v2/application/Users/f0b1d561c-21ff-4092-beab-8154b17f82f2" \
--header "Authorization: Bearer <your_scim_token>" --header "Content-Type: application/scim+json"
```
Example response:
```json
{
"schemas": [
"urn:ietf:params:scim:schemas:core:2.0:User"
],
"id": "0b1d561c-21ff-4092-beab-8154b17f82f2",
"active": true,
"name.formatted": "Test User",
"userName": "username",
"meta": { "resourceType":"User" },
"emails": [
{
"type": "work",
"value": "name@example.com",
"primary": true
}
]
}
```
#### Create a SCIM provisioned user
```plaintext
POST /api/scim/v2/application/Users
```
Parameters:
| Attribute | Type | Required | Description |
|:---------------|:----------|:----|:--------------------------|
| `externalId` | string | yes | External UID of the user. |
| `userName` | string | yes | Username of the user. |
| `emails` | JSON string | yes | Work email. |
| `name` | JSON string | yes | Name of the user. |
| `meta` | string | no | Resource type (`User`). |
Example request:
```shell
curl --verbose --request POST "https://gitlab.example.com/api/scim/v2/application/Users" \
--data '{"externalId":"test_uid","active":null,"userName":"username","emails":[{"primary":true,"type":"work","value":"name@example.com"}],"name":{"formatted":"Test User","familyName":"User","givenName":"Test"},"schemas":["urn:ietf:params:scim:schemas:core:2.0:User"],"meta":{"resourceType":"User"}}' \
--header "Authorization: Bearer <your_scim_token>" --header "Content-Type: application/scim+json"
```
Example response:
```json
{
"schemas": [
"urn:ietf:params:scim:schemas:core:2.0:User"
],
"id": "0b1d561c-21ff-4092-beab-8154b17f82f2",
"active": true,
"name.formatted": "Test User",
"userName": "username",
"meta": { "resourceType":"User" },
"emails": [
{
"type": "work",
"value": "name@example.com",
"primary": true
}
]
}
```
Returns a `201` status code if successful.
#### Update a single SCIM provisioned user
Fields that can be updated are:
| SCIM/IdP field | GitLab field |
|:---------------------------------|:-----------------------------------------------------------------------------|
| `id/externalId` | `extern_uid` |
| `active` | If `false`, the user is blocked, but the SCIM identity remains linked. |
```plaintext
PATCH /api/scim/v2/application/Users/:id
```
Parameters:
| Attribute | Type | Required | Description |
|:----------|:--------|:---------|:----------------------------------------------------------------------------------------------------------------------------------------|
| `id` | string | yes | External UID of the user. |
| `Operations` | JSON string | yes | An [operations](#available-operations) expression. |
Example request:
```shell
curl --verbose --request PATCH "https://gitlab.example.com/api/scim/v2/application/Users/f0b1d561c-21ff-4092-beab-8154b17f82f2" \
--data '{ "Operations": [{"op":"Update","path":"active","value":"false"}] }' \
--header "Authorization: Bearer <your_scim_token>" --header "Content-Type: application/scim+json"
```
Returns an empty response with a `204` status code if successful.
#### Block a single SCIM provisioned user
The user is placed in a `blocked` state and signed out. This means
the user cannot sign in or push or pull code.
```plaintext
DELETE /api/scim/v2/application/Users/:id
```
Parameters:
| Attribute | Type | Required | Description |
| ------------ | ------ | -------- | ------------------------- |
| `id` | string | yes | External UID of the user. |
Example request:
```shell
curl --verbose --request DELETE "https://gitlab.example.com/api/scim/v2/application/Users/f0b1d561c-21ff-4092-beab-8154b17f82f2" \
--header "Authorization: Bearer <your_scim_token>" --header "Content-Type: application/scim+json"
```
Returns an empty response with a `204` status code if successful.
### Group endpoints
Use group endpoints to automatically synchronize GitLab with the SCIM identity provider.
This API uses [SAML group links](../../user/group/saml_sso/group_sync.md#configure-saml-group-links) to connect IdP groups with GitLab groups.
Before using these endpoints, you must create the necessary SAML group links for the groups you want to synchronize.
#### Get a list of SCIM groups
This endpoint returns a list of groups that have SCIM IDs assigned.
```plaintext
GET /api/scim/v2/application/Groups
```
Parameters:
| Attribute | Type | Required | Description |
|:----------|:--------|:---------|:--------------------------------------------------------------------------------------------------------------------------|
| `filter` | string | no | A filter expression to search groups by name. |
| `startIndex` | integer | no | The 1-based index indicating where to start returning results from. |
| `count` | integer | no | Desired maximum number of query results. |
| `excludedAttributes` | string | no | Comma-separated list of attributes to exclude from the response. |
{{< alert type="note" >}}
Pagination follows the [SCIM spec](https://www.rfc-editor.org/rfc/rfc7644#section-3.4.2.4), not the GitLab pagination.
{{< /alert >}}
Example request:
```shell
curl "https://gitlab.example.com/api/scim/v2/application/Groups?filter=displayName%20eq%20%22Developers%22" \
--header "Authorization: Bearer <your_scim_token>" \
--header "Content-Type: application/scim+json"
```
Example response:
```json
{
"schemas": [
"urn:ietf:params:scim:api:messages:2.0:ListResponse"
],
"totalResults": 1,
"itemsPerPage": 20,
"startIndex": 1,
"Resources": [
{
"schemas": [
"urn:ietf:params:scim:schemas:core:2.0:Group"
],
"id": "86e7d437-1a55-4731-b3a3-2867fb4d2a94",
"displayName": "Developers",
"members": [],
"meta": {
"resourceType": "Group"
}
}
]
}
```
#### Get a single SCIM group
```plaintext
GET /api/scim/v2/application/Groups/:id
```
Parameters:
| Attribute | Type | Required | Description |
|:----------|:--------|:---------|:--------------------------------------------------------------------------------------------------------------------------|
| `id` | string | yes | SCIM group ID (UUID format). |
Example request:
```shell
curl "https://gitlab.example.com/api/scim/v2/application/Groups/86e7d437-1a55-4731-b3a3-2867fb4d2a94" \
--header "Authorization: Bearer <your_scim_token>" --header "Content-Type: application/scim+json"
```
Example response:
```json
{
"schemas": [
"urn:ietf:params:scim:schemas:core:2.0:Group"
],
"id": "86e7d437-1a55-4731-b3a3-2867fb4d2a94",
"displayName": "Developers",
"members": [],
"meta": {
"resourceType": "Group"
}
}
```
#### Create a SCIM group
This endpoint associates a SCIM group ID with existing SAML group links that have the same name.
```plaintext
POST /api/scim/v2/application/Groups
```
Parameters:
| Attribute | Type | Required | Description |
|:---------------|:----------|:----|:--------------------------|
| `displayName` | string | yes | Name of the group as configured in GitLab SAML group links. |
| `externalId` | string | no | Optional SCIM group ID. If not provided, a UUID is generated. |
Example request:
```shell
curl --verbose --request POST "https://gitlab.example.com/api/scim/v2/application/Groups" \
--data '{"displayName":"Developers","schemas":["urn:ietf:params:scim:schemas:core:2.0:Group"]}' \
--header "Authorization: Bearer <your_scim_token>" --header "Content-Type: application/scim+json"
```
Example response:
```json
{
"schemas": [
"urn:ietf:params:scim:schemas:core:2.0:Group"
],
"id": "86e7d437-1a55-4731-b3a3-2867fb4d2a94",
"displayName": "Developers",
"members": [],
"meta": {
"resourceType": "Group"
}
}
```
Returns a `201` status code if successful.
{{< alert type="note" >}}
This endpoint does not create GitLab groups. It only associates a SCIM ID with existing SAML group links that have the specified display name.
{{< /alert >}}
#### Update a SCIM group
Updates the members of a SCIM group. Used to add or remove users from GitLab groups associated with the SCIM group.
```plaintext
PATCH /api/scim/v2/application/Groups/:id
```
Parameters:
| Attribute | Type | Required | Description |
|:----------|:--------|:---------|:--------------------------------------------------------------------------------------------------------------------------|
| `id` | string | yes | SCIM group ID. |
| `Operations` | JSON array | yes | Array of operations to perform. Each operation includes `op` (operation type), `path` (attribute to modify), and `value` (new value). |
Supported operations:
- `add` with path `members` to add members to the group
- `remove` with path `members` to remove members from the group
Example request to add a member:
```shell
curl --verbose --request PATCH "https://gitlab.example.com/api/scim/v2/application/Groups/86e7d437-1a55-4731-b3a3-2867fb4d2a94" \
--data '{"schemas":["urn:ietf:params:scim:api:messages:2.0:PatchOp"],"Operations":[{"op":"add","path":"members","value":[{"value":"f0b1d561c-21ff-4092-beab-8154b17f82f2"}]}]}' \
--header "Authorization: Bearer <your_scim_token>" --header "Content-Type: application/scim+json"
```
Example request to remove a member:
```shell
curl --verbose --request PATCH "https://gitlab.example.com/api/scim/v2/application/Groups/86e7d437-1a55-4731-b3a3-2867fb4d2a94" \
--data '{"schemas":["urn:ietf:params:scim:api:messages:2.0:PatchOp"],"Operations":[{"op":"remove","path":"members","value":[{"value":"f0b1d561c-21ff-4092-beab-8154b17f82f2"}]}]}' \
--header "Authorization: Bearer <your_scim_token>" --header "Content-Type: application/scim+json"
```
Returns an empty response with a `204` status code if successful.
#### Replace a SCIM group
Replaces all members of a SCIM group with a new set of members.
```plaintext
PUT /api/scim/v2/application/Groups/:id
```
Parameters:
| Attribute | Type | Required | Description |
| ------------ | ------ | -------- | ------------------------- |
| `id` | string | yes | SCIM group ID. |
| `schemas` | array | yes | SCIM schemas array. Must include `["urn:ietf:params:scim:schemas:core:2.0:Group"]`. |
| `displayName` | string | yes | Group display name. |
| `members` | array | no | Array of members, each with a `value` attribute containing the user's SCIM ID. |
Example request:
```shell
curl --verbose --request PUT "https://gitlab.example.com/api/scim/v2/application/Groups/86e7d437-1a55-4731-b3a3-2867fb4d2a94" \
--data '{"schemas":["urn:ietf:params:scim:schemas:core:2.0:Group"],"displayName":"Developers","members":[{"value":"f0b1d561c-21ff-4092-beab-8154b17f82f2"}]}' \
--header "Authorization: Bearer <your_scim_token>" --header "Content-Type: application/scim+json"
```
Response includes the updated group information.
{{< alert type="warning" >}}
The `PUT` operation replaces all group members. Any existing members not included in the request are removed from all GitLab groups associated with this SCIM group.
{{< /alert >}}
#### Delete a SCIM group
Removes SCIM management from existing SAML group links by clearing the SCIM group ID. This endpoint also schedules background cleanup of SCIM group membership tracking records.
```plaintext
DELETE /api/scim/v2/application/Groups/:id
```
Parameters:
| Attribute | Type | Required | Description |
| ------------ | ------ | -------- | ------------------------- |
| `id` | string | yes | SCIM group ID (UUID format). |
Example request:
```shell
curl --verbose --request DELETE "https://gitlab.example.com/api/scim/v2/application/Groups/86e7d437-1a55-4731-b3a3-2867fb4d2a94" \
--header "Authorization: Bearer <your_scim_token>" --header "Content-Type: application/scim+json"
```
Returns an empty response with a `204` status code if successful.
{{< alert type="note" >}}
This endpoint does not delete GitLab groups. It only removes SCIM management from SAML group links with the specified SCIM group ID, allowing identity providers to deprovision unneeded SCIM groups.
{{< /alert >}}
### Available filters
They match an expression as specified in [the RFC7644 filtering section](https://www.rfc-editor.org/rfc/rfc7644#section-3.4.2.2).
| Filter | Description |
| ----- | ----------- |
| `eq` | The attribute matches exactly the specified value. |
Example:
```plaintext
id eq a-b-c-d
```
### Available operations
They perform an operation as specified in [the RFC7644 update section](https://www.rfc-editor.org/rfc/rfc7644#section-3.5.2).
| Operator | Description |
| ----- | ----------- |
| `Replace` | The attribute's value is updated. |
| `Add` | The attribute has a new value. |
Example:
```json
{ "op": "Add", "path": "name.formatted", "value": "New Name" }
```
|
---
stage: Create
group: Source Code
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Internal API
breadcrumbs:
- doc
- development
- internal_api
---
The internal API is used by different GitLab components, it cannot be
used by other consumers. This documentation is intended for people
working on the GitLab codebase.
This documentation does not yet include the internal API used by
GitLab Pages.
For information on the GitLab Subscriptions internal API, see [the dedicated page](gitlab_subscriptions.md).
## Add new endpoints
API endpoints should be externally accessible by default, with proper authentication and authorization.
Before adding a new internal endpoint, consider if the API would benefit the wider GitLab community and can be made externally accessible.
One reason we might favor internal API endpoints sometimes is when using such an endpoint requires
internal data that external actors cannot have. For example, in the internal Pages API we might use
a secret token that identifies a request as internal or sign a request with a public key that is
not available to a wider community.
Another reason to separate something into an internal API is when request to such API endpoint
should never go through an edge (public) load balancer. This way we can configure different rate
limiting rules and policies around how the endpoint is being accessed, because we know that only
internal requests can be made to that endpoint going through an internal load balancer.
## Authentication
These methods are all authenticated using a shared secret. This secret
is stored in a file at the path configured in `config/gitlab.yml` by
default this is in the root of the rails app named
`.gitlab_shell_secret`
To authenticate using that token, clients:
1. Read the contents of that file.
1. Use the file contents to generate a JSON Web Token (`JWT`).
1. Pass the JWT in the `Gitlab-Shell-Api-Request` header.
## Git Authentication
Called by [Gitaly](https://gitlab.com/gitlab-org/gitaly) and
[GitLab Shell](https://gitlab.com/gitlab-org/gitlab-shell) to check access to a
repository.
- When called from GitLab Shell: No changes are passed, and the internal
API replies with the information needed to pass the request on to Gitaly.
- When called from Gitaly in a `pre-receive` hook: The changes are passed
and validated to determine if the push is allowed.
Calls are limited to 50 seconds each.
This endpoint is covered in more detail on [its own page](internal_api_allowed.md), due to the scope of what it covers.
```plaintext
POST /internal/allowed
```
| Attribute | Type | Required | Description |
|:----------|:-------|:---------|:------------|
| `key_id` | string | no | ID of the SSH-key used to connect to GitLab Shell |
| `username` | string | no | Username from the certificate used to connect to GitLab Shell |
| `project` | string | no (if `gl_repository` is passed) | Path to the project |
| `gl_repository` | string | no (if `project` is passed) | Repository identifier, such as `project-7` |
| `protocol` | string | yes | SSH when called from GitLab Shell, HTTP or SSH when called from Gitaly |
| `action` | string | yes | Git command being run (`git-upload-pack`, `git-receive-pack`, `git-upload-archive`) |
| `changes` | string | yes | `<oldrev> <newrev> <refname>` when called from Gitaly, the magic string `_any` when called from GitLab Shell |
| `check_ip` | string | no | IP address from which call to GitLab Shell was made |
Example request:
```shell
curl --request POST --header "Gitlab-Shell-Api-Request: <JWT token>" \
--data "key_id=11&project=gnuwget/wget2&action=git-upload-pack&protocol=ssh" \
"http://localhost:3001/api/v4/internal/allowed"
```
Example response:
```json
{
"status": true,
"gl_repository": "project-3",
"gl_project_path": "gnuwget/wget2",
"gl_id": "user-1",
"gl_username": "root",
"git_config_options": [],
"gitaly": {
"repository": {
"storage_name": "default",
"relative_path": "@hashed/4e/07/4e07408562bedb8b60ce05c1decfe3ad16b72230967de01f640b7e4729b49fce.git",
"git_object_directory": "",
"git_alternate_object_directories": [],
"gl_repository": "project-3",
"gl_project_path": "gnuwget/wget2"
},
"address": "unix:/Users/bvl/repos/gitlab/gitaly.socket",
"token": null
},
"gl_console_messages": []
}
```
### Known consumers
- Gitaly
- GitLab Shell
## LFS Authentication
This is the endpoint that gets called from GitLab Shell to provide
information for LFS clients when the repository is accessed over SSH.
| Attribute | Type | Required | Description |
|:----------|:-------|:---------|:------------|
| `key_id` | string | no | ID of the SSH-key used to connect to GitLab Shell |
| `username`| string | no | Username from the certificate used to connect to GitLab Shell |
| `project` | string | no | Path to the project |
Example request:
```shell
curl --request POST --header "Gitlab-Shell-Api-Request: <JWT token>" \
--data "key_id=11&project=gnuwget/wget2" "http://localhost:3001/api/v4/internal/lfs_authenticate"
```
```json
{
"username": "root",
"lfs_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjp7ImFjdG9yIjoicm9vdCJ9LCJqdGkiOiIyYWJhZDcxZC0xNDFlLTQ2NGUtOTZlMi1mODllYWRiMGVmZTYiLCJpYXQiOjE1NzAxMTc2NzYsIm5iZiI6MTU3MDExNzY3MSwiZXhwIjoxNTcwMTE5NDc2fQ.g7atlBw1QMY7QEBVPE0LZ8ZlKtaRzaMRmNn41r2YITM",
"repository_http_path": "http://localhost:3001/gnuwget/wget2.git",
"expires_in": 1800
}
```
### Known consumers
- GitLab Shell
## Authorized Keys Check
This endpoint is called by the GitLab Shell authorized keys
check. Which is called by OpenSSH or GitLab SSHD for
[fast SSH key lookup](../../administration/operations/fast_ssh_key_lookup.md).
| Attribute | Type | Required | Description |
|:----------|:-------|:---------|:------------|
| `key` | string | yes | An authorized key used for public key authentication. |
```plaintext
GET /internal/authorized_keys
```
Example request:
```shell
curl --request GET --header "Gitlab-Shell-Api-Request: <JWT token>" "http://localhost:3001/api/v4/internal/authorized_keys?key=<key>"
```
Example response:
```json
{
"id": 11,
"title": "admin@example.com",
"key": "ssh-rsa ...",
"created_at": "2019-06-27T15:29:02.219Z"
}
```
### Known consumers
- GitLab Shell
## Authorized Certs
This endpoint is called by the GitLab Shell to get the namespace that has a particular CA SSH certificate
configured. It also accepts `user_identifier` to return a GitLab user for specified identifier.
| Attribute | Type | Required | Description |
|:----------------------|:-------|:---------|:------------|
| `key` | string | yes | The fingerprint of the SSH certificate. |
| `user_identifier` | string | yes | The identifier of the user to whom the SSH certificate has been issued (username or primary email). |
```plaintext
GET /internal/authorized_certs
```
Example request:
```shell
curl --request GET --header "Gitlab-Shell-Api-Request: <JWT token>" "http://localhost:3001/api/v4/internal/authorized_certs?key=<key>&user_identifier=<user_identifier>"
```
Example response:
```json
{
"success": true,
"namespace": "gitlab-org",
"username": "root"
}
```
### Known consumers
- GitLab Shell
## Get user for user ID or key
This endpoint is used when a user performs `ssh git@gitlab.com`. It
discovers the user associated with an SSH key.
| Attribute | Type | Required | Description |
|:----------|:-------|:---------|:------------|
| `key_id` | integer | no | The ID of the SSH key used as found in the authorized-keys file or through the `/authorized_keys` check |
| `username` | string | no | Username of the user being looked up, used by GitLab Shell when authenticating using a certificate |
```plaintext
GET /internal/discover
```
Example request:
```shell
curl --request GET --header "Gitlab-Shell-Api-Request: <JWT token>" "http://localhost:3001/api/v4/internal/discover?key_id=7"
```
Example response:
```json
{
"id": 7,
"name": "Dede Eichmann",
"username": "rubi"
}
```
### Known consumers
- GitLab Shell
## Instance information
This gets some generic information about the instance. It's used
by Geo nodes to get information about each other.
```plaintext
GET /internal/check
```
Example request:
```shell
curl --request GET --header "Gitlab-Shell-Api-Request: <JWT token>" "http://localhost:3001/api/v4/internal/check"
```
Example response:
```json
{
"api_version": "v4",
"gitlab_version": "12.3.0-pre",
"gitlab_rev": "d69c988e6a6",
"redis": true
}
```
### Known consumers
- GitLab Geo
- GitLab Shell's `bin/check`
- Gitaly
## Get new 2FA recovery codes using an SSH key
This is called from GitLab Shell and allows users to get new 2FA
recovery codes based on their SSH key.
| Attribute | Type | Required | Description |
|:----------|:-------|:---------|:------------|
| `key_id` | integer | no | The ID of the SSH key used as found in the authorized-keys file or through the `/authorized_keys` check |
| `user_id` | integer | no | Deprecated. User ID for which to generate new recovery codes |
```plaintext
GET /internal/two_factor_recovery_codes
```
Example request:
```shell
curl --request POST --header "Gitlab-Shell-Api-Request: <JWT token>" \
--data "key_id=7" "http://localhost:3001/api/v4/internal/two_factor_recovery_codes"
```
Example response:
```json
{
"success": true,
"recovery_codes": [
"d93ee7037944afd5",
"19d7b84862de93dd",
"1e8c52169195bf71",
"be50444dddb7ca84",
"26048c77d161d5b7",
"482d5c03d1628c47",
"d2c695e309ce7679",
"dfb4748afc4f12a7",
"0e5f53d1399d7979",
"af04d5622153b020"
]
}
```
### Known consumers
- GitLab Shell
## Get new personal access-token
Called from GitLab Shell and allows users to generate a new
personal access token.
| Attribute | Type | Required | Description |
|:----------|:-------|:---------|:------------|
| `name` | string | yes | The name of the new token |
| `scopes` | string array | yes | The authorization scopes for the new token, these must be valid token scopes |
| `expires_at` | string | no | Expiration date of the access token in ISO format (`YYYY-MM-DD`). |
| `key_id` | integer | no | The ID of the SSH key used as found in the authorized-keys file or through the `/authorized_keys` check |
| `user_id` | integer | no | User ID for which to generate the new token |
```plaintext
POST /internal/personal_access_token
```
Example request:
```shell
curl --request POST --header "Gitlab-Shell-Api-Request: <JWT token>" \
--data "user_id=29&name=mytokenname&scopes[]=read_user&scopes[]=read_repository&expires_at=2020-07-24" \
"http://localhost:3001/api/v4/internal/personal_access_token"
```
Example response:
```json
{
"success": true,
"token": "Hf_79B288hRv_3-TSD1R",
"scopes": ["read_user","read_repository"],
"expires_at": "2020-07-24"
}
```
### Known consumers
- GitLab Shell
## Authenticate Error Tracking requests
This endpoint is called by the error tracking Go REST API application to authenticate a project.
| Attribute | Type | Required | Description |
|:-------------|:--------|:---------|:-------------------------------------------------------------------|
| `project_id` | integer | yes | The ID of the project which has the associated key. |
| `public_key` | string | yes | The [public key](../../api/error_tracking.md#create-a-client-key) generated by the integrated Error Tracking feature. |
```plaintext
POST /internal/error_tracking/allowed
```
Example request:
```shell
curl --request POST --header "Gitlab-Shell-Api-Request: <JWT token>" \
--data "project_id=111&public_key=generated-error-tracking-key" \
"http://localhost:3001/api/v4/internal/error_tracking/allowed"
```
Example response:
```json
{ "enabled": true }
```
### Known consumers
- OpsTrace
## Incrementing counter on pre-receive
This is called from the Gitaly hooks increasing the reference counter
for a push that might be accepted.
| Attribute | Type | Required | Description |
|:----------|:-------|:---------|:------------|
| `gl_repository` | string | yes | repository identifier for the repository receiving the push |
```plaintext
POST /internal/pre_receive
```
Example request:
```shell
curl --request POST --header "Gitlab-Shell-Api-Request: <JWT token>" \
--data "gl_repository=project-7" "http://localhost:3001/api/v4/internal/pre_receive"
```
Example response:
```json
{
"reference_counter_increased": true
}
```
## PostReceive
Called from Gitaly after a receiving a push. This triggers the
`PostReceive`-worker in Sidekiq, processes the passed push options and
builds the response including messages that need to be displayed to
the user.
| Attribute | Type | Required | Description |
|:----------|:-------|:---------|:------------|
| `identifier` | string | yes | `user-[id]` or `key-[id]` Identifying the user performing the push |
| `gl_repository` | string | yes | identifier of the repository being pushed to |
| `push_options` | string array | no | array of push options |
| `changes` | string | no | refs to be updated in the push in the format `oldrev newrev refname\n`. |
```plaintext
POST /internal/post_receive
```
Example Request:
```shell
curl --request POST --header "Gitlab-Shell-Api-Request: <JWT token>" \
--data "gl_repository=project-7" --data "identifier=user-1" \
--data "changes=0000000000000000000000000000000000000000 fd9e76b9136bdd9fe217061b497745792fe5a5ee gh-pages\n" \
"http://localhost:3001/api/v4/internal/post_receive"
```
Example response:
```json
{
"messages": [
{
"message": "Hello from post-receive",
"type": "alert"
}
],
"reference_counter_decreased": true
}
```
## GitLab agent for Kubernetes endpoints
{{< history >}}
- [Feature flag removed](https://gitlab.com/gitlab-org/gitlab/-/issues/432773) in GitLab 16.7.
{{< /history >}}
The following endpoints are used by the GitLab agent server for Kubernetes (`kas`)
for various purposes.
These endpoints are all authenticated using JWT. The JWT secret is stored in a file
specified in `config/gitlab.yml`. By default, the location is in the root of the
GitLab Rails app in a file called `.gitlab_kas_secret`.
### GitLab agent for Kubernetes information
Called from the GitLab agent server for Kubernetes (`kas`) to retrieve agent
information for the given agent token. This returns the Gitaly connection
information for the agent's project in order for `kas` to fetch and update
the agent's configuration.
```plaintext
GET /internal/kubernetes/agent_info
```
Example Request:
```shell
curl --request GET --header "Gitlab-Kas-Api-Request: <JWT token>" \
--header "Authorization: Bearer <agent token>" "http://localhost:3000/api/v4/internal/kubernetes/agent_info"
```
### GitLab agent for Kubernetes project information
Called from the GitLab agent server for Kubernetes (`kas`) to retrieve project
information for the given agent token. This returns the Gitaly
connection for the requested project. GitLab `kas` uses this to configure
the agent to fetch Kubernetes resources from the project repository to
sync.
Only public projects are supported. For private projects, the ability for the
agent to be authorized is [not yet implemented](https://gitlab.com/gitlab-org/gitlab/-/issues/220912).
| Attribute | Type | Required | Description |
|:----------|:-------|:---------|:------------|
| `id` | integer/string | yes | The ID or [URL-encoded path of the project](../../api/rest/_index.md#namespaced-paths) |
```plaintext
GET /internal/kubernetes/project_info
```
Example Request:
```shell
curl --request GET --header "Gitlab-Kas-Api-Request: <JWT token>" \
--header "Authorization: Bearer <agent token>" "http://localhost:3000/api/v4/internal/kubernetes/project_info?id=7"
```
### GitLab agent for Kubernetes usage metrics
Called from the GitLab agent server for Kubernetes (`kas`) to increase the usage
metric counters.
| Attribute | Type | Required | Description |
|:--------------------------------------------------------------------------|:--------------|:---------|:----------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `counters` | hash | no | Hash of counters |
| `counters["k8s_api_proxy_request"]` | integer | no | The number to increase the `k8s_api_proxy_request` counter by |
| `counters["flux_git_push_notifications_total"]` | integer | no | The number to increase the `flux_git_push_notifications_total` counter by |
| `counters["k8s_api_proxy_requests_via_ci_access"]` | integer | no | The number to increase the `k8s_api_proxy_requests_via_ci_access` counter by |
| `counters["k8s_api_proxy_requests_via_user_access"]` | integer | no | The number to increase the `k8s_api_proxy_requests_via_user_access` counter by |
| `counters["k8s_api_proxy_requests_via_pat_access"]` | integer | no | The number to increase the `k8s_api_proxy_requests_via_pat_access` counter by |
| `unique_counters` | hash | no | Array of unique numbers |
| `unique_counters["k8s_api_proxy_requests_unique_users_via_ci_access"]` | integer array | no | The set of unique user ids that have interacted a CI Tunnel via `ci_access` to track the `k8s_api_proxy_requests_unique_users_via_ci_access` metric event |
| `unique_counters["k8s_api_proxy_requests_unique_agents_via_ci_access"]` | integer array | no | The set of unique agent ids that have interacted a CI Tunnel via `ci_access` to track the `k8s_api_proxy_requests_unique_agents_via_ci_access` metric event |
| `unique_counters["k8s_api_proxy_requests_unique_users_via_user_access"]` | integer array | no | The set of unique user ids that have interacted a CI Tunnel via `user_access` to track the `k8s_api_proxy_requests_unique_users_via_user_access` metric event |
| `unique_counters["k8s_api_proxy_requests_unique_agents_via_user_access"]` | integer array | no | The set of unique agent ids that have interacted a CI Tunnel via `user_access` to track the `k8s_api_proxy_requests_unique_agents_via_user_access` metric event |
| `unique_counters["k8s_api_proxy_requests_unique_users_via_pat_access"]` | integer array | no | The set of unique user ids that have used the KAS Kubernetes API proxy with PAT to track the `k8s_api_proxy_requests_unique_users_via_pat_access` metric event |
| `unique_counters["k8s_api_proxy_requests_unique_agents_via_pat_access"]` | integer array | no | The set of unique agent ids that have used the KAS Kubernetes API proxy with PAT to track the `k8s_api_proxy_requests_unique_agents_via_pat_access` metric event |
| `unique_counters["flux_git_push_notified_unique_projects"]` | integer array | no | The set of unique projects ids that have been notified to reconcile their Flux workloads to track the `flux_git_push_notified_unique_projects` metric event |
```plaintext
POST /internal/kubernetes/usage_metrics
```
Example Request:
```shell
curl --request POST --header "Gitlab-Kas-Api-Request: <JWT token>" --header "Content-Type: application/json" \
--data '{"counters": {"k8s_api_proxy_request":1}}' "http://localhost:3000/api/v4/internal/kubernetes/usage_metrics"
```
### GitLab agent for Kubernetes events
Called from the GitLab agent server for Kubernetes (`kas`) to track events.
| Attribute | Type | Required | Description |
|:------------------------------------------------------------------------------|:--------------|:---------|:--------------------------------------------------------------------------|
| `events` | hash | no | Hash of events |
| `events["k8s_api_proxy_requests_unique_users_via_ci_access"]` | hash array | no | Array of events for `k8s_api_proxy_requests_unique_users_via_ci_access` |
| `events["k8s_api_proxy_requests_unique_users_via_ci_access"]["user_id"]` | integer | no | The user ID for the event |
| `events["k8s_api_proxy_requests_unique_users_via_ci_access"]["project_id"]` | integer | no | The project ID for the event |
| `events["k8s_api_proxy_requests_unique_users_via_user_access"]` | hash array | no | Array of events for `k8s_api_proxy_requests_unique_users_via_user_access` |
| `events["k8s_api_proxy_requests_unique_users_via_user_access"]["user_id"]` | integer | no | The user ID for the event |
| `events["k8s_api_proxy_requests_unique_users_via_user_access"]["project_id"]` | integer | no | The project ID for the event |
| `events["k8s_api_proxy_requests_unique_users_via_pat_access"]` | hash array | no | Array of events for `k8s_api_proxy_requests_unique_users_via_pat_access` |
| `events["k8s_api_proxy_requests_unique_users_via_pat_access"]["user_id"]` | integer | no | The user ID for the event |
| `events["k8s_api_proxy_requests_unique_users_via_pat_access"]["project_id"]` | integer | no | The project ID for the event |
```plaintext
POST /internal/kubernetes/agent_events
```
Example Request:
```shell
curl --request POST \
--url "http://localhost:3000/api/v4/internal/kubernetes/agent_events" \
--header "Gitlab-Kas-Api-Request: <JWT token>" \
--header "Content-Type: application/json" \
--data '{
"events": {
"k8s_api_proxy_requests_unique_users_via_ci_access": [
{
"user_id": 1,
"project_id": 1
}
]
}
}'
```
### Create Starboard vulnerability
Called from the GitLab agent server for Kubernetes (`kas`) to create a security vulnerability
from a Starboard vulnerability report. This request is idempotent. Multiple requests with the same data
create a single vulnerability. The response contains the UUID of the created vulnerability finding.
| Attribute | Type | Required | Description |
|:----------------|:-------|:---------|:------------|
| `vulnerability` | Hash | yes | Vulnerability data matching the security report schema [`vulnerability` field](https://gitlab.com/gitlab-org/security-products/security-report-schemas/-/blob/master/src/security-report-format.json). |
| `scanner` | Hash | yes | Scanner data matching the security report schema [`scanner` field](https://gitlab.com/gitlab-org/security-products/security-report-schemas/-/blob/master/src/security-report-format.json). |
```plaintext
PUT internal/kubernetes/modules/starboard_vulnerability
```
Example Request:
```shell
curl --request PUT --header "Gitlab-Kas-Api-Request: <JWT token>" \
--header "Authorization: Bearer <agent token>" --header "Content-Type: application/json" \
--url "http://localhost:3000/api/v4/internal/kubernetes/modules/starboard_vulnerability" \
--data '{
"vulnerability": {
"name": "CVE-123-4567 in libc",
"severity": "high",
"confidence": "unknown",
"location": {
"kubernetes_resource": {
"namespace": "production",
"kind": "deployment",
"name": "nginx",
"container": "nginx"
}
},
"identifiers": [
{
"type": "cve",
"name": "CVE-123-4567",
"value": "CVE-123-4567"
}
]
},
"scanner": {
"id": "starboard_trivy",
"name": "Trivy (via Starboard Operator)",
"vendor": "GitLab"
}
}'
```
Example response:
```json
{
"uuid": "4773b2ee-5ba5-5e9f-b48c-5f7a17f0faac"
}
```
### Resolve Starboard vulnerabilities
Called from the GitLab agent server for Kubernetes (`kas`) to resolve Starboard security vulnerabilities.
Accepts a list of finding UUIDs and marks all Starboard vulnerabilities not identified by
the list as resolved.
| Attribute | Type | Required | Description |
|:----------|:-------------|:---------|:----------------------------------------------------------------------------------------------------------------------------------|
| `uuids` | string array | yes | UUIDs of detected vulnerabilities, as collected from [Create Starboard vulnerability](#create-starboard-vulnerability) responses. |
```plaintext
POST internal/kubernetes/modules/starboard_vulnerability/scan_result
```
Example Request:
```shell
curl --request POST --header "Gitlab-Kas-Api-Request: <JWT token>" \
--header "Authorization: Bearer <agent token>" --header "Content-Type: application/json" \
--url "http://localhost:3000/api/v4/internal/kubernetes/modules/starboard_vulnerability/scan_result" \
--data '{ "uuids": ["102e8a0a-fe29-59bd-b46c-57c3e9bc6411", "5eb12985-0ed5-51f4-b545-fd8871dc2870"] }'
```
### Scan Execution Policies
Called from GitLab agent server for Kubernetes (`kas`) to retrieve `scan_execution_policies`
configured for the project belonging to the agent token. GitLab `kas` uses
this to configure the agent to scan images in the Kubernetes cluster based on the policy.
```plaintext
GET /internal/kubernetes/modules/starboard_vulnerability/scan_execution_policies
```
Example Request:
```shell
curl --request GET --header "Gitlab-Kas-Api-Request: <JWT token>" \
--header "Authorization: Bearer <agent token>" "http://localhost:3000/api/v4/internal/kubernetes/modules/starboard_vulnerability/scan_execution_policies"
```
Example response:
```json
{
"policies": [
{
"name": "Policy",
"description": "Policy description",
"enabled": true,
"yaml": "---\nname: Policy\ndescription: 'Policy description'\nenabled: true\nactions:\n- scan: container_scanning\nrules:\n- type: pipeline\n branches:\n - main\n",
"updated_at": "2022-06-02T05:36:26+00:00"
}
]
}
```
### Policy Configuration
Called from GitLab agent server for Kubernetes (`kas`) to retrieve `policies_configuration`
configured for the project belonging to the agent token. GitLab `kas` uses
this to configure the agent to scan images in the Kubernetes cluster based on the configuration.
```plaintext
GET /internal/kubernetes/modules/starboard_vulnerability/policies_configuration
```
Example Request:
```shell
curl --request GET --header "Gitlab-Kas-Api-Request: <JWT token>" \
--header "Authorization: Bearer <agent token>" "http://localhost:3000/api/v4/internal/kubernetes/modules/starboard_vulnerability/policies_configuration"
```
Example response:
```json
{
"configurations": [
{
"cadence": "30 2 * * *",
"namespaces": [
"namespace-a",
"namespace-b"
],
"updated_at": "2022-06-02T05:36:26+00:00"
}
]
}
```
## Storage limit exclusions
The namespace storage limit exclusion endpoints manage storage limit exclusions on top-level namespaces on GitLab.com.
These endpoints can only be consumed in the **Admin** area of GitLab.com.
### Retrieve storage limit exclusions
Use a GET request to retrieve all `Namespaces::Storage::LimitExclusion` records.
```plaintext
GET /namespaces/storage/limit_exclusions
```
Example request:
```shell
curl --request GET \
--url "https://gitlab.com/v4/namespaces/storage/limit_exclusions" \
--header 'PRIVATE-TOKEN: <admin access token>'
```
Example response:
```json
[
{
"id": 1,
"namespace_id": 1234,
"namespace_name": "A Namespace Name",
"reason": "a reason to exclude the Namespace"
},
{
"id": 2,
"namespace_id": 4321,
"namespace_name": "Another Namespace Name",
"reason": "another reason to exclude the Namespace"
},
]
```
### Create a storage limit exclusion
Use a POST request to create an `Namespaces::Storage::LimitExclusion`.
```plaintext
POST /namespaces/:id/storage/limit_exclusion
```
| Attribute | Type | Required | Description |
|:------------|:--------|:---------|:------------|
| `reason` | string | yes | The reason to exclude the namespace. |
Example request:
```shell
curl --request POST \
--url "https://gitlab.com/v4/namespaces/123/storage/limit_exclusion" \
--header 'Content-Type: application/json' \
--header 'PRIVATE-TOKEN: <admin access token>' \
--data '{
"reason": "a reason to exclude the Namespace"
}'
```
Example response:
```json
{
"id": 1,
"namespace_id": 1234,
"namespace_name": "A Namespace Name",
"reason": "a reason to exclude the Namespace"
}
```
### Delete a storage limit exclusion
Use a DELETE request to delete a `Namespaces::Storage::LimitExclusion` for a namespace.
```plaintext
DELETE /namespaces/:id/storage/limit_exclusion
```
Example request:
```shell
curl --request DELETE \
--url "https://gitlab.com/v4/namespaces/123/storage/limit_exclusion" \
--header 'PRIVATE-TOKEN: <admin access token>'
```
Example response:
```plaintext
204
```
### Known consumers
- GitLab.com **Admin** area
## Group SCIM API
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab.com
{{< /details >}}
The group SCIM API partially implements the [RFC7644 protocol](https://www.rfc-editor.org/rfc/rfc7644). This API provides the `/groups/:group_path/Users` and `/groups/:group_path/Users/:id` endpoints. The base URL is `<http|https>://<GitLab host>/api/scim/v2`. Because this API is for
system use for SCIM provider integration, it is subject to change without notice.
To use this API, enable [Group SSO](../../user/group/saml_sso/_index.md) for the group.
This API is only in use where [SCIM for Group SSO](../../user/group/saml_sso/scim_setup.md) is enabled. It's a prerequisite to the creation of SCIM identities.
This group SCIM API:
- Is for system use for SCIM provider integration.
- Implements the [RFC7644 protocol](https://www.rfc-editor.org/rfc/rfc7644).
- Gets a list of SCIM provisioned users for the group.
- Creates, deletes and updates SCIM provisioned users for the group.
The [instance SCIM API](#instance-scim-api) does the same for instances.
This group SCIM API is different to the [SCIM API](../../api/scim.md). The SCIM API:
- Is not an internal API.
- Does not implement the [RFC7644 protocol](https://www.rfc-editor.org/rfc/rfc7644).
- Gets, checks, updates, and deletes SCIM identities in groups.
{{< alert type="note" >}}
This API does not require the `Gitlab-Shell-Api-Request` header.
{{< /alert >}}
### Get a list of SCIM provisioned users
This endpoint is used as part of the SCIM syncing mechanism. It returns a list of users depending on the filter used.
```plaintext
GET /api/scim/v2/groups/:group_path/Users
```
Parameters:
| Attribute | Type | Required | Description |
|:----------|:--------|:---------|:----------------------------------------------------------------------------------------------------------------------------------------|
| `filter` | string | no | A [filter](#available-filters) expression. |
| `group_path` | string | yes | Full path to the group. |
| `startIndex` | integer | no | The 1-based index indicating where to start returning results from. A value of less than one is interpreted as 1. |
| `count` | integer | no | Desired maximum number of query results. |
{{< alert type="note" >}}
Pagination follows the [SCIM spec](https://www.rfc-editor.org/rfc/rfc7644#section-3.4.2.4) rather than GitLab pagination as used elsewhere. If records change between requests it is possible for a page to either be missing records that have moved to a different page or repeat records from a previous request.
{{< /alert >}}
Example request filtering on a specific identifier:
```shell
curl "https://gitlab.example.com/api/scim/v2/groups/test_group/Users?filter=id%20eq%20%220b1d561c-21ff-4092-beab-8154b17f82f2%22" \
--header "Authorization: Bearer <your_scim_token>" \
--header "Content-Type: application/scim+json"
```
Example response:
```json
{
"schemas": [
"urn:ietf:params:scim:api:messages:2.0:ListResponse"
],
"totalResults": 1,
"itemsPerPage": 20,
"startIndex": 1,
"Resources": [
{
"schemas": [
"urn:ietf:params:scim:schemas:core:2.0:User"
],
"id": "0b1d561c-21ff-4092-beab-8154b17f82f2",
"active": true,
"name.formatted": "Test User",
"userName": "username",
"meta": { "resourceType":"User" },
"emails": [
{
"type": "work",
"value": "name@example.com",
"primary": true
}
]
}
]
}
```
### Get a single SCIM provisioned user
```plaintext
GET /api/scim/v2/groups/:group_path/Users/:id
```
Parameters:
| Attribute | Type | Required | Description |
|:----------|:--------|:---------|:----------------------------------------------------------------------------------------------------------------------------------------|
| `id` | string | yes | External UID of the user. |
| `group_path` | string | yes | Full path to the group. |
Example request:
```shell
curl "https://gitlab.example.com/api/scim/v2/groups/test_group/Users/f0b1d561c-21ff-4092-beab-8154b17f82f2" \
--header "Authorization: Bearer <your_scim_token>" --header "Content-Type: application/scim+json"
```
Example response:
```json
{
"schemas": [
"urn:ietf:params:scim:schemas:core:2.0:User"
],
"id": "0b1d561c-21ff-4092-beab-8154b17f82f2",
"active": true,
"name.formatted": "Test User",
"userName": "username",
"meta": { "resourceType":"User" },
"emails": [
{
"type": "work",
"value": "name@example.com",
"primary": true
}
]
}
```
### Create a SCIM provisioned user
```plaintext
POST /api/scim/v2/groups/:group_path/Users/
```
Parameters:
| Attribute | Type | Required | Description |
|:---------------|:----------|:----|:--------------------------|
| `externalId` | string | yes | External UID of the user. |
| `userName` | string | yes | Username of the user. |
| `emails` | JSON string | yes | Work email. |
| `name` | JSON string | yes | Name of the user. |
| `meta` | string | no | Resource type (`User`). |
Example request:
```shell
curl --verbose --request POST "https://gitlab.example.com/api/scim/v2/groups/test_group/Users" \
--data '{"externalId":"test_uid","active":null,"userName":"username","emails":[{"primary":true,"type":"work","value":"name@example.com"}],"name":{"formatted":"Test User","familyName":"User","givenName":"Test"},"schemas":["urn:ietf:params:scim:schemas:core:2.0:User"],"meta":{"resourceType":"User"}}' \
--header "Authorization: Bearer <your_scim_token>" --header "Content-Type: application/scim+json"
```
Example response:
```json
{
"schemas": [
"urn:ietf:params:scim:schemas:core:2.0:User"
],
"id": "0b1d561c-21ff-4092-beab-8154b17f82f2",
"active": true,
"name.formatted": "Test User",
"userName": "username",
"meta": { "resourceType":"User" },
"emails": [
{
"type": "work",
"value": "name@example.com",
"primary": true
}
]
}
```
Returns a `201` status code if successful.
{{< alert type="note" >}}
After you create a group SCIM identity for a user, you can see that SCIM identity in the **Admin** area.
{{< /alert >}}
### Update a single SCIM provisioned user
Fields that can be updated are:
| SCIM/IdP field | GitLab field |
|:---------------------------------|:-----------------------------------------------------------------------------|
| `id/externalId` | `extern_uid` |
| `name.formatted` | `name` ([Removed](https://gitlab.com/gitlab-org/gitlab/-/issues/363058)) |
| `emails\[type eq "work"\].value` | `email` ([Removed](https://gitlab.com/gitlab-org/gitlab/-/issues/363058)) |
| `active` | Identity removal if `active` = `false` |
| `userName` | `username` ([Removed](https://gitlab.com/gitlab-org/gitlab/-/issues/363058)) |
```plaintext
PATCH /api/scim/v2/groups/:group_path/Users/:id
```
Parameters:
| Attribute | Type | Required | Description |
|:----------|:--------|:---------|:----------------------------------------------------------------------------------------------------------------------------------------|
| `id` | string | yes | External UID of the user. |
| `group_path` | string | yes | Full path to the group. |
| `Operations` | JSON string | yes | An [operations](#available-operations) expression. |
Example request to update the user's `id`:
```shell
curl --verbose --request PATCH "https://gitlab.example.com/api/scim/v2/groups/test_group/Users/f0b1d561c-21ff-4092-beab-8154b17f82f2" \
--data '{ "Operations": [{"op":"replace","path":"id","value":"1234abcd"}] }' \
--header "Authorization: Bearer <your_scim_token>" --header "Content-Type: application/scim+json"
```
Returns an empty response with a `204` status code if successful.
Example request to set the user's `active` state:
```shell
curl --verbose --request PATCH "https://gitlab.example.com/api/scim/v2/groups/test_group/Users/f0b1d561c-21ff-4092-beab-8154b17f82f2" \
--data '{ "Operations": [{"op":"replace","path":"active","value":"true"}] }' \
--header "Authorization: Bearer <your_scim_token>" --header "Content-Type: application/scim+json"
```
Returns an empty response with a `204` status code if successful.
### Remove a single SCIM provisioned user
Removes the user's SSO identity and group membership.
```plaintext
DELETE /api/scim/v2/groups/:group_path/Users/:id
```
Parameters:
| Attribute | Type | Required | Description |
| ------------ | ------ | -------- | ------------------------- |
| `id` | string | yes | External UID of the user. |
| `group_path` | string | yes | Full path to the group. |
Example request:
```shell
curl --verbose --request DELETE "https://gitlab.example.com/api/scim/v2/groups/test_group/Users/f0b1d561c-21ff-4092-beab-8154b17f82f2" \
--header "Authorization: Bearer <your_scim_token>" --header "Content-Type: application/scim+json"
```
Returns an empty response with a `204` status code if successful.
## Instance SCIM API
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
{{< history >}}
- Group sync support [added](https://gitlab.com/groups/gitlab-org/-/epics/15990) in GitLab 18.0.
{{< /history >}}
The instance SCIM API partially implements the [RFC7644 protocol](https://www.rfc-editor.org/rfc/rfc7644). This API provides endpoints for managing users and groups. The base URL is `<http|https>://<GitLab host>/api/scim/v2`. Because this API is for system use for SCIM provider integration, it is subject to change without notice.
To use this API, enable [SAML SSO](../../integration/saml.md) for the instance.
This instance SCIM API:
- Is for system use for SCIM provider integration.
- Implements the [RFC7644 protocol](https://www.rfc-editor.org/rfc/rfc7644).
- Gets a list of SCIM provisioned users.
- Creates, deletes, and updates SCIM provisioned users.
- Manages group memberships through [SAML group links](../../user/group/saml_sso/group_sync.md#configure-saml-group-links).
The [group SCIM API](#group-scim-api) does the same for groups.
This instance SCIM API is different to the [SCIM API](../../api/scim.md). The SCIM API:
- Is not an internal API.
- Does not implement the [RFC7644 protocol](https://www.rfc-editor.org/rfc/rfc7644).
- Gets, checks, updates, and deletes SCIM identities within groups.
{{< alert type="note" >}}
This API does not require the `Gitlab-Shell-Api-Request` header.
{{< /alert >}}
### User endpoints
Use user endpoints to manage SCIM provisioned users.
#### Get a list of SCIM provisioned users
This endpoint is used as part of the SCIM syncing mechanism. It returns a list of users depending on the filter used.
```plaintext
GET /api/scim/v2/application/Users
```
Parameters:
| Attribute | Type | Required | Description |
|:----------|:--------|:---------|:----------------------------------------------------------------------------------------------------------------------------------------|
| `filter` | string | no | A [filter](#available-filters) expression. |
| `startIndex` | integer | no | The 1-based index indicating where to start returning results from. A value of less than one is interpreted as 1. |
| `count` | integer | no | Desired maximum number of query results. |
{{< alert type="note" >}}
Pagination follows the [SCIM spec](https://www.rfc-editor.org/rfc/rfc7644#section-3.4.2.4) rather than GitLab pagination as used elsewhere. If records change between requests it is possible for a page to either be missing records that have moved to a different page or repeat records from a previous request.
{{< /alert >}}
Example request:
```shell
curl "https://gitlab.example.com/api/scim/v2/application/Users?filter=id%20eq%20%220b1d561c-21ff-4092-beab-8154b17f82f2%22" \
--header "Authorization: Bearer <your_scim_token>" \
--header "Content-Type: application/scim+json"
```
Example response:
```json
{
"schemas": [
"urn:ietf:params:scim:api:messages:2.0:ListResponse"
],
"totalResults": 1,
"itemsPerPage": 20,
"startIndex": 1,
"Resources": [
{
"schemas": [
"urn:ietf:params:scim:schemas:core:2.0:User"
],
"id": "0b1d561c-21ff-4092-beab-8154b17f82f2",
"active": true,
"name.formatted": "Test User",
"userName": "username",
"meta": { "resourceType":"User" },
"emails": [
{
"type": "work",
"value": "name@example.com",
"primary": true
}
]
}
]
}
```
#### Get a single SCIM provisioned user
```plaintext
GET /api/scim/v2/application/Users/:id
```
Parameters:
| Attribute | Type | Required | Description |
|:----------|:--------|:---------|:----------------------------------------------------------------------------------------------------------------------------------------|
| `id` | string | yes | External UID of the user. |
Example request:
```shell
curl "https://gitlab.example.com/api/scim/v2/application/Users/f0b1d561c-21ff-4092-beab-8154b17f82f2" \
--header "Authorization: Bearer <your_scim_token>" --header "Content-Type: application/scim+json"
```
Example response:
```json
{
"schemas": [
"urn:ietf:params:scim:schemas:core:2.0:User"
],
"id": "0b1d561c-21ff-4092-beab-8154b17f82f2",
"active": true,
"name.formatted": "Test User",
"userName": "username",
"meta": { "resourceType":"User" },
"emails": [
{
"type": "work",
"value": "name@example.com",
"primary": true
}
]
}
```
#### Create a SCIM provisioned user
```plaintext
POST /api/scim/v2/application/Users
```
Parameters:
| Attribute | Type | Required | Description |
|:---------------|:----------|:----|:--------------------------|
| `externalId` | string | yes | External UID of the user. |
| `userName` | string | yes | Username of the user. |
| `emails` | JSON string | yes | Work email. |
| `name` | JSON string | yes | Name of the user. |
| `meta` | string | no | Resource type (`User`). |
Example request:
```shell
curl --verbose --request POST "https://gitlab.example.com/api/scim/v2/application/Users" \
--data '{"externalId":"test_uid","active":null,"userName":"username","emails":[{"primary":true,"type":"work","value":"name@example.com"}],"name":{"formatted":"Test User","familyName":"User","givenName":"Test"},"schemas":["urn:ietf:params:scim:schemas:core:2.0:User"],"meta":{"resourceType":"User"}}' \
--header "Authorization: Bearer <your_scim_token>" --header "Content-Type: application/scim+json"
```
Example response:
```json
{
"schemas": [
"urn:ietf:params:scim:schemas:core:2.0:User"
],
"id": "0b1d561c-21ff-4092-beab-8154b17f82f2",
"active": true,
"name.formatted": "Test User",
"userName": "username",
"meta": { "resourceType":"User" },
"emails": [
{
"type": "work",
"value": "name@example.com",
"primary": true
}
]
}
```
Returns a `201` status code if successful.
#### Update a single SCIM provisioned user
Fields that can be updated are:
| SCIM/IdP field | GitLab field |
|:---------------------------------|:-----------------------------------------------------------------------------|
| `id/externalId` | `extern_uid` |
| `active` | If `false`, the user is blocked, but the SCIM identity remains linked. |
```plaintext
PATCH /api/scim/v2/application/Users/:id
```
Parameters:
| Attribute | Type | Required | Description |
|:----------|:--------|:---------|:----------------------------------------------------------------------------------------------------------------------------------------|
| `id` | string | yes | External UID of the user. |
| `Operations` | JSON string | yes | An [operations](#available-operations) expression. |
Example request:
```shell
curl --verbose --request PATCH "https://gitlab.example.com/api/scim/v2/application/Users/f0b1d561c-21ff-4092-beab-8154b17f82f2" \
--data '{ "Operations": [{"op":"Update","path":"active","value":"false"}] }' \
--header "Authorization: Bearer <your_scim_token>" --header "Content-Type: application/scim+json"
```
Returns an empty response with a `204` status code if successful.
#### Block a single SCIM provisioned user
The user is placed in a `blocked` state and signed out. This means
the user cannot sign in or push or pull code.
```plaintext
DELETE /api/scim/v2/application/Users/:id
```
Parameters:
| Attribute | Type | Required | Description |
| ------------ | ------ | -------- | ------------------------- |
| `id` | string | yes | External UID of the user. |
Example request:
```shell
curl --verbose --request DELETE "https://gitlab.example.com/api/scim/v2/application/Users/f0b1d561c-21ff-4092-beab-8154b17f82f2" \
--header "Authorization: Bearer <your_scim_token>" --header "Content-Type: application/scim+json"
```
Returns an empty response with a `204` status code if successful.
### Group endpoints
Use group endpoints to automatically synchronize GitLab with the SCIM identity provider.
This API uses [SAML group links](../../user/group/saml_sso/group_sync.md#configure-saml-group-links) to connect IdP groups with GitLab groups.
Before using these endpoints, you must create the necessary SAML group links for the groups you want to synchronize.
#### Get a list of SCIM groups
This endpoint returns a list of groups that have SCIM IDs assigned.
```plaintext
GET /api/scim/v2/application/Groups
```
Parameters:
| Attribute | Type | Required | Description |
|:----------|:--------|:---------|:--------------------------------------------------------------------------------------------------------------------------|
| `filter` | string | no | A filter expression to search groups by name. |
| `startIndex` | integer | no | The 1-based index indicating where to start returning results from. |
| `count` | integer | no | Desired maximum number of query results. |
| `excludedAttributes` | string | no | Comma-separated list of attributes to exclude from the response. |
{{< alert type="note" >}}
Pagination follows the [SCIM spec](https://www.rfc-editor.org/rfc/rfc7644#section-3.4.2.4), not the GitLab pagination.
{{< /alert >}}
Example request:
```shell
curl "https://gitlab.example.com/api/scim/v2/application/Groups?filter=displayName%20eq%20%22Developers%22" \
--header "Authorization: Bearer <your_scim_token>" \
--header "Content-Type: application/scim+json"
```
Example response:
```json
{
"schemas": [
"urn:ietf:params:scim:api:messages:2.0:ListResponse"
],
"totalResults": 1,
"itemsPerPage": 20,
"startIndex": 1,
"Resources": [
{
"schemas": [
"urn:ietf:params:scim:schemas:core:2.0:Group"
],
"id": "86e7d437-1a55-4731-b3a3-2867fb4d2a94",
"displayName": "Developers",
"members": [],
"meta": {
"resourceType": "Group"
}
}
]
}
```
#### Get a single SCIM group
```plaintext
GET /api/scim/v2/application/Groups/:id
```
Parameters:
| Attribute | Type | Required | Description |
|:----------|:--------|:---------|:--------------------------------------------------------------------------------------------------------------------------|
| `id` | string | yes | SCIM group ID (UUID format). |
Example request:
```shell
curl "https://gitlab.example.com/api/scim/v2/application/Groups/86e7d437-1a55-4731-b3a3-2867fb4d2a94" \
--header "Authorization: Bearer <your_scim_token>" --header "Content-Type: application/scim+json"
```
Example response:
```json
{
"schemas": [
"urn:ietf:params:scim:schemas:core:2.0:Group"
],
"id": "86e7d437-1a55-4731-b3a3-2867fb4d2a94",
"displayName": "Developers",
"members": [],
"meta": {
"resourceType": "Group"
}
}
```
#### Create a SCIM group
This endpoint associates a SCIM group ID with existing SAML group links that have the same name.
```plaintext
POST /api/scim/v2/application/Groups
```
Parameters:
| Attribute | Type | Required | Description |
|:---------------|:----------|:----|:--------------------------|
| `displayName` | string | yes | Name of the group as configured in GitLab SAML group links. |
| `externalId` | string | no | Optional SCIM group ID. If not provided, a UUID is generated. |
Example request:
```shell
curl --verbose --request POST "https://gitlab.example.com/api/scim/v2/application/Groups" \
--data '{"displayName":"Developers","schemas":["urn:ietf:params:scim:schemas:core:2.0:Group"]}' \
--header "Authorization: Bearer <your_scim_token>" --header "Content-Type: application/scim+json"
```
Example response:
```json
{
"schemas": [
"urn:ietf:params:scim:schemas:core:2.0:Group"
],
"id": "86e7d437-1a55-4731-b3a3-2867fb4d2a94",
"displayName": "Developers",
"members": [],
"meta": {
"resourceType": "Group"
}
}
```
Returns a `201` status code if successful.
{{< alert type="note" >}}
This endpoint does not create GitLab groups. It only associates a SCIM ID with existing SAML group links that have the specified display name.
{{< /alert >}}
#### Update a SCIM group
Updates the members of a SCIM group. Used to add or remove users from GitLab groups associated with the SCIM group.
```plaintext
PATCH /api/scim/v2/application/Groups/:id
```
Parameters:
| Attribute | Type | Required | Description |
|:----------|:--------|:---------|:--------------------------------------------------------------------------------------------------------------------------|
| `id` | string | yes | SCIM group ID. |
| `Operations` | JSON array | yes | Array of operations to perform. Each operation includes `op` (operation type), `path` (attribute to modify), and `value` (new value). |
Supported operations:
- `add` with path `members` to add members to the group
- `remove` with path `members` to remove members from the group
Example request to add a member:
```shell
curl --verbose --request PATCH "https://gitlab.example.com/api/scim/v2/application/Groups/86e7d437-1a55-4731-b3a3-2867fb4d2a94" \
--data '{"schemas":["urn:ietf:params:scim:api:messages:2.0:PatchOp"],"Operations":[{"op":"add","path":"members","value":[{"value":"f0b1d561c-21ff-4092-beab-8154b17f82f2"}]}]}' \
--header "Authorization: Bearer <your_scim_token>" --header "Content-Type: application/scim+json"
```
Example request to remove a member:
```shell
curl --verbose --request PATCH "https://gitlab.example.com/api/scim/v2/application/Groups/86e7d437-1a55-4731-b3a3-2867fb4d2a94" \
--data '{"schemas":["urn:ietf:params:scim:api:messages:2.0:PatchOp"],"Operations":[{"op":"remove","path":"members","value":[{"value":"f0b1d561c-21ff-4092-beab-8154b17f82f2"}]}]}' \
--header "Authorization: Bearer <your_scim_token>" --header "Content-Type: application/scim+json"
```
Returns an empty response with a `204` status code if successful.
#### Replace a SCIM group
Replaces all members of a SCIM group with a new set of members.
```plaintext
PUT /api/scim/v2/application/Groups/:id
```
Parameters:
| Attribute | Type | Required | Description |
| ------------ | ------ | -------- | ------------------------- |
| `id` | string | yes | SCIM group ID. |
| `schemas` | array | yes | SCIM schemas array. Must include `["urn:ietf:params:scim:schemas:core:2.0:Group"]`. |
| `displayName` | string | yes | Group display name. |
| `members` | array | no | Array of members, each with a `value` attribute containing the user's SCIM ID. |
Example request:
```shell
curl --verbose --request PUT "https://gitlab.example.com/api/scim/v2/application/Groups/86e7d437-1a55-4731-b3a3-2867fb4d2a94" \
--data '{"schemas":["urn:ietf:params:scim:schemas:core:2.0:Group"],"displayName":"Developers","members":[{"value":"f0b1d561c-21ff-4092-beab-8154b17f82f2"}]}' \
--header "Authorization: Bearer <your_scim_token>" --header "Content-Type: application/scim+json"
```
Response includes the updated group information.
{{< alert type="warning" >}}
The `PUT` operation replaces all group members. Any existing members not included in the request are removed from all GitLab groups associated with this SCIM group.
{{< /alert >}}
#### Delete a SCIM group
Removes SCIM management from existing SAML group links by clearing the SCIM group ID. This endpoint also schedules background cleanup of SCIM group membership tracking records.
```plaintext
DELETE /api/scim/v2/application/Groups/:id
```
Parameters:
| Attribute | Type | Required | Description |
| ------------ | ------ | -------- | ------------------------- |
| `id` | string | yes | SCIM group ID (UUID format). |
Example request:
```shell
curl --verbose --request DELETE "https://gitlab.example.com/api/scim/v2/application/Groups/86e7d437-1a55-4731-b3a3-2867fb4d2a94" \
--header "Authorization: Bearer <your_scim_token>" --header "Content-Type: application/scim+json"
```
Returns an empty response with a `204` status code if successful.
{{< alert type="note" >}}
This endpoint does not delete GitLab groups. It only removes SCIM management from SAML group links with the specified SCIM group ID, allowing identity providers to deprovision unneeded SCIM groups.
{{< /alert >}}
### Available filters
They match an expression as specified in [the RFC7644 filtering section](https://www.rfc-editor.org/rfc/rfc7644#section-3.4.2.2).
| Filter | Description |
| ----- | ----------- |
| `eq` | The attribute matches exactly the specified value. |
Example:
```plaintext
id eq a-b-c-d
```
### Available operations
They perform an operation as specified in [the RFC7644 update section](https://www.rfc-editor.org/rfc/rfc7644#section-3.5.2).
| Operator | Description |
| ----- | ----------- |
| `Replace` | The attribute's value is updated. |
| `Add` | The attribute has a new value. |
Example:
```json
{ "op": "Add", "path": "name.formatted", "value": "New Name" }
```
|
https://docs.gitlab.com/development/adding_database_indexes
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/adding_database_indexes.md
|
2025-08-13
|
doc/development/database
|
[
"doc",
"development",
"database"
] |
adding_database_indexes.md
|
Data Access
|
Database Frameworks
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Adding Database Indexes
| null |
Indexes can be used to speed up database queries, but when should you add a new
index? Traditionally the answer to this question has been to add an index for
every column used for filtering or joining data. For example, consider the
following query:
```sql
SELECT *
FROM projects
WHERE user_id = 2;
```
Here we are filtering by the `user_id` column and as such a developer may decide
to index this column.
While in certain cases indexing columns using the above approach may make sense,
it can actually have a negative impact. Whenever you write data to a table, any
existing indexes must also be updated. The more indexes there are, the slower this
can potentially become. Indexes can also take up significant disk space, depending
on the amount of data indexed and the index type. For example, PostgreSQL offers
`GIN` indexes which can be used to index certain data types that cannot be
indexed by regular B-tree indexes. These indexes, however, generally take up more
data and are slower to update compared to B-tree indexes.
Because of all this, it's important make the following considerations
when adding a new index:
1. Do the new queries re-use as many existing indexes as possible?
1. Is there enough data that using an index is faster than iterating over
rows in the table?
1. Is the overhead of maintaining the index worth the reduction in query
timings?
In some situations, an index might not be required:
- The table is small (less than `1,000` records) and it's not expected to exponentially grow in size.
- Any existing indexes filter out enough rows.
- The reduction in query timings after the index is added is not significant.
Additionally, wide indexes are not required to match all filter criteria of queries. We just need
to cover enough columns so that the index lookup has a small enough selectivity.
## Re-using Queries
The first step is to make sure your query re-uses as many existing indexes as
possible. For example, consider the following query:
```sql
SELECT *
FROM todos
WHERE user_id = 123
AND state = 'open';
```
Now imagine we already have an index on the `user_id` column but not on the
`state` column. One may think this query performs badly due to `state` being
unindexed. In reality the query may perform just fine given the index on
`user_id` can filter out enough rows.
The best way to determine if indexes are re-used is to run your query using
`EXPLAIN ANALYZE`. Depending on the joined tables and the columns being used for filtering,
you may find an extra index doesn't make much, if any, difference.
In short:
1. Try to write your query in such a way that it re-uses as many existing
indexes as possible.
1. Run the query using `EXPLAIN ANALYZE` and study the output to find the most
ideal query.
## Partial Indexes
Partial indexes are indexes with a `WHERE` clause that limits them to a subset of matching rows.
They can offer several advantages over full indexes, including:
- Reduced index size and memory usage
- Less write and vacuum overhead
- Improved query performance for selective conditions
Partial indexes work best for queries that always filter on known conditions and target a specific subset of data.
Common use cases include:
- Nullable columns: `WHERE column IS NOT NULL`
- Boolean flags: `WHERE feature_enabled = true`
- Soft deletes: `WHERE deleted_at IS NULL`
- Status filters: `WHERE status IN ('queued', 'running')`
Before creating any new partial index, first examine existing indexes for potential reuse or modification.
Since each index incurs maintenance overhead, prioritize adapting current indexes over adding new ones.
### Example
Consider the following application code which introduces a new count query:
```ruby
def namespace_count
NamespaceSetting.where(duo_features_enabled: duo_settings_value).count
end
def duo_settings_value
params['duo_settings_value'] == 'default_on'
end
```
where `namespace_settings` is a table with 1 million records,
and `duo_features_enabled` is a nullable Boolean column.
Let's assume that we recently introduced this column and it was not backfilled.
This means we know that the majority of the records in the `namespace_settings` table have a `NULL`
value for `duo_features_enabled`. We can also see that `duo_settings_value` will only either yield
`true` or `false`.
Indexing all rows would be inefficient as we mostly have `NULL` values. Instead,
we can introduce a partial index that targets only the data of interest:
```sql
CREATE INDEX index_namespace_settings_on_duo_features_enabled_not_null
ON namespace_settings (duo_features_enabled)
WHERE duo_features_enabled IS NOT NULL;
```
Now we have an index that is just a small fraction of the full index size and the
query planner can effectively skip over hundreds of thousands of irrelevant records.
## Data Size
A database may not use an index even when a regular sequence scan
(iterating over all rows) is faster, especially for small tables.
Consider adding an index if a table is expected to grow, and your query has to filter a lot of rows.
You may not want to add an index if the table size is small (<`1,000` records),
or if existing indexes already filter out enough rows.
## Maintenance Overhead
Indexes have to be updated on every table write. In the case of PostgreSQL, _all_
existing indexes are updated whenever data is written to a table. As a
result, having many indexes on the same table slows down writes. It's therefore important
to balance query performance with the overhead of maintaining an extra index.
For example, if adding an index reduces SELECT timings by 5 milliseconds but increases
INSERT/UPDATE/DELETE timings by 10 milliseconds, the new index may not be worth
it. A new index is more valuable when SELECT timings are reduced and INSERT/UPDATE/DELETE
timings are unaffected.
### Index limitations
GitLab enforces a limit of **15 indexes** per table. This limitation:
- Helps maintain optimal database performance
- Reduces maintenance overhead
- Prevents excessive disk space usage
{{< alert type="note" >}}
If you need to add an index to a table that already has 15 indexes, consider:
{{< /alert >}}
- Removing unused indexes
- Combining existing indexes
- Using a composite index that can serve multiple query patterns
### Some tables should not have any more indexes
We have RuboCop checks (`PreventIndexCreation`) against further new indexes on selected tables
that are frequently accessed.
This is due to [LockManager LWLock contention](https://gitlab.com/groups/gitlab-org/-/epics/11543).
For the same reason, there are also RuboCop checks (`AddColumnsToWideTables`) against adding
new columns to these tables.
### Add index and make application code change together if possible
To minimize the risk of creating unnecessary indexes, do these in the same merge request if possible:
- Make application code changes.
- Create or remove indexes.
The migrations that create indexes are usually short, and do not significantly increase a merge request's size.
Doing so allows backend and database reviewers to review more efficiently without
switching contexts between merge requests or commits.
## Migration type to use
The authoritative guide is [the migration style guide](../migration_style_guide.md#choose-an-appropriate-migration-type).
When in doubt, consult the guide.
Here are some common scenarios with a recommended choice as a quick reference.
### Add an index to improve existing queries
Use a post-deployment migration.
Existing queries already work without the added indexes, and
would not critical to operating the application.
If indexing takes a long time to finish
(a post-deployment migration should take less than [10 minutes](../migration_style_guide.md#how-long-a-migration-should-take))
consider [indexing asynchronously](#create-indexes-asynchronously).
### Add an index to support new or updated queries
Always examine the query plans for new or updated queries. First, confirm they do not time-out
or significantly exceed [the recommended query timings](query_performance.md)
without a dedicated index.
If the queries don't time-out or breach the query timings:
- Any index added to improve the performance of the new queries is non-critical
to operating the application.
- Use a post-deployment migration to create the index.
- In the same merge request, ship the application code changes that generate and use the new queries.
Queries that time-out or breach query timings require different actions, depending on
whether they do so only on GitLab.com, or for all GitLab instances.
Most features require a dedicated index only for GitLab.com, one of the largest GitLab installations.
#### New or updated queries perform slowly on GitLab.com
Use two MRs to create the index in a post-deployment migration and make the application code change:
- The first MR uses a post-deployment migration to create the index.
- The second MR makes application code changes. It should merge only after the first MR's
post-deployment migrations are executed on GitLab.com.
{{< alert type="note" >}}
If you can use a feature flag, you might be able to use a single MR
to make the code changes behind the feature flag. Include the post-deployment migration at the same time.
After the post-deployment migration executes, you can enable the feature flag.
{{< /alert >}}
For GitLab.com, we execute post-deployment migrations throughout a single release through continuous integration:
- At some time `t`, a group of merge requests are merged and ready to deploy.
- At `t+1`, the regular migrations from the group are executed on GitLab.com's staging and production database.
- At `t+2`, the application code changes from the group start deploying in a rolling manner
After the application code changes are fully deployed,
The release manager can choose to execute post-deployment migrations at their discretion at a much later time.
The post-deployment migration executes one time per day pending GitLab.com availability.
For this reason, you need a [confirmation](https://gitlab.com/gitlab-org/release/docs/-/tree/master/general/post_deploy_migration#how-to-determine-if-a-post-deploy-migration-has-been-executed-on-gitlabcom)
the post-deployment migrations included in the first MR were executed before merging the second MR.
#### New or updated queries might be slow on a large GitLab instance
It's not possible to check query performance directly on GitLab Self-Managed instances.
PostgreSQL produces an execution plan based on the data distribution, so
guessing query performance is a hard task.
If you are concerned about the performance of a query on GitLab Self-Managed instances
and decide that GitLab Self-Managed instances must have an index, follow these recommendations:
- For GitLab Self-Managed instances following [zero-downtime](../../update/zero_downtime.md)
upgrades, post-deploy migrations execute when performing an upgrade after the application code deploys.
- For GitLab Self-Managed instances that do not follow a zero-downtime upgrade,
the administrator might choose to execute the post-deployment migrations for a release later,
at the time of their choosing, after the regular migrations execute. The application code deploys when they upgrade.
For this reason, an application must not assume a database schema applied by the
post-deployment migrations has shipped in the same release. The application code
should continue to work without the indexes added in the post-deployment migrations
in the same release.
You have two options depending on [how long it takes to create the index](../migration_style_guide.md#how-long-a-migration-should-take):
1. Single release: if a regular migration can create the required index very fast
(usually because the table is new or very small) you can create the index in a
regular migration, and ship the application code change in the same MR and milestone.
1. At least two releases: if the required index takes time to create,
you must create it in a PDM in one release then wait for the next release to
make the application code changes that rely on the index.
### Add a unique index acting as a constraint to an existing table
PostgreSQL's unique index acts as a constraint. Adding one to an existing table can be tricky.
Unless the table is absolutely guaranteed to be tiny for GitLab.com and GitLab Self-Managed instances,
you must use multiple post-deployment migrations over multiple releases to:
- Remove and(or) fix the duplicate records.
- Introduce a unique index constraining existing columns.
Refer to the multi-release approach outlined in
[the section for adding a NOT NULL constraint](not_null_constraints.md#add-a-not-null-constraint-to-an-existing-column).
PostgreSQL's unique index, unlike the regular constraints, cannot be introduced in a non-validated state.
You must use PostgreSQL's partial unique index and the application validation to enforce the desired uniqueness
for new and updated records while the removal and fix are in progress.
The details of the work might vary and require different approaches.
Consult the Database team, reviewers, or maintainers to plan the work.
## Dropping unused indexes
Unused indexes should be dropped because they increase [maintenance overhead](#maintenance-overhead), consume
disk space, and can degrade query planning efficiency without providing any performance benefit.
However, dropping an index that's still used could result in query performance degradation or timeouts,
potentially leading to incidents. It's important to [verify the index is unused](#verifying-that-an-index-is-unused)
on both on GitLab.com and GitLab Self-Managed instances prior to removal.
- For large tables, consider [dropping the index asynchronously](#drop-indexes-asynchronously).
- For partitioned tables, only the parent index can be dropped. PostgreSQL does not permit child indexes
(i.e. the corresponding indexes on its partitions) to be independently removed.
### Finding possible unused indexes
To see which indexes are candidates for removal, you can run the following query:
```sql
SELECT relname as table_name, indexrelname as index_name, idx_scan, idx_tup_read, idx_tup_fetch, pg_size_pretty(pg_relation_size(indexrelname::regclass))
FROM pg_stat_all_indexes
WHERE schemaname = 'public'
AND idx_scan = 0
AND idx_tup_read = 0
AND idx_tup_fetch = 0
ORDER BY pg_relation_size(indexrelname::regclass) desc;
```
This query outputs a list containing all indexes that have not been used since the stats were last reset and sorts
them by index size in descending order. More information on the meaning of the various columns can be found at
<https://www.postgresql.org/docs/16/monitoring-stats.html>.
For GitLab.com, you can check the latest generated [production reports](https://console.postgres.ai/gitlab/reports/)
on postgres.ai and inspect the `H002 Unused Indexes` file.
{{< alert type="warning" >}}
These reports only show indexes that have no recorded usage **since the last statistics reset.**
They do not guarantee that the indexes are never used.
{{< /alert >}}
### Verifying that an index is unused
This section contains resources to help you evaluate an index and confirm that it's safe to remove. Note that
this is only a suggested guide and is not exhaustive. Ultimately, the goal is to gather enough data to justify
dropping the index.
Be aware that certain factors can give the false impression that an index is unused, such as:
- There may be queries that run on GitLab Self-Managed but not on GitLab.com.
- The index may be used for very infrequent processes such as periodic cron jobs.
- On tables that have little data, PostgreSQL may initially prefer a sequential scan over an index scan
until the table is large enough.
#### Investigating index usage
1. Start by gathering all the metadata available for the index, verifying its name and definition.
- The index name in the development environment may not match production. It's important to correlate the indexes
based on definition rather than name. To check its definition, you can:
- Manually inspect [db/structure.sql](https://gitlab.com/gitlab-org/gitlab/-/blob/master/db/structure.sql)
(This file does **not** include data on dynamically generated partitions.)
- [Use Database Lab to check the status of an index.](database_lab.md#checking-indexes)
- For partitioned tables, child indexes are often named differently than the parent index.
To list all child indexes, you can:
- Run `\d+ <PARENT_INDEX_NAME>` in [Database Lab](database_lab.md).
- Run the following query to see the full parent-child index structure in more detail:
```sql
SELECT
parent_idx.relname AS parent_index,
child_tbl.relname AS child_table,
child_idx.relname AS child_index,
dep.deptype,
pg_get_indexdef(child_idx.oid) AS child_index_def
FROM
pg_class parent_idx
JOIN pg_depend dep ON dep.refobjid = parent_idx.oid
JOIN pg_class child_idx ON child_idx.oid = dep.objid
JOIN pg_index i ON i.indexrelid = child_idx.oid
JOIN pg_class child_tbl ON i.indrelid = child_tbl.oid
WHERE
parent_idx.relname = '<PARENT_INDEX_NAME>';
```
1. For GitLab.com, you can view index usage data in [Grafana](https://dashboards.gitlab.net/goto/TsYVxcBHR?orgId=1).
- Query the metric `pg_stat_user_indexes_idx_scan` filtered by the relevant index(s) for at least the last 6 months.
The query below shows index usage rate across all database instances combined.
```sql
sum by (indexrelname) (rate(pg_stat_user_indexes_idx_scan{env="gprd", relname=~"<TABLE_NAME_REGEX>", indexrelname=~"<INDEX_NAME_REGEX>"}[30d]))
```
- For partitioned tables, we must check that **all child indexes are unused** prior to dropping the parent.
If the data shows that an index has zero or negligible usage, it's a strong candidate for removal. However, keep in mind that
this is limited to usage on GitLab.com. We should still [investigate all related queries](#investigating-related-queries) to
ensure it can be safely removed for GitLab Self-Managed instances.
An index that shows low usage may still be dropped **if** we can confirm that other existing indexes would sufficiently
support the queries using it. PostgreSQL decides which index to use based on data distribution statistics, so in certain
situations it may slightly prefer one index over another even if both indexes adequately support the query, which may
account for the occasional usage.
#### Investigating related queries
The following are ways to find all queries that may utilize the index. It's important to understand the context in
which the queries are or may be executed so that we can determine if the index either:
- Has no queries on GitLab.com nor on GitLab Self-Managed that depend on it.
- Can be sufficiently supported by other existing indexes.
1. Investigate the origins of the index.
- Dig through the commit history, related merge requests, and issues that introduced the index.
- Try to find answers to questions such as:
- Why was the index added in the first place? What query was it meant to support?
- Does that query still exist and get executed?
- Is it only applicable to GitLab Self-Managed instances?
1. Examine queries outputted from running the [`rspec:merge-auto-explain-logs`](https://gitlab.com/gitlab-org/gitlab/-/jobs/9805995367) CI job.
- This job collects and analyzes queries executed through tests. The output is saved as an artifact: `auto_explain/auto_explain.ndjson.gz`
- Since we don't always have 100% test coverage, this job may not capture all possible queries and variations.
1. Examine queries recorded in [postgres logs](https://log.gprd.gitlab.net/app/r/s/A55hK) on Kibana.
- Generally, you can filter for `json.sql` values that contain the table name and key column(s) from the index definition. Example KQL:
```plaintext
json.sql: <TABLE_NAME> AND json.sql: *<COLUMN_NAME>*
```
- While there are many factors that affect index usage, the query's filtering and ordering clauses often have the most influence.
A general guideline is to find queries whose conditions align with the index structure. For example, PostgreSQL is more likely
to utilize a B-Tree index for queries that filter on the index's leading column(s) and satisfy its partial predicate (if any).
- Caveat: We only keep the last 7 days of logs and this data does not apply to GitLab Self-Managed usage.
1. Manually search through the GitLab codebase.
- This process may be tedious but it's the most reliable way to ensure there are no other queries we missed from the previous actions,
especially ones that are infrequent or only apply to GitLab Self-Managed instances.
- It's possible there are queries that were introduced some time after the index was initially added,
so we can't always depend on the index origins; we must also examine the current state of the codebase.
- To help direct your search, try to gather context about how the table is used and what features access it. Look for queries
that involve key columns from the index definition, particularly those that are part of the filtering or ordering clauses.
- Another approach is to conduct a keyword search for the model/table name and any relevant columns. However, this could be a
trickier and long-winded process since some queries may be dynamically compiled from code across multiple files.
After collecting the relevant queries, you can then obtain [EXPLAIN plans](understanding_explain_plans.md) to help you assess if a query
relies on the index in question. For this process, it's necessary to have a good understanding of how indexes support queries and how
their usage is affected by data distribution changes. We recommend seeking guidance from a database domain expert to help with your assessment.
## Requirements for naming indexes
Indexes with complex definitions must be explicitly named rather than
relying on the implicit naming behavior of migration methods. In short,
that means you **must** provide an explicit name argument for an index
created with one or more of the following options:
- `where`
- `using`
- `order`
- `length`
- `type`
- `opclass`
### Considerations for index names
Check our [Constraints naming conventions](constraint_naming_convention.md) page.
### Why explicit names are required
As Rails is database agnostic, it generates an index name only
from the required options of all indexes: table name and column names.
For example, imagine the following two indexes are created in a migration:
```ruby
def up
add_index :my_table, :my_column
add_index :my_table, :my_column, where: 'my_column IS NOT NULL'
end
```
Creation of the second index would fail, because Rails would generate
the same name for both indexes.
This naming issue is further complicated by the behavior of the `index_exists?` method.
It considers only the table name, column names, and uniqueness specification
of the index when making a comparison. Consider:
```ruby
def up
unless index_exists?(:my_table, :my_column, where: 'my_column IS NOT NULL')
add_index :my_table, :my_column, where: 'my_column IS NOT NULL'
end
end
```
The call to `index_exists?` returns true if **any** index exists on
`:my_table` and `:my_column`, and index creation is bypassed.
The `add_concurrent_index` helper is a requirement for creating indexes
on populated tables. Because it cannot be used inside a transactional
migration, it has a built-in check that detects if the index already
exists. In the event a match is found, index creation is skipped.
Without an explicit name argument, Rails can return a false positive
for `index_exists?`, causing a required index to not be created
properly. By always requiring a name for certain types of indexes, the
chance of error is greatly reduced.
## Testing for existence of indexes
The easiest way to test for existence of an index by name is to use the `index_name_exists?` method, but the `index_exists?` method can also be used with a name option. For example:
```ruby
class MyMigration < Gitlab::Database::Migration[2.1]
INDEX_NAME = 'index_name'
def up
# an index must be conditionally created due to schema inconsistency
unless index_exists?(:table_name, :column_name, name: INDEX_NAME)
add_index :table_name, :column_name, name: INDEX_NAME
end
end
def down
# no op
end
end
```
Keep in mind that concurrent index helpers like `add_concurrent_index`, `remove_concurrent_index`, and `remove_concurrent_index_by_name` already perform existence checks internally.
## Temporary indexes
There may be times when an index is only needed temporarily.
For example, in a migration, a column of a table might be conditionally
updated. To query which columns must be updated in the
[query performance guidelines](query_performance.md), an index is needed
that would otherwise not be used.
In these cases, consider a temporary index. To specify a
temporary index:
1. Prefix the index name with `tmp_` and follow the [naming conventions](constraint_naming_convention.md).
1. Create a follow-up issue to remove the index in the next (or future) milestone.
1. Add a comment in the migration mentioning the removal issue.
A temporary migration would look like:
```ruby
INDEX_NAME = 'tmp_index_projects_on_owner_where_emails_disabled'
def up
# Temporary index to be removed in 13.9 https://gitlab.com/gitlab-org/gitlab/-/issues/1234
add_concurrent_index :projects, :creator_id, where: 'emails_disabled = false', name: INDEX_NAME
end
def down
remove_concurrent_index_by_name :projects, INDEX_NAME
end
```
## Analyzing a new index before a batched background migration
Sometimes it is necessary to add an index to support a [batched background migration](batched_background_migrations.md).
It is commonly done by creating two [post deployment migrations](post_deployment_migrations.md):
1. Add the new index, often a [temporary index](#temporary-indexes).
1. [Queue the batched background migration](batched_background_migrations.md#enqueue-a-batched-background-migration).
In most cases, no additional work is needed. The new index is created and is used
as expected when queuing and executing the batched background migration.
[Expression indexes](https://www.postgresql.org/docs/16/indexes-expressional.html),
however, do not generate statistics for the new index on creation. Autovacuum
eventually runs `ANALYZE`, and updates the statistics so the new index is used.
Run `ANALYZE` explicitly only if it is needed right after the index
is created, such as in the background migration scenario described above.
To trigger `ANALYZE` after the index is created, update the index creation migration
to analyze the table:
```ruby
# in db/post_migrate/
INDEX_NAME = 'tmp_index_projects_on_owner_and_lower_name_where_emails_disabled'
TABLE = :projects
disable_ddl_transaction!
def up
add_concurrent_index TABLE, '(creator_id, lower(name))', where: 'emails_disabled = false', name: INDEX_NAME
connection.execute("ANALYZE #{TABLE}")
end
```
`ANALYZE` should only be run in post deployment migrations and should not target
[large tables](https://gitlab.com/gitlab-org/gitlab/-/blob/master/rubocop/rubocop-migrations.yml#L3).
If this behavior is needed on a larger table, ask for assistance in the `#database` Slack channel.
## Indexes for partitioned tables
You [cannot create indexes](https://www.postgresql.org/docs/15/ddl-partitioning.html#DDL-PARTITIONING-DECLARATIVE-MAINTENANCE)
concurrently on partitioned tables.
However, creating indexes non-concurrently holds a write lock on the table being indexed.
Therefore, you must use `CONCURRENTLY` when you create indexes to avoid service disruption in a hot system.
As a workaround, the Database team has provided `add_concurrent_partitioned_index`.
This helper creates indexes on partitioned tables without holding a write lock.
Under the hood, `add_concurrent_partitioned_index`:
1. Creates indexes on each partition using `CONCURRENTLY`.
1. Creates an index on the parent table.
A Rails migration example:
```ruby
# in db/post_migrate/
class AddIndexToPartitionedTable < Gitlab::Database::Migration[2.1]
include Gitlab::Database::PartitioningMigrationHelpers
disable_ddl_transaction!
TABLE_NAME = :table_name
COLUMN_NAMES = [:partition_id, :id]
INDEX_NAME = :index_name
def up
add_concurrent_partitioned_index(TABLE_NAME, COLUMN_NAMES, name: INDEX_NAME)
end
def down
remove_concurrent_partitioned_index_by_name(TABLE_NAME, INDEX_NAME)
end
end
```
## Create indexes asynchronously
For very large tables, index creation can be a challenge to manage.
While `add_concurrent_index` creates indexes in a way that does not block
ordinary traffic, it can still be problematic when index creation runs for
many hours. Necessary database operations like `autovacuum` cannot run, and
on GitLab.com, the deployment process is blocked waiting for index
creation to finish.
To limit impact on GitLab.com, a process exists to create indexes
asynchronously during weekend hours. Due to generally lower traffic and fewer deployments,
index creation can proceed at a lower level of risk.
### Schedule index creation for a low-impact time
1. [Schedule the index to be created](#schedule-the-index-to-be-created).
1. [Verify the MR was deployed and the index exists in production](#verify-the-mr-was-deployed-and-the-index-exists-in-production).
1. [Add a migration to create the index synchronously](#add-a-migration-to-create-the-index-synchronously).
### Schedule the index to be created
1. Create a merge request containing a post-deployment migration, which prepares
the index for asynchronous creation.
1. [Create a follow-up issue](https://gitlab.com/gitlab-org/gitlab/-/issues/new?issuable_template=Synchronous%20Database%20Index)
to add a migration that creates the index synchronously.
1. In the merge request that prepares the asynchronous index, add a comment mentioning the follow-up issue.
An example of creating an index using
the asynchronous index helpers can be seen in the block below. This migration
enters the index name and definition into the `postgres_async_indexes`
table. The process that runs on weekends pulls indexes from this
table and attempt to create them.
```ruby
# in db/post_migrate/
INDEX_NAME = 'index_ci_builds_on_some_column'
# TODO: Index to be created synchronously in https://gitlab.com/gitlab-org/gitlab/-/issues/XXXXX
def up
prepare_async_index :ci_builds, :some_column, name: INDEX_NAME
end
def down
unprepare_async_index :ci_builds, :some_column, name: INDEX_NAME
end
```
For partitioned table, use:
```ruby
# in db/post_migrate/
include Gitlab::Database::PartitioningMigrationHelpers
PARTITIONED_INDEX_NAME = 'index_p_ci_builds_on_some_column'
# TODO: Partitioned index to be created synchronously in https://gitlab.com/gitlab-org/gitlab/-/issues/XXXXX
def up
prepare_partitioned_async_index :p_ci_builds, :some_column, name: PARTITIONED_INDEX_NAME
end
def down
unprepare_partitioned_async_index :p_ci_builds, :some_column, name: PARTITIONED_INDEX_NAME
end
```
{{< alert type="note" >}}
Async indexes are only supported for GitLab.com environments,
so `prepare_async_index` and `prepare_partitioned_async_index` are no-ops for other environments.
{{< /alert >}}
{{< alert type="note" >}}
`prepare_partitioned_async_index` only creates the indexes for partitions asynchronously. It doesn't attach the partition indexes to the partitioned table.
In the [next step for the partitioned table](#create-the-index-synchronously-for-partitioned-table), `add_concurrent_partitioned_index` will not only add the index synchronously but also attach the partition indexes to the partitioned table.
{{< /alert >}}
### Verify the MR was deployed and the index exists in production
1. Verify that the post-deploy migration was executed on GitLab.com using ChatOps with
`/chatops run auto_deploy status <merge_sha>`. If the output returns `db/gprd`,
the post-deploy migration has been executed in the production database. For more information, see
[How to determine if a post-deploy migration has been executed on GitLab.com](https://gitlab.com/gitlab-org/release/docs/-/blob/master/general/post_deploy_migration/readme.md#how-to-determine-if-a-post-deploy-migration-has-been-executed-on-gitlabcom).
1. In the case of an [index created asynchronously](#schedule-the-index-to-be-created), wait
until the next week so that the index can be created over a weekend.
1. Use [Database Lab](database_lab.md) to check [if creation was successful](database_lab.md#checking-indexes).
Ensure the output does not indicate the index is `invalid`.
### Add a migration to create the index synchronously
After the index is verified to exist on the production database, create a second
merge request that adds the index synchronously. The schema changes must be
updated and committed to `structure.sql` in this second merge request.
The synchronous migration results in a no-op on GitLab.com, but you should still add the
migration as expected for other installations. The below block
demonstrates how to create the second migration for the previous
asynchronous example.
{{< alert type="warning" >}}
Verify that the index exists in production before merging a second migration with `add_concurrent_index`.
If the second migration is deployed before the index has been created,
the index is created synchronously when the second migration executes.
{{< /alert >}}
```ruby
# in db/post_migrate/
INDEX_NAME = 'index_ci_builds_on_some_column'
disable_ddl_transaction!
def up
add_concurrent_index :ci_builds, :some_column, name: INDEX_NAME
end
def down
remove_concurrent_index_by_name :ci_builds, INDEX_NAME
end
```
#### Create the index synchronously for partitioned table
```ruby
# in db/post_migrate/
include Gitlab::Database::PartitioningMigrationHelpers
PARTITIONED_INDEX_NAME = 'index_p_ci_builds_on_some_column'
disable_ddl_transaction!
def up
add_concurrent_partitioned_index :p_ci_builds, :some_column, name: PARTITIONED_INDEX_NAME
end
def down
remove_concurrent_partitioned_index_by_name :p_ci_builds, PARTITIONED_INDEX_NAME
end
```
## Test database index changes locally
You must test the database index changes locally before creating a merge request.
### Verify indexes created asynchronously
Use the asynchronous index helpers on your local environment to test changes for creating an index:
1. Enable the feature flags by running `Feature.enable(:database_async_index_creation)` and `Feature.enable(:database_reindexing)` in the Rails console.
1. Run `bundle exec rails db:migrate` so that it creates an entry in the `postgres_async_indexes` table.
<!-- markdownlint-disable MD044 -->
1. Run `bundle exec rails gitlab:db:execute_async_index_operations:all` so that the index is created asynchronously on all databases.
<!-- markdownlint-enable MD044 -->
1. To verify the index, open the PostgreSQL console using the [GDK](https://gitlab.com/gitlab-org/gitlab-development-kit/-/blob/main/doc/howto/postgresql.md) command `gdk psql` and run the command `\d <index_name>` to check that your newly created index exists.
- For indexes created on partitions, check that a unique name has been autogenerated for that table `\d gitlab_partitions_dynamic.<table_name>`
## Drop indexes asynchronously
For very large tables, index destruction can be a challenge to manage.
While `remove_concurrent_index` removes indexes in a way that does not block
ordinary traffic, it can still be problematic if index destruction runs for
many hours. Necessary database operations like `autovacuum` cannot run, and
the deployment process on GitLab.com is blocked while waiting for index
destruction to finish.
To limit the impact on GitLab.com, use the following process to remove indexes
asynchronously during weekend hours. Due to generally lower traffic and fewer deployments,
index destruction can proceed at a lower level of risk.
1. [Schedule the index to be removed](#schedule-the-index-to-be-removed).
1. [Verify the MR was deployed and the index exists in production](#verify-the-mr-was-deployed-and-the-index-no-longer-exists-in-production).
1. [Add a migration to destroy the index synchronously](#add-a-migration-to-destroy-the-index-synchronously).
### Schedule the index to be removed
1. Create a merge request containing a post-deployment migration, which prepares
the index for asynchronous destruction.
1. [Create a follow-up issue](https://gitlab.com/gitlab-org/gitlab/-/issues/new?issuable_template=Synchronous%20Database%20Index)
to add a migration that destroys the index synchronously.
1. In the merge request that prepares the asynchronous index removal, add a comment mentioning the follow-up issue.
For example, to destroy an index using
the asynchronous index helpers:
```ruby
# in db/post_migrate/
INDEX_NAME = 'index_ci_builds_on_some_column'
# TODO: Index to be destroyed synchronously in https://gitlab.com/gitlab-org/gitlab/-/issues/XXXXX
def up
prepare_async_index_removal :ci_builds, :some_column, name: INDEX_NAME
end
def down
unprepare_async_index :ci_builds, :some_column, name: INDEX_NAME
end
```
This migration enters the index name and definition into the `postgres_async_indexes`
table. The process that runs on weekends pulls indexes from this table and attempt
to remove them.
You must [test the database index changes locally](#verify-indexes-removed-asynchronously) before creating a merge request.
Include the output of the test in the merge request description.
### Verify the MR was deployed and the index no longer exists in production
1. Verify that the post-deploy migration was executed on GitLab.com using ChatOps with
`/chatops run auto_deploy status <merge_sha>`. If the output returns `db/gprd`,
the post-deploy migration has been executed in the production database. For more information, see
[How to determine if a post-deploy migration has been executed on GitLab.com](https://gitlab.com/gitlab-org/release/docs/-/blob/master/general/post_deploy_migration/readme.md#how-to-determine-if-a-post-deploy-migration-has-been-executed-on-gitlabcom).
1. In the case of an [index removed asynchronously](#schedule-the-index-to-be-removed), wait
until the next week so that the index can be removed over a weekend.
1. Use Database Lab [to check if removal was successful](database_lab.md#checking-indexes).
[Database Lab](database_lab.md)
should report an error when trying to find the removed index. If not, the index may still exist.
### Add a migration to destroy the index synchronously
After you verify the index no longer exists in the production database, create a second
merge request that removes the index synchronously. The schema changes must be
updated and committed to `structure.sql` in this second merge request.
The synchronous migration results in a no-op on GitLab.com, but you should still add the
migration as expected for other installations. For example, to
create the second migration for the previous asynchronous example:
{{< alert type="warning" >}}
Verify that the index no longer exists in production before merging a second migration with `remove_concurrent_index_by_name`.
If the second migration is deployed before the index has been destroyed,
the index is destroyed synchronously when the second migration executes.
{{< /alert >}}
```ruby
# in db/post_migrate/
INDEX_NAME = 'index_ci_builds_on_some_column'
disable_ddl_transaction!
def up
remove_concurrent_index_by_name :ci_builds, name: INDEX_NAME
end
def down
add_concurrent_index :ci_builds, :some_column, name: INDEX_NAME
end
```
### Verify indexes removed asynchronously
To test changes for removing an index, use the asynchronous index helpers on your local environment:
1. Enable the feature flags by running `Feature.enable(:database_reindexing)` in the Rails console.
1. Run `bundle exec rails db:migrate` which should create an entry in the `postgres_async_indexes` table.
1. Run `bundle exec rails gitlab:db:reindex` destroy the index asynchronously.
1. To verify the index, open the PostgreSQL console by using the [GDK](https://gitlab.com/gitlab-org/gitlab-development-kit/-/blob/main/doc/howto/postgresql.md)
command `gdk psql` and run `\d <index_name>` to check that the destroyed index no longer exists.
|
---
stage: Data Access
group: Database Frameworks
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: Adding Database Indexes
breadcrumbs:
- doc
- development
- database
---
Indexes can be used to speed up database queries, but when should you add a new
index? Traditionally the answer to this question has been to add an index for
every column used for filtering or joining data. For example, consider the
following query:
```sql
SELECT *
FROM projects
WHERE user_id = 2;
```
Here we are filtering by the `user_id` column and as such a developer may decide
to index this column.
While in certain cases indexing columns using the above approach may make sense,
it can actually have a negative impact. Whenever you write data to a table, any
existing indexes must also be updated. The more indexes there are, the slower this
can potentially become. Indexes can also take up significant disk space, depending
on the amount of data indexed and the index type. For example, PostgreSQL offers
`GIN` indexes which can be used to index certain data types that cannot be
indexed by regular B-tree indexes. These indexes, however, generally take up more
data and are slower to update compared to B-tree indexes.
Because of all this, it's important make the following considerations
when adding a new index:
1. Do the new queries re-use as many existing indexes as possible?
1. Is there enough data that using an index is faster than iterating over
rows in the table?
1. Is the overhead of maintaining the index worth the reduction in query
timings?
In some situations, an index might not be required:
- The table is small (less than `1,000` records) and it's not expected to exponentially grow in size.
- Any existing indexes filter out enough rows.
- The reduction in query timings after the index is added is not significant.
Additionally, wide indexes are not required to match all filter criteria of queries. We just need
to cover enough columns so that the index lookup has a small enough selectivity.
## Re-using Queries
The first step is to make sure your query re-uses as many existing indexes as
possible. For example, consider the following query:
```sql
SELECT *
FROM todos
WHERE user_id = 123
AND state = 'open';
```
Now imagine we already have an index on the `user_id` column but not on the
`state` column. One may think this query performs badly due to `state` being
unindexed. In reality the query may perform just fine given the index on
`user_id` can filter out enough rows.
The best way to determine if indexes are re-used is to run your query using
`EXPLAIN ANALYZE`. Depending on the joined tables and the columns being used for filtering,
you may find an extra index doesn't make much, if any, difference.
In short:
1. Try to write your query in such a way that it re-uses as many existing
indexes as possible.
1. Run the query using `EXPLAIN ANALYZE` and study the output to find the most
ideal query.
## Partial Indexes
Partial indexes are indexes with a `WHERE` clause that limits them to a subset of matching rows.
They can offer several advantages over full indexes, including:
- Reduced index size and memory usage
- Less write and vacuum overhead
- Improved query performance for selective conditions
Partial indexes work best for queries that always filter on known conditions and target a specific subset of data.
Common use cases include:
- Nullable columns: `WHERE column IS NOT NULL`
- Boolean flags: `WHERE feature_enabled = true`
- Soft deletes: `WHERE deleted_at IS NULL`
- Status filters: `WHERE status IN ('queued', 'running')`
Before creating any new partial index, first examine existing indexes for potential reuse or modification.
Since each index incurs maintenance overhead, prioritize adapting current indexes over adding new ones.
### Example
Consider the following application code which introduces a new count query:
```ruby
def namespace_count
NamespaceSetting.where(duo_features_enabled: duo_settings_value).count
end
def duo_settings_value
params['duo_settings_value'] == 'default_on'
end
```
where `namespace_settings` is a table with 1 million records,
and `duo_features_enabled` is a nullable Boolean column.
Let's assume that we recently introduced this column and it was not backfilled.
This means we know that the majority of the records in the `namespace_settings` table have a `NULL`
value for `duo_features_enabled`. We can also see that `duo_settings_value` will only either yield
`true` or `false`.
Indexing all rows would be inefficient as we mostly have `NULL` values. Instead,
we can introduce a partial index that targets only the data of interest:
```sql
CREATE INDEX index_namespace_settings_on_duo_features_enabled_not_null
ON namespace_settings (duo_features_enabled)
WHERE duo_features_enabled IS NOT NULL;
```
Now we have an index that is just a small fraction of the full index size and the
query planner can effectively skip over hundreds of thousands of irrelevant records.
## Data Size
A database may not use an index even when a regular sequence scan
(iterating over all rows) is faster, especially for small tables.
Consider adding an index if a table is expected to grow, and your query has to filter a lot of rows.
You may not want to add an index if the table size is small (<`1,000` records),
or if existing indexes already filter out enough rows.
## Maintenance Overhead
Indexes have to be updated on every table write. In the case of PostgreSQL, _all_
existing indexes are updated whenever data is written to a table. As a
result, having many indexes on the same table slows down writes. It's therefore important
to balance query performance with the overhead of maintaining an extra index.
For example, if adding an index reduces SELECT timings by 5 milliseconds but increases
INSERT/UPDATE/DELETE timings by 10 milliseconds, the new index may not be worth
it. A new index is more valuable when SELECT timings are reduced and INSERT/UPDATE/DELETE
timings are unaffected.
### Index limitations
GitLab enforces a limit of **15 indexes** per table. This limitation:
- Helps maintain optimal database performance
- Reduces maintenance overhead
- Prevents excessive disk space usage
{{< alert type="note" >}}
If you need to add an index to a table that already has 15 indexes, consider:
{{< /alert >}}
- Removing unused indexes
- Combining existing indexes
- Using a composite index that can serve multiple query patterns
### Some tables should not have any more indexes
We have RuboCop checks (`PreventIndexCreation`) against further new indexes on selected tables
that are frequently accessed.
This is due to [LockManager LWLock contention](https://gitlab.com/groups/gitlab-org/-/epics/11543).
For the same reason, there are also RuboCop checks (`AddColumnsToWideTables`) against adding
new columns to these tables.
### Add index and make application code change together if possible
To minimize the risk of creating unnecessary indexes, do these in the same merge request if possible:
- Make application code changes.
- Create or remove indexes.
The migrations that create indexes are usually short, and do not significantly increase a merge request's size.
Doing so allows backend and database reviewers to review more efficiently without
switching contexts between merge requests or commits.
## Migration type to use
The authoritative guide is [the migration style guide](../migration_style_guide.md#choose-an-appropriate-migration-type).
When in doubt, consult the guide.
Here are some common scenarios with a recommended choice as a quick reference.
### Add an index to improve existing queries
Use a post-deployment migration.
Existing queries already work without the added indexes, and
would not critical to operating the application.
If indexing takes a long time to finish
(a post-deployment migration should take less than [10 minutes](../migration_style_guide.md#how-long-a-migration-should-take))
consider [indexing asynchronously](#create-indexes-asynchronously).
### Add an index to support new or updated queries
Always examine the query plans for new or updated queries. First, confirm they do not time-out
or significantly exceed [the recommended query timings](query_performance.md)
without a dedicated index.
If the queries don't time-out or breach the query timings:
- Any index added to improve the performance of the new queries is non-critical
to operating the application.
- Use a post-deployment migration to create the index.
- In the same merge request, ship the application code changes that generate and use the new queries.
Queries that time-out or breach query timings require different actions, depending on
whether they do so only on GitLab.com, or for all GitLab instances.
Most features require a dedicated index only for GitLab.com, one of the largest GitLab installations.
#### New or updated queries perform slowly on GitLab.com
Use two MRs to create the index in a post-deployment migration and make the application code change:
- The first MR uses a post-deployment migration to create the index.
- The second MR makes application code changes. It should merge only after the first MR's
post-deployment migrations are executed on GitLab.com.
{{< alert type="note" >}}
If you can use a feature flag, you might be able to use a single MR
to make the code changes behind the feature flag. Include the post-deployment migration at the same time.
After the post-deployment migration executes, you can enable the feature flag.
{{< /alert >}}
For GitLab.com, we execute post-deployment migrations throughout a single release through continuous integration:
- At some time `t`, a group of merge requests are merged and ready to deploy.
- At `t+1`, the regular migrations from the group are executed on GitLab.com's staging and production database.
- At `t+2`, the application code changes from the group start deploying in a rolling manner
After the application code changes are fully deployed,
The release manager can choose to execute post-deployment migrations at their discretion at a much later time.
The post-deployment migration executes one time per day pending GitLab.com availability.
For this reason, you need a [confirmation](https://gitlab.com/gitlab-org/release/docs/-/tree/master/general/post_deploy_migration#how-to-determine-if-a-post-deploy-migration-has-been-executed-on-gitlabcom)
the post-deployment migrations included in the first MR were executed before merging the second MR.
#### New or updated queries might be slow on a large GitLab instance
It's not possible to check query performance directly on GitLab Self-Managed instances.
PostgreSQL produces an execution plan based on the data distribution, so
guessing query performance is a hard task.
If you are concerned about the performance of a query on GitLab Self-Managed instances
and decide that GitLab Self-Managed instances must have an index, follow these recommendations:
- For GitLab Self-Managed instances following [zero-downtime](../../update/zero_downtime.md)
upgrades, post-deploy migrations execute when performing an upgrade after the application code deploys.
- For GitLab Self-Managed instances that do not follow a zero-downtime upgrade,
the administrator might choose to execute the post-deployment migrations for a release later,
at the time of their choosing, after the regular migrations execute. The application code deploys when they upgrade.
For this reason, an application must not assume a database schema applied by the
post-deployment migrations has shipped in the same release. The application code
should continue to work without the indexes added in the post-deployment migrations
in the same release.
You have two options depending on [how long it takes to create the index](../migration_style_guide.md#how-long-a-migration-should-take):
1. Single release: if a regular migration can create the required index very fast
(usually because the table is new or very small) you can create the index in a
regular migration, and ship the application code change in the same MR and milestone.
1. At least two releases: if the required index takes time to create,
you must create it in a PDM in one release then wait for the next release to
make the application code changes that rely on the index.
### Add a unique index acting as a constraint to an existing table
PostgreSQL's unique index acts as a constraint. Adding one to an existing table can be tricky.
Unless the table is absolutely guaranteed to be tiny for GitLab.com and GitLab Self-Managed instances,
you must use multiple post-deployment migrations over multiple releases to:
- Remove and(or) fix the duplicate records.
- Introduce a unique index constraining existing columns.
Refer to the multi-release approach outlined in
[the section for adding a NOT NULL constraint](not_null_constraints.md#add-a-not-null-constraint-to-an-existing-column).
PostgreSQL's unique index, unlike the regular constraints, cannot be introduced in a non-validated state.
You must use PostgreSQL's partial unique index and the application validation to enforce the desired uniqueness
for new and updated records while the removal and fix are in progress.
The details of the work might vary and require different approaches.
Consult the Database team, reviewers, or maintainers to plan the work.
## Dropping unused indexes
Unused indexes should be dropped because they increase [maintenance overhead](#maintenance-overhead), consume
disk space, and can degrade query planning efficiency without providing any performance benefit.
However, dropping an index that's still used could result in query performance degradation or timeouts,
potentially leading to incidents. It's important to [verify the index is unused](#verifying-that-an-index-is-unused)
on both on GitLab.com and GitLab Self-Managed instances prior to removal.
- For large tables, consider [dropping the index asynchronously](#drop-indexes-asynchronously).
- For partitioned tables, only the parent index can be dropped. PostgreSQL does not permit child indexes
(i.e. the corresponding indexes on its partitions) to be independently removed.
### Finding possible unused indexes
To see which indexes are candidates for removal, you can run the following query:
```sql
SELECT relname as table_name, indexrelname as index_name, idx_scan, idx_tup_read, idx_tup_fetch, pg_size_pretty(pg_relation_size(indexrelname::regclass))
FROM pg_stat_all_indexes
WHERE schemaname = 'public'
AND idx_scan = 0
AND idx_tup_read = 0
AND idx_tup_fetch = 0
ORDER BY pg_relation_size(indexrelname::regclass) desc;
```
This query outputs a list containing all indexes that have not been used since the stats were last reset and sorts
them by index size in descending order. More information on the meaning of the various columns can be found at
<https://www.postgresql.org/docs/16/monitoring-stats.html>.
For GitLab.com, you can check the latest generated [production reports](https://console.postgres.ai/gitlab/reports/)
on postgres.ai and inspect the `H002 Unused Indexes` file.
{{< alert type="warning" >}}
These reports only show indexes that have no recorded usage **since the last statistics reset.**
They do not guarantee that the indexes are never used.
{{< /alert >}}
### Verifying that an index is unused
This section contains resources to help you evaluate an index and confirm that it's safe to remove. Note that
this is only a suggested guide and is not exhaustive. Ultimately, the goal is to gather enough data to justify
dropping the index.
Be aware that certain factors can give the false impression that an index is unused, such as:
- There may be queries that run on GitLab Self-Managed but not on GitLab.com.
- The index may be used for very infrequent processes such as periodic cron jobs.
- On tables that have little data, PostgreSQL may initially prefer a sequential scan over an index scan
until the table is large enough.
#### Investigating index usage
1. Start by gathering all the metadata available for the index, verifying its name and definition.
- The index name in the development environment may not match production. It's important to correlate the indexes
based on definition rather than name. To check its definition, you can:
- Manually inspect [db/structure.sql](https://gitlab.com/gitlab-org/gitlab/-/blob/master/db/structure.sql)
(This file does **not** include data on dynamically generated partitions.)
- [Use Database Lab to check the status of an index.](database_lab.md#checking-indexes)
- For partitioned tables, child indexes are often named differently than the parent index.
To list all child indexes, you can:
- Run `\d+ <PARENT_INDEX_NAME>` in [Database Lab](database_lab.md).
- Run the following query to see the full parent-child index structure in more detail:
```sql
SELECT
parent_idx.relname AS parent_index,
child_tbl.relname AS child_table,
child_idx.relname AS child_index,
dep.deptype,
pg_get_indexdef(child_idx.oid) AS child_index_def
FROM
pg_class parent_idx
JOIN pg_depend dep ON dep.refobjid = parent_idx.oid
JOIN pg_class child_idx ON child_idx.oid = dep.objid
JOIN pg_index i ON i.indexrelid = child_idx.oid
JOIN pg_class child_tbl ON i.indrelid = child_tbl.oid
WHERE
parent_idx.relname = '<PARENT_INDEX_NAME>';
```
1. For GitLab.com, you can view index usage data in [Grafana](https://dashboards.gitlab.net/goto/TsYVxcBHR?orgId=1).
- Query the metric `pg_stat_user_indexes_idx_scan` filtered by the relevant index(s) for at least the last 6 months.
The query below shows index usage rate across all database instances combined.
```sql
sum by (indexrelname) (rate(pg_stat_user_indexes_idx_scan{env="gprd", relname=~"<TABLE_NAME_REGEX>", indexrelname=~"<INDEX_NAME_REGEX>"}[30d]))
```
- For partitioned tables, we must check that **all child indexes are unused** prior to dropping the parent.
If the data shows that an index has zero or negligible usage, it's a strong candidate for removal. However, keep in mind that
this is limited to usage on GitLab.com. We should still [investigate all related queries](#investigating-related-queries) to
ensure it can be safely removed for GitLab Self-Managed instances.
An index that shows low usage may still be dropped **if** we can confirm that other existing indexes would sufficiently
support the queries using it. PostgreSQL decides which index to use based on data distribution statistics, so in certain
situations it may slightly prefer one index over another even if both indexes adequately support the query, which may
account for the occasional usage.
#### Investigating related queries
The following are ways to find all queries that may utilize the index. It's important to understand the context in
which the queries are or may be executed so that we can determine if the index either:
- Has no queries on GitLab.com nor on GitLab Self-Managed that depend on it.
- Can be sufficiently supported by other existing indexes.
1. Investigate the origins of the index.
- Dig through the commit history, related merge requests, and issues that introduced the index.
- Try to find answers to questions such as:
- Why was the index added in the first place? What query was it meant to support?
- Does that query still exist and get executed?
- Is it only applicable to GitLab Self-Managed instances?
1. Examine queries outputted from running the [`rspec:merge-auto-explain-logs`](https://gitlab.com/gitlab-org/gitlab/-/jobs/9805995367) CI job.
- This job collects and analyzes queries executed through tests. The output is saved as an artifact: `auto_explain/auto_explain.ndjson.gz`
- Since we don't always have 100% test coverage, this job may not capture all possible queries and variations.
1. Examine queries recorded in [postgres logs](https://log.gprd.gitlab.net/app/r/s/A55hK) on Kibana.
- Generally, you can filter for `json.sql` values that contain the table name and key column(s) from the index definition. Example KQL:
```plaintext
json.sql: <TABLE_NAME> AND json.sql: *<COLUMN_NAME>*
```
- While there are many factors that affect index usage, the query's filtering and ordering clauses often have the most influence.
A general guideline is to find queries whose conditions align with the index structure. For example, PostgreSQL is more likely
to utilize a B-Tree index for queries that filter on the index's leading column(s) and satisfy its partial predicate (if any).
- Caveat: We only keep the last 7 days of logs and this data does not apply to GitLab Self-Managed usage.
1. Manually search through the GitLab codebase.
- This process may be tedious but it's the most reliable way to ensure there are no other queries we missed from the previous actions,
especially ones that are infrequent or only apply to GitLab Self-Managed instances.
- It's possible there are queries that were introduced some time after the index was initially added,
so we can't always depend on the index origins; we must also examine the current state of the codebase.
- To help direct your search, try to gather context about how the table is used and what features access it. Look for queries
that involve key columns from the index definition, particularly those that are part of the filtering or ordering clauses.
- Another approach is to conduct a keyword search for the model/table name and any relevant columns. However, this could be a
trickier and long-winded process since some queries may be dynamically compiled from code across multiple files.
After collecting the relevant queries, you can then obtain [EXPLAIN plans](understanding_explain_plans.md) to help you assess if a query
relies on the index in question. For this process, it's necessary to have a good understanding of how indexes support queries and how
their usage is affected by data distribution changes. We recommend seeking guidance from a database domain expert to help with your assessment.
## Requirements for naming indexes
Indexes with complex definitions must be explicitly named rather than
relying on the implicit naming behavior of migration methods. In short,
that means you **must** provide an explicit name argument for an index
created with one or more of the following options:
- `where`
- `using`
- `order`
- `length`
- `type`
- `opclass`
### Considerations for index names
Check our [Constraints naming conventions](constraint_naming_convention.md) page.
### Why explicit names are required
As Rails is database agnostic, it generates an index name only
from the required options of all indexes: table name and column names.
For example, imagine the following two indexes are created in a migration:
```ruby
def up
add_index :my_table, :my_column
add_index :my_table, :my_column, where: 'my_column IS NOT NULL'
end
```
Creation of the second index would fail, because Rails would generate
the same name for both indexes.
This naming issue is further complicated by the behavior of the `index_exists?` method.
It considers only the table name, column names, and uniqueness specification
of the index when making a comparison. Consider:
```ruby
def up
unless index_exists?(:my_table, :my_column, where: 'my_column IS NOT NULL')
add_index :my_table, :my_column, where: 'my_column IS NOT NULL'
end
end
```
The call to `index_exists?` returns true if **any** index exists on
`:my_table` and `:my_column`, and index creation is bypassed.
The `add_concurrent_index` helper is a requirement for creating indexes
on populated tables. Because it cannot be used inside a transactional
migration, it has a built-in check that detects if the index already
exists. In the event a match is found, index creation is skipped.
Without an explicit name argument, Rails can return a false positive
for `index_exists?`, causing a required index to not be created
properly. By always requiring a name for certain types of indexes, the
chance of error is greatly reduced.
## Testing for existence of indexes
The easiest way to test for existence of an index by name is to use the `index_name_exists?` method, but the `index_exists?` method can also be used with a name option. For example:
```ruby
class MyMigration < Gitlab::Database::Migration[2.1]
INDEX_NAME = 'index_name'
def up
# an index must be conditionally created due to schema inconsistency
unless index_exists?(:table_name, :column_name, name: INDEX_NAME)
add_index :table_name, :column_name, name: INDEX_NAME
end
end
def down
# no op
end
end
```
Keep in mind that concurrent index helpers like `add_concurrent_index`, `remove_concurrent_index`, and `remove_concurrent_index_by_name` already perform existence checks internally.
## Temporary indexes
There may be times when an index is only needed temporarily.
For example, in a migration, a column of a table might be conditionally
updated. To query which columns must be updated in the
[query performance guidelines](query_performance.md), an index is needed
that would otherwise not be used.
In these cases, consider a temporary index. To specify a
temporary index:
1. Prefix the index name with `tmp_` and follow the [naming conventions](constraint_naming_convention.md).
1. Create a follow-up issue to remove the index in the next (or future) milestone.
1. Add a comment in the migration mentioning the removal issue.
A temporary migration would look like:
```ruby
INDEX_NAME = 'tmp_index_projects_on_owner_where_emails_disabled'
def up
# Temporary index to be removed in 13.9 https://gitlab.com/gitlab-org/gitlab/-/issues/1234
add_concurrent_index :projects, :creator_id, where: 'emails_disabled = false', name: INDEX_NAME
end
def down
remove_concurrent_index_by_name :projects, INDEX_NAME
end
```
## Analyzing a new index before a batched background migration
Sometimes it is necessary to add an index to support a [batched background migration](batched_background_migrations.md).
It is commonly done by creating two [post deployment migrations](post_deployment_migrations.md):
1. Add the new index, often a [temporary index](#temporary-indexes).
1. [Queue the batched background migration](batched_background_migrations.md#enqueue-a-batched-background-migration).
In most cases, no additional work is needed. The new index is created and is used
as expected when queuing and executing the batched background migration.
[Expression indexes](https://www.postgresql.org/docs/16/indexes-expressional.html),
however, do not generate statistics for the new index on creation. Autovacuum
eventually runs `ANALYZE`, and updates the statistics so the new index is used.
Run `ANALYZE` explicitly only if it is needed right after the index
is created, such as in the background migration scenario described above.
To trigger `ANALYZE` after the index is created, update the index creation migration
to analyze the table:
```ruby
# in db/post_migrate/
INDEX_NAME = 'tmp_index_projects_on_owner_and_lower_name_where_emails_disabled'
TABLE = :projects
disable_ddl_transaction!
def up
add_concurrent_index TABLE, '(creator_id, lower(name))', where: 'emails_disabled = false', name: INDEX_NAME
connection.execute("ANALYZE #{TABLE}")
end
```
`ANALYZE` should only be run in post deployment migrations and should not target
[large tables](https://gitlab.com/gitlab-org/gitlab/-/blob/master/rubocop/rubocop-migrations.yml#L3).
If this behavior is needed on a larger table, ask for assistance in the `#database` Slack channel.
## Indexes for partitioned tables
You [cannot create indexes](https://www.postgresql.org/docs/15/ddl-partitioning.html#DDL-PARTITIONING-DECLARATIVE-MAINTENANCE)
concurrently on partitioned tables.
However, creating indexes non-concurrently holds a write lock on the table being indexed.
Therefore, you must use `CONCURRENTLY` when you create indexes to avoid service disruption in a hot system.
As a workaround, the Database team has provided `add_concurrent_partitioned_index`.
This helper creates indexes on partitioned tables without holding a write lock.
Under the hood, `add_concurrent_partitioned_index`:
1. Creates indexes on each partition using `CONCURRENTLY`.
1. Creates an index on the parent table.
A Rails migration example:
```ruby
# in db/post_migrate/
class AddIndexToPartitionedTable < Gitlab::Database::Migration[2.1]
include Gitlab::Database::PartitioningMigrationHelpers
disable_ddl_transaction!
TABLE_NAME = :table_name
COLUMN_NAMES = [:partition_id, :id]
INDEX_NAME = :index_name
def up
add_concurrent_partitioned_index(TABLE_NAME, COLUMN_NAMES, name: INDEX_NAME)
end
def down
remove_concurrent_partitioned_index_by_name(TABLE_NAME, INDEX_NAME)
end
end
```
## Create indexes asynchronously
For very large tables, index creation can be a challenge to manage.
While `add_concurrent_index` creates indexes in a way that does not block
ordinary traffic, it can still be problematic when index creation runs for
many hours. Necessary database operations like `autovacuum` cannot run, and
on GitLab.com, the deployment process is blocked waiting for index
creation to finish.
To limit impact on GitLab.com, a process exists to create indexes
asynchronously during weekend hours. Due to generally lower traffic and fewer deployments,
index creation can proceed at a lower level of risk.
### Schedule index creation for a low-impact time
1. [Schedule the index to be created](#schedule-the-index-to-be-created).
1. [Verify the MR was deployed and the index exists in production](#verify-the-mr-was-deployed-and-the-index-exists-in-production).
1. [Add a migration to create the index synchronously](#add-a-migration-to-create-the-index-synchronously).
### Schedule the index to be created
1. Create a merge request containing a post-deployment migration, which prepares
the index for asynchronous creation.
1. [Create a follow-up issue](https://gitlab.com/gitlab-org/gitlab/-/issues/new?issuable_template=Synchronous%20Database%20Index)
to add a migration that creates the index synchronously.
1. In the merge request that prepares the asynchronous index, add a comment mentioning the follow-up issue.
An example of creating an index using
the asynchronous index helpers can be seen in the block below. This migration
enters the index name and definition into the `postgres_async_indexes`
table. The process that runs on weekends pulls indexes from this
table and attempt to create them.
```ruby
# in db/post_migrate/
INDEX_NAME = 'index_ci_builds_on_some_column'
# TODO: Index to be created synchronously in https://gitlab.com/gitlab-org/gitlab/-/issues/XXXXX
def up
prepare_async_index :ci_builds, :some_column, name: INDEX_NAME
end
def down
unprepare_async_index :ci_builds, :some_column, name: INDEX_NAME
end
```
For partitioned table, use:
```ruby
# in db/post_migrate/
include Gitlab::Database::PartitioningMigrationHelpers
PARTITIONED_INDEX_NAME = 'index_p_ci_builds_on_some_column'
# TODO: Partitioned index to be created synchronously in https://gitlab.com/gitlab-org/gitlab/-/issues/XXXXX
def up
prepare_partitioned_async_index :p_ci_builds, :some_column, name: PARTITIONED_INDEX_NAME
end
def down
unprepare_partitioned_async_index :p_ci_builds, :some_column, name: PARTITIONED_INDEX_NAME
end
```
{{< alert type="note" >}}
Async indexes are only supported for GitLab.com environments,
so `prepare_async_index` and `prepare_partitioned_async_index` are no-ops for other environments.
{{< /alert >}}
{{< alert type="note" >}}
`prepare_partitioned_async_index` only creates the indexes for partitions asynchronously. It doesn't attach the partition indexes to the partitioned table.
In the [next step for the partitioned table](#create-the-index-synchronously-for-partitioned-table), `add_concurrent_partitioned_index` will not only add the index synchronously but also attach the partition indexes to the partitioned table.
{{< /alert >}}
### Verify the MR was deployed and the index exists in production
1. Verify that the post-deploy migration was executed on GitLab.com using ChatOps with
`/chatops run auto_deploy status <merge_sha>`. If the output returns `db/gprd`,
the post-deploy migration has been executed in the production database. For more information, see
[How to determine if a post-deploy migration has been executed on GitLab.com](https://gitlab.com/gitlab-org/release/docs/-/blob/master/general/post_deploy_migration/readme.md#how-to-determine-if-a-post-deploy-migration-has-been-executed-on-gitlabcom).
1. In the case of an [index created asynchronously](#schedule-the-index-to-be-created), wait
until the next week so that the index can be created over a weekend.
1. Use [Database Lab](database_lab.md) to check [if creation was successful](database_lab.md#checking-indexes).
Ensure the output does not indicate the index is `invalid`.
### Add a migration to create the index synchronously
After the index is verified to exist on the production database, create a second
merge request that adds the index synchronously. The schema changes must be
updated and committed to `structure.sql` in this second merge request.
The synchronous migration results in a no-op on GitLab.com, but you should still add the
migration as expected for other installations. The below block
demonstrates how to create the second migration for the previous
asynchronous example.
{{< alert type="warning" >}}
Verify that the index exists in production before merging a second migration with `add_concurrent_index`.
If the second migration is deployed before the index has been created,
the index is created synchronously when the second migration executes.
{{< /alert >}}
```ruby
# in db/post_migrate/
INDEX_NAME = 'index_ci_builds_on_some_column'
disable_ddl_transaction!
def up
add_concurrent_index :ci_builds, :some_column, name: INDEX_NAME
end
def down
remove_concurrent_index_by_name :ci_builds, INDEX_NAME
end
```
#### Create the index synchronously for partitioned table
```ruby
# in db/post_migrate/
include Gitlab::Database::PartitioningMigrationHelpers
PARTITIONED_INDEX_NAME = 'index_p_ci_builds_on_some_column'
disable_ddl_transaction!
def up
add_concurrent_partitioned_index :p_ci_builds, :some_column, name: PARTITIONED_INDEX_NAME
end
def down
remove_concurrent_partitioned_index_by_name :p_ci_builds, PARTITIONED_INDEX_NAME
end
```
## Test database index changes locally
You must test the database index changes locally before creating a merge request.
### Verify indexes created asynchronously
Use the asynchronous index helpers on your local environment to test changes for creating an index:
1. Enable the feature flags by running `Feature.enable(:database_async_index_creation)` and `Feature.enable(:database_reindexing)` in the Rails console.
1. Run `bundle exec rails db:migrate` so that it creates an entry in the `postgres_async_indexes` table.
<!-- markdownlint-disable MD044 -->
1. Run `bundle exec rails gitlab:db:execute_async_index_operations:all` so that the index is created asynchronously on all databases.
<!-- markdownlint-enable MD044 -->
1. To verify the index, open the PostgreSQL console using the [GDK](https://gitlab.com/gitlab-org/gitlab-development-kit/-/blob/main/doc/howto/postgresql.md) command `gdk psql` and run the command `\d <index_name>` to check that your newly created index exists.
- For indexes created on partitions, check that a unique name has been autogenerated for that table `\d gitlab_partitions_dynamic.<table_name>`
## Drop indexes asynchronously
For very large tables, index destruction can be a challenge to manage.
While `remove_concurrent_index` removes indexes in a way that does not block
ordinary traffic, it can still be problematic if index destruction runs for
many hours. Necessary database operations like `autovacuum` cannot run, and
the deployment process on GitLab.com is blocked while waiting for index
destruction to finish.
To limit the impact on GitLab.com, use the following process to remove indexes
asynchronously during weekend hours. Due to generally lower traffic and fewer deployments,
index destruction can proceed at a lower level of risk.
1. [Schedule the index to be removed](#schedule-the-index-to-be-removed).
1. [Verify the MR was deployed and the index exists in production](#verify-the-mr-was-deployed-and-the-index-no-longer-exists-in-production).
1. [Add a migration to destroy the index synchronously](#add-a-migration-to-destroy-the-index-synchronously).
### Schedule the index to be removed
1. Create a merge request containing a post-deployment migration, which prepares
the index for asynchronous destruction.
1. [Create a follow-up issue](https://gitlab.com/gitlab-org/gitlab/-/issues/new?issuable_template=Synchronous%20Database%20Index)
to add a migration that destroys the index synchronously.
1. In the merge request that prepares the asynchronous index removal, add a comment mentioning the follow-up issue.
For example, to destroy an index using
the asynchronous index helpers:
```ruby
# in db/post_migrate/
INDEX_NAME = 'index_ci_builds_on_some_column'
# TODO: Index to be destroyed synchronously in https://gitlab.com/gitlab-org/gitlab/-/issues/XXXXX
def up
prepare_async_index_removal :ci_builds, :some_column, name: INDEX_NAME
end
def down
unprepare_async_index :ci_builds, :some_column, name: INDEX_NAME
end
```
This migration enters the index name and definition into the `postgres_async_indexes`
table. The process that runs on weekends pulls indexes from this table and attempt
to remove them.
You must [test the database index changes locally](#verify-indexes-removed-asynchronously) before creating a merge request.
Include the output of the test in the merge request description.
### Verify the MR was deployed and the index no longer exists in production
1. Verify that the post-deploy migration was executed on GitLab.com using ChatOps with
`/chatops run auto_deploy status <merge_sha>`. If the output returns `db/gprd`,
the post-deploy migration has been executed in the production database. For more information, see
[How to determine if a post-deploy migration has been executed on GitLab.com](https://gitlab.com/gitlab-org/release/docs/-/blob/master/general/post_deploy_migration/readme.md#how-to-determine-if-a-post-deploy-migration-has-been-executed-on-gitlabcom).
1. In the case of an [index removed asynchronously](#schedule-the-index-to-be-removed), wait
until the next week so that the index can be removed over a weekend.
1. Use Database Lab [to check if removal was successful](database_lab.md#checking-indexes).
[Database Lab](database_lab.md)
should report an error when trying to find the removed index. If not, the index may still exist.
### Add a migration to destroy the index synchronously
After you verify the index no longer exists in the production database, create a second
merge request that removes the index synchronously. The schema changes must be
updated and committed to `structure.sql` in this second merge request.
The synchronous migration results in a no-op on GitLab.com, but you should still add the
migration as expected for other installations. For example, to
create the second migration for the previous asynchronous example:
{{< alert type="warning" >}}
Verify that the index no longer exists in production before merging a second migration with `remove_concurrent_index_by_name`.
If the second migration is deployed before the index has been destroyed,
the index is destroyed synchronously when the second migration executes.
{{< /alert >}}
```ruby
# in db/post_migrate/
INDEX_NAME = 'index_ci_builds_on_some_column'
disable_ddl_transaction!
def up
remove_concurrent_index_by_name :ci_builds, name: INDEX_NAME
end
def down
add_concurrent_index :ci_builds, :some_column, name: INDEX_NAME
end
```
### Verify indexes removed asynchronously
To test changes for removing an index, use the asynchronous index helpers on your local environment:
1. Enable the feature flags by running `Feature.enable(:database_reindexing)` in the Rails console.
1. Run `bundle exec rails db:migrate` which should create an entry in the `postgres_async_indexes` table.
1. Run `bundle exec rails gitlab:db:reindex` destroy the index asynchronously.
1. To verify the index, open the PostgreSQL console by using the [GDK](https://gitlab.com/gitlab-org/gitlab-development-kit/-/blob/main/doc/howto/postgresql.md)
command `gdk psql` and run `\d <index_name>` to check that the destroyed index no longer exists.
|
https://docs.gitlab.com/development/database_migration_pipeline
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/database_migration_pipeline.md
|
2025-08-13
|
doc/development/database
|
[
"doc",
"development",
"database"
] |
database_migration_pipeline.md
|
Data Access
|
Database Frameworks
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Database migration pipeline
| null |
With the [automated migration testing pipeline](https://gitlab.com/gitlab-org/database-team/gitlab-com-database-testing)
we can automatically test migrations in a production-like environment (using [Database Lab](database_lab.md)).
It is based on an [architecture design document](https://handbook.gitlab.com/handbook/engineering/architecture/design-documents/database_testing/).
Migration testing is enabled in the [GitLab project](https://gitlab.com/gitlab-org/gitlab)
for changes that add a new database migration. Trigger this job manually by running the
`db:gitlabcom-database-testing` job within in `test` stage. To avoid wasting resources,
only run this job when your MR is ready for review. Additionally, ensure that the MR has the "database" label for the pipeline to appear in the test stage.
The job starts a pipeline on the [ops GitLab instance](https://ops.gitlab.net/).
For security reasons, access to the pipeline is restricted to database maintainers.
When the pipeline starts, a bot notifies you with a comment in the merge request.
When it finishes, the comment gets updated with the test results.
The comment contains testing information for both the `main` and `ci` databases.
Each database tested has four sections which are described below.
## Summary
The first section of the comment contains a summary of the test results, including:
- **Warnings** - Highlights critical issues such as exceptions or long-running queries.
- **Migrations** - The time each migration took to complete, whether it was successful,
and the increment in the size of the database.
- **Runtime histogram** - Expand this section to see a histogram of query runtimes across all migrations.
## Migration details
The next section of the comment contains detailed information for each migration, including:
- **Details** - The type of migration, total duration, and database size change.
- **Queries** - Every query executed during the migration, along with the number of
calls, timings, and the number of the changed rows.
- **Runtime histogram** - Indicates the distribution of query times for the migration.
### Database size increase
Occasionally, a migration shows a +8.00 KiB size increase, even if the migration was not
expected to result in a size increase. Completing any migration adds a row to the
`schema_migrations` table, which may require a new disk page to be created.
If a new disk page is created, the size of the database will grow by exactly 8 KiB.
## Background migration details
The next section of the comment contains detailed information about each batched background migration, including:
- **Sampling information** - The number of batches sampled during this test run.
Sampled batches are chosen uniformly across the table's ID range. Sampling runs
for 30 minutes, split evenly across each background migration to test.
- **Aggregated query information** - Aggregate data about each query executed across
all the sampled batches, along with the number of calls, timings, and the number of changed rows.
- **Batch runtime histogram** - A histogram of timings for each sampled batch
from the background migration.
- **Query runtime histogram** - A histogram of timings for all queries executed
in any batch of this background migration.
## Clone details and artifacts
Some additional information is included at the bottom of the comment:
- **Migrations pending on GitLab.com** - A summary of migrations not deployed yet
to GitLab.com. This information is useful when testing a migration that was merged
but not deployed yet.
- **Clone details** - A link to the `Postgres.ai` thin clone created for this
testing pipeline, along with information about its expiry. This can be used to
further explore the results of running the migration. Only accessible by
database maintainers or with an access request.
- **Artifacts** - A link to the pipeline's artifacts. Full query logs for each
migration (ending in `.log`) are available there, and only accessible by
database maintainers or with an access request. Details of the specific
batched background migration batches sampled are also available.
## Test changes to the database testing pipeline
To test a change to the database testing pipeline itself, you need:
1. A merge request against GitLab Org.
1. The change to be tested must be present on a branch on GitLab Ops.
Use this self-documented script to test a merge request on GitLab Org against an arbitrary branch on GitLab Ops:
```shell
#! /usr/bin/env bash
# The following must be set on a per-invocation basis:
TESTING_TRIGGER_TOKEN='[REDACTED]' # Testing trigger token created in the CI section of the project
CI_COMMIT_REF_NAME='55-post-notice-on-failure' # The branch on ops that you want to run against
CI_MERGE_REQUEST_IID='117901' # Merge request ID of the MR on gitlab.com that you want to test
SHA="fed6dd8a58d75a0e053a4972765b4fc08c5814a3" # The commit SHA of the HEAD of the branch you want to test on gitlab-org/gitlab
# The following should not be changed between invocations:
CI_JOB_URL='https://gitlab.com/gitlab-org/database-team/gitlab-com-database-testing/-/jobs/1590162939'
# It doesn't appear that CI_JOB_URL has to be set to anything in particular for the pipeline to run
# successfully, but this would usually be the URL to the upstream job that invokes the DB testing pipeline.
CI_MERGE_REQUEST_PROJECT_ID='278964' # gitlab-org/gitlab numeric ID. Shouldn't change.
CI_PROJECT_ID="gitlab-org/gitlab" # The slug identifying gitlab-org/gitlab.
curl --verbose --request POST \
--form "token=$TESTING_TRIGGER_TOKEN" \
--form "ref=$CI_COMMIT_REF_NAME" \
--form "variables[TOP_UPSTREAM_MERGE_REQUEST_IID]=$CI_MERGE_REQUEST_IID" \
--form "variables[TOP_UPSTREAM_MERGE_REQUEST_PROJECT_ID]=$CI_MERGE_REQUEST_PROJECT_ID" \
--form "variables[TOP_UPSTREAM_SOURCE_JOB]=$CI_JOB_URL" \
--form "variables[TOP_UPSTREAM_SOURCE_PROJECT]=$CI_PROJECT_ID" \
--form "variables[VALIDATION_PIPELINE]=true" \
--form "variables[GITLAB_COMMIT_SHA]=$SHA" \
--form "variables[TRIGGER_SOURCE]=$CI_JOB_URL" \
"https://ops.gitlab.net/api/v4/projects/429/trigger/pipeline"
```
|
---
stage: Data Access
group: Database Frameworks
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: Database migration pipeline
breadcrumbs:
- doc
- development
- database
---
With the [automated migration testing pipeline](https://gitlab.com/gitlab-org/database-team/gitlab-com-database-testing)
we can automatically test migrations in a production-like environment (using [Database Lab](database_lab.md)).
It is based on an [architecture design document](https://handbook.gitlab.com/handbook/engineering/architecture/design-documents/database_testing/).
Migration testing is enabled in the [GitLab project](https://gitlab.com/gitlab-org/gitlab)
for changes that add a new database migration. Trigger this job manually by running the
`db:gitlabcom-database-testing` job within in `test` stage. To avoid wasting resources,
only run this job when your MR is ready for review. Additionally, ensure that the MR has the "database" label for the pipeline to appear in the test stage.
The job starts a pipeline on the [ops GitLab instance](https://ops.gitlab.net/).
For security reasons, access to the pipeline is restricted to database maintainers.
When the pipeline starts, a bot notifies you with a comment in the merge request.
When it finishes, the comment gets updated with the test results.
The comment contains testing information for both the `main` and `ci` databases.
Each database tested has four sections which are described below.
## Summary
The first section of the comment contains a summary of the test results, including:
- **Warnings** - Highlights critical issues such as exceptions or long-running queries.
- **Migrations** - The time each migration took to complete, whether it was successful,
and the increment in the size of the database.
- **Runtime histogram** - Expand this section to see a histogram of query runtimes across all migrations.
## Migration details
The next section of the comment contains detailed information for each migration, including:
- **Details** - The type of migration, total duration, and database size change.
- **Queries** - Every query executed during the migration, along with the number of
calls, timings, and the number of the changed rows.
- **Runtime histogram** - Indicates the distribution of query times for the migration.
### Database size increase
Occasionally, a migration shows a +8.00 KiB size increase, even if the migration was not
expected to result in a size increase. Completing any migration adds a row to the
`schema_migrations` table, which may require a new disk page to be created.
If a new disk page is created, the size of the database will grow by exactly 8 KiB.
## Background migration details
The next section of the comment contains detailed information about each batched background migration, including:
- **Sampling information** - The number of batches sampled during this test run.
Sampled batches are chosen uniformly across the table's ID range. Sampling runs
for 30 minutes, split evenly across each background migration to test.
- **Aggregated query information** - Aggregate data about each query executed across
all the sampled batches, along with the number of calls, timings, and the number of changed rows.
- **Batch runtime histogram** - A histogram of timings for each sampled batch
from the background migration.
- **Query runtime histogram** - A histogram of timings for all queries executed
in any batch of this background migration.
## Clone details and artifacts
Some additional information is included at the bottom of the comment:
- **Migrations pending on GitLab.com** - A summary of migrations not deployed yet
to GitLab.com. This information is useful when testing a migration that was merged
but not deployed yet.
- **Clone details** - A link to the `Postgres.ai` thin clone created for this
testing pipeline, along with information about its expiry. This can be used to
further explore the results of running the migration. Only accessible by
database maintainers or with an access request.
- **Artifacts** - A link to the pipeline's artifacts. Full query logs for each
migration (ending in `.log`) are available there, and only accessible by
database maintainers or with an access request. Details of the specific
batched background migration batches sampled are also available.
## Test changes to the database testing pipeline
To test a change to the database testing pipeline itself, you need:
1. A merge request against GitLab Org.
1. The change to be tested must be present on a branch on GitLab Ops.
Use this self-documented script to test a merge request on GitLab Org against an arbitrary branch on GitLab Ops:
```shell
#! /usr/bin/env bash
# The following must be set on a per-invocation basis:
TESTING_TRIGGER_TOKEN='[REDACTED]' # Testing trigger token created in the CI section of the project
CI_COMMIT_REF_NAME='55-post-notice-on-failure' # The branch on ops that you want to run against
CI_MERGE_REQUEST_IID='117901' # Merge request ID of the MR on gitlab.com that you want to test
SHA="fed6dd8a58d75a0e053a4972765b4fc08c5814a3" # The commit SHA of the HEAD of the branch you want to test on gitlab-org/gitlab
# The following should not be changed between invocations:
CI_JOB_URL='https://gitlab.com/gitlab-org/database-team/gitlab-com-database-testing/-/jobs/1590162939'
# It doesn't appear that CI_JOB_URL has to be set to anything in particular for the pipeline to run
# successfully, but this would usually be the URL to the upstream job that invokes the DB testing pipeline.
CI_MERGE_REQUEST_PROJECT_ID='278964' # gitlab-org/gitlab numeric ID. Shouldn't change.
CI_PROJECT_ID="gitlab-org/gitlab" # The slug identifying gitlab-org/gitlab.
curl --verbose --request POST \
--form "token=$TESTING_TRIGGER_TOKEN" \
--form "ref=$CI_COMMIT_REF_NAME" \
--form "variables[TOP_UPSTREAM_MERGE_REQUEST_IID]=$CI_MERGE_REQUEST_IID" \
--form "variables[TOP_UPSTREAM_MERGE_REQUEST_PROJECT_ID]=$CI_MERGE_REQUEST_PROJECT_ID" \
--form "variables[TOP_UPSTREAM_SOURCE_JOB]=$CI_JOB_URL" \
--form "variables[TOP_UPSTREAM_SOURCE_PROJECT]=$CI_PROJECT_ID" \
--form "variables[VALIDATION_PIPELINE]=true" \
--form "variables[GITLAB_COMMIT_SHA]=$SHA" \
--form "variables[TRIGGER_SOURCE]=$CI_JOB_URL" \
"https://ops.gitlab.net/api/v4/projects/429/trigger/pipeline"
```
|
https://docs.gitlab.com/development/post_deployment_migrations
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/post_deployment_migrations.md
|
2025-08-13
|
doc/development/database
|
[
"doc",
"development",
"database"
] |
post_deployment_migrations.md
|
Data Access
|
Database Frameworks
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Post Deployment Migrations
| null |
Post deployment migrations are regular Rails migrations that can optionally be
executed after a deployment. By default these migrations are executed alongside
the other migrations, but this would require a downtime. To skip these migrations you must set the
environment variable `SKIP_POST_DEPLOYMENT_MIGRATIONS` to a non-empty value
when running `rake db:migrate`.
For example, this would run all migrations including any post deployment
migrations:
```shell
bundle exec rake db:migrate
```
This however skips post deployment migrations:
```shell
export SKIP_POST_DEPLOYMENT_MIGRATIONS=true
bundle exec rake db:migrate
```
For GitLab.com, these migrations are executed on a daily basis at the discretion of
release managers through the
[post-deploy migration pipeline](https://gitlab.com/gitlab-org/release/docs/-/blob/master/general/post_deploy_migration/readme.md).
## Deployment Integration
Say you're using Chef for deploying new versions of GitLab and you'd like to run
post deployment migrations after deploying a new version. Let's assume you
usually use the command `chef-client` to do so. To make use of this feature
you'd have to run this command as follows:
```shell
export SKIP_POST_DEPLOYMENT_MIGRATIONS=true
sudo chef-client
```
Once all servers have been updated you can run `chef-client` again on a single
server _without_ the environment variable.
The process is similar for other deployment techniques: first you would deploy
with the environment variable set, then you re-deploy a single
server but with the variable _unset_.
## Creating Migrations
To create a post deployment migration you can use the following Rails generator:
```shell
bundle exec rails g post_deployment_migration migration_name_here
```
This generates the migration file in `db/post_migrate`. These migrations
behave exactly like regular Rails migrations.
## Use Cases
Post deployment migrations can be used to perform migrations that mutate state
that an existing version of GitLab depends on. For example, say you want to
remove a column from a table. This requires downtime as a GitLab instance
depends on this column being present while it's running. Usually you'd follow
these steps in such a case:
1. Stop the GitLab instance
1. Run the migration removing the column
1. Start the GitLab instance again
Using post deployment migrations we can instead follow these steps:
1. Deploy a new version of GitLab while ignoring post deployment migrations
1. Re-run `rake db:migrate` but without the environment variable set
Here we don't need any downtime as the migration takes place _after_ a new
version (which doesn't depend on the column anymore) has been deployed.
Some other examples where these migrations are useful:
- Cleaning up data generated due to a bug in GitLab
- Removing tables
- Migrating jobs from one Sidekiq queue to another
|
---
stage: Data Access
group: Database Frameworks
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: Post Deployment Migrations
breadcrumbs:
- doc
- development
- database
---
Post deployment migrations are regular Rails migrations that can optionally be
executed after a deployment. By default these migrations are executed alongside
the other migrations, but this would require a downtime. To skip these migrations you must set the
environment variable `SKIP_POST_DEPLOYMENT_MIGRATIONS` to a non-empty value
when running `rake db:migrate`.
For example, this would run all migrations including any post deployment
migrations:
```shell
bundle exec rake db:migrate
```
This however skips post deployment migrations:
```shell
export SKIP_POST_DEPLOYMENT_MIGRATIONS=true
bundle exec rake db:migrate
```
For GitLab.com, these migrations are executed on a daily basis at the discretion of
release managers through the
[post-deploy migration pipeline](https://gitlab.com/gitlab-org/release/docs/-/blob/master/general/post_deploy_migration/readme.md).
## Deployment Integration
Say you're using Chef for deploying new versions of GitLab and you'd like to run
post deployment migrations after deploying a new version. Let's assume you
usually use the command `chef-client` to do so. To make use of this feature
you'd have to run this command as follows:
```shell
export SKIP_POST_DEPLOYMENT_MIGRATIONS=true
sudo chef-client
```
Once all servers have been updated you can run `chef-client` again on a single
server _without_ the environment variable.
The process is similar for other deployment techniques: first you would deploy
with the environment variable set, then you re-deploy a single
server but with the variable _unset_.
## Creating Migrations
To create a post deployment migration you can use the following Rails generator:
```shell
bundle exec rails g post_deployment_migration migration_name_here
```
This generates the migration file in `db/post_migrate`. These migrations
behave exactly like regular Rails migrations.
## Use Cases
Post deployment migrations can be used to perform migrations that mutate state
that an existing version of GitLab depends on. For example, say you want to
remove a column from a table. This requires downtime as a GitLab instance
depends on this column being present while it's running. Usually you'd follow
these steps in such a case:
1. Stop the GitLab instance
1. Run the migration removing the column
1. Start the GitLab instance again
Using post deployment migrations we can instead follow these steps:
1. Deploy a new version of GitLab while ignoring post deployment migrations
1. Re-run `rake db:migrate` but without the environment variable set
Here we don't need any downtime as the migration takes place _after_ a new
version (which doesn't depend on the column anymore) has been deployed.
Some other examples where these migrations are useful:
- Cleaning up data generated due to a bug in GitLab
- Removing tables
- Migrating jobs from one Sidekiq queue to another
|
https://docs.gitlab.com/development/database_lab_pgai
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/database_lab_pgai.md
|
2025-08-13
|
doc/development/database
|
[
"doc",
"development",
"database"
] |
database_lab_pgai.md
|
Data Access
|
Database Frameworks
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Database Lab access using the `pgai` Ruby gem
| null |
[@mbobin](https://gitlab.com/mbobin) created the [`pgai` Ruby Gem](https://gitlab.com/mbobin/pgai/#pgai) that
greatly simplifies access to a database clone, with support for:
- Access to all database clones listed in the [Postgres.ai instances page](https://console.postgres.ai/gitlab/instances);
- Multiple `psql` sessions on the same clone.
If you have `AllFeaturesUser` [`psql` access](database_lab.md#access-database-lab-engine),
you can follow the steps below to configure the `pgai` Gem:
1. To get started, you need to gather some values from the [Postgres.ai instances page](https://console.postgres.ai/gitlab/instances):
1. Go to the instance that you want to configure and the on right side of the screen.
1. Under **Connection**, select **Connect**. The menu might be collapsed.
A dialog with everything that's needed for configuration appears, using this format:
```shell
dblab init --url "http://127.0.0.1:<local-port>" --token TOKEN --environment-id <environment-id>
```
```shell
ssh -NTML <local-port>:localhost:<instance-port> <instance-host> -i ~/.ssh/id_rsa
```
1. To configure `ssh`, follow the instruction at [Access the console with `psql`](database_lab.md#access-the-console-with-psql), replacing `${USER}` with your postgres.ai username.
1. Run the following commands:
```shell
gem install pgai
# Before running the following command,
# grab an access token from https://console.postgres.ai/gitlab/tokens
pgai config --prefix=<postgresai-user>
# Grab the respective port values from https://console.postgres.ai/gitlab/instances
# for the instances you'll be using (in this case, for the `main` database instance)
pgai env add --alias main --id <instance-host> --port <instance-port> -n gitlabhq_dblab
```
1. Once this one-time configuration is done, you can use `pgai connect` to connect to a particular database. For
instance, to connect to the `main` database:
```shell
pgai connect main
```
1. Once done with the clone, you can destroy it:
```shell
pgai destroy main
```
|
---
stage: Data Access
group: Database Frameworks
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: Database Lab access using the `pgai` Ruby gem
breadcrumbs:
- doc
- development
- database
---
[@mbobin](https://gitlab.com/mbobin) created the [`pgai` Ruby Gem](https://gitlab.com/mbobin/pgai/#pgai) that
greatly simplifies access to a database clone, with support for:
- Access to all database clones listed in the [Postgres.ai instances page](https://console.postgres.ai/gitlab/instances);
- Multiple `psql` sessions on the same clone.
If you have `AllFeaturesUser` [`psql` access](database_lab.md#access-database-lab-engine),
you can follow the steps below to configure the `pgai` Gem:
1. To get started, you need to gather some values from the [Postgres.ai instances page](https://console.postgres.ai/gitlab/instances):
1. Go to the instance that you want to configure and the on right side of the screen.
1. Under **Connection**, select **Connect**. The menu might be collapsed.
A dialog with everything that's needed for configuration appears, using this format:
```shell
dblab init --url "http://127.0.0.1:<local-port>" --token TOKEN --environment-id <environment-id>
```
```shell
ssh -NTML <local-port>:localhost:<instance-port> <instance-host> -i ~/.ssh/id_rsa
```
1. To configure `ssh`, follow the instruction at [Access the console with `psql`](database_lab.md#access-the-console-with-psql), replacing `${USER}` with your postgres.ai username.
1. Run the following commands:
```shell
gem install pgai
# Before running the following command,
# grab an access token from https://console.postgres.ai/gitlab/tokens
pgai config --prefix=<postgresai-user>
# Grab the respective port values from https://console.postgres.ai/gitlab/instances
# for the instances you'll be using (in this case, for the `main` database instance)
pgai env add --alias main --id <instance-host> --port <instance-port> -n gitlabhq_dblab
```
1. Once this one-time configuration is done, you can use `pgai connect` to connect to a particular database. For
instance, to connect to the `main` database:
```shell
pgai connect main
```
1. Once done with the clone, you can destroy it:
```shell
pgai destroy main
```
|
https://docs.gitlab.com/development/database_lab
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/database_lab.md
|
2025-08-13
|
doc/development/database
|
[
"doc",
"development",
"database"
] |
database_lab.md
|
Data Access
|
Database Frameworks
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Database Lab and Postgres.ai
|
Database access for engineers and related parties.
|
Internal users at GitLab have access to the Database Lab Engine (DLE) and
[postgres.ai](https://console.postgres.ai/) for testing performance of database queries
on replicated production data. Unlike a typical read-only production replica, in the DLE you can
also create, update, and delete rows. You can also test the performance of
schema changes, like additional indexes or columns, in an isolated copy of production data.
## Database Lab quick start
1. [Visit the console](https://console.postgres.ai/).
1. Select **Sign in with Google**. (Not GitLab, as you need Google SSO to connect with our project.)
1. After signing in, select the GitLab organization, select "Joe Bot" in the sidebar, and then visit "Ask Joe".
1. Select the database you're testing against:
- Most queries for the GitLab project run against `gitlab-production-main`.
- If the query is for a CI table, select `gitlab-production-ci`.
- If the query is for the container registry, select `gitlab-production-registry`.
1. Type `explain <Query Text>` in the chat box to get a plan.
## Access Database Lab Engine
Access to the DLE is helpful for:
- Database reviewers and maintainers.
- Engineers who work on merge requests that have large effects on databases.
To access the DLE's services, you can:
- Perform query testing in the Postgres.ai web console.
Employees access both services with their GitLab Google account. Query testing
provides `EXPLAIN` (analyze, buffers) plans for queries executed there.
- Migration testing by triggering a job as a part of a merge request.
- Direct `psql` access to DLE instead of a production replica. Available to authorized users only.
To request `psql` access, file an [access request](https://handbook.gitlab.com/handbook/it/end-user-services/onboarding-access-requests/access-requests/#individual-or-bulk-access-request).
For more assistance, use the `#database` Slack channel.
{{< alert type="note" >}}
If you need only temporary access to a production replica, instead of a Database Lab
clone, follow the runbook procedure for connecting to the
[database console with Teleport](https://gitlab.com/gitlab-com/runbooks/-/blob/master/docs/teleport/Connect_to_Database_Console_via_Teleport.md).
This procedure is similar to [Rails console access with Teleport](https://gitlab.com/gitlab-com/runbooks/-/blob/master/docs/teleport/Connect_to_Rails_Console_via_Teleport.md#how-to-use-teleport-to-connect-to-rails-console).
{{< /alert >}}
### Query testing
You can access Database Lab's query analysis features either:
- In [the Postgres.ai web console](https://console.postgres.ai/gitlab/joe-instances).
Shows only the commands you run.
#### Generate query plans
Query plans are an essential part of the database review process. These plans
enable us to decide quickly if a given query can be performant on GitLab.com.
Running the `explain` command generates an `explain` plan and a link to the Postgres.ai
console with more query analysis. For example, running `EXPLAIN SELECT * FROM application_settings`
does the following:
1. Runs `explain (analyze, buffers) select * from application_settings;` against a database clone.
1. Responds with timing and buffer details from the run.
1. Provides a [detailed, shareable report on the results](https://console.postgres.ai/shared/24d543c9-893b-4ff6-8deb-a8f902f85a53).
#### Making schema changes
Sometimes when testing queries, a contributor may realize that the query needs an index
or other schema change to make added queries more performant. To test the query, run the `exec` command.
For example, running this command:
```sql
exec CREATE INDEX on application_settings USING btree (restricted_visibility_levels)
```
creates the specified index on the table. You can [test queries](#generate-query-plans) leveraging
the new index. `exec` does not return any results, only the time required to execute the query.
#### Reset the clone
After many changes, such as after a destructive query or an ineffective index,
you must start over. To reset your designated clone, run `reset`.
#### Checking indexes
Use Database Lab to check the status of an index with the meta-command `\d <index_name>`.
Caveats:
- Indexes are created in both the `main` and `ci` databases, so be sure to use the instance
that matches the table's `gitlab_schema`. For example, if the index is added to
[`ci_builds`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/db/docs/ci_builds.yml#L14),
use `gitlab-production-ci`.
- Database Lab typically has a small delay of a few hours. If more up-to-date information
is required, you can instead request access to a replica [via Teleport](https://gitlab.com/gitlab-com/runbooks/-/blob/master/docs/teleport/Connect_to_Database_Console_via_Teleport.md)
For example: `\d index_design_management_designs_on_project_id` produces:
```plaintext
Index "public.index_design_management_designs_on_project_id"
Column | Type | Key? | Definition
------------+---------+------+------------
project_id | integer | yes | project_id
btree, for table "public.design_management_designs"
```
In the case of an invalid index, the output ends with `invalid`, like:
```plaintext
Index "public.index_design_management_designs_on_project_id"
Column | Type | Key? | Definition
------------+---------+------+------------
project_id | integer | yes | project_id
btree, for table "public.design_management_designs", invalid
```
If the index doesn't exist, JoeBot throws an error like:
```plaintext
ERROR: psql error: psql:/tmp/psql-query-932227396:1: error: Did not find any relation named "no_index".
```
### Migration testing
For information on testing migrations, review our
[database migration testing documentation](database_migration_pipeline.md).
### Access the console with `psql`
{{< alert type="note" >}}
You must have `AllFeaturesUser` [`psql` access](#access-database-lab-engine) to access the console with `psql`.
{{< /alert >}}
To access the database lab instances, you must:
- File an [access request](https://handbook.gitlab.com/handbook/it/end-user-services/onboarding-access-requests/access-requests/#individual-or-bulk-access-request), requesting the following:
- `AllFeaturesUser` role in Postgres.ai
- `db-lab` role in `chef-repo`
- Have a user data bag entry in [chef-repo](https://gitlab.com/gitlab-com/gl-infra/chef-repo) with your SSH key and the `db-lab` role.
- Configure `ssh` as follows:
```plaintext
Host lb-bastion.db-lab.gitlab.com
# Typically, the username is `name` in `name@gitlab.com`
# or your GitLab's username.
# Check with the access provisioner if it is not working.
# If not provided, defaults to your system username.
User YOUR_USERNAME_HERE
# Path to your SSH key. Adjust or remove if using a different key or SSH agent.
IdentityFile ~/.ssh/id_ed25519
Host *.gitlab-db-lab.internal
User YOUR_USERNAME_HERE # Same as above.
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_ed25519 # Same as above.
ProxyCommand ssh lb-bastion.db-lab.gitlab.com -W %h:%p
```
#### Manual access through the Postgres.ai instances page
Team members with [`psql` access](#access-database-lab-engine), can gain direct access
to a clone via `psql`. Access to `psql` enables you to see data, not just metadata.
To connect to a clone using `psql`:
1. Create a clone from the [desired instance](https://console.postgres.ai/gitlab/instances/).
1. Provide a **Clone ID**: Something that uniquely identifies your clone, such as `yourname-testing-gitlabissue`.
1. Provide a **Database username** and **Database password**: Connects `psql` to your clone.
1. Select **Enable deletion protection** if you need to preserve your clone. Avoid selecting this option.
Clones are removed after 12 hours.
1. In the **Clone details** page of the Postgres.ai web interface, copy and run
the command to start SSH port forwarding for the clone.
1. You may notice that it's suggested to run the command with the `-N` flag, meaning no shell will be started,
so you should not expect any output if it runs successfully.
1. Optionally, you can add `LogLevel DEBUG3` to your `~/.ssh/config`
to output detailed debugging information.
1. After running the command, leave it running to keep the port forwarding active,
and then you can open a new terminal tab to do the next step.
1. In the **Clone details** page of the Postgres.ai web interface, copy and run the `psql` connection string.
Use the password provided at setup and set the `dbname` to `gitlabhq_dblab` (or check what databases are available by using `psql -l` with the same query string but `dbname=postgres`).
After you connect, use clone like you would any `psql` console in production, but with
the added benefit and safety of an isolated writeable environment.
#### Simplified access through `pgai` Ruby gem
For instructions on using the `pgai` Ruby gem, see: [Database Lab access using the pgai Ruby gem](database_lab_pgai.md).
|
---
type: reference, howto
stage: Data Access
group: Database Frameworks
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
description: Database access for engineers and related parties.
title: Database Lab and Postgres.ai
breadcrumbs:
- doc
- development
- database
---
Internal users at GitLab have access to the Database Lab Engine (DLE) and
[postgres.ai](https://console.postgres.ai/) for testing performance of database queries
on replicated production data. Unlike a typical read-only production replica, in the DLE you can
also create, update, and delete rows. You can also test the performance of
schema changes, like additional indexes or columns, in an isolated copy of production data.
## Database Lab quick start
1. [Visit the console](https://console.postgres.ai/).
1. Select **Sign in with Google**. (Not GitLab, as you need Google SSO to connect with our project.)
1. After signing in, select the GitLab organization, select "Joe Bot" in the sidebar, and then visit "Ask Joe".
1. Select the database you're testing against:
- Most queries for the GitLab project run against `gitlab-production-main`.
- If the query is for a CI table, select `gitlab-production-ci`.
- If the query is for the container registry, select `gitlab-production-registry`.
1. Type `explain <Query Text>` in the chat box to get a plan.
## Access Database Lab Engine
Access to the DLE is helpful for:
- Database reviewers and maintainers.
- Engineers who work on merge requests that have large effects on databases.
To access the DLE's services, you can:
- Perform query testing in the Postgres.ai web console.
Employees access both services with their GitLab Google account. Query testing
provides `EXPLAIN` (analyze, buffers) plans for queries executed there.
- Migration testing by triggering a job as a part of a merge request.
- Direct `psql` access to DLE instead of a production replica. Available to authorized users only.
To request `psql` access, file an [access request](https://handbook.gitlab.com/handbook/it/end-user-services/onboarding-access-requests/access-requests/#individual-or-bulk-access-request).
For more assistance, use the `#database` Slack channel.
{{< alert type="note" >}}
If you need only temporary access to a production replica, instead of a Database Lab
clone, follow the runbook procedure for connecting to the
[database console with Teleport](https://gitlab.com/gitlab-com/runbooks/-/blob/master/docs/teleport/Connect_to_Database_Console_via_Teleport.md).
This procedure is similar to [Rails console access with Teleport](https://gitlab.com/gitlab-com/runbooks/-/blob/master/docs/teleport/Connect_to_Rails_Console_via_Teleport.md#how-to-use-teleport-to-connect-to-rails-console).
{{< /alert >}}
### Query testing
You can access Database Lab's query analysis features either:
- In [the Postgres.ai web console](https://console.postgres.ai/gitlab/joe-instances).
Shows only the commands you run.
#### Generate query plans
Query plans are an essential part of the database review process. These plans
enable us to decide quickly if a given query can be performant on GitLab.com.
Running the `explain` command generates an `explain` plan and a link to the Postgres.ai
console with more query analysis. For example, running `EXPLAIN SELECT * FROM application_settings`
does the following:
1. Runs `explain (analyze, buffers) select * from application_settings;` against a database clone.
1. Responds with timing and buffer details from the run.
1. Provides a [detailed, shareable report on the results](https://console.postgres.ai/shared/24d543c9-893b-4ff6-8deb-a8f902f85a53).
#### Making schema changes
Sometimes when testing queries, a contributor may realize that the query needs an index
or other schema change to make added queries more performant. To test the query, run the `exec` command.
For example, running this command:
```sql
exec CREATE INDEX on application_settings USING btree (restricted_visibility_levels)
```
creates the specified index on the table. You can [test queries](#generate-query-plans) leveraging
the new index. `exec` does not return any results, only the time required to execute the query.
#### Reset the clone
After many changes, such as after a destructive query or an ineffective index,
you must start over. To reset your designated clone, run `reset`.
#### Checking indexes
Use Database Lab to check the status of an index with the meta-command `\d <index_name>`.
Caveats:
- Indexes are created in both the `main` and `ci` databases, so be sure to use the instance
that matches the table's `gitlab_schema`. For example, if the index is added to
[`ci_builds`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/db/docs/ci_builds.yml#L14),
use `gitlab-production-ci`.
- Database Lab typically has a small delay of a few hours. If more up-to-date information
is required, you can instead request access to a replica [via Teleport](https://gitlab.com/gitlab-com/runbooks/-/blob/master/docs/teleport/Connect_to_Database_Console_via_Teleport.md)
For example: `\d index_design_management_designs_on_project_id` produces:
```plaintext
Index "public.index_design_management_designs_on_project_id"
Column | Type | Key? | Definition
------------+---------+------+------------
project_id | integer | yes | project_id
btree, for table "public.design_management_designs"
```
In the case of an invalid index, the output ends with `invalid`, like:
```plaintext
Index "public.index_design_management_designs_on_project_id"
Column | Type | Key? | Definition
------------+---------+------+------------
project_id | integer | yes | project_id
btree, for table "public.design_management_designs", invalid
```
If the index doesn't exist, JoeBot throws an error like:
```plaintext
ERROR: psql error: psql:/tmp/psql-query-932227396:1: error: Did not find any relation named "no_index".
```
### Migration testing
For information on testing migrations, review our
[database migration testing documentation](database_migration_pipeline.md).
### Access the console with `psql`
{{< alert type="note" >}}
You must have `AllFeaturesUser` [`psql` access](#access-database-lab-engine) to access the console with `psql`.
{{< /alert >}}
To access the database lab instances, you must:
- File an [access request](https://handbook.gitlab.com/handbook/it/end-user-services/onboarding-access-requests/access-requests/#individual-or-bulk-access-request), requesting the following:
- `AllFeaturesUser` role in Postgres.ai
- `db-lab` role in `chef-repo`
- Have a user data bag entry in [chef-repo](https://gitlab.com/gitlab-com/gl-infra/chef-repo) with your SSH key and the `db-lab` role.
- Configure `ssh` as follows:
```plaintext
Host lb-bastion.db-lab.gitlab.com
# Typically, the username is `name` in `name@gitlab.com`
# or your GitLab's username.
# Check with the access provisioner if it is not working.
# If not provided, defaults to your system username.
User YOUR_USERNAME_HERE
# Path to your SSH key. Adjust or remove if using a different key or SSH agent.
IdentityFile ~/.ssh/id_ed25519
Host *.gitlab-db-lab.internal
User YOUR_USERNAME_HERE # Same as above.
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_ed25519 # Same as above.
ProxyCommand ssh lb-bastion.db-lab.gitlab.com -W %h:%p
```
#### Manual access through the Postgres.ai instances page
Team members with [`psql` access](#access-database-lab-engine), can gain direct access
to a clone via `psql`. Access to `psql` enables you to see data, not just metadata.
To connect to a clone using `psql`:
1. Create a clone from the [desired instance](https://console.postgres.ai/gitlab/instances/).
1. Provide a **Clone ID**: Something that uniquely identifies your clone, such as `yourname-testing-gitlabissue`.
1. Provide a **Database username** and **Database password**: Connects `psql` to your clone.
1. Select **Enable deletion protection** if you need to preserve your clone. Avoid selecting this option.
Clones are removed after 12 hours.
1. In the **Clone details** page of the Postgres.ai web interface, copy and run
the command to start SSH port forwarding for the clone.
1. You may notice that it's suggested to run the command with the `-N` flag, meaning no shell will be started,
so you should not expect any output if it runs successfully.
1. Optionally, you can add `LogLevel DEBUG3` to your `~/.ssh/config`
to output detailed debugging information.
1. After running the command, leave it running to keep the port forwarding active,
and then you can open a new terminal tab to do the next step.
1. In the **Clone details** page of the Postgres.ai web interface, copy and run the `psql` connection string.
Use the password provided at setup and set the `dbname` to `gitlabhq_dblab` (or check what databases are available by using `psql -l` with the same query string but `dbname=postgres`).
After you connect, use clone like you would any `psql` console in production, but with
the added benefit and safety of an isolated writeable environment.
#### Simplified access through `pgai` Ruby gem
For instructions on using the `pgai` Ruby gem, see: [Database Lab access using the pgai Ruby gem](database_lab_pgai.md).
|
https://docs.gitlab.com/development/database_query_comments
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/database_query_comments.md
|
2025-08-13
|
doc/development/database
|
[
"doc",
"development",
"database"
] |
database_query_comments.md
|
Data Access
|
Database Frameworks
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Database query comments with Marginalia
| null |
The [Marginalia gem](https://github.com/basecamp/marginalia) is used to add
query comments containing application related context information to PostgreSQL
queries generated by ActiveRecord.
It is very useful for tracing problematic queries back to the application source.
An engineer during an on-call incident has the full context of a query
and its application source from the comments.
## Metadata information in comments
Queries generated from **Rails** include the following metadata in comments:
- `application`
- `correlation_id`
- `endpoint_id`
- `db_config_database`
- `line`
Queries generated from **Sidekiq** workers include the following metadata
in comments:
- `application`
- `jid`
- `correlation_id`
- `endpoint_id`
- `db_config_database`
- `line`
`endpoint_id` is a single field that can represent any endpoint in the application:
- For Rails controllers, it's the controller and action. For example, `Projects::BlobController#show`.
- For Grape API endpoints, it's the route. For example, `/api/:version/users/:id`.
- For Sidekiq workers, it's the worker class name. For example, `UserStatusCleanup::BatchWorker`.
`db_config_database` is a single field that represents the `database` field in the database configuration hash in `database.yml`.
`line` is not present in production logs due to the additional overhead required.
Examples of queries with comments:
- Rails:
```sql
/*application:web,controller:blob,action:show,correlation_id:01EZVMR923313VV44ZJDJ7PMEZ,endpoint_id:Projects::BlobController#show,db_config_database:gitlabhq_production*/ SELECT "routes".* FROM "routes" WHERE "routes"."source_id" = 75 AND "routes"."source_type" = 'Namespace' LIMIT 1
```
- Grape:
```sql
/*application:web,correlation_id:01EZVN0DAYGJF5XHG9N4VX8FAH,endpoint_id:/api/:version/users/:id,db_config_database:gitlabhq_production*/ SELECT COUNT(*) FROM "users" INNER JOIN "user_follow_users" ON "users"."id" = "user_follow_users"."followee_id" WHERE "user_follow_users"."follower_id" = 1
```
- Sidekiq:
```sql
/*application:sidekiq,correlation_id:df643992563683313bc0a0288fb55e23,jid:15fbc506590c625d7664b074,endpoint_id:UserStatusCleanup::BatchWorker,db_config_database:gitlabhq_production,line:/app/workers/user_status_cleanup/batch_worker.rb:19:in `perform'*/ SELECT $1 AS one FROM "user_statuses" WHERE "user_statuses"."clear_status_at" <= $2 LIMIT $3
```
|
---
stage: Data Access
group: Database Frameworks
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: Database query comments with Marginalia
breadcrumbs:
- doc
- development
- database
---
The [Marginalia gem](https://github.com/basecamp/marginalia) is used to add
query comments containing application related context information to PostgreSQL
queries generated by ActiveRecord.
It is very useful for tracing problematic queries back to the application source.
An engineer during an on-call incident has the full context of a query
and its application source from the comments.
## Metadata information in comments
Queries generated from **Rails** include the following metadata in comments:
- `application`
- `correlation_id`
- `endpoint_id`
- `db_config_database`
- `line`
Queries generated from **Sidekiq** workers include the following metadata
in comments:
- `application`
- `jid`
- `correlation_id`
- `endpoint_id`
- `db_config_database`
- `line`
`endpoint_id` is a single field that can represent any endpoint in the application:
- For Rails controllers, it's the controller and action. For example, `Projects::BlobController#show`.
- For Grape API endpoints, it's the route. For example, `/api/:version/users/:id`.
- For Sidekiq workers, it's the worker class name. For example, `UserStatusCleanup::BatchWorker`.
`db_config_database` is a single field that represents the `database` field in the database configuration hash in `database.yml`.
`line` is not present in production logs due to the additional overhead required.
Examples of queries with comments:
- Rails:
```sql
/*application:web,controller:blob,action:show,correlation_id:01EZVMR923313VV44ZJDJ7PMEZ,endpoint_id:Projects::BlobController#show,db_config_database:gitlabhq_production*/ SELECT "routes".* FROM "routes" WHERE "routes"."source_id" = 75 AND "routes"."source_type" = 'Namespace' LIMIT 1
```
- Grape:
```sql
/*application:web,correlation_id:01EZVN0DAYGJF5XHG9N4VX8FAH,endpoint_id:/api/:version/users/:id,db_config_database:gitlabhq_production*/ SELECT COUNT(*) FROM "users" INNER JOIN "user_follow_users" ON "users"."id" = "user_follow_users"."followee_id" WHERE "user_follow_users"."follower_id" = 1
```
- Sidekiq:
```sql
/*application:sidekiq,correlation_id:df643992563683313bc0a0288fb55e23,jid:15fbc506590c625d7664b074,endpoint_id:UserStatusCleanup::BatchWorker,db_config_database:gitlabhq_production,line:/app/workers/user_status_cleanup/batch_worker.rb:19:in `perform'*/ SELECT $1 AS one FROM "user_statuses" WHERE "user_statuses"."clear_status_at" <= $2 LIMIT $3
```
|
https://docs.gitlab.com/development/batching_best_practices
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/batching_best_practices.md
|
2025-08-13
|
doc/development/database
|
[
"doc",
"development",
"database"
] |
batching_best_practices.md
|
Data Access
|
Database Frameworks
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Batching best practices
| null |
This document gives an overview about the available batching strategies we use at GitLab. We list the pros and cons of each strategy so engineers can pick the ideal approach for their use case.
## Why do we need batching
When dealing with a large volume of records, reading, updating or deleting the records in one database query can be challenging; the operation could easily time out. To avoid this problem, we should process the records in batches. Batching usually happens in background jobs, where runtime constraints are more relaxed than during web requests.
### Use batching in background jobs and not in web requests
In rare cases (older features), batching also happens in web requests. However, for new features this is discouraged due to the short web request timeout (60 seconds by default). As a guideline, using background jobs (Sidekiq workers) should be considered as the first option when implementing a feature that needs to process a large volume of records.
### Performance considerations
Batching performance is closely related to pagination performance since the underlying libraries and database queries are essentially the same. When implementing batching it's important to be familiar with the [pagination performance guidelines](pagination_performance_guidelines.md) and the documentation related to our [batching utilities](iterating_tables_in_batches.md).
## Batching in background jobs
There are two main aspects to consider when implementing batching in background jobs: total runtime and data modification volume.
Background jobs shouldn't run for a long time. A Sidekiq process can crash or it can be forcefully stopped (for example, on restart or deployment). Additionally, due to our [error budget](../stage_group_observability/_index.md#error-budget) rules, after 5 minutes of runtime, error budget violations will be added to the group where the feature is registered. When implementing batching in background jobs, make sure that you're familiar with our guidelines related to [idempotent jobs](../sidekiq/idempotent_jobs.md)
Updating or deleting a large volume of records can increase database replication lag and it can add extra strain to the primary database. It's advisable to limit the total number of records we process (or batch over) within the background job.
To address the potential issues mentioned above the following measures should be considered:
- Limit the total runtime for the job.
- Limit record modifications.
- Rest period between batches. (a few milliseconds)
When applying limits, it's important to mention that long-running background jobs should implement a "continue later" mechanism where a new job is scheduled after the limit is reached to continue the work where the batching was stopped. This is important when a job is so long that it's very likely that it won't fit into the 5 minutes runtime.
An example implementation of runtime limiting using the `Gitlab::Metrics::RuntimeLimiter` class:
```ruby
def perform(project_id)
runtime_limiter = Gitlab::Metrics::RuntimeLimiter.new(3.minutes)
project = Project.find(1)
project.issues.each_batch(of: :iid) do |scope|
scope.update_all(updated_at: Time.current)
break if runtime_limiter.over_time?
end
end
```
The batching in the code snippet stops when 3 minutes of runtime is reached. The problem now is that we have no way to continue the processing. To do that, we need to schedule a new background job with enough information to continue the processing. In the snippet, we batch issues within a project by the `iid` column. For the next job, we need to provide the project ID and the last processed `iid` values. This information we often call as the cursor.
```ruby
def perform(project_id, iid = nil)
runtime_limiter = Gitlab::Metrics::RuntimeLimiter.new(3.minutes)
project = Project.find(project_id)
# Restore the previous iid if present
project.issues.where('iid > ?', iid || 0).each_batch(of: :iid) do |scope|
max_iid = scope.maximum(:iid)
scope.update_all(updated_at: Time.current)
if runtime_limiter.over_time?
MyJob.perform_in(2.minutes, project_id, iid)
break
end
end
end
```
Implementing a "continue later" mechanism can add significant complexity to the implementation. Hence, before committing to this work, analyze the existing data in the production database and try to extrapolate data growth. A few examples:
- Mark all `pending` todos for a given user as `done` does not need a "continue later" mechanism.
- Reasoning: The number of pending todos will most likely not going to be over a few thousand database rows, even for the busiest users. Updating these rows would finish 99.9% of the time under 1 minute.
- Store CI build records in a CSV files within a given project might require a "continue later" mechanism.
- Reasoning: for very active projects, CI job count can grow at a very high rate into millions of rows.
When a very large volume of updates happen in the background job, it's advisable (not a strict requirement) to add some sleep to the code and limit the total number of records we update. This reduces the pressure on the primary databases and gives a small window for potential database migrations to acquire heavier locks.
```ruby
def perform(project_id, iid = nil)
max_updates = 100_000 # Allow maximum N updates
updates = 0
status = :completed
runtime_limiter = Gitlab::Metrics::RuntimeLimiter.new(3.minutes)
project = Project.find(project_id)
project.issues.where('iid > ?', iid || 0).each_batch(of: :iid) do |scope|
max_iid = scope.maximum(:iid)
updates += scope.update_all(updated_at: Time.current)
if runtime_limiter.over_time? || updates >= max_updates
MyJob.perform_in(2.minutes, project_id, iid)
status = :limit_reached
break
end
# Adding sleep when we expect long running batching that modifies large volume of data
sleep 0.01
end
end
```
### Traceability
For traceability purposes, it's a good practice to expose metrics so we can see how the batching performs in Kibana:
```ruby
log_extra_metadata_on_done(:result, {
status: :limit_reached, # or :completed
updated_rows: updates
})
```
### Scheduling of the next jobs
Scheduling the next job in the example above is not crash safe (the job can be lost), for very important tasks this approach is not suitable. A safe and common pattern is using a scheduled worker that executes the work based on a cursor. The cursor can be persisted in the DB or in Redis depending on the consistency requirements. This means that the cursor is no longer passed via the job arguments.
The frequency of the scheduled worker can be adjusted depending on the urgency of the task. We have examples when a scheduled worker is enqueued every minute to process urgent items.
#### Redis based cursor
Example: process all issues in a project.
```ruby
def perform
project_id, iid = load_cursor # Load cursor from Redis
return unless project_id # Nothing was enqueued
project = Project.find(project_id)
project.issues.where('iid > ?', iid || 0).each_batch(of: :iid) do |scope|
# Do something with issues.
# Break here, set interrupted flag if time limit is up.
# Set iid to the last processed value.
end
# Continue the work later
push_cursor(project_id, iid) if interrupted?
end
private
def load_cursor
# Take 1 element, not crash safe.
raw_cursor = Gitlab::Redis::SharedState.with do |redis|
redis.lpop('my_cursor')
end
return unless raw_cursor
cursor = Gitlab::Json.parse(raw_cursor)
[cursor['project_id'], cursor['iid']]
end
def push_cursor(project_id, iid)
# Work is not finished, put the cursor at the beginning of the list so the next job can pick it up.
Gitlab::Redis::SharedState.with do |redis|
redis.lpush('my_cursor', Gitlab::Json.dump({ project_id: project_id, iid: iid }))
end
end
```
In the application code, you can put an item in the queue after the database transaction commits (see [transaction guidelines](transaction_guidelines.md) for more details):
```ruby
def execute
ApplicationRecord.transaction do
user.save!
Event.create!(user: user, issue: issue)
end
# Application could crash here
MyRedieQueue.add(user: user, issue: issue)
end
```
This approach is not crash-safe, the item would not be enqueued if the application crashes right after the transaction commits.
Pros:
- Easier to implement, no extra database table is needed for tracking the jobs.
- Good for low throughput, internally invoked jobs. (example: full-table periodical consistency checks, background aggregations)
Cons:
- Scheduling the work (putting the cursor in the queue) is not crash safe.
- Potential serialization issues when the cursor is read (multi-version compatibility).
- Extra care needs to be taken about database transactions.
#### PostgreSQL based cursor
An alternative approach would be storing the queue in the PostgreSQL database. In this case, we can implement the [transactional outbox pattern](https://microservices.io/patterns/data/transactional-outbox) which ensures consistency in case of application (web or worker) crashes.
Pros:
- Scheduling the work can be made fully consistent with other record changes (example: schedule the work within the issue create transaction).
- Tolerates large number of items in the queue.
Cons:
- Depending on the volume, the implementation can be quite complex:
- Partitioned database table: this should be considered for high-throughput workers.
- Consider the [sliding-window partitioning strategy](loose_foreign_keys.md#database-partitioning).
- Complex, cross-partition queries.
Example: set up reliable way of sending emails
```ruby
# In a service
def execute
ApplicationRecord.transaction do
user.save!
Event.create!(user: user, issue: issue)
IssueEmailWorkerQueue.insert!(user: user, issue: issue)
end
end
```
The `IssueEmailWorkerQueue` record stores all necessary information for executing a job. In the scheduled background job we can process the table in a specific order.
```ruby
def perform
runtime_limiter = Gitlab::Metrics::RuntimeLimiter.new(3.minutes)
items = EmailWorkerQueue.order(:id).take(25)
items.each do |item|
# Do something with the item
end
end
```
{{< alert type="note" >}}
To avoid parallel processing of records, you might need to wrap the execution with a distributed Redis lock.
{{< /alert >}}
Example Redis lock usage:
```ruby
class MyJob
include ApplicationWorker
include Gitlab::ExclusiveLeaseHelpers
MAX_TTL = 2.5.minutes.to_i # It should be similar to the runtime limit.
def perform
in_lock('my_lock_key', ttl: MAX_TTL, retries: 0) do
# Do the work here.
end
end
end
```
### Considerations for Sidekiq jobs
Sidekiq jobs can consume substantial database resources. If your job only batches over data but does not modify anything in the database, consider setting attributes favoring database replicas. See the documentation for the [Sidekiq worker attributes](../sidekiq/worker_attributes.md#job-data-consistency-strategies).
## Batching strategies
{{< alert type="note" >}}
To keep the examples easy to follow, we omit the code for limiting the runtime.
{{< /alert >}}
{{< alert type="note" >}}
Some examples include an optional variable assignment to the `cursor` variable. This is optional step which can be used when implementing the "continue later" mechanism.
{{< /alert >}}
### Loop-based batching
The strategy leverages the fact that after updating or deleting records in the database, the exact same query will return different records. This strategy can only be used when we want to delete or update certain records.
Example:
```ruby
loop do
# Requires an index on project_id
delete_count = project.issues.limit(1000).delete_all
break if delete_count == 0 # Exit the loop when there are not records to be deleted
end
```
Pros:
- Easy to implement, maintaining a cursor is not required.
- A single-column database index is sufficient to implement the batching which is often available (foreign keys).
- If order is not important, complex filter conditions can be also used as long as they're covered with an index.
Cons:
- Query performance degrades in subsequent loops due to [negative side effects](https://gitlab.com/gitlab-org/gitlab/-/issues/544662) from repeated scans of stale index entries and visibility checks. As such, this strategy is only suitable for short-lived operations affecting a relatively small volume of data. The safe limit is generally at most 10k rows, but this can vary based on factors such as table size and index structure.
- Thorough testing and manual verification of the underlying `DELETE` or `UPDATE` query is a must. There are some issues with [CTEs](../sql.md#when-to-use-common-table-expressions) when updating or deleting records.
- If the `break` logic has a bug we might end up in an infinite loop.
It's possible to make the loop-based approach process records in a specific order:
```ruby
loop do
# Requires a composite index on (project_id, created_at)
delete_count = project.issues.limit(1000).order(created_at: :desc).delete_all
break if delete_count == 0
end
```
With the index mentioned in the previous example, we can also use `timestamp` conditions:
```ruby
loop do
# Requires a composite index on (project_id, created_at)
delete_count = project
.issues
.where('created_at < ?', 1.month.ago)
.limit(1000)
.order(created_at: :desc)
.delete_all
break if delete_count == 0
end
```
## Single-column batching
We can use a single, unique column (primary key or column which has a unique index) for batching with the `EachBatch` module. This is one of the most commonly used batching strategy in GitLab.
```ruby
# Requires a composite index on (project_id, id).
# EachBatch uses the primary key by default for the batching.
cursor = nil
project.issues.where('id > ?', cursor || 0).each_batch do |batch|
issues = batch.to_a
cursor = issues.last.id # For the next job
# do something with the issues records
end
```
Pros:
- The most popular way of batching within the GitLab application.
- Easy to implement, covers a wide range of use cases.
Cons:
- The `ORDER BY` column (ID) must be unique in the context of the query.
- It does not work efficiently when `timestamp` column condition or other complex conditions (`IN`, `NOT EXISTS`) are present.
### Batching over distinct values
`EachBatch` requires a unique database column (usually the ID column) however, there are rare cases when the feature needs to batch over a non-unique column. Example: bump all project `timestamp` values which have at least one issue.
One approach is to batch over the "parent" table, in this case using the `Project` model.
```ruby
cursor = nil
# Uses the primary key index
Project.where('id > ?', cursor || 0).each_batch do |batch|
cursor = batch.maximum(:id) # For the next job
project_ids = batch
.where('EXISTS (SELECT 1 FROM issues WHERE projects.id=issues.project_id)')
.pluck(:id)
Project.where(id: project_ids).update_all(update_all: Time.current)
end
```
Pros:
- When the column is a foreign key, batching the parent table's primary key should be already covered with an index.
Cons:
- Can be wasteful when the extra condition within the block would match only a small number of rows.
The batching query runs a full table scan over the `projects` table which might be wasteful, alternatively, we can use the `distinct_each_batch` helper method:
```ruby
# requires an index on (project_id)
Issue.distinct_each_batch(column: :project_id) do |scope|
project_ids = scope.pluck(:project_id)
cursor = project_ids.last # For the next job
Project.where(id: project_ids).update_all(update_all: Time.current)
end
```
Pros:
- When the column is a foreign key column then index is already available.
- It can significantly reduce the amount of data the batching logic needs to scan.
Cons:
- Limited usage, not widely used.
## Keyset-based batching
Keyset-based batching allows you to iterate over records in a specific order where multi-column sorting is also possible. The most common use cases are when we need to process data ordered via a `timestamp` column.
Example: delete issue records older than one year.
```ruby
def perform
cursor = load_cursor || {}
# Requires a composite index on (created_at, id) columns
scope = Issue.where('created_at > ?', 1.year.ago).order(:created_at, :id)
iterator = Gitlab::Pagination::Keyset::Iterator.new(scope: scope, cursor: cursor)
iterator.each_batch(of: 100) do |records|
loaded_records = records.to_a
loaded_records.each { |record| record.destroy } # Calling destroy so callbacks are invoked
end
cursor = iterator.send(:cursor) # Store the cursor after this step, for the next job
end
```
With keyset-based batching, you could adjust the `ORDER BY` clause to match the column configuration of an existing index. Consider the following index:
```sql
CREATE INDEX issues_search_index ON issues (project_id, state, created_at, id)
```
This index cannot be used by the snippet above because the `ORDER BY` column list doesn't match exactly the column list in the index definition. However, if we alter the `ORDER BY` clause then the index would be picked up by the query planner:
```ruby
# Note: this is a different sort order but at least we can use an existing index
scope = Issue.where('created_at > ?', 1.year.ago).order(:project_id, :state, :created_at, :id)
```
Pros:
- Multi-column sort orders and more complex filtering are possible.
- You might be able to reuse existing indexes without introducing new ones.
Cons:
- Cursor size could be larger (each `ORDER BY` column will be stored in the cursor).
## Offset batching
This batching technique uses [offset pagination](pagination_guidelines.md#offset-pagination) when loading new records. Offset pagination should be used only as a last resort when the given query cannot be paginated via `EachBatch` or via keyset-pagination. One reason for choosing this technique is when there is no suitable index available for the SQL query to use a different batching technique. Example: in a background job we load too many records without limit and it started to time out. The order of the records are important.
```ruby
def perform(project_id)
# We have a composite index on (project_id, created_at) columns
issues = Issue
.where(project_id: project_id)
.order(:created_at)
.to_a
# do something with the issues
end
```
As the number of issues within the project grows, the query gets slower and eventually times out. Using a different batching technique such as keyset-pagination is not possible because the `ORDER BY` clause is depending on a `timestamp` column which is not unique (see the [tie-breaker](pagination_performance_guidelines.md#tie-breaker-column) section). Ideally, we should order on the `created_at, id` columns, however we don't have that index available. In a time-sensitive scenario (such as an incident) it might not be feasible to introduce a new index right away so as a last resort we can attempt offset pagination.
```ruby
def perform(project_id)
page = 1
loop do
issues = Issue.where(project_id: project_id).order(:created_at).page(page).to_a
page +=1
break if issues.empty?
# do something with the issues
end
end
```
The snippet above can be a short term fix until a proper solution is in place. Offset pagination gets slower as the page number increases which means that there might be a chance where the offset paginated query times out the same way as the original query. The chances are reduced to some extent by the database buffer cache which keeps the previously loaded records in memory; Thus, the consecutive (short-term) lookup of the same rows will not have very high impact on the performance.
Pros:
- Easy to implement.
Cons:
- Performance degrades linearly as the page number is increased.
- This is only a stop-gap measure which shouldn't be used for new features.
- You can store the page number as the cursor but restoring the processing from the previous point can be unreliable.
## Batching over the Group hierarchy
We have several features where we need to query data in the top-level namespace and its subgroups. There are outlier group hierarchies which contain several thousand subgroups or projects. Querying such hierarchies can easily lead to database statement timeouts when additional subqueries or joins are added.
Example: iterate over issues in a group
```ruby
group = Group.find(9970)
Issue.where(project_id: group.all_project_ids).each_batch do |scope|
# Do something with issues
end
```
The example above will load all subgroups, all projects and all issues in the group hierarchy which will very likely lead to database statement timeout. The query above can be slightly improved with database indexes as a short-term solution.
### Using the in-operator optimization
When you need to process records in a specific order in a group, you can use the [in-operator optimization](efficient_in_operator_queries.md) which can provide better performance than using a standard `each_batch` based batching strategy.
You can see an example for batching over records in the group hierarchy [here](efficient_in_operator_queries.md#batch-iteration).
Pros:
- This is the only way to batch over records efficiently within the group hierarchy in a specific order.
Cons:
- Requires more complex setup.
- Batching over very large hierarchies (high number of projects or subgroups) will require lower batch size.
### Always batch from the top-level group
This technique can be used when we always have to batch from the top-level group (group without parent group). In this case we can leverage the following index in the `namespaces` table:
```sql
"index_on_namespaces_namespaces_by_top_level_namespace" btree ((traversal_ids[1]), type, id) -- traversal_ids[1] is the top-level group id
```
Example batching query:
```ruby
Namespace.where('traversal_ids[1] = ?', 9970).where(type: 'Project').each_batch do |project_namespaces|
project_ids = Project.where(project_namespace_id: project_namespaces.select(:id)).pluck(:id)
cursor = project_namespaces.last.id # For the next job
project_ids.each do |project_id|
Issue.where(project_id: project_id).each_batch(column: :iid) do |issues|
# do something with the issues
end
end
end
```
Pros:
- Loading the whole group hierarchy can be avoided.
- Processing evenly distributed batches using a nested `EachBatch`.
Cons:
- More database queries due to the double batching.
### Batch from any node from the group hierarchy
Using the `NamespaceEachBatch` class allows us to batch a specific branch of the group hierarchy (tree).
```ruby
# current_id: id of the namespace record where we iterate from
# depth: depth of the tree where the iteration was stopped previously. Initially, it should be the same as the current_id
cursor = { current_id: 9970, depth: [9970] } # This can be any namespace id
iterator = Gitlab::Database::NamespaceEachBatch.new(namespace_class: Namespace, cursor: cursor)
# Requires a composite index on (parent_id, id) columns
iterator.each_batch(of: 100) do |ids, new_cursor|
namespace_ids = Namespaces::ProjectNamespace.where(id: ids)
cursor = new_cursor # For the next job, contains the new current_id and depth values
project_ids = Project.where(project_namespace_id: namespace_ids)
project_ids.each do |project_id|
Issue.where(project_id: project_id).each_batch(column: :iid) do |issues|
# do something with the issues
end
end
end
```
Pros:
- It can process the group hierarchy from any node.
Cons:
- Rarely used, useful in only very rare use cases.
### Batching over complex queries
We consider complex queries where the query contains multiple filters and joins. Most of the time these queries cannot be batched easily. A few examples:
- Use [`JOIN`](iterating_tables_in_batches.md#using-join-and-exists) to filter out rows.
- Use [subqueries](iterating_tables_in_batches.md#using-subqueries).
- Use [multiple `IN` filters](efficient_in_operator_queries.md#multiple-in-queries) or complex `AND` or `OR` conditions.
|
---
stage: Data Access
group: Database Frameworks
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: Batching best practices
breadcrumbs:
- doc
- development
- database
---
This document gives an overview about the available batching strategies we use at GitLab. We list the pros and cons of each strategy so engineers can pick the ideal approach for their use case.
## Why do we need batching
When dealing with a large volume of records, reading, updating or deleting the records in one database query can be challenging; the operation could easily time out. To avoid this problem, we should process the records in batches. Batching usually happens in background jobs, where runtime constraints are more relaxed than during web requests.
### Use batching in background jobs and not in web requests
In rare cases (older features), batching also happens in web requests. However, for new features this is discouraged due to the short web request timeout (60 seconds by default). As a guideline, using background jobs (Sidekiq workers) should be considered as the first option when implementing a feature that needs to process a large volume of records.
### Performance considerations
Batching performance is closely related to pagination performance since the underlying libraries and database queries are essentially the same. When implementing batching it's important to be familiar with the [pagination performance guidelines](pagination_performance_guidelines.md) and the documentation related to our [batching utilities](iterating_tables_in_batches.md).
## Batching in background jobs
There are two main aspects to consider when implementing batching in background jobs: total runtime and data modification volume.
Background jobs shouldn't run for a long time. A Sidekiq process can crash or it can be forcefully stopped (for example, on restart or deployment). Additionally, due to our [error budget](../stage_group_observability/_index.md#error-budget) rules, after 5 minutes of runtime, error budget violations will be added to the group where the feature is registered. When implementing batching in background jobs, make sure that you're familiar with our guidelines related to [idempotent jobs](../sidekiq/idempotent_jobs.md)
Updating or deleting a large volume of records can increase database replication lag and it can add extra strain to the primary database. It's advisable to limit the total number of records we process (or batch over) within the background job.
To address the potential issues mentioned above the following measures should be considered:
- Limit the total runtime for the job.
- Limit record modifications.
- Rest period between batches. (a few milliseconds)
When applying limits, it's important to mention that long-running background jobs should implement a "continue later" mechanism where a new job is scheduled after the limit is reached to continue the work where the batching was stopped. This is important when a job is so long that it's very likely that it won't fit into the 5 minutes runtime.
An example implementation of runtime limiting using the `Gitlab::Metrics::RuntimeLimiter` class:
```ruby
def perform(project_id)
runtime_limiter = Gitlab::Metrics::RuntimeLimiter.new(3.minutes)
project = Project.find(1)
project.issues.each_batch(of: :iid) do |scope|
scope.update_all(updated_at: Time.current)
break if runtime_limiter.over_time?
end
end
```
The batching in the code snippet stops when 3 minutes of runtime is reached. The problem now is that we have no way to continue the processing. To do that, we need to schedule a new background job with enough information to continue the processing. In the snippet, we batch issues within a project by the `iid` column. For the next job, we need to provide the project ID and the last processed `iid` values. This information we often call as the cursor.
```ruby
def perform(project_id, iid = nil)
runtime_limiter = Gitlab::Metrics::RuntimeLimiter.new(3.minutes)
project = Project.find(project_id)
# Restore the previous iid if present
project.issues.where('iid > ?', iid || 0).each_batch(of: :iid) do |scope|
max_iid = scope.maximum(:iid)
scope.update_all(updated_at: Time.current)
if runtime_limiter.over_time?
MyJob.perform_in(2.minutes, project_id, iid)
break
end
end
end
```
Implementing a "continue later" mechanism can add significant complexity to the implementation. Hence, before committing to this work, analyze the existing data in the production database and try to extrapolate data growth. A few examples:
- Mark all `pending` todos for a given user as `done` does not need a "continue later" mechanism.
- Reasoning: The number of pending todos will most likely not going to be over a few thousand database rows, even for the busiest users. Updating these rows would finish 99.9% of the time under 1 minute.
- Store CI build records in a CSV files within a given project might require a "continue later" mechanism.
- Reasoning: for very active projects, CI job count can grow at a very high rate into millions of rows.
When a very large volume of updates happen in the background job, it's advisable (not a strict requirement) to add some sleep to the code and limit the total number of records we update. This reduces the pressure on the primary databases and gives a small window for potential database migrations to acquire heavier locks.
```ruby
def perform(project_id, iid = nil)
max_updates = 100_000 # Allow maximum N updates
updates = 0
status = :completed
runtime_limiter = Gitlab::Metrics::RuntimeLimiter.new(3.minutes)
project = Project.find(project_id)
project.issues.where('iid > ?', iid || 0).each_batch(of: :iid) do |scope|
max_iid = scope.maximum(:iid)
updates += scope.update_all(updated_at: Time.current)
if runtime_limiter.over_time? || updates >= max_updates
MyJob.perform_in(2.minutes, project_id, iid)
status = :limit_reached
break
end
# Adding sleep when we expect long running batching that modifies large volume of data
sleep 0.01
end
end
```
### Traceability
For traceability purposes, it's a good practice to expose metrics so we can see how the batching performs in Kibana:
```ruby
log_extra_metadata_on_done(:result, {
status: :limit_reached, # or :completed
updated_rows: updates
})
```
### Scheduling of the next jobs
Scheduling the next job in the example above is not crash safe (the job can be lost), for very important tasks this approach is not suitable. A safe and common pattern is using a scheduled worker that executes the work based on a cursor. The cursor can be persisted in the DB or in Redis depending on the consistency requirements. This means that the cursor is no longer passed via the job arguments.
The frequency of the scheduled worker can be adjusted depending on the urgency of the task. We have examples when a scheduled worker is enqueued every minute to process urgent items.
#### Redis based cursor
Example: process all issues in a project.
```ruby
def perform
project_id, iid = load_cursor # Load cursor from Redis
return unless project_id # Nothing was enqueued
project = Project.find(project_id)
project.issues.where('iid > ?', iid || 0).each_batch(of: :iid) do |scope|
# Do something with issues.
# Break here, set interrupted flag if time limit is up.
# Set iid to the last processed value.
end
# Continue the work later
push_cursor(project_id, iid) if interrupted?
end
private
def load_cursor
# Take 1 element, not crash safe.
raw_cursor = Gitlab::Redis::SharedState.with do |redis|
redis.lpop('my_cursor')
end
return unless raw_cursor
cursor = Gitlab::Json.parse(raw_cursor)
[cursor['project_id'], cursor['iid']]
end
def push_cursor(project_id, iid)
# Work is not finished, put the cursor at the beginning of the list so the next job can pick it up.
Gitlab::Redis::SharedState.with do |redis|
redis.lpush('my_cursor', Gitlab::Json.dump({ project_id: project_id, iid: iid }))
end
end
```
In the application code, you can put an item in the queue after the database transaction commits (see [transaction guidelines](transaction_guidelines.md) for more details):
```ruby
def execute
ApplicationRecord.transaction do
user.save!
Event.create!(user: user, issue: issue)
end
# Application could crash here
MyRedieQueue.add(user: user, issue: issue)
end
```
This approach is not crash-safe, the item would not be enqueued if the application crashes right after the transaction commits.
Pros:
- Easier to implement, no extra database table is needed for tracking the jobs.
- Good for low throughput, internally invoked jobs. (example: full-table periodical consistency checks, background aggregations)
Cons:
- Scheduling the work (putting the cursor in the queue) is not crash safe.
- Potential serialization issues when the cursor is read (multi-version compatibility).
- Extra care needs to be taken about database transactions.
#### PostgreSQL based cursor
An alternative approach would be storing the queue in the PostgreSQL database. In this case, we can implement the [transactional outbox pattern](https://microservices.io/patterns/data/transactional-outbox) which ensures consistency in case of application (web or worker) crashes.
Pros:
- Scheduling the work can be made fully consistent with other record changes (example: schedule the work within the issue create transaction).
- Tolerates large number of items in the queue.
Cons:
- Depending on the volume, the implementation can be quite complex:
- Partitioned database table: this should be considered for high-throughput workers.
- Consider the [sliding-window partitioning strategy](loose_foreign_keys.md#database-partitioning).
- Complex, cross-partition queries.
Example: set up reliable way of sending emails
```ruby
# In a service
def execute
ApplicationRecord.transaction do
user.save!
Event.create!(user: user, issue: issue)
IssueEmailWorkerQueue.insert!(user: user, issue: issue)
end
end
```
The `IssueEmailWorkerQueue` record stores all necessary information for executing a job. In the scheduled background job we can process the table in a specific order.
```ruby
def perform
runtime_limiter = Gitlab::Metrics::RuntimeLimiter.new(3.minutes)
items = EmailWorkerQueue.order(:id).take(25)
items.each do |item|
# Do something with the item
end
end
```
{{< alert type="note" >}}
To avoid parallel processing of records, you might need to wrap the execution with a distributed Redis lock.
{{< /alert >}}
Example Redis lock usage:
```ruby
class MyJob
include ApplicationWorker
include Gitlab::ExclusiveLeaseHelpers
MAX_TTL = 2.5.minutes.to_i # It should be similar to the runtime limit.
def perform
in_lock('my_lock_key', ttl: MAX_TTL, retries: 0) do
# Do the work here.
end
end
end
```
### Considerations for Sidekiq jobs
Sidekiq jobs can consume substantial database resources. If your job only batches over data but does not modify anything in the database, consider setting attributes favoring database replicas. See the documentation for the [Sidekiq worker attributes](../sidekiq/worker_attributes.md#job-data-consistency-strategies).
## Batching strategies
{{< alert type="note" >}}
To keep the examples easy to follow, we omit the code for limiting the runtime.
{{< /alert >}}
{{< alert type="note" >}}
Some examples include an optional variable assignment to the `cursor` variable. This is optional step which can be used when implementing the "continue later" mechanism.
{{< /alert >}}
### Loop-based batching
The strategy leverages the fact that after updating or deleting records in the database, the exact same query will return different records. This strategy can only be used when we want to delete or update certain records.
Example:
```ruby
loop do
# Requires an index on project_id
delete_count = project.issues.limit(1000).delete_all
break if delete_count == 0 # Exit the loop when there are not records to be deleted
end
```
Pros:
- Easy to implement, maintaining a cursor is not required.
- A single-column database index is sufficient to implement the batching which is often available (foreign keys).
- If order is not important, complex filter conditions can be also used as long as they're covered with an index.
Cons:
- Query performance degrades in subsequent loops due to [negative side effects](https://gitlab.com/gitlab-org/gitlab/-/issues/544662) from repeated scans of stale index entries and visibility checks. As such, this strategy is only suitable for short-lived operations affecting a relatively small volume of data. The safe limit is generally at most 10k rows, but this can vary based on factors such as table size and index structure.
- Thorough testing and manual verification of the underlying `DELETE` or `UPDATE` query is a must. There are some issues with [CTEs](../sql.md#when-to-use-common-table-expressions) when updating or deleting records.
- If the `break` logic has a bug we might end up in an infinite loop.
It's possible to make the loop-based approach process records in a specific order:
```ruby
loop do
# Requires a composite index on (project_id, created_at)
delete_count = project.issues.limit(1000).order(created_at: :desc).delete_all
break if delete_count == 0
end
```
With the index mentioned in the previous example, we can also use `timestamp` conditions:
```ruby
loop do
# Requires a composite index on (project_id, created_at)
delete_count = project
.issues
.where('created_at < ?', 1.month.ago)
.limit(1000)
.order(created_at: :desc)
.delete_all
break if delete_count == 0
end
```
## Single-column batching
We can use a single, unique column (primary key or column which has a unique index) for batching with the `EachBatch` module. This is one of the most commonly used batching strategy in GitLab.
```ruby
# Requires a composite index on (project_id, id).
# EachBatch uses the primary key by default for the batching.
cursor = nil
project.issues.where('id > ?', cursor || 0).each_batch do |batch|
issues = batch.to_a
cursor = issues.last.id # For the next job
# do something with the issues records
end
```
Pros:
- The most popular way of batching within the GitLab application.
- Easy to implement, covers a wide range of use cases.
Cons:
- The `ORDER BY` column (ID) must be unique in the context of the query.
- It does not work efficiently when `timestamp` column condition or other complex conditions (`IN`, `NOT EXISTS`) are present.
### Batching over distinct values
`EachBatch` requires a unique database column (usually the ID column) however, there are rare cases when the feature needs to batch over a non-unique column. Example: bump all project `timestamp` values which have at least one issue.
One approach is to batch over the "parent" table, in this case using the `Project` model.
```ruby
cursor = nil
# Uses the primary key index
Project.where('id > ?', cursor || 0).each_batch do |batch|
cursor = batch.maximum(:id) # For the next job
project_ids = batch
.where('EXISTS (SELECT 1 FROM issues WHERE projects.id=issues.project_id)')
.pluck(:id)
Project.where(id: project_ids).update_all(update_all: Time.current)
end
```
Pros:
- When the column is a foreign key, batching the parent table's primary key should be already covered with an index.
Cons:
- Can be wasteful when the extra condition within the block would match only a small number of rows.
The batching query runs a full table scan over the `projects` table which might be wasteful, alternatively, we can use the `distinct_each_batch` helper method:
```ruby
# requires an index on (project_id)
Issue.distinct_each_batch(column: :project_id) do |scope|
project_ids = scope.pluck(:project_id)
cursor = project_ids.last # For the next job
Project.where(id: project_ids).update_all(update_all: Time.current)
end
```
Pros:
- When the column is a foreign key column then index is already available.
- It can significantly reduce the amount of data the batching logic needs to scan.
Cons:
- Limited usage, not widely used.
## Keyset-based batching
Keyset-based batching allows you to iterate over records in a specific order where multi-column sorting is also possible. The most common use cases are when we need to process data ordered via a `timestamp` column.
Example: delete issue records older than one year.
```ruby
def perform
cursor = load_cursor || {}
# Requires a composite index on (created_at, id) columns
scope = Issue.where('created_at > ?', 1.year.ago).order(:created_at, :id)
iterator = Gitlab::Pagination::Keyset::Iterator.new(scope: scope, cursor: cursor)
iterator.each_batch(of: 100) do |records|
loaded_records = records.to_a
loaded_records.each { |record| record.destroy } # Calling destroy so callbacks are invoked
end
cursor = iterator.send(:cursor) # Store the cursor after this step, for the next job
end
```
With keyset-based batching, you could adjust the `ORDER BY` clause to match the column configuration of an existing index. Consider the following index:
```sql
CREATE INDEX issues_search_index ON issues (project_id, state, created_at, id)
```
This index cannot be used by the snippet above because the `ORDER BY` column list doesn't match exactly the column list in the index definition. However, if we alter the `ORDER BY` clause then the index would be picked up by the query planner:
```ruby
# Note: this is a different sort order but at least we can use an existing index
scope = Issue.where('created_at > ?', 1.year.ago).order(:project_id, :state, :created_at, :id)
```
Pros:
- Multi-column sort orders and more complex filtering are possible.
- You might be able to reuse existing indexes without introducing new ones.
Cons:
- Cursor size could be larger (each `ORDER BY` column will be stored in the cursor).
## Offset batching
This batching technique uses [offset pagination](pagination_guidelines.md#offset-pagination) when loading new records. Offset pagination should be used only as a last resort when the given query cannot be paginated via `EachBatch` or via keyset-pagination. One reason for choosing this technique is when there is no suitable index available for the SQL query to use a different batching technique. Example: in a background job we load too many records without limit and it started to time out. The order of the records are important.
```ruby
def perform(project_id)
# We have a composite index on (project_id, created_at) columns
issues = Issue
.where(project_id: project_id)
.order(:created_at)
.to_a
# do something with the issues
end
```
As the number of issues within the project grows, the query gets slower and eventually times out. Using a different batching technique such as keyset-pagination is not possible because the `ORDER BY` clause is depending on a `timestamp` column which is not unique (see the [tie-breaker](pagination_performance_guidelines.md#tie-breaker-column) section). Ideally, we should order on the `created_at, id` columns, however we don't have that index available. In a time-sensitive scenario (such as an incident) it might not be feasible to introduce a new index right away so as a last resort we can attempt offset pagination.
```ruby
def perform(project_id)
page = 1
loop do
issues = Issue.where(project_id: project_id).order(:created_at).page(page).to_a
page +=1
break if issues.empty?
# do something with the issues
end
end
```
The snippet above can be a short term fix until a proper solution is in place. Offset pagination gets slower as the page number increases which means that there might be a chance where the offset paginated query times out the same way as the original query. The chances are reduced to some extent by the database buffer cache which keeps the previously loaded records in memory; Thus, the consecutive (short-term) lookup of the same rows will not have very high impact on the performance.
Pros:
- Easy to implement.
Cons:
- Performance degrades linearly as the page number is increased.
- This is only a stop-gap measure which shouldn't be used for new features.
- You can store the page number as the cursor but restoring the processing from the previous point can be unreliable.
## Batching over the Group hierarchy
We have several features where we need to query data in the top-level namespace and its subgroups. There are outlier group hierarchies which contain several thousand subgroups or projects. Querying such hierarchies can easily lead to database statement timeouts when additional subqueries or joins are added.
Example: iterate over issues in a group
```ruby
group = Group.find(9970)
Issue.where(project_id: group.all_project_ids).each_batch do |scope|
# Do something with issues
end
```
The example above will load all subgroups, all projects and all issues in the group hierarchy which will very likely lead to database statement timeout. The query above can be slightly improved with database indexes as a short-term solution.
### Using the in-operator optimization
When you need to process records in a specific order in a group, you can use the [in-operator optimization](efficient_in_operator_queries.md) which can provide better performance than using a standard `each_batch` based batching strategy.
You can see an example for batching over records in the group hierarchy [here](efficient_in_operator_queries.md#batch-iteration).
Pros:
- This is the only way to batch over records efficiently within the group hierarchy in a specific order.
Cons:
- Requires more complex setup.
- Batching over very large hierarchies (high number of projects or subgroups) will require lower batch size.
### Always batch from the top-level group
This technique can be used when we always have to batch from the top-level group (group without parent group). In this case we can leverage the following index in the `namespaces` table:
```sql
"index_on_namespaces_namespaces_by_top_level_namespace" btree ((traversal_ids[1]), type, id) -- traversal_ids[1] is the top-level group id
```
Example batching query:
```ruby
Namespace.where('traversal_ids[1] = ?', 9970).where(type: 'Project').each_batch do |project_namespaces|
project_ids = Project.where(project_namespace_id: project_namespaces.select(:id)).pluck(:id)
cursor = project_namespaces.last.id # For the next job
project_ids.each do |project_id|
Issue.where(project_id: project_id).each_batch(column: :iid) do |issues|
# do something with the issues
end
end
end
```
Pros:
- Loading the whole group hierarchy can be avoided.
- Processing evenly distributed batches using a nested `EachBatch`.
Cons:
- More database queries due to the double batching.
### Batch from any node from the group hierarchy
Using the `NamespaceEachBatch` class allows us to batch a specific branch of the group hierarchy (tree).
```ruby
# current_id: id of the namespace record where we iterate from
# depth: depth of the tree where the iteration was stopped previously. Initially, it should be the same as the current_id
cursor = { current_id: 9970, depth: [9970] } # This can be any namespace id
iterator = Gitlab::Database::NamespaceEachBatch.new(namespace_class: Namespace, cursor: cursor)
# Requires a composite index on (parent_id, id) columns
iterator.each_batch(of: 100) do |ids, new_cursor|
namespace_ids = Namespaces::ProjectNamespace.where(id: ids)
cursor = new_cursor # For the next job, contains the new current_id and depth values
project_ids = Project.where(project_namespace_id: namespace_ids)
project_ids.each do |project_id|
Issue.where(project_id: project_id).each_batch(column: :iid) do |issues|
# do something with the issues
end
end
end
```
Pros:
- It can process the group hierarchy from any node.
Cons:
- Rarely used, useful in only very rare use cases.
### Batching over complex queries
We consider complex queries where the query contains multiple filters and joins. Most of the time these queries cannot be batched easily. A few examples:
- Use [`JOIN`](iterating_tables_in_batches.md#using-join-and-exists) to filter out rows.
- Use [subqueries](iterating_tables_in_batches.md#using-subqueries).
- Use [multiple `IN` filters](efficient_in_operator_queries.md#multiple-in-queries) or complex `AND` or `OR` conditions.
|
https://docs.gitlab.com/development/rename_database_tables
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/rename_database_tables.md
|
2025-08-13
|
doc/development/database
|
[
"doc",
"development",
"database"
] |
rename_database_tables.md
|
Data Access
|
Database Frameworks
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Rename table without downtime
| null |
With our database helper methods built into GitLab, it's possible to rename a database table without downtime.
The technique builds on top of database views, using the following steps:
1. Rename the database table.
1. Create a database view using the old table name by pointing to the new table name.
1. Add workaround for ActiveRecord's schema cache.
For example, consider that we are renaming the `issues` table name to `tickets`. Run:
```sql
BEGIN;
ALTER TABLE issues RENAME TO tickets;
CREATE VIEW issues AS SELECT * FROM tickets;
COMMIT;
```
As database views do not expose the underlying table schema (default values, not null
constraints, and indexes), we need further steps to update the application to use the new
table name. ActiveRecord heavily relies on this data, for example, to initialize new
models.
To work around this limitation, we need to tell ActiveRecord to acquire this information
from a different table using the new table name.
## Migration strategy breakdown
### Release N.M: Mark the ActiveRecord model's table
Consider the current release as "Release N.M".
In this release, register the database table so that it instructs ActiveRecord to fetch the
database table information (for `SchemaCache`) using the new table name (if it's present). Otherwise, fall back
to the old table name. This is necessary to avoid errors during a zero-downtime deployment.
1. Edit the `TABLES_TO_BE_RENAMED` constant in: `lib/gitlab/database.rb`
```ruby
TABLES_TO_BE_RENAMED = {
'issues' => 'tickets'
}.freeze
```
Note that, in this release (N.M), the `tickets` database table does not exist yet. This step is preparing for the actual table rename in release N.M+1.
### Release N.M+1: Rename the database table
Consider the next release as "Release N.M+1".
1. Execute a standard migration (not a post-migration):
```ruby
def up
rename_table_safely(:issues, :tickets)
end
def down
undo_rename_table_safely(:issues, :tickets)
end
```
<!-- vale gitlab_base.Substitutions = NO -->
1. Rename the table's [dictionary file](database_dictionary.md) (under `db/docs`) with the new name (like `db/docs/tickets.yml` in this example). Update `introduced_by_url` and `milestone` attributes.
<!-- vale gitlab_base.Substitutions = YES -->
1. Create an entry for the interim view (with the old table's name) in `db/docs/deleted_views`. This is because the view gets deleted by [`finalize_table_rename`](https://gitlab.com/gitlab-org/gitlab/-/blob/33dabf39e75ef01cd0914ed44f0954c8b72d5fe3/lib/gitlab/database/rename_table_helpers.rb#L20) in the post-deployment migration of the same merge request.
**Important notes**:
- Let other developers know that the table is going to be renamed.
- Ping the `@gl-database` group in your merge request.
- Add a note in the Engineering Week-in-Review document: `table_name` is going to be renamed in N.M. Modifications to this table are not allowed in release N.M and N.M+1.
- The helper method uses the standard `rename_table` helper from Rails for renaming the table.
- The helper renames the sequence and the indexes. Sometimes it diverges from the standard Rails convention
when naming indexes, so there is a possibility that not all indexes are properly renamed. After running
the migration locally, check if there are inconsistently named indexes (`db/structure.sql`). Those can be
renamed manually in a separate migration, which can be also part of the release M.N+1.
- Foreign key columns might still contain the old table name. For smaller tables, follow our
[standard column rename process](avoiding_downtime_in_migrations.md#renaming-columns)
- Avoid renaming database tables which are using with triggers.
- Table modifications (add or remove columns) are not allowed during the rename process. Make sure that all changes to the table happen before the rename migration is started (or in the next release).
- As the index names might change, verify that the model does not use bulk insert
(for example, `insert_all` and `upsert_all`) with the `unique_by: index_name` option.
Renaming an index while using these methods may break functionality.
- Modify the model code to point to the new database table. Do this by
renaming the model directly or setting the `self.table_name` variable.
At this point, we don't have applications using the old database table name in their queries.
1. Remove the database view through a post-migration:
```ruby
def up
finalize_table_rename(:issues, :tickets)
end
def down
undo_finalize_table_rename(:issues, :tickets)
end
```
1. The table name **must** be removed from `TABLES_TO_BE_RENAMED`.
To do so, edit the `TABLES_TO_BE_RENAMED` constant in `lib/gitlab/database.rb`:
From:
```ruby
TABLES_TO_BE_RENAMED = {
'issues' => 'tickets'
}.freeze
```
To:
```ruby
TABLES_TO_BE_RENAMED = {}.freeze
```
#### Zero-downtime deployments
When the application is upgraded without downtime, there can be application instances
running the old code. The old code still references the old database table. The queries
still function without any problems, because the backward-compatible database view is
in place.
In case the old version of the application needs to be restarted or reconnected to the
database, ActiveRecord fetches the column information again. At this time, our previously
marked table (`TABLES_TO_BE_RENAMED`) instructs ActiveRecord to use the new database table name
when fetching the database table information.
The new version of the application uses the new database table.
|
---
stage: Data Access
group: Database Frameworks
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: Rename table without downtime
breadcrumbs:
- doc
- development
- database
---
With our database helper methods built into GitLab, it's possible to rename a database table without downtime.
The technique builds on top of database views, using the following steps:
1. Rename the database table.
1. Create a database view using the old table name by pointing to the new table name.
1. Add workaround for ActiveRecord's schema cache.
For example, consider that we are renaming the `issues` table name to `tickets`. Run:
```sql
BEGIN;
ALTER TABLE issues RENAME TO tickets;
CREATE VIEW issues AS SELECT * FROM tickets;
COMMIT;
```
As database views do not expose the underlying table schema (default values, not null
constraints, and indexes), we need further steps to update the application to use the new
table name. ActiveRecord heavily relies on this data, for example, to initialize new
models.
To work around this limitation, we need to tell ActiveRecord to acquire this information
from a different table using the new table name.
## Migration strategy breakdown
### Release N.M: Mark the ActiveRecord model's table
Consider the current release as "Release N.M".
In this release, register the database table so that it instructs ActiveRecord to fetch the
database table information (for `SchemaCache`) using the new table name (if it's present). Otherwise, fall back
to the old table name. This is necessary to avoid errors during a zero-downtime deployment.
1. Edit the `TABLES_TO_BE_RENAMED` constant in: `lib/gitlab/database.rb`
```ruby
TABLES_TO_BE_RENAMED = {
'issues' => 'tickets'
}.freeze
```
Note that, in this release (N.M), the `tickets` database table does not exist yet. This step is preparing for the actual table rename in release N.M+1.
### Release N.M+1: Rename the database table
Consider the next release as "Release N.M+1".
1. Execute a standard migration (not a post-migration):
```ruby
def up
rename_table_safely(:issues, :tickets)
end
def down
undo_rename_table_safely(:issues, :tickets)
end
```
<!-- vale gitlab_base.Substitutions = NO -->
1. Rename the table's [dictionary file](database_dictionary.md) (under `db/docs`) with the new name (like `db/docs/tickets.yml` in this example). Update `introduced_by_url` and `milestone` attributes.
<!-- vale gitlab_base.Substitutions = YES -->
1. Create an entry for the interim view (with the old table's name) in `db/docs/deleted_views`. This is because the view gets deleted by [`finalize_table_rename`](https://gitlab.com/gitlab-org/gitlab/-/blob/33dabf39e75ef01cd0914ed44f0954c8b72d5fe3/lib/gitlab/database/rename_table_helpers.rb#L20) in the post-deployment migration of the same merge request.
**Important notes**:
- Let other developers know that the table is going to be renamed.
- Ping the `@gl-database` group in your merge request.
- Add a note in the Engineering Week-in-Review document: `table_name` is going to be renamed in N.M. Modifications to this table are not allowed in release N.M and N.M+1.
- The helper method uses the standard `rename_table` helper from Rails for renaming the table.
- The helper renames the sequence and the indexes. Sometimes it diverges from the standard Rails convention
when naming indexes, so there is a possibility that not all indexes are properly renamed. After running
the migration locally, check if there are inconsistently named indexes (`db/structure.sql`). Those can be
renamed manually in a separate migration, which can be also part of the release M.N+1.
- Foreign key columns might still contain the old table name. For smaller tables, follow our
[standard column rename process](avoiding_downtime_in_migrations.md#renaming-columns)
- Avoid renaming database tables which are using with triggers.
- Table modifications (add or remove columns) are not allowed during the rename process. Make sure that all changes to the table happen before the rename migration is started (or in the next release).
- As the index names might change, verify that the model does not use bulk insert
(for example, `insert_all` and `upsert_all`) with the `unique_by: index_name` option.
Renaming an index while using these methods may break functionality.
- Modify the model code to point to the new database table. Do this by
renaming the model directly or setting the `self.table_name` variable.
At this point, we don't have applications using the old database table name in their queries.
1. Remove the database view through a post-migration:
```ruby
def up
finalize_table_rename(:issues, :tickets)
end
def down
undo_finalize_table_rename(:issues, :tickets)
end
```
1. The table name **must** be removed from `TABLES_TO_BE_RENAMED`.
To do so, edit the `TABLES_TO_BE_RENAMED` constant in `lib/gitlab/database.rb`:
From:
```ruby
TABLES_TO_BE_RENAMED = {
'issues' => 'tickets'
}.freeze
```
To:
```ruby
TABLES_TO_BE_RENAMED = {}.freeze
```
#### Zero-downtime deployments
When the application is upgraded without downtime, there can be application instances
running the old code. The old code still references the old database table. The queries
still function without any problems, because the backward-compatible database view is
in place.
In case the old version of the application needs to be restarted or reconnected to the
database, ActiveRecord fetches the column information again. At this time, our previously
marked table (`TABLES_TO_BE_RENAMED`) instructs ActiveRecord to use the new database table name
when fetching the database table information.
The new version of the application uses the new database table.
|
https://docs.gitlab.com/development/single_table_inheritance
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/single_table_inheritance.md
|
2025-08-13
|
doc/development/database
|
[
"doc",
"development",
"database"
] |
single_table_inheritance.md
|
Data Access
|
Database Frameworks
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Single Table Inheritance
| null |
**Summary**: Don't design new tables using Single Table Inheritance (STI). For existing tables that use STI as a pattern, avoid adding new types, and consider splitting them into separate tables.
STI is a database design pattern where a single table stores
different types of records. These records have a subset of shared columns and another column
that instructs the application which object that record should be represented by.
This can be used to for example store two different types of SSH keys in the same
table. ActiveRecord makes use of it and provides some features that make STI usage
more convenient.
We no longer allow new STI tables because they:
- Lead to tables with large number of rows, when we should strive to keep tables small.
- Need additional indexes, increasing our usage of lightweight locks, whose saturation can cause incidents.
- Add overhead by having to filter all of the data by a value, leading to more page accesses on read.
- Use the `class_name` to load the correct class for an object, but storing
the class name is costly and unnecessary.
Instead of using STI, consider the following alternatives:
- Use a different table for each type.
- Avoid adding `*_type` columns. This is a code smell that might indicate that new types will be added in the future, and refactoring in the future will be much harder.
- If you already have a table that is effectively an STI on a `_type` column, consider:
- Splitting the existent data into multiple tables.
- Refactoring so that new types can be added as new tables while keeping existing ones (for example, move logic of the base class into a concern).
If, **after considering all of the above downsides and alternatives**, STI
is the only solution for the problem at hand, we can at least avoid the
issues with saving the class name in the record by using an enum type
instead and the `EnumInheritance` concern:
```ruby
class Animal < ActiveRecord::Base
include EnumInheritance
enum species: {
dog: 1,
cat: 2
}
def self.inheritance_column_to_class_map = {
dog: 'Dog',
cat: 'Cat'
}
def self.inheritance_column = 'species'
end
class Dog < Animal
self.allow_legacy_sti_class = true
end
class Cat < Animal
self.allow_legacy_sti_class = true
end
```
If your table already has a `*_type`, new classes for the different types can be added as needed.
## In migrations
Whenever a model is used in a migration, single table inheritance should be disabled.
Due to the way Rails loads associations (even in migrations), failing to disable STI
could result in loading unexpected code or associations which may cause unintended
side effects or failures during upgrades.
```ruby
class SomeMigration < Gitlab::Database::Migration[2.1]
class Services < MigrationRecord
self.table_name = 'services'
self.inheritance_column = :_type_disabled
end
def up
...
```
If nothing needs to be added to the model other than disabling STI or `EachBatch`,
use the helper `define_batchable_model` instead of defining the class.
This ensures that the migration loads the columns for the migration in isolation,
and the helper disables STI by default.
```ruby
class EnqueueSomeBackgroundMigration < Gitlab::Database::Migration[2.1]
disable_ddl_transaction!
def up
define_batchable_model('services').select(:id).in_batches do |relation|
jobs = relation.pluck(:id).map do |id|
['ExtractServicesUrl', [id]]
end
BackgroundMigrationWorker.bulk_perform_async(jobs)
end
end
...
```
|
---
stage: Data Access
group: Database Frameworks
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: Single Table Inheritance
breadcrumbs:
- doc
- development
- database
---
**Summary**: Don't design new tables using Single Table Inheritance (STI). For existing tables that use STI as a pattern, avoid adding new types, and consider splitting them into separate tables.
STI is a database design pattern where a single table stores
different types of records. These records have a subset of shared columns and another column
that instructs the application which object that record should be represented by.
This can be used to for example store two different types of SSH keys in the same
table. ActiveRecord makes use of it and provides some features that make STI usage
more convenient.
We no longer allow new STI tables because they:
- Lead to tables with large number of rows, when we should strive to keep tables small.
- Need additional indexes, increasing our usage of lightweight locks, whose saturation can cause incidents.
- Add overhead by having to filter all of the data by a value, leading to more page accesses on read.
- Use the `class_name` to load the correct class for an object, but storing
the class name is costly and unnecessary.
Instead of using STI, consider the following alternatives:
- Use a different table for each type.
- Avoid adding `*_type` columns. This is a code smell that might indicate that new types will be added in the future, and refactoring in the future will be much harder.
- If you already have a table that is effectively an STI on a `_type` column, consider:
- Splitting the existent data into multiple tables.
- Refactoring so that new types can be added as new tables while keeping existing ones (for example, move logic of the base class into a concern).
If, **after considering all of the above downsides and alternatives**, STI
is the only solution for the problem at hand, we can at least avoid the
issues with saving the class name in the record by using an enum type
instead and the `EnumInheritance` concern:
```ruby
class Animal < ActiveRecord::Base
include EnumInheritance
enum species: {
dog: 1,
cat: 2
}
def self.inheritance_column_to_class_map = {
dog: 'Dog',
cat: 'Cat'
}
def self.inheritance_column = 'species'
end
class Dog < Animal
self.allow_legacy_sti_class = true
end
class Cat < Animal
self.allow_legacy_sti_class = true
end
```
If your table already has a `*_type`, new classes for the different types can be added as needed.
## In migrations
Whenever a model is used in a migration, single table inheritance should be disabled.
Due to the way Rails loads associations (even in migrations), failing to disable STI
could result in loading unexpected code or associations which may cause unintended
side effects or failures during upgrades.
```ruby
class SomeMigration < Gitlab::Database::Migration[2.1]
class Services < MigrationRecord
self.table_name = 'services'
self.inheritance_column = :_type_disabled
end
def up
...
```
If nothing needs to be added to the model other than disabling STI or `EachBatch`,
use the helper `define_batchable_model` instead of defining the class.
This ensures that the migration loads the columns for the migration in isolation,
and the helper disables STI by default.
```ruby
class EnqueueSomeBackgroundMigration < Gitlab::Database::Migration[2.1]
disable_ddl_transaction!
def up
define_batchable_model('services').select(:id).in_batches do |relation|
jobs = relation.pluck(:id).map do |id|
['ExtractServicesUrl', [id]]
end
BackgroundMigrationWorker.bulk_perform_async(jobs)
end
end
...
```
|
https://docs.gitlab.com/development/insert_into_tables_in_batches
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/insert_into_tables_in_batches.md
|
2025-08-13
|
doc/development/database
|
[
"doc",
"development",
"database"
] |
insert_into_tables_in_batches.md
|
Data Access
|
Database Frameworks
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Insert into tables in batches
|
Sometimes it is necessary to store large amounts of records at once, which can be inefficient when iterating collections and performing individual `save`s. With the arrival of `insert_all` in Rails 6, which operates at the row level (that is, using `Hash`es), GitLab has added a set of APIs that make it safe and simple to insert ActiveRecord objects in bulk.
|
Sometimes it is necessary to store large amounts of records at once, which can be inefficient
when iterating collections and saving each record individually. With the arrival of
[`insert_all`](https://apidock.com/rails/ActiveRecord/Persistence/ClassMethods/insert_all)
in Rails 6, which operates at the row level (that is, using `Hash` objects), GitLab has added a set
of APIs that make it safe and simple to insert `ActiveRecord` objects in bulk.
## Prepare `ApplicationRecord`s for bulk insertion
In order for a model class to take advantage of the bulk insertion API, it has to include the
`BulkInsertSafe` concern first:
```ruby
class MyModel < ApplicationRecord
# other includes here
# ...
include BulkInsertSafe # include this last
# ...
end
```
The `BulkInsertSafe` concern has two functions:
- It performs checks against your model class to ensure that it does not use ActiveRecord
APIs that are not safe to use with respect to bulk insertions (more on that below).
- It adds new class methods `bulk_insert!` and `bulk_upsert!`, which you can use to insert many records at once.
## Insert records with `bulk_insert!` and `bulk_upsert!`
If the target class passes the checks performed by `BulkInsertSafe`, you can insert an array of
ActiveRecord model objects as follows:
```ruby
records = [MyModel.new, ...]
MyModel.bulk_insert!(records)
```
Calls to `bulk_insert!` always attempt to insert _new records_. If instead
you would like to replace existing records with new values, while still inserting those
that do not already exist, then you can use `bulk_upsert!`:
```ruby
records = [MyModel.new, existing_model, ...]
MyModel.bulk_upsert!(records, unique_by: [:name])
```
In this example, `unique_by` specifies the columns by which records are considered to be
unique and as such are updated if they existed prior to insertion. For example, if
`existing_model` has a `name` attribute, and if a record with the same `name` value already
exists, its fields are updated with those of `existing_model`.
The `unique_by` parameter can also be passed as a `Symbol`, in which case it specifies
a database index by which a column is considered unique:
```ruby
MyModel.bulk_insert!(records, unique_by: :index_on_name)
```
### Record validation
The `bulk_insert!` method guarantees that `records` are inserted transactionally, and
runs validations on each record prior to insertion. If any record fails to validate,
an error is raised and the transaction is rolled back. You can turn off validations via
the `:validate` option:
```ruby
MyModel.bulk_insert!(records, validate: false)
```
### Batch size configuration
In those cases where the number of `records` is above a given threshold, insertions
occur in multiple batches. The default batch size is defined in
[`BulkInsertSafe::DEFAULT_BATCH_SIZE`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/app/models/concerns/bulk_insert_safe.rb).
Assuming a default threshold of 500, inserting 950 records
would result in two batches being written sequentially (of size 500 and 450).
You can override the default batch size via the `:batch_size` option:
```ruby
MyModel.bulk_insert!(records, batch_size: 100)
```
Assuming the same number of 950 records, this would result in 10 batches being written instead.
Since this also affects the number of `INSERT` statements that occur, make sure you measure the
performance impact this might have on your code. There is a trade-off between the number of
`INSERT` statements the database has to process and the size and cost of each `INSERT`.
### Handling duplicate records
{{< alert type="note" >}}
This parameter applies only to `bulk_insert!`. If you intend to update existing
records, use `bulk_upsert!` instead.
{{< /alert >}}
It may happen that some records you are trying to insert already exist, which would result in
primary key conflicts. There are two ways to address this problem: failing fast by raising an
error or skipping duplicate records. The default behavior of `bulk_insert!` is to fail fast
and raise an `ActiveRecord::RecordNotUnique` error.
If this is undesirable, you can instead skip duplicate records with the `skip_duplicates` flag:
```ruby
MyModel.bulk_insert!(records, skip_duplicates: true)
```
### Requirements for safe bulk insertions
Large parts of ActiveRecord's persistence API are built around the notion of callbacks. Many
of these callbacks fire in response to model lifecycle events such as `save` or `create`.
These callbacks cannot be used with bulk insertions, since they are meant to be called for
every instance that is saved or created. Since these events do not fire when
records are inserted in bulk, we prevent their use.
The specifics around which callbacks are explicitly allowed are defined in
[`BulkInsertSafe`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/app/models/concerns/bulk_insert_safe.rb).
Consult the module source code for details. If your class uses callbacks that are not explicitly designated
safe and you `include BulkInsertSafe` the application fails with an error.
### `BulkInsertSafe` versus `InsertAll`
Internally, `BulkInsertSafe` is based on `InsertAll`, and you may wonder when to choose
the former over the latter. To help you make the decision,
the key differences between these classes are listed in the table below.
| | Input type | Validates input | Specify batch size | Can bypass callbacks | Transactional |
|--------------- | -------------------- | --------------- | ------------------ | --------------------------------- | ------------- |
| `bulk_insert!` | ActiveRecord objects | Yes (optional) | Yes (optional) | No (prevents unsafe callback use) | Yes |
| `insert_all!` | Attribute hashes | No | No | Yes | Yes |
To summarize, `BulkInsertSafe` moves bulk inserts closer to how ActiveRecord objects
and inserts would usually behave. However, if all you need is to insert raw data in bulk, then
`insert_all` is more efficient.
## Insert `has_many` associations in bulk
A common use case is to save collections of associated relations through the owner side of the relation,
where the owned relation is associated to the owner through the `has_many` class method:
```ruby
owner = OwnerModel.new(owned_relations: array_of_owned_relations)
# saves all `owned_relations` one-by-one
owner.save!
```
This issues a single `INSERT`, and transaction, for every record in `owned_relations`, which is inefficient if
`array_of_owned_relations` is large. To remedy this, the `BulkInsertableAssociations` concern can be
used to declare that the owner defines associations that are safe for bulk insertion:
```ruby
class OwnerModel < ApplicationRecord
# other includes here
# ...
include BulkInsertableAssociations # include this last
has_many :my_models
end
```
Here `my_models` must be declared `BulkInsertSafe` (as described previously) for bulk insertions
to happen. You can now insert any yet unsaved records as follows:
```ruby
BulkInsertableAssociations.with_bulk_insert do
owner = OwnerModel.new(my_models: array_of_my_model_instances)
# saves `my_models` using a single bulk insert (possibly via multiple batches)
owner.save!
end
```
You can still save relations that are not `BulkInsertSafe` in this block; they
are treated as if you had invoked `save` from outside the block.
## Known limitations
There are a few restrictions to how these APIs can be used:
- `BulkInsertableAssociations`:
- It is currently only compatible with `has_many` relations.
- It does not yet support `has_many through: ...` relations.
Moreover, input data should either be limited to around 1000 records at most,
or already batched prior to calling bulk insert. The `INSERT` statement runs in a single
transaction, so for large amounts of records it may negatively affect database stability.
|
---
stage: Data Access
group: Database Frameworks
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
description: Sometimes it is necessary to store large amounts of records at once,
which can be inefficient when iterating collections and performing individual `save`s.
With the arrival of `insert_all` in Rails 6, which operates at the row level (that
is, using `Hash`es), GitLab has added a set of APIs that make it safe and simple
to insert ActiveRecord objects in bulk.
title: Insert into tables in batches
breadcrumbs:
- doc
- development
- database
---
Sometimes it is necessary to store large amounts of records at once, which can be inefficient
when iterating collections and saving each record individually. With the arrival of
[`insert_all`](https://apidock.com/rails/ActiveRecord/Persistence/ClassMethods/insert_all)
in Rails 6, which operates at the row level (that is, using `Hash` objects), GitLab has added a set
of APIs that make it safe and simple to insert `ActiveRecord` objects in bulk.
## Prepare `ApplicationRecord`s for bulk insertion
In order for a model class to take advantage of the bulk insertion API, it has to include the
`BulkInsertSafe` concern first:
```ruby
class MyModel < ApplicationRecord
# other includes here
# ...
include BulkInsertSafe # include this last
# ...
end
```
The `BulkInsertSafe` concern has two functions:
- It performs checks against your model class to ensure that it does not use ActiveRecord
APIs that are not safe to use with respect to bulk insertions (more on that below).
- It adds new class methods `bulk_insert!` and `bulk_upsert!`, which you can use to insert many records at once.
## Insert records with `bulk_insert!` and `bulk_upsert!`
If the target class passes the checks performed by `BulkInsertSafe`, you can insert an array of
ActiveRecord model objects as follows:
```ruby
records = [MyModel.new, ...]
MyModel.bulk_insert!(records)
```
Calls to `bulk_insert!` always attempt to insert _new records_. If instead
you would like to replace existing records with new values, while still inserting those
that do not already exist, then you can use `bulk_upsert!`:
```ruby
records = [MyModel.new, existing_model, ...]
MyModel.bulk_upsert!(records, unique_by: [:name])
```
In this example, `unique_by` specifies the columns by which records are considered to be
unique and as such are updated if they existed prior to insertion. For example, if
`existing_model` has a `name` attribute, and if a record with the same `name` value already
exists, its fields are updated with those of `existing_model`.
The `unique_by` parameter can also be passed as a `Symbol`, in which case it specifies
a database index by which a column is considered unique:
```ruby
MyModel.bulk_insert!(records, unique_by: :index_on_name)
```
### Record validation
The `bulk_insert!` method guarantees that `records` are inserted transactionally, and
runs validations on each record prior to insertion. If any record fails to validate,
an error is raised and the transaction is rolled back. You can turn off validations via
the `:validate` option:
```ruby
MyModel.bulk_insert!(records, validate: false)
```
### Batch size configuration
In those cases where the number of `records` is above a given threshold, insertions
occur in multiple batches. The default batch size is defined in
[`BulkInsertSafe::DEFAULT_BATCH_SIZE`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/app/models/concerns/bulk_insert_safe.rb).
Assuming a default threshold of 500, inserting 950 records
would result in two batches being written sequentially (of size 500 and 450).
You can override the default batch size via the `:batch_size` option:
```ruby
MyModel.bulk_insert!(records, batch_size: 100)
```
Assuming the same number of 950 records, this would result in 10 batches being written instead.
Since this also affects the number of `INSERT` statements that occur, make sure you measure the
performance impact this might have on your code. There is a trade-off between the number of
`INSERT` statements the database has to process and the size and cost of each `INSERT`.
### Handling duplicate records
{{< alert type="note" >}}
This parameter applies only to `bulk_insert!`. If you intend to update existing
records, use `bulk_upsert!` instead.
{{< /alert >}}
It may happen that some records you are trying to insert already exist, which would result in
primary key conflicts. There are two ways to address this problem: failing fast by raising an
error or skipping duplicate records. The default behavior of `bulk_insert!` is to fail fast
and raise an `ActiveRecord::RecordNotUnique` error.
If this is undesirable, you can instead skip duplicate records with the `skip_duplicates` flag:
```ruby
MyModel.bulk_insert!(records, skip_duplicates: true)
```
### Requirements for safe bulk insertions
Large parts of ActiveRecord's persistence API are built around the notion of callbacks. Many
of these callbacks fire in response to model lifecycle events such as `save` or `create`.
These callbacks cannot be used with bulk insertions, since they are meant to be called for
every instance that is saved or created. Since these events do not fire when
records are inserted in bulk, we prevent their use.
The specifics around which callbacks are explicitly allowed are defined in
[`BulkInsertSafe`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/app/models/concerns/bulk_insert_safe.rb).
Consult the module source code for details. If your class uses callbacks that are not explicitly designated
safe and you `include BulkInsertSafe` the application fails with an error.
### `BulkInsertSafe` versus `InsertAll`
Internally, `BulkInsertSafe` is based on `InsertAll`, and you may wonder when to choose
the former over the latter. To help you make the decision,
the key differences between these classes are listed in the table below.
| | Input type | Validates input | Specify batch size | Can bypass callbacks | Transactional |
|--------------- | -------------------- | --------------- | ------------------ | --------------------------------- | ------------- |
| `bulk_insert!` | ActiveRecord objects | Yes (optional) | Yes (optional) | No (prevents unsafe callback use) | Yes |
| `insert_all!` | Attribute hashes | No | No | Yes | Yes |
To summarize, `BulkInsertSafe` moves bulk inserts closer to how ActiveRecord objects
and inserts would usually behave. However, if all you need is to insert raw data in bulk, then
`insert_all` is more efficient.
## Insert `has_many` associations in bulk
A common use case is to save collections of associated relations through the owner side of the relation,
where the owned relation is associated to the owner through the `has_many` class method:
```ruby
owner = OwnerModel.new(owned_relations: array_of_owned_relations)
# saves all `owned_relations` one-by-one
owner.save!
```
This issues a single `INSERT`, and transaction, for every record in `owned_relations`, which is inefficient if
`array_of_owned_relations` is large. To remedy this, the `BulkInsertableAssociations` concern can be
used to declare that the owner defines associations that are safe for bulk insertion:
```ruby
class OwnerModel < ApplicationRecord
# other includes here
# ...
include BulkInsertableAssociations # include this last
has_many :my_models
end
```
Here `my_models` must be declared `BulkInsertSafe` (as described previously) for bulk insertions
to happen. You can now insert any yet unsaved records as follows:
```ruby
BulkInsertableAssociations.with_bulk_insert do
owner = OwnerModel.new(my_models: array_of_my_model_instances)
# saves `my_models` using a single bulk insert (possibly via multiple batches)
owner.save!
end
```
You can still save relations that are not `BulkInsertSafe` in this block; they
are treated as if you had invoked `save` from outside the block.
## Known limitations
There are a few restrictions to how these APIs can be used:
- `BulkInsertableAssociations`:
- It is currently only compatible with `has_many` relations.
- It does not yet support `has_many through: ...` relations.
Moreover, input data should either be limited to around 1000 records at most,
or already batched prior to calling bulk insert. The `INSERT` statement runs in a single
transaction, so for large amounts of records it may negatively affect database stability.
|
https://docs.gitlab.com/development/multiple_databases
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/multiple_databases.md
|
2025-08-13
|
doc/development/database
|
[
"doc",
"development",
"database"
] |
multiple_databases.md
|
Tenant Scale
|
Cells Infrastructure
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Multiple Databases
| null |
To allow GitLab to scale further we
[decomposed the GitLab application database into multiple databases](https://gitlab.com/groups/gitlab-org/-/epics/6168).
The main databases are `main`, `ci`, and `sec`. GitLab supports being run with one, two, or three databases.
On GitLab.com we are using separate `main` `ci`, and `sec` databases.
For the purpose of building the [Cells](https://handbook.gitlab.com/handbook/engineering/architecture/design-documents/cells/) architecture, we are decomposing
the databases further, to introduce another database `gitlab_main_clusterwide`.
## GitLab Schema
For properly discovering allowed patterns between different databases
the GitLab application implements the [database dictionary](database_dictionary.md).
The database dictionary provides a virtual classification of tables into a `gitlab_schema`
which conceptually is similar to [PostgreSQL Schema](https://www.postgresql.org/docs/16/ddl-schemas.html).
We decided as part of [using database schemas to better isolated CI decomposed features](https://gitlab.com/gitlab-org/gitlab/-/issues/333415)
that we cannot use PostgreSQL schema due to complex migration procedures. Instead we implemented
the concept of application-level classification.
Each table of GitLab needs to have a `gitlab_schema` assigned:
| Schema | Description | Notes |
| -------- | ----------- | ------- |
| `gitlab_main` | See [Cells / Organizations schemas](../cells/_index.md#available-cells--organization-schemas) | |
| `gitlab_main_cell` | See [Cells / Organizations schemas](../cells/_index.md#available-cells--organization-schemas) | |
| `gitlab_main_cell_setting` | See [Cells / Organizations schemas](../cells/_index.md#available-cells--organization-schemas) | |
| `gitlab_main_clusterwide` | See [Cells / Organizations schemas](../cells/_index.md#available-cells--organization-schemas) | |
| `gitlab_main_cell_local` | See [Cells / Organizations schemas](../cells/_index.md#available-cells--organization-schemas) | |
| `gitlab_ci` | All CI tables that are being stored in the `ci:` database (for example, `ci_pipelines`, `ci_builds`) | |
| `gitlab_ci_cell_local` | See [Cells / Organizations schemas](../cells/_index.md#available-cells--organization-schemas) | |
| `gitlab_geo` | All Geo tables that are being stored in the `geo:` database (for example, like `project_registry`, `secondary_usage_data`) | |
| `gitlab_shared` | All application tables that contain data across all decomposed databases (for example, `loose_foreign_keys_deleted_records`) for models that inherit from `Gitlab::Database::SharedModel`. | |
| `gitlab_internal` | All internal tables of Rails and PostgreSQL (for example, `ar_internal_metadata`, `schema_migrations`, `pg_*`) | |
| `gitlab_pm` | All tables that store `package_metadata`| It is an alias for `gitlab_main`, to be replaced with `gitlab_sec` |
| `gitlab_sec` | All Security and Vulnerability feature tables to be stored in the `sec:` database | [Decomposition in progress](https://gitlab.com/groups/gitlab-org/-/epics/13043) |
More schemas to be introduced with additional decomposed databases
The usage of schema enforces the base class to be used:
- `ApplicationRecord` for `gitlab_main`/`gitlab_main_cell.`
- `Ci::ApplicationRecord` for `gitlab_ci`
- `Geo::TrackingBase` for `gitlab_geo`
- `Gitlab::Database::SharedModel` for `gitlab_shared`
- `PackageMetadata::ApplicationRecord` for `gitlab_pm`
- `SecApplicationRecord` for `gitlab_sec`
### Defining a sharding key for all cell-local tables
This content has been moved to a
[new location](../organization/_index.md#defining-a-sharding-key-for-all-organizational-tables)
### The impact of `gitlab_schema`
The usage of `gitlab_schema` has a significant impact on the application.
The `gitlab_schema` primary purpose is to introduce a barrier between different data access patterns.
This is used as a primary source of classification for:
- [Discovering cross-joins across tables from different schemas](#removing-joins-between-main-and-non-main-tables)
- [Discovering cross-database transactions across tables from different schemas](#removing-cross-database-transactions)
### The special purpose of `gitlab_shared`
`gitlab_shared` is a special case that describes tables or views that, by design, contain data across
all decomposed databases. This classification describes application-defined tables (like `loose_foreign_keys_deleted_records`).
**Be careful** to use `gitlab_shared` as it requires special handling while accessing data.
Since `gitlab_shared` shares not only structure but also data, the application needs to be written in a way
that traverses all data from all databases in sequential manner.
```ruby
Gitlab::Database::EachDatabase.each_model_connection([MySharedModel]) do |connection, connection_name|
MySharedModel.select_all_data...
end
```
As such, migrations modifying data of `gitlab_shared` tables are expected to run across
all decomposed databases.
### The special purpose of `gitlab_internal`
`gitlab_internal` describes Rails-defined tables (like `schema_migrations` or `ar_internal_metadata`), as well as internal PostgreSQL tables (for example, `pg_attribute`). Its primary purpose is to [support other databases](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/85842#note_943453682), like Geo, that
might be missing some of those application-defined `gitlab_shared` tables (like `loose_foreign_keys_deleted_records`), but are valid Rails databases.
### The special purpose of `gitlab_pm`
`gitlab_pm` stores package metadata describing public repositories. This data is used for the License Compliance and Dependency Scanning product categories and is maintained by the [Composition Analysis Group](https://handbook.gitlab.com/handbook/engineering/development/sec/secure/composition-analysis/). It is an alias for `gitlab_main` intended to make it easier to route to a different database in the future.
## Migrations
Read [Migrations for Multiple Databases](migrations_for_multiple_databases.md).
## CI and Sec Databases
### Configure single database
By default, GDK is configured to run with multiple databases.
{{< alert type="warning" >}}
Switching back-and-forth between single and multiple databases in
the same development instance is discouraged. Any data in the `ci` or `sec`
database will not be accessible in single database mode. For single database, you should use a separate development instance.
{{< /alert >}}
To configure GDK to use a single database:
1. On the GDK root directory, run:
```shell
gdk config set gitlab.rails.databases.ci.enabled false
gdk config set gitlab.rails.databases.sec.enabled false
```
1. Reconfigure GDK:
```shell
gdk reconfigure
```
To switch back to using multiple databases, set `gitlab.rails.databases.<db_name>.enabled` to `true` and run `gdk reconfigure`.
<!--
The `validate_cross_joins!` method in `spec/support/database/prevent_cross_joins.rb` references
the following heading in the code, so if you make a change to this heading, make sure to update
the corresponding documentation URL used in `spec/support/database/prevent_cross_joins.rb`.
-->
### Removing joins between `main` and non `main` tables
Queries that join across databases raise an error. [Introduced](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/68620)
in GitLab 14.3, for new queries only. Pre-existing queries do not raise an error.
Because GitLab can be run with multiple separate databases, referencing `main`
tables with non `main` tables in a single query is not possible. Therefore,
using any kind of `JOIN` in SQL queries will not work.
#### Suggestions for removing cross-database joins
The following sections are some real examples that were identified as joining across databases,
along with possible suggestions on how to fix them.
##### Remove the code
The simplest solution we've seen several times now has been an existing scope
that is unused. This is the easiest example to fix. So the first step is to
investigate if the code is unused and then remove it. These are some
real examples:
- <https://gitlab.com/gitlab-org/gitlab/-/merge_requests/67162>
- <https://gitlab.com/gitlab-org/gitlab/-/merge_requests/66714>
- <https://gitlab.com/gitlab-org/gitlab/-/merge_requests/66503>
There may be more examples where the code is used, but we can evaluate
if we need it or if the feature should behave this way.
Before complicating things by adding new columns and tables,
consider if you can simplify the solution and still meet the requirements.
One case being evaluated involves changing how certain `UsageData` is
calculated to remove a join query in
<https://gitlab.com/gitlab-org/gitlab/-/issues/336170>. This is a good candidate
to evaluate, because `UsageData` is not critical to users and it may be possible
to get a similarly useful metric with a simpler approach. Alternatively we may
find that nobody is using these metrics, so we can remove them.
##### Use `preload` instead of `includes`
The `includes` and `preload` methods in Rails are both ways to avoid an N+1
query. The `includes` method in Rails uses a heuristic approach to determine
if it needs to join to the table, or if it can load all of the
records in a separate query. This method assumes it needs to join if it thinks
you need to query the columns from the other table, but sometimes
this method gets it wrong and executes a join even when not needed. In
this case using `preload` to explicitly load the data in a separate query
allows you to avoid the join, while still avoiding the N+1 query.
You can see a real example of this solution being used in
<https://gitlab.com/gitlab-org/gitlab/-/merge_requests/67655>.
##### Remove a redundant join
Sometimes there are cases where a query is doing excess (or redundant) joins.
A common example occurs where a query is joining from `A` to `C`, via some
table with both foreign keys, `B`.
When you only care about counting how
many rows there are in `C` and if there are foreign keys and `NOT NULL` constraints
on the foreign keys in `B`, then it might be enough to count those rows.
For example, in
[MR 71811](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/71811), it was
previously doing `project.runners.count`, which would produce a query like:
```sql
select count(*) from projects
inner join ci_runner_projects on ci_runner_projects.project_id = projects.id
where ci_runner_projects.runner_id IN (1, 2, 3)
```
This was changed to avoid the cross-join by changing the code to
`project.runner_projects.count`. It produces the same response with the
following query:
```sql
select count(*) from ci_runner_projects
where ci_runner_projects.runner_id IN (1, 2, 3)
```
Another common redundant join is joining all the way to another table,
then filtering by primary key when you could have instead filtered on a foreign
key. See an example in
[MR 71614](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/71614). The previous
code was `joins(scan: :build).where(ci_builds: { id: build_ids })`, which
generated a query like:
```sql
select ...
inner join security_scans
inner join ci_builds on security_scans.build_id = ci_builds.id
where ci_builds.id IN (1, 2, 3)
```
However, as `security_scans` already has a foreign key `build_id`, the code
can be changed to `joins(:scan).where(security_scans: { build_id: build_ids })`,
which produces the same response with the following query:
```sql
select ...
inner join security_scans
where security_scans.build_id IN (1, 2, 3)
```
Both of these examples of removing redundant joins remove the cross-joins,
but they have the added benefit of producing simpler and faster
queries.
##### Limited pluck followed by a find
Using `pluck` or `pick` to get an array of `id`s is not advisable unless the returned
array is guaranteed to be bounded in size. Usually this is a good pattern where
you know the result will be at most 1, or in cases where you have a list of in
memory ids (or usernames) that need to be mapped to another list of equal size.
It would not be suitable when mapping a list of ids in a one-to-many
relationship as the result will be unbounded. We can then use the
returned `id`s to obtain the related record:
```ruby
allowed_user_id = board_user_finder
.where(user_id: params['assignee_id'])
.pick(:user_id)
User.find_by(id: allowed_user_id)
```
You can see an example where this was used in
<https://gitlab.com/gitlab-org/gitlab/-/merge_requests/126856>
Sometimes it might seem easy to convert a join into a `pluck` but often this
results in loading an unbounded amount of ids into memory and then
re-serializing those in a following query back to Postgres. These cases do not
scale and we recommend attempting one of the other options. It might seem like a
good idea to just apply some `limit` to the plucked data to have bounded memory
but this introduces unpredictable results for users and often is most
problematic for our largest customers (including ourselves), and as such we
advise against it.
##### De-normalize some foreign key to the table
De-normalization refers to adding redundant precomputed (duplicated) data to
a table to simplify certain queries or to improve performance. In this
case, it can be useful when you are doing a join that involves three tables, where
you are joining through some intermediate table.
Generally when modeling a database schema, a "normalized" structure is
preferred because of the following reasons:
- Duplicate data uses extra storage.
- Duplicate data needs to be kept in sync.
Sometimes normalized data is less performant so de-normalization has been a
common technique GitLab has used to improve the performance of database queries
for a while. The above problems are mitigated when the following conditions are
met:
1. There isn't much data (for example, it's just an integer column).
1. The data does not update often (for example, the `project_id` column is almost
never updated for most tables).
One example we found was the `terraform_state_versions` table. This table has a foreign
key `terraform_state_versions.ci_build_id` which allows you to join to the build. Therefore
you could join to the project like so:
```sql
select projects.* from terraform_state_versions
inner join ci_builds on terraform_state_versions.ci_build_id = ci_builds.id
inner join projects on ci_builds.project_id = projects.id
```
The problem with this query is that `ci_builds` is in a different database
from the other two tables.
The solution in this case is to add the `project_id` column to
`terraform_state_versions`. This doesn't use much extra storage, and due to the way
these features work, it's never updated (a build never moves projects).
This simplified the query to:
```sql
select projects.* from terraform_state_versions
inner join projects on terraform_state_versions.project_id = projects.id
```
This also improves performance because you don't need to join through an extra
table.
You can see this approach implemented in
<https://gitlab.com/gitlab-org/gitlab/-/merge_requests/66963> . This MR also
de-normalizes `pipeline_id` to fix a similar query.
##### De-normalize into an extra table
Sometimes the previous de-normalization (adding an extra column) doesn't work for
your specific case. This may be due to the fact that your data is not 1:1, or
because the table you're adding to is already too wide (for example, the `projects`
table shouldn't have more columns added).
In this case you may decide to just store the extra data in a separate table.
One example where this approach is being used was to implement the
`Project.with_code_coverage` scope. This scope was essentially used to narrow
down a list of projects to only those that have at one point in time used code
coverage features. This query (simplified) was:
```sql
select projects.* from projects
inner join ci_daily_build_group_report_results on ci_daily_build_group_report_results.project_id = projects.id
where ((data->'coverage') is not null)
and ci_daily_build_group_report_results.default_branch = true
group by projects.id
```
This work is still in progress but the current plan is to introduce a new table
called `projects_with_ci_feature_usage` which has 2 columns `project_id` and
`ci_feature`. This table would be written to the first time a project creates a
`ci_daily_build_group_report_results` for code coverage. Therefore the new
query would be:
```sql
select projects.* from projects
inner join projects_with_ci_feature_usage on projects_with_ci_feature_usage.project_id = projects.id
where projects_with_ci_feature_usage.ci_feature = 'code_coverage'
```
The above example uses as a text column for simplicity but we should probably
use an [enum](creating_enums.md) to save space.
The downside of this new design is that this may need to be
updated (removed if the `ci_daily_build_group_report_results` is deleted).
Depending on your domain, however, this may not be necessary because deletes are
edge cases or impossible, or because the user impact of seeing the project on the
list page may not be problematic. It's also possible to implement the
logic to delete these rows if or whenever necessary in your domain.
Finally, this de-normalization and new query also improves performance because
it does less joins and needs less filtering.
##### Use `disable_joins` for `has_one` or `has_many` `through:` relations
Sometimes a join query is caused by using `has_one ... through:` or `has_many ... through:`
across tables that span the different databases. These joins
sometimes can be solved by adding
[`disable_joins:true`](https://edgeguides.rubyonrails.org/active_record_multiple_databases.html#handling-associations-with-joins-across-databases).
This is a Rails feature which we
[backported](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/66400). We
also extended the feature to allow a lambda syntax for enabling `disable_joins`
with a feature flag. If you use this feature we encourage using a feature flag
as it mitigates risk if there is some serious performance regression.
You can see an example where this was used in
<https://gitlab.com/gitlab-org/gitlab/-/merge_requests/66709/diffs>.
With any change to DB queries it is important to analyze and compare the SQL
before and after the change. `disable_joins` can introduce very poorly performing
code depending on the actual logic of the `has_many` or `has_one` relationship.
The key thing to look for is whether any of the intermediate result sets
used to construct the final result set have an unbounded amount of data loaded.
The best way to tell is by looking at the SQL generated and confirming that
each one is limited in some way. You can tell by either a `LIMIT 1` clause or
by `WHERE` clause that is limiting based on a unique column. Any unbounded
intermediate dataset could lead to loading too many IDs into memory.
An example where you may see very poor performance is the following
hypothetical code:
```ruby
class Project
has_many :pipelines
has_many :builds, through: :pipelines
end
class Pipeline
has_many :builds
end
class Build
belongs_to :pipeline
end
def some_action
@builds = Project.find(5).builds.order(created_at: :desc).limit(10)
end
```
In the above case `some_action` will generate a query like:
```sql
select * from builds
inner join pipelines on builds.pipeline_id = pipelines.id
where pipelines.project_id = 5
order by builds.created_at desc
limit 10
```
However, if you changed the relation to be:
```ruby
class Project
has_many :pipelines
has_many :builds, through: :pipelines, disable_joins: true
end
```
Then you would get the following 2 queries:
```sql
select id from pipelines where project_id = 5;
select * from builds where pipeline_id in (...)
order by created_at desc
limit 10;
```
Because the first query does not limit by any unique column or
have a `LIMIT` clause, it can load an unlimited number of
pipeline IDs into memory, which are then sent in the following query.
This can lead to very poor performance in the Rails application and the
database. In cases like this, you might need to re-write the
query or look at other patterns described above for removing cross-joins.
#### How to validate you have correctly removed a cross-join
RSpec is configured to automatically validate all SQL queries do not join
across databases. If this validation is disabled in
`spec/support/database/cross-join-allowlist.yml` then you can still validate an
isolated code block using `with_cross_joins_prevented`.
You can use this method like so:
```ruby
it 'does not join across databases' do
with_cross_joins_prevented do
::Ci::Build.joins(:project).to_a
end
end
```
This will raise an exception if the query joins across the two databases. The
previous example is fixed by removing the join, like so:
```ruby
it 'does not join across databases' do
with_cross_joins_prevented do
::Ci::Build.preload(:project).to_a
end
end
```
You can see a real example of using this method for fixing a cross-join in
<https://gitlab.com/gitlab-org/gitlab/-/merge_requests/67655>.
#### Allowlist for existing cross-joins
The easiest way of identifying a cross-join is via failing pipelines.
As an example, in [!130038](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/130038/diffs) we moved the `notification_settings` table to the `gitlab_main_cell` schema, by marking it as such in the `db/docs/notification_settings.yml` file.
The pipeline failed with the following [error](https://gitlab.com/gitlab-org/gitlab/-/jobs/4929130983):
```ruby
Database::PreventCrossJoins::CrossJoinAcrossUnsupportedTablesError:
Unsupported cross-join across 'users, notification_settings' querying 'gitlab_main_clusterwide, gitlab_main_cell' discovered when executing query 'SELECT "users".* FROM "users" WHERE "users"."id" IN (SELECT "notification_settings"."user_id" FROM ((SELECT "notification_settings"."user_id" FROM "notification_settings" WHERE "notification_settings"."source_id" = 119 AND "notification_settings"."source_type" = 'Project' AND (("notification_settings"."level" = 3 AND EXISTS (SELECT true FROM "notification_settings" "notification_settings_2" WHERE "notification_settings_2"."user_id" = "notification_settings"."user_id" AND "notification_settings_2"."source_id" IS NULL AND "notification_settings_2"."source_type" IS NULL AND "notification_settings_2"."level" = 2)) OR "notification_settings"."level" = 2))) notification_settings)'
```
To make the pipeline green, this cross-join query must be allow-listed.
A cross-join across databases can be explicitly allowed by wrapping the code in the
`::Gitlab::Database.allow_cross_joins_across_databases` helper method. Alternative
way is to mark a given relation as `relation.allow_cross_joins_across_databases`.
This method should only be used:
- For existing code.
- If the code is required to help migrate away from a cross-join. For example,
in a migration that backfills data for future use to remove a cross-join.
The `allow_cross_joins_across_databases` helper method can be used as follows:
```ruby
# Scope the block executing a object from database
::Gitlab::Database.allow_cross_joins_across_databases(url: 'https://gitlab.com/gitlab-org/gitlab/-/issues/336590') do
subject.perform(1, 4)
end
```
```ruby
# Mark a relation as allowed to cross-join databases
def find_diff_head_pipeline
all_pipelines
.allow_cross_joins_across_databases(url: 'https://gitlab.com/gitlab-org/gitlab/-/issues/336891')
.for_sha_or_source_sha(diff_head_sha)
.first
end
```
In model associations or scopes, this can be used as in the following example:
```ruby
class Group < Namespace
has_many :users, -> {
allow_cross_joins_across_databases(url: "https://gitlab.com/gitlab-org/gitlab/-/issues/422405")
}, through: :group_members
end
```
{{< alert type="warning" >}}
Overriding an association can have unintended consequences and may even lead to data loss, as we noticed in [issue 424307](https://gitlab.com/gitlab-org/gitlab/-/issues/424307). Do not override existing ActiveRecord associations to mark a cross-join as allowed, as in the example below.
{{< /alert >}}
```ruby
class Group < Namespace
has_many :users, through: :group_members
# DO NOT override an association like this.
def users
super.allow_cross_joins_across_databases(url: "https://gitlab.com/gitlab-org/gitlab/-/issues/422405")
end
end
```
The `url` parameter should point to an issue with a milestone for when we intend
to fix the cross-join. If the cross-join is being used in a migration, we do not
need to fix the code. See <https://gitlab.com/gitlab-org/gitlab/-/issues/340017>
for more details.
### Removing cross-database transactions
When dealing with multiple databases, it's important to pay close attention to data modification
that affects more than one database.
[Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/339811) GitLab 14.4, an automated check
prevents cross-database modifications.
When at least two different databases are modified during a transaction initiated on any database
server, the application triggers a cross-database modification error (only in test environment).
Example:
```ruby
# Open transaction on Main DB
ApplicationRecord.transaction do
ci_build.update!(updated_at: Time.current) # UPDATE on CI DB
ci_build.project.update!(updated_at: Time.current) # UPDATE on Main DB
end
# raises error: Cross-database data modification of 'main, ci' were detected within
# a transaction modifying the 'ci_build, projects' tables
```
The code example above updates the timestamp for two records within a transaction. With the
ongoing work on the CI database decomposition, we cannot ensure the schematics of a database
transaction.
If the second update query fails, the first update query will not be
rolled back because the `ci_build` record is located on a different database server. For
more information, look at the
[transaction guidelines](transaction_guidelines.md#dangerous-example-third-party-api-calls)
page.
#### Fixing cross-database transactions
A transaction across databases can be explicitly allowed by wrapping the code in the
`Gitlab::Database::QueryAnalyzers::PreventCrossDatabaseModification.temporary_ignore_tables_in_transaction` helper method.
This method should only be used for existing code.
The `temporary_ignore_tables_in_transaction` helper method can be used as follows:
```ruby
class GroupMember < Member
def update_two_factor_requirement
return unless user
# To mark and ignore cross-database transactions involving members and users/user_details/user_preferences
Gitlab::Database::QueryAnalyzers::PreventCrossDatabaseModification.temporary_ignore_tables_in_transaction(
%w[users user_details user_preferences], url: 'https://gitlab.com/gitlab-org/gitlab/-/issues/424288'
) do
user.update_two_factor_requirement
end
end
end
```
##### Removing the transaction block
Without an open transaction, the cross-database modification check cannot raise an error.
By making this change, we sacrifice consistency. In case of an application failure after the
first `UPDATE` query, the second `UPDATE` query will never execute.
The same code without the `transaction` block:
```ruby
ci_build.update!(updated_at: Time.current) # CI DB
ci_build.project.update!(updated_at: Time.current) # Main DB
```
##### Asynchronous processing
If we need more guarantee that an operation finishes the work consistently we can execute it
within a background job. A background job is scheduled asynchronously and retried several times
in case of an error. There is still a very small chance of introducing inconsistency.
Example:
```ruby
current_time = Time.current
MyAsyncConsistencyJob.perform_async(cu_build.id)
ci_build.update!(updated_at: current_time)
ci_build.project.update!(updated_at: current_time)
```
The `MyAsyncConsistencyJob` would also attempt to update the timestamp if they differ.
##### Aiming for perfect consistency
At this point, we don't have the tooling (we might not even need it) to ensure similar consistency
characteristics as we had with one database. If you think that the code you're working on requires
these properties, then you can disable the cross-database modification check in your tests by wrapping the
offending test code with a block and create a follow-up issue.
```ruby
allow_cross_database_modification_within_transaction(url: 'gitlab issue URL') do
ApplicationRecord.transaction do
ci_build.update!(updated_at: Time.current) # UPDATE on CI DB
ci_build.project.update!(updated_at: Time.current) # UPDATE on Main DB
end
end
```
Don't hesitate to reach out to the
[Tenant Scale group](https://handbook.gitlab.com/handbook/engineering/infrastructure-platforms/tenant-scale/)
for advice.
##### Avoid `dependent: :nullify` and `dependent: :destroy` across databases
There may be cases where we want to use `dependent: :nullify` or `dependent: :destroy`
across databases. This is technically possible, but it's problematic because
these hooks run in the context of an outer transaction from the call to
`#destroy`, which creates a cross-database transaction and we are trying to
avoid that. Cross-database transactions caused this way could lead to confusing
outcomes when we switch to decomposed, because now you have some queries
happening outside the transaction and they may be partially applied while the
outer transaction fails, which could lead to surprising bugs.
For non-trivial objects that need to clean up data outside the
database (for example, object storage), we recommend the setting
[`dependent: :restrict_with_error`](https://guides.rubyonrails.org/association_basics.html#options-for-has-one-dependent).
Such objects should be removed explicitly ahead of time. Using `dependent: :restrict_with_error`
ensures that we forbid destroying the parent object if something is not cleaned up.
If all you need to do is clean up the child records themselves from PostgreSQL,
consider using [loose foreign keys](loose_foreign_keys.md).
## Foreign keys that cross databases
There are many places where we use foreign keys that reference across the two
databases. This is not possible to do with two separate PostgreSQL
databases, so we need to replicate the behavior we get from PostgreSQL in a
performant way. We can't, and shouldn't, try to replicate the data guarantees
given by PostgreSQL which prevent creating invalid references, but we still need a
way to replace cascading deletes so we don't end up with orphaned data
or records that point to nowhere, which might lead to bugs. As such we created
["loose foreign keys"](loose_foreign_keys.md) which is an asynchronous
process of cleaning up orphaned records.
### Allowlist for existing cross-database foreign keys
The easiest way of identifying a cross-database foreign key is via failing pipelines.
As an example, in [!130038](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/130038/diffs) we moved the `notification_settings` table to the `gitlab_main_cell` schema, by marking it in the `db/docs/notification_settings.yml` file.
`notification_settings.user_id` is a column that points to `users`, but the `users` table belongs to a different database, thus this is now treated as a cross-database foreign key.
We have a spec to capture such cases of cross-database foreign keys in [`no_cross_db_foreign_keys_spec.rb`](https://gitlab.com/gitlab-org/gitlab/-/blob/01d3a1e41513200368a22bbab5d4312174762ee0/spec/lib/gitlab/database/no_cross_db_foreign_keys_spec.rb), which would fail if such a cross-database foreign key is encountered.
To make the pipeline green, this cross-database foreign key must be allow-listed.
To do this, explicitly allow the existing cross-database foreign key to exist by adding it as an exception in the same spec (as in [this example](https://gitlab.com/gitlab-org/gitlab/-/blob/7d99387f399c548af24d93d564b35f2f9510662d/spec/lib/gitlab/database/no_cross_db_foreign_keys_spec.rb#L26)).
This way, the spec will not fail.
Later, this foreign key can be converted to a loose foreign key, like we did in [!130080](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/130080/diffs).
## Testing for multiple databases
In our testing CI pipelines, we test GitLab by default with multiple databases set up, using
both `main` and `ci` databases. But in merge requests, for example when we modify some database-related code or
add the label `~"pipeline:run-single-db"` to the MR, we additionally run our tests in
[two other database modes](../pipelines/_index.md#single-database-testing):
`single-db` and `single-db-ci-connection`.
To handle situations where our tests need to run in specific database modes, we have some RSpec helpers
to limit the modes where tests can run, and skip them on any other modes.
| Helper name | Test runs |
|---------------------------------------------| --- |
| `skip_if_shared_database(:ci)` | On **multiple databases** |
| `skip_if_database_exists(:ci)` | On **single-db** and **single-db-ci-connection** |
| `skip_if_multiple_databases_are_setup(:ci)` | Only on **single-db** |
| `skip_if_multiple_databases_not_setup(:ci)` | On **single-db-ci-connection** and **multiple databases** |
## Locking writes on the tables that don't belong to the database schemas
When a separate database is promoted and the split from main,
as an extra safeguard against creating a split brain situation,
run the Rake task `gitlab:db:lock_writes`. This command locks writes on:
- Legacy tables on `gitlab_ci` belonging to the Main or Sec Databases.
- Legacy tables on `gitlab_main` belonging to the CI or Sec Databases.
- Legacy tables on `gitlab_sec` belonging to the CI or Main Databases.
This Rake task adds triggers to all the tables, to prevent any
`INSERT`, `UPDATE`, `DELETE`, or `TRUNCATE` statements from running
against the tables that need to be locked.
If this task was run against a GitLab setup that uses only a single database
for both `gitlab_main` and `gitlab_ci` tables, then no tables will be locked.
To undo the operation, run the opposite Rake task: `gitlab:db:unlock_writes`.
### Monitoring
The status of the table locks is checked using the
[`Database::MonitorLockedTablesWorker`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/app/workers/database/monitor_locked_tables_worker.rb).
It will lock tables if needed.
The result of this script is available in [Kibana](https://log.gprd.gitlab.net/app/r/s/4qrz2).
If the counts are not 0, there are some tables that should have been locked but are not.
The fields `json.extra.database_monitor_locked_tables_worker.results.ci.tables_need_locks` and
`json.extra.database_monitor_locked_tables_worker.results.main.tables_need_locks` should contain
a list of tables that have the wrong state.
The logging is monitored using a [Elasticsearch Watcher](https://log.gprd.gitlab.net/app/management/insightsAndAlerting/watcher/watches).
The watcher is called `table_locks_needed` and the source code is in the
[GitLab Runbook repository](https://gitlab.com/gitlab-com/runbooks/-/tree/master/elastic/managed-objects/log_gprd/watches).
The alerts are sent to [#g_tenant-scale](https://gitlab.enterprise.slack.com/archives/C01TQ838Y3T) Slack channel.
### Automation
There are two processes that automatically lock tables:
- Database migrations. See [`Gitlab::Database::MigrationHelpers::AutomaticLockWritesOnTables`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/lib/gitlab/database/migration_helpers/automatic_lock_writes_on_tables.rb)
- The `Database::MonitorLockedTablesWorker` locks tables if needed.
This can be disabled by the `lock_tables_in_monitoring` feature flag.
`Gitlab::Database::MigrationHelpers::AutomaticLockWritesOnTables` compares the list of tables before and after each database migration runs. Then
it locks the newly added tables on the relevant database. This does not
cover all cases. Because some migrations need
to re-create the tables within the same transactional migration. For example: To convert standard unpartitioned tables into partitioned tables.
See [this example](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/184636).
Such migrations leave the re-created tables unlocked. But the daily cron job of `Database::MonitorLockedTablesWorker` takes care of
alerting about this on Slack, and then automatically locks these tables for writes.
### Manually lock tables
If you need to manually lock a table, use a database migration.
Create a regular migration and add the code for locking the table.
For example, set a write lock on `shards` table in CI database:
```ruby
class EnableWriteLocksOnShards < Gitlab::Database::Migration[2.2]
def up
# On main database, the migration should be skipped
# We can't use restrict_gitlab_migration in DDL migrations
return if Gitlab::Database.db_config_name(connection) != 'ci'
Gitlab::Database::LockWritesManager.new(
table_name: 'shards',
connection: connection,
database_name: :ci,
with_retries: false
).lock_writes
end
def down
# no-op
end
end
```
## Truncating tables
When separate databases from `main` are fully split, we can free up disk
space by truncating tables. This results in a smaller data set: For example,
the data in `users` table on CI database is no longer read and also no
longer updated. So this data can be removed by truncating the tables.
For this purpose, GitLab provides separate Rake tasks, one for each database:
- `gitlab:db:truncate_legacy_tables:main` will truncate the legacy tables in Main database.
- `gitlab:db:truncate_legacy_tables:ci` will truncate the legacy tables in CI database.
- `gitlab:db:truncate_legacy_tables:sec` will truncate the legacy tables in Sec database.
{{< alert type="note" >}}
These tasks can only be run when the tables in the database are
[locked for writes](#locking-writes-on-the-tables-that-dont-belong-to-the-database-schemas).
{{< /alert >}}
{{< alert type="warning" >}}
The examples in this section use `DRY_RUN=true`. This ensures no data is actually
truncated. GitLab highly recommends to have a backup available before you run any of
these tasks without `DRY_RUN=true`.
{{< /alert >}}
These tasks have the option to see what they do without actually changing the
data:
```shell
$ sudo DRY_RUN=true gitlab-rake gitlab:db:truncate_legacy_tables:main
I, [2023-07-14T17:08:06.665151 #92505] INFO -- : DRY RUN:
I, [2023-07-14T17:08:06.761586 #92505] INFO -- : Truncating legacy tables for the database main
I, [2023-07-14T17:08:06.761709 #92505] INFO -- : SELECT set_config('lock_writes.ci_build_needs', 'false', false)
I, [2023-07-14T17:08:06.765272 #92505] INFO -- : SELECT set_config('lock_writes.ci_build_pending_states', 'false', false)
I, [2023-07-14T17:08:06.768220 #92505] INFO -- : SELECT set_config('lock_writes.ci_build_report_results', 'false', false)
[...]
I, [2023-07-14T17:08:06.957294 #92505] INFO -- : TRUNCATE TABLE ci_build_needs, ci_build_pending_states, ci_build_report_results, ci_build_trace_chunks, ci_build_trace_metadata, ci_builds, ci_builds_metadata, ci_builds_runner_session, ci_cost_settings, ci_daily_build_group_report_results, ci_deleted_objects, ci_freeze_periods, ci_group_variables, ci_instance_variables, ci_job_artifact_states, ci_job_artifacts, ci_job_token_project_scope_links, ci_job_variables, ci_minutes_additional_packs, ci_namespace_mirrors, ci_namespace_monthly_usages, ci_partitions, ci_pending_builds, ci_pipeline_artifacts, ci_pipeline_chat_data, ci_pipeline_messages, ci_pipeline_metadata, ci_pipeline_schedule_variables, ci_pipeline_schedules, ci_pipeline_variables, ci_pipelines, ci_pipelines_config, ci_platform_metrics, ci_project_mirrors, ci_project_monthly_usages, ci_refs, ci_resource_groups, ci_resources, ci_runner_machines, ci_runner_namespaces, ci_runner_projects, ci_runner_versions, ci_runners, ci_running_builds, ci_secure_file_states, ci_secure_files, ci_sources_pipelines, ci_sources_projects, ci_stages, ci_subscriptions_projects, ci_trigger_requests, ci_triggers, ci_unit_test_failures, ci_unit_tests, ci_variables, external_pull_requests, p_ci_builds, p_ci_builds_metadata, p_ci_job_annotations, p_ci_runner_machine_builds, taggings, tags RESTRICT
```
The tasks will first find out the tables that need to be truncated. Truncation will
happen in stages because we need to limit the amount of data removed in one database
transaction. The tables are processed in a specific order depending on the definition
of the foreign keys. The number of tables processed in one stage can be changed by
adding a number when invoking the task. The default value is 5:
```shell
sudo DRY_RUN=true gitlab-rake gitlab:db:truncate_legacy_tables:main\[10\]
```
It is also possible to limit the number of tables to be truncated by setting the `UNTIL_TABLE`
variable. For example in this case, the process will stop when `ci_unit_test_failures` has been
truncated:
```shell
sudo DRY_RUN=true UNTIL_TABLE=ci_unit_test_failures gitlab-rake gitlab:db:truncate_legacy_tables:main
```
|
---
stage: Tenant Scale
group: Cells Infrastructure
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: Multiple Databases
breadcrumbs:
- doc
- development
- database
---
To allow GitLab to scale further we
[decomposed the GitLab application database into multiple databases](https://gitlab.com/groups/gitlab-org/-/epics/6168).
The main databases are `main`, `ci`, and `sec`. GitLab supports being run with one, two, or three databases.
On GitLab.com we are using separate `main` `ci`, and `sec` databases.
For the purpose of building the [Cells](https://handbook.gitlab.com/handbook/engineering/architecture/design-documents/cells/) architecture, we are decomposing
the databases further, to introduce another database `gitlab_main_clusterwide`.
## GitLab Schema
For properly discovering allowed patterns between different databases
the GitLab application implements the [database dictionary](database_dictionary.md).
The database dictionary provides a virtual classification of tables into a `gitlab_schema`
which conceptually is similar to [PostgreSQL Schema](https://www.postgresql.org/docs/16/ddl-schemas.html).
We decided as part of [using database schemas to better isolated CI decomposed features](https://gitlab.com/gitlab-org/gitlab/-/issues/333415)
that we cannot use PostgreSQL schema due to complex migration procedures. Instead we implemented
the concept of application-level classification.
Each table of GitLab needs to have a `gitlab_schema` assigned:
| Schema | Description | Notes |
| -------- | ----------- | ------- |
| `gitlab_main` | See [Cells / Organizations schemas](../cells/_index.md#available-cells--organization-schemas) | |
| `gitlab_main_cell` | See [Cells / Organizations schemas](../cells/_index.md#available-cells--organization-schemas) | |
| `gitlab_main_cell_setting` | See [Cells / Organizations schemas](../cells/_index.md#available-cells--organization-schemas) | |
| `gitlab_main_clusterwide` | See [Cells / Organizations schemas](../cells/_index.md#available-cells--organization-schemas) | |
| `gitlab_main_cell_local` | See [Cells / Organizations schemas](../cells/_index.md#available-cells--organization-schemas) | |
| `gitlab_ci` | All CI tables that are being stored in the `ci:` database (for example, `ci_pipelines`, `ci_builds`) | |
| `gitlab_ci_cell_local` | See [Cells / Organizations schemas](../cells/_index.md#available-cells--organization-schemas) | |
| `gitlab_geo` | All Geo tables that are being stored in the `geo:` database (for example, like `project_registry`, `secondary_usage_data`) | |
| `gitlab_shared` | All application tables that contain data across all decomposed databases (for example, `loose_foreign_keys_deleted_records`) for models that inherit from `Gitlab::Database::SharedModel`. | |
| `gitlab_internal` | All internal tables of Rails and PostgreSQL (for example, `ar_internal_metadata`, `schema_migrations`, `pg_*`) | |
| `gitlab_pm` | All tables that store `package_metadata`| It is an alias for `gitlab_main`, to be replaced with `gitlab_sec` |
| `gitlab_sec` | All Security and Vulnerability feature tables to be stored in the `sec:` database | [Decomposition in progress](https://gitlab.com/groups/gitlab-org/-/epics/13043) |
More schemas to be introduced with additional decomposed databases
The usage of schema enforces the base class to be used:
- `ApplicationRecord` for `gitlab_main`/`gitlab_main_cell.`
- `Ci::ApplicationRecord` for `gitlab_ci`
- `Geo::TrackingBase` for `gitlab_geo`
- `Gitlab::Database::SharedModel` for `gitlab_shared`
- `PackageMetadata::ApplicationRecord` for `gitlab_pm`
- `SecApplicationRecord` for `gitlab_sec`
### Defining a sharding key for all cell-local tables
This content has been moved to a
[new location](../organization/_index.md#defining-a-sharding-key-for-all-organizational-tables)
### The impact of `gitlab_schema`
The usage of `gitlab_schema` has a significant impact on the application.
The `gitlab_schema` primary purpose is to introduce a barrier between different data access patterns.
This is used as a primary source of classification for:
- [Discovering cross-joins across tables from different schemas](#removing-joins-between-main-and-non-main-tables)
- [Discovering cross-database transactions across tables from different schemas](#removing-cross-database-transactions)
### The special purpose of `gitlab_shared`
`gitlab_shared` is a special case that describes tables or views that, by design, contain data across
all decomposed databases. This classification describes application-defined tables (like `loose_foreign_keys_deleted_records`).
**Be careful** to use `gitlab_shared` as it requires special handling while accessing data.
Since `gitlab_shared` shares not only structure but also data, the application needs to be written in a way
that traverses all data from all databases in sequential manner.
```ruby
Gitlab::Database::EachDatabase.each_model_connection([MySharedModel]) do |connection, connection_name|
MySharedModel.select_all_data...
end
```
As such, migrations modifying data of `gitlab_shared` tables are expected to run across
all decomposed databases.
### The special purpose of `gitlab_internal`
`gitlab_internal` describes Rails-defined tables (like `schema_migrations` or `ar_internal_metadata`), as well as internal PostgreSQL tables (for example, `pg_attribute`). Its primary purpose is to [support other databases](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/85842#note_943453682), like Geo, that
might be missing some of those application-defined `gitlab_shared` tables (like `loose_foreign_keys_deleted_records`), but are valid Rails databases.
### The special purpose of `gitlab_pm`
`gitlab_pm` stores package metadata describing public repositories. This data is used for the License Compliance and Dependency Scanning product categories and is maintained by the [Composition Analysis Group](https://handbook.gitlab.com/handbook/engineering/development/sec/secure/composition-analysis/). It is an alias for `gitlab_main` intended to make it easier to route to a different database in the future.
## Migrations
Read [Migrations for Multiple Databases](migrations_for_multiple_databases.md).
## CI and Sec Databases
### Configure single database
By default, GDK is configured to run with multiple databases.
{{< alert type="warning" >}}
Switching back-and-forth between single and multiple databases in
the same development instance is discouraged. Any data in the `ci` or `sec`
database will not be accessible in single database mode. For single database, you should use a separate development instance.
{{< /alert >}}
To configure GDK to use a single database:
1. On the GDK root directory, run:
```shell
gdk config set gitlab.rails.databases.ci.enabled false
gdk config set gitlab.rails.databases.sec.enabled false
```
1. Reconfigure GDK:
```shell
gdk reconfigure
```
To switch back to using multiple databases, set `gitlab.rails.databases.<db_name>.enabled` to `true` and run `gdk reconfigure`.
<!--
The `validate_cross_joins!` method in `spec/support/database/prevent_cross_joins.rb` references
the following heading in the code, so if you make a change to this heading, make sure to update
the corresponding documentation URL used in `spec/support/database/prevent_cross_joins.rb`.
-->
### Removing joins between `main` and non `main` tables
Queries that join across databases raise an error. [Introduced](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/68620)
in GitLab 14.3, for new queries only. Pre-existing queries do not raise an error.
Because GitLab can be run with multiple separate databases, referencing `main`
tables with non `main` tables in a single query is not possible. Therefore,
using any kind of `JOIN` in SQL queries will not work.
#### Suggestions for removing cross-database joins
The following sections are some real examples that were identified as joining across databases,
along with possible suggestions on how to fix them.
##### Remove the code
The simplest solution we've seen several times now has been an existing scope
that is unused. This is the easiest example to fix. So the first step is to
investigate if the code is unused and then remove it. These are some
real examples:
- <https://gitlab.com/gitlab-org/gitlab/-/merge_requests/67162>
- <https://gitlab.com/gitlab-org/gitlab/-/merge_requests/66714>
- <https://gitlab.com/gitlab-org/gitlab/-/merge_requests/66503>
There may be more examples where the code is used, but we can evaluate
if we need it or if the feature should behave this way.
Before complicating things by adding new columns and tables,
consider if you can simplify the solution and still meet the requirements.
One case being evaluated involves changing how certain `UsageData` is
calculated to remove a join query in
<https://gitlab.com/gitlab-org/gitlab/-/issues/336170>. This is a good candidate
to evaluate, because `UsageData` is not critical to users and it may be possible
to get a similarly useful metric with a simpler approach. Alternatively we may
find that nobody is using these metrics, so we can remove them.
##### Use `preload` instead of `includes`
The `includes` and `preload` methods in Rails are both ways to avoid an N+1
query. The `includes` method in Rails uses a heuristic approach to determine
if it needs to join to the table, or if it can load all of the
records in a separate query. This method assumes it needs to join if it thinks
you need to query the columns from the other table, but sometimes
this method gets it wrong and executes a join even when not needed. In
this case using `preload` to explicitly load the data in a separate query
allows you to avoid the join, while still avoiding the N+1 query.
You can see a real example of this solution being used in
<https://gitlab.com/gitlab-org/gitlab/-/merge_requests/67655>.
##### Remove a redundant join
Sometimes there are cases where a query is doing excess (or redundant) joins.
A common example occurs where a query is joining from `A` to `C`, via some
table with both foreign keys, `B`.
When you only care about counting how
many rows there are in `C` and if there are foreign keys and `NOT NULL` constraints
on the foreign keys in `B`, then it might be enough to count those rows.
For example, in
[MR 71811](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/71811), it was
previously doing `project.runners.count`, which would produce a query like:
```sql
select count(*) from projects
inner join ci_runner_projects on ci_runner_projects.project_id = projects.id
where ci_runner_projects.runner_id IN (1, 2, 3)
```
This was changed to avoid the cross-join by changing the code to
`project.runner_projects.count`. It produces the same response with the
following query:
```sql
select count(*) from ci_runner_projects
where ci_runner_projects.runner_id IN (1, 2, 3)
```
Another common redundant join is joining all the way to another table,
then filtering by primary key when you could have instead filtered on a foreign
key. See an example in
[MR 71614](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/71614). The previous
code was `joins(scan: :build).where(ci_builds: { id: build_ids })`, which
generated a query like:
```sql
select ...
inner join security_scans
inner join ci_builds on security_scans.build_id = ci_builds.id
where ci_builds.id IN (1, 2, 3)
```
However, as `security_scans` already has a foreign key `build_id`, the code
can be changed to `joins(:scan).where(security_scans: { build_id: build_ids })`,
which produces the same response with the following query:
```sql
select ...
inner join security_scans
where security_scans.build_id IN (1, 2, 3)
```
Both of these examples of removing redundant joins remove the cross-joins,
but they have the added benefit of producing simpler and faster
queries.
##### Limited pluck followed by a find
Using `pluck` or `pick` to get an array of `id`s is not advisable unless the returned
array is guaranteed to be bounded in size. Usually this is a good pattern where
you know the result will be at most 1, or in cases where you have a list of in
memory ids (or usernames) that need to be mapped to another list of equal size.
It would not be suitable when mapping a list of ids in a one-to-many
relationship as the result will be unbounded. We can then use the
returned `id`s to obtain the related record:
```ruby
allowed_user_id = board_user_finder
.where(user_id: params['assignee_id'])
.pick(:user_id)
User.find_by(id: allowed_user_id)
```
You can see an example where this was used in
<https://gitlab.com/gitlab-org/gitlab/-/merge_requests/126856>
Sometimes it might seem easy to convert a join into a `pluck` but often this
results in loading an unbounded amount of ids into memory and then
re-serializing those in a following query back to Postgres. These cases do not
scale and we recommend attempting one of the other options. It might seem like a
good idea to just apply some `limit` to the plucked data to have bounded memory
but this introduces unpredictable results for users and often is most
problematic for our largest customers (including ourselves), and as such we
advise against it.
##### De-normalize some foreign key to the table
De-normalization refers to adding redundant precomputed (duplicated) data to
a table to simplify certain queries or to improve performance. In this
case, it can be useful when you are doing a join that involves three tables, where
you are joining through some intermediate table.
Generally when modeling a database schema, a "normalized" structure is
preferred because of the following reasons:
- Duplicate data uses extra storage.
- Duplicate data needs to be kept in sync.
Sometimes normalized data is less performant so de-normalization has been a
common technique GitLab has used to improve the performance of database queries
for a while. The above problems are mitigated when the following conditions are
met:
1. There isn't much data (for example, it's just an integer column).
1. The data does not update often (for example, the `project_id` column is almost
never updated for most tables).
One example we found was the `terraform_state_versions` table. This table has a foreign
key `terraform_state_versions.ci_build_id` which allows you to join to the build. Therefore
you could join to the project like so:
```sql
select projects.* from terraform_state_versions
inner join ci_builds on terraform_state_versions.ci_build_id = ci_builds.id
inner join projects on ci_builds.project_id = projects.id
```
The problem with this query is that `ci_builds` is in a different database
from the other two tables.
The solution in this case is to add the `project_id` column to
`terraform_state_versions`. This doesn't use much extra storage, and due to the way
these features work, it's never updated (a build never moves projects).
This simplified the query to:
```sql
select projects.* from terraform_state_versions
inner join projects on terraform_state_versions.project_id = projects.id
```
This also improves performance because you don't need to join through an extra
table.
You can see this approach implemented in
<https://gitlab.com/gitlab-org/gitlab/-/merge_requests/66963> . This MR also
de-normalizes `pipeline_id` to fix a similar query.
##### De-normalize into an extra table
Sometimes the previous de-normalization (adding an extra column) doesn't work for
your specific case. This may be due to the fact that your data is not 1:1, or
because the table you're adding to is already too wide (for example, the `projects`
table shouldn't have more columns added).
In this case you may decide to just store the extra data in a separate table.
One example where this approach is being used was to implement the
`Project.with_code_coverage` scope. This scope was essentially used to narrow
down a list of projects to only those that have at one point in time used code
coverage features. This query (simplified) was:
```sql
select projects.* from projects
inner join ci_daily_build_group_report_results on ci_daily_build_group_report_results.project_id = projects.id
where ((data->'coverage') is not null)
and ci_daily_build_group_report_results.default_branch = true
group by projects.id
```
This work is still in progress but the current plan is to introduce a new table
called `projects_with_ci_feature_usage` which has 2 columns `project_id` and
`ci_feature`. This table would be written to the first time a project creates a
`ci_daily_build_group_report_results` for code coverage. Therefore the new
query would be:
```sql
select projects.* from projects
inner join projects_with_ci_feature_usage on projects_with_ci_feature_usage.project_id = projects.id
where projects_with_ci_feature_usage.ci_feature = 'code_coverage'
```
The above example uses as a text column for simplicity but we should probably
use an [enum](creating_enums.md) to save space.
The downside of this new design is that this may need to be
updated (removed if the `ci_daily_build_group_report_results` is deleted).
Depending on your domain, however, this may not be necessary because deletes are
edge cases or impossible, or because the user impact of seeing the project on the
list page may not be problematic. It's also possible to implement the
logic to delete these rows if or whenever necessary in your domain.
Finally, this de-normalization and new query also improves performance because
it does less joins and needs less filtering.
##### Use `disable_joins` for `has_one` or `has_many` `through:` relations
Sometimes a join query is caused by using `has_one ... through:` or `has_many ... through:`
across tables that span the different databases. These joins
sometimes can be solved by adding
[`disable_joins:true`](https://edgeguides.rubyonrails.org/active_record_multiple_databases.html#handling-associations-with-joins-across-databases).
This is a Rails feature which we
[backported](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/66400). We
also extended the feature to allow a lambda syntax for enabling `disable_joins`
with a feature flag. If you use this feature we encourage using a feature flag
as it mitigates risk if there is some serious performance regression.
You can see an example where this was used in
<https://gitlab.com/gitlab-org/gitlab/-/merge_requests/66709/diffs>.
With any change to DB queries it is important to analyze and compare the SQL
before and after the change. `disable_joins` can introduce very poorly performing
code depending on the actual logic of the `has_many` or `has_one` relationship.
The key thing to look for is whether any of the intermediate result sets
used to construct the final result set have an unbounded amount of data loaded.
The best way to tell is by looking at the SQL generated and confirming that
each one is limited in some way. You can tell by either a `LIMIT 1` clause or
by `WHERE` clause that is limiting based on a unique column. Any unbounded
intermediate dataset could lead to loading too many IDs into memory.
An example where you may see very poor performance is the following
hypothetical code:
```ruby
class Project
has_many :pipelines
has_many :builds, through: :pipelines
end
class Pipeline
has_many :builds
end
class Build
belongs_to :pipeline
end
def some_action
@builds = Project.find(5).builds.order(created_at: :desc).limit(10)
end
```
In the above case `some_action` will generate a query like:
```sql
select * from builds
inner join pipelines on builds.pipeline_id = pipelines.id
where pipelines.project_id = 5
order by builds.created_at desc
limit 10
```
However, if you changed the relation to be:
```ruby
class Project
has_many :pipelines
has_many :builds, through: :pipelines, disable_joins: true
end
```
Then you would get the following 2 queries:
```sql
select id from pipelines where project_id = 5;
select * from builds where pipeline_id in (...)
order by created_at desc
limit 10;
```
Because the first query does not limit by any unique column or
have a `LIMIT` clause, it can load an unlimited number of
pipeline IDs into memory, which are then sent in the following query.
This can lead to very poor performance in the Rails application and the
database. In cases like this, you might need to re-write the
query or look at other patterns described above for removing cross-joins.
#### How to validate you have correctly removed a cross-join
RSpec is configured to automatically validate all SQL queries do not join
across databases. If this validation is disabled in
`spec/support/database/cross-join-allowlist.yml` then you can still validate an
isolated code block using `with_cross_joins_prevented`.
You can use this method like so:
```ruby
it 'does not join across databases' do
with_cross_joins_prevented do
::Ci::Build.joins(:project).to_a
end
end
```
This will raise an exception if the query joins across the two databases. The
previous example is fixed by removing the join, like so:
```ruby
it 'does not join across databases' do
with_cross_joins_prevented do
::Ci::Build.preload(:project).to_a
end
end
```
You can see a real example of using this method for fixing a cross-join in
<https://gitlab.com/gitlab-org/gitlab/-/merge_requests/67655>.
#### Allowlist for existing cross-joins
The easiest way of identifying a cross-join is via failing pipelines.
As an example, in [!130038](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/130038/diffs) we moved the `notification_settings` table to the `gitlab_main_cell` schema, by marking it as such in the `db/docs/notification_settings.yml` file.
The pipeline failed with the following [error](https://gitlab.com/gitlab-org/gitlab/-/jobs/4929130983):
```ruby
Database::PreventCrossJoins::CrossJoinAcrossUnsupportedTablesError:
Unsupported cross-join across 'users, notification_settings' querying 'gitlab_main_clusterwide, gitlab_main_cell' discovered when executing query 'SELECT "users".* FROM "users" WHERE "users"."id" IN (SELECT "notification_settings"."user_id" FROM ((SELECT "notification_settings"."user_id" FROM "notification_settings" WHERE "notification_settings"."source_id" = 119 AND "notification_settings"."source_type" = 'Project' AND (("notification_settings"."level" = 3 AND EXISTS (SELECT true FROM "notification_settings" "notification_settings_2" WHERE "notification_settings_2"."user_id" = "notification_settings"."user_id" AND "notification_settings_2"."source_id" IS NULL AND "notification_settings_2"."source_type" IS NULL AND "notification_settings_2"."level" = 2)) OR "notification_settings"."level" = 2))) notification_settings)'
```
To make the pipeline green, this cross-join query must be allow-listed.
A cross-join across databases can be explicitly allowed by wrapping the code in the
`::Gitlab::Database.allow_cross_joins_across_databases` helper method. Alternative
way is to mark a given relation as `relation.allow_cross_joins_across_databases`.
This method should only be used:
- For existing code.
- If the code is required to help migrate away from a cross-join. For example,
in a migration that backfills data for future use to remove a cross-join.
The `allow_cross_joins_across_databases` helper method can be used as follows:
```ruby
# Scope the block executing a object from database
::Gitlab::Database.allow_cross_joins_across_databases(url: 'https://gitlab.com/gitlab-org/gitlab/-/issues/336590') do
subject.perform(1, 4)
end
```
```ruby
# Mark a relation as allowed to cross-join databases
def find_diff_head_pipeline
all_pipelines
.allow_cross_joins_across_databases(url: 'https://gitlab.com/gitlab-org/gitlab/-/issues/336891')
.for_sha_or_source_sha(diff_head_sha)
.first
end
```
In model associations or scopes, this can be used as in the following example:
```ruby
class Group < Namespace
has_many :users, -> {
allow_cross_joins_across_databases(url: "https://gitlab.com/gitlab-org/gitlab/-/issues/422405")
}, through: :group_members
end
```
{{< alert type="warning" >}}
Overriding an association can have unintended consequences and may even lead to data loss, as we noticed in [issue 424307](https://gitlab.com/gitlab-org/gitlab/-/issues/424307). Do not override existing ActiveRecord associations to mark a cross-join as allowed, as in the example below.
{{< /alert >}}
```ruby
class Group < Namespace
has_many :users, through: :group_members
# DO NOT override an association like this.
def users
super.allow_cross_joins_across_databases(url: "https://gitlab.com/gitlab-org/gitlab/-/issues/422405")
end
end
```
The `url` parameter should point to an issue with a milestone for when we intend
to fix the cross-join. If the cross-join is being used in a migration, we do not
need to fix the code. See <https://gitlab.com/gitlab-org/gitlab/-/issues/340017>
for more details.
### Removing cross-database transactions
When dealing with multiple databases, it's important to pay close attention to data modification
that affects more than one database.
[Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/339811) GitLab 14.4, an automated check
prevents cross-database modifications.
When at least two different databases are modified during a transaction initiated on any database
server, the application triggers a cross-database modification error (only in test environment).
Example:
```ruby
# Open transaction on Main DB
ApplicationRecord.transaction do
ci_build.update!(updated_at: Time.current) # UPDATE on CI DB
ci_build.project.update!(updated_at: Time.current) # UPDATE on Main DB
end
# raises error: Cross-database data modification of 'main, ci' were detected within
# a transaction modifying the 'ci_build, projects' tables
```
The code example above updates the timestamp for two records within a transaction. With the
ongoing work on the CI database decomposition, we cannot ensure the schematics of a database
transaction.
If the second update query fails, the first update query will not be
rolled back because the `ci_build` record is located on a different database server. For
more information, look at the
[transaction guidelines](transaction_guidelines.md#dangerous-example-third-party-api-calls)
page.
#### Fixing cross-database transactions
A transaction across databases can be explicitly allowed by wrapping the code in the
`Gitlab::Database::QueryAnalyzers::PreventCrossDatabaseModification.temporary_ignore_tables_in_transaction` helper method.
This method should only be used for existing code.
The `temporary_ignore_tables_in_transaction` helper method can be used as follows:
```ruby
class GroupMember < Member
def update_two_factor_requirement
return unless user
# To mark and ignore cross-database transactions involving members and users/user_details/user_preferences
Gitlab::Database::QueryAnalyzers::PreventCrossDatabaseModification.temporary_ignore_tables_in_transaction(
%w[users user_details user_preferences], url: 'https://gitlab.com/gitlab-org/gitlab/-/issues/424288'
) do
user.update_two_factor_requirement
end
end
end
```
##### Removing the transaction block
Without an open transaction, the cross-database modification check cannot raise an error.
By making this change, we sacrifice consistency. In case of an application failure after the
first `UPDATE` query, the second `UPDATE` query will never execute.
The same code without the `transaction` block:
```ruby
ci_build.update!(updated_at: Time.current) # CI DB
ci_build.project.update!(updated_at: Time.current) # Main DB
```
##### Asynchronous processing
If we need more guarantee that an operation finishes the work consistently we can execute it
within a background job. A background job is scheduled asynchronously and retried several times
in case of an error. There is still a very small chance of introducing inconsistency.
Example:
```ruby
current_time = Time.current
MyAsyncConsistencyJob.perform_async(cu_build.id)
ci_build.update!(updated_at: current_time)
ci_build.project.update!(updated_at: current_time)
```
The `MyAsyncConsistencyJob` would also attempt to update the timestamp if they differ.
##### Aiming for perfect consistency
At this point, we don't have the tooling (we might not even need it) to ensure similar consistency
characteristics as we had with one database. If you think that the code you're working on requires
these properties, then you can disable the cross-database modification check in your tests by wrapping the
offending test code with a block and create a follow-up issue.
```ruby
allow_cross_database_modification_within_transaction(url: 'gitlab issue URL') do
ApplicationRecord.transaction do
ci_build.update!(updated_at: Time.current) # UPDATE on CI DB
ci_build.project.update!(updated_at: Time.current) # UPDATE on Main DB
end
end
```
Don't hesitate to reach out to the
[Tenant Scale group](https://handbook.gitlab.com/handbook/engineering/infrastructure-platforms/tenant-scale/)
for advice.
##### Avoid `dependent: :nullify` and `dependent: :destroy` across databases
There may be cases where we want to use `dependent: :nullify` or `dependent: :destroy`
across databases. This is technically possible, but it's problematic because
these hooks run in the context of an outer transaction from the call to
`#destroy`, which creates a cross-database transaction and we are trying to
avoid that. Cross-database transactions caused this way could lead to confusing
outcomes when we switch to decomposed, because now you have some queries
happening outside the transaction and they may be partially applied while the
outer transaction fails, which could lead to surprising bugs.
For non-trivial objects that need to clean up data outside the
database (for example, object storage), we recommend the setting
[`dependent: :restrict_with_error`](https://guides.rubyonrails.org/association_basics.html#options-for-has-one-dependent).
Such objects should be removed explicitly ahead of time. Using `dependent: :restrict_with_error`
ensures that we forbid destroying the parent object if something is not cleaned up.
If all you need to do is clean up the child records themselves from PostgreSQL,
consider using [loose foreign keys](loose_foreign_keys.md).
## Foreign keys that cross databases
There are many places where we use foreign keys that reference across the two
databases. This is not possible to do with two separate PostgreSQL
databases, so we need to replicate the behavior we get from PostgreSQL in a
performant way. We can't, and shouldn't, try to replicate the data guarantees
given by PostgreSQL which prevent creating invalid references, but we still need a
way to replace cascading deletes so we don't end up with orphaned data
or records that point to nowhere, which might lead to bugs. As such we created
["loose foreign keys"](loose_foreign_keys.md) which is an asynchronous
process of cleaning up orphaned records.
### Allowlist for existing cross-database foreign keys
The easiest way of identifying a cross-database foreign key is via failing pipelines.
As an example, in [!130038](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/130038/diffs) we moved the `notification_settings` table to the `gitlab_main_cell` schema, by marking it in the `db/docs/notification_settings.yml` file.
`notification_settings.user_id` is a column that points to `users`, but the `users` table belongs to a different database, thus this is now treated as a cross-database foreign key.
We have a spec to capture such cases of cross-database foreign keys in [`no_cross_db_foreign_keys_spec.rb`](https://gitlab.com/gitlab-org/gitlab/-/blob/01d3a1e41513200368a22bbab5d4312174762ee0/spec/lib/gitlab/database/no_cross_db_foreign_keys_spec.rb), which would fail if such a cross-database foreign key is encountered.
To make the pipeline green, this cross-database foreign key must be allow-listed.
To do this, explicitly allow the existing cross-database foreign key to exist by adding it as an exception in the same spec (as in [this example](https://gitlab.com/gitlab-org/gitlab/-/blob/7d99387f399c548af24d93d564b35f2f9510662d/spec/lib/gitlab/database/no_cross_db_foreign_keys_spec.rb#L26)).
This way, the spec will not fail.
Later, this foreign key can be converted to a loose foreign key, like we did in [!130080](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/130080/diffs).
## Testing for multiple databases
In our testing CI pipelines, we test GitLab by default with multiple databases set up, using
both `main` and `ci` databases. But in merge requests, for example when we modify some database-related code or
add the label `~"pipeline:run-single-db"` to the MR, we additionally run our tests in
[two other database modes](../pipelines/_index.md#single-database-testing):
`single-db` and `single-db-ci-connection`.
To handle situations where our tests need to run in specific database modes, we have some RSpec helpers
to limit the modes where tests can run, and skip them on any other modes.
| Helper name | Test runs |
|---------------------------------------------| --- |
| `skip_if_shared_database(:ci)` | On **multiple databases** |
| `skip_if_database_exists(:ci)` | On **single-db** and **single-db-ci-connection** |
| `skip_if_multiple_databases_are_setup(:ci)` | Only on **single-db** |
| `skip_if_multiple_databases_not_setup(:ci)` | On **single-db-ci-connection** and **multiple databases** |
## Locking writes on the tables that don't belong to the database schemas
When a separate database is promoted and the split from main,
as an extra safeguard against creating a split brain situation,
run the Rake task `gitlab:db:lock_writes`. This command locks writes on:
- Legacy tables on `gitlab_ci` belonging to the Main or Sec Databases.
- Legacy tables on `gitlab_main` belonging to the CI or Sec Databases.
- Legacy tables on `gitlab_sec` belonging to the CI or Main Databases.
This Rake task adds triggers to all the tables, to prevent any
`INSERT`, `UPDATE`, `DELETE`, or `TRUNCATE` statements from running
against the tables that need to be locked.
If this task was run against a GitLab setup that uses only a single database
for both `gitlab_main` and `gitlab_ci` tables, then no tables will be locked.
To undo the operation, run the opposite Rake task: `gitlab:db:unlock_writes`.
### Monitoring
The status of the table locks is checked using the
[`Database::MonitorLockedTablesWorker`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/app/workers/database/monitor_locked_tables_worker.rb).
It will lock tables if needed.
The result of this script is available in [Kibana](https://log.gprd.gitlab.net/app/r/s/4qrz2).
If the counts are not 0, there are some tables that should have been locked but are not.
The fields `json.extra.database_monitor_locked_tables_worker.results.ci.tables_need_locks` and
`json.extra.database_monitor_locked_tables_worker.results.main.tables_need_locks` should contain
a list of tables that have the wrong state.
The logging is monitored using a [Elasticsearch Watcher](https://log.gprd.gitlab.net/app/management/insightsAndAlerting/watcher/watches).
The watcher is called `table_locks_needed` and the source code is in the
[GitLab Runbook repository](https://gitlab.com/gitlab-com/runbooks/-/tree/master/elastic/managed-objects/log_gprd/watches).
The alerts are sent to [#g_tenant-scale](https://gitlab.enterprise.slack.com/archives/C01TQ838Y3T) Slack channel.
### Automation
There are two processes that automatically lock tables:
- Database migrations. See [`Gitlab::Database::MigrationHelpers::AutomaticLockWritesOnTables`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/lib/gitlab/database/migration_helpers/automatic_lock_writes_on_tables.rb)
- The `Database::MonitorLockedTablesWorker` locks tables if needed.
This can be disabled by the `lock_tables_in_monitoring` feature flag.
`Gitlab::Database::MigrationHelpers::AutomaticLockWritesOnTables` compares the list of tables before and after each database migration runs. Then
it locks the newly added tables on the relevant database. This does not
cover all cases. Because some migrations need
to re-create the tables within the same transactional migration. For example: To convert standard unpartitioned tables into partitioned tables.
See [this example](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/184636).
Such migrations leave the re-created tables unlocked. But the daily cron job of `Database::MonitorLockedTablesWorker` takes care of
alerting about this on Slack, and then automatically locks these tables for writes.
### Manually lock tables
If you need to manually lock a table, use a database migration.
Create a regular migration and add the code for locking the table.
For example, set a write lock on `shards` table in CI database:
```ruby
class EnableWriteLocksOnShards < Gitlab::Database::Migration[2.2]
def up
# On main database, the migration should be skipped
# We can't use restrict_gitlab_migration in DDL migrations
return if Gitlab::Database.db_config_name(connection) != 'ci'
Gitlab::Database::LockWritesManager.new(
table_name: 'shards',
connection: connection,
database_name: :ci,
with_retries: false
).lock_writes
end
def down
# no-op
end
end
```
## Truncating tables
When separate databases from `main` are fully split, we can free up disk
space by truncating tables. This results in a smaller data set: For example,
the data in `users` table on CI database is no longer read and also no
longer updated. So this data can be removed by truncating the tables.
For this purpose, GitLab provides separate Rake tasks, one for each database:
- `gitlab:db:truncate_legacy_tables:main` will truncate the legacy tables in Main database.
- `gitlab:db:truncate_legacy_tables:ci` will truncate the legacy tables in CI database.
- `gitlab:db:truncate_legacy_tables:sec` will truncate the legacy tables in Sec database.
{{< alert type="note" >}}
These tasks can only be run when the tables in the database are
[locked for writes](#locking-writes-on-the-tables-that-dont-belong-to-the-database-schemas).
{{< /alert >}}
{{< alert type="warning" >}}
The examples in this section use `DRY_RUN=true`. This ensures no data is actually
truncated. GitLab highly recommends to have a backup available before you run any of
these tasks without `DRY_RUN=true`.
{{< /alert >}}
These tasks have the option to see what they do without actually changing the
data:
```shell
$ sudo DRY_RUN=true gitlab-rake gitlab:db:truncate_legacy_tables:main
I, [2023-07-14T17:08:06.665151 #92505] INFO -- : DRY RUN:
I, [2023-07-14T17:08:06.761586 #92505] INFO -- : Truncating legacy tables for the database main
I, [2023-07-14T17:08:06.761709 #92505] INFO -- : SELECT set_config('lock_writes.ci_build_needs', 'false', false)
I, [2023-07-14T17:08:06.765272 #92505] INFO -- : SELECT set_config('lock_writes.ci_build_pending_states', 'false', false)
I, [2023-07-14T17:08:06.768220 #92505] INFO -- : SELECT set_config('lock_writes.ci_build_report_results', 'false', false)
[...]
I, [2023-07-14T17:08:06.957294 #92505] INFO -- : TRUNCATE TABLE ci_build_needs, ci_build_pending_states, ci_build_report_results, ci_build_trace_chunks, ci_build_trace_metadata, ci_builds, ci_builds_metadata, ci_builds_runner_session, ci_cost_settings, ci_daily_build_group_report_results, ci_deleted_objects, ci_freeze_periods, ci_group_variables, ci_instance_variables, ci_job_artifact_states, ci_job_artifacts, ci_job_token_project_scope_links, ci_job_variables, ci_minutes_additional_packs, ci_namespace_mirrors, ci_namespace_monthly_usages, ci_partitions, ci_pending_builds, ci_pipeline_artifacts, ci_pipeline_chat_data, ci_pipeline_messages, ci_pipeline_metadata, ci_pipeline_schedule_variables, ci_pipeline_schedules, ci_pipeline_variables, ci_pipelines, ci_pipelines_config, ci_platform_metrics, ci_project_mirrors, ci_project_monthly_usages, ci_refs, ci_resource_groups, ci_resources, ci_runner_machines, ci_runner_namespaces, ci_runner_projects, ci_runner_versions, ci_runners, ci_running_builds, ci_secure_file_states, ci_secure_files, ci_sources_pipelines, ci_sources_projects, ci_stages, ci_subscriptions_projects, ci_trigger_requests, ci_triggers, ci_unit_test_failures, ci_unit_tests, ci_variables, external_pull_requests, p_ci_builds, p_ci_builds_metadata, p_ci_job_annotations, p_ci_runner_machine_builds, taggings, tags RESTRICT
```
The tasks will first find out the tables that need to be truncated. Truncation will
happen in stages because we need to limit the amount of data removed in one database
transaction. The tables are processed in a specific order depending on the definition
of the foreign keys. The number of tables processed in one stage can be changed by
adding a number when invoking the task. The default value is 5:
```shell
sudo DRY_RUN=true gitlab-rake gitlab:db:truncate_legacy_tables:main\[10\]
```
It is also possible to limit the number of tables to be truncated by setting the `UNTIL_TABLE`
variable. For example in this case, the process will stop when `ci_unit_test_failures` has been
truncated:
```shell
sudo DRY_RUN=true UNTIL_TABLE=ci_unit_test_failures gitlab-rake gitlab:db:truncate_legacy_tables:main
```
|
https://docs.gitlab.com/development/transaction_guidelines
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/transaction_guidelines.md
|
2025-08-13
|
doc/development/database
|
[
"doc",
"development",
"database"
] |
transaction_guidelines.md
|
Data Access
|
Database Frameworks
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Transaction guidelines
| null |
This document gives a few examples of the usage of database transactions in application code.
For further reference, check PostgreSQL documentation about [transactions](https://www.postgresql.org/docs/16/tutorial-transactions.html).
## Database decomposition and sharding
The [Tenant Scale group](https://handbook.gitlab.com/handbook/engineering/infrastructure-platforms/tenant-scale/) plans
to split the main GitLab database and move some of the database tables to other database servers.
We start decomposing the `ci_*`-related database tables first. To maintain the current application
development experience, we add tooling and static analyzers to the codebase to ensure correct
data access and data modification methods. By using the correct form for defining database transactions,
we can save significant refactoring work in the future.
## The transaction block
The `ActiveRecord` library provides a convenient way to group database statements into a transaction:
```ruby
issue = Issue.find(10)
project = issue.project
ApplicationRecord.transaction do
issue.update!(title: 'updated title')
project.update!(last_update_at: Time.now)
end
```
This transaction involves two database tables. In case of an error, each `UPDATE`
statement rolls back to the previous consistent state.
{{< alert type="note" >}}
Avoid referencing the `ActiveRecord::Base` class and use `ApplicationRecord` instead.
{{< /alert >}}
## Transaction and database locks
When a transaction block is opened, the database tries to acquire the necessary
locks on the resources. The type of locks depend on the actual database statements.
Consider a concurrent update scenario where the following code is executed at the
same time from two different processes:
```ruby
issue = Issue.find(10)
project = issue.project
ApplicationRecord.transaction do
issue.update!(title: 'updated title')
project.update!(last_update_at: Time.now)
end
```
The database tries to acquire the `FOR UPDATE` lock for the referenced `issue` and
`project` records. In our case, we have two competing transactions for these locks,
and only one of them successfully acquires them. The other transaction has
to wait in the lock queue until the first transaction finishes. The execution of the
second transaction is blocked at this point.
## Transaction speed
To prevent lock contention and maintain stable application performance, the transaction
block should finish as fast as possible. When a transaction acquires locks, it holds
on to them until the transaction finishes.
Apart from application performance, long-running transactions can also affect application
upgrade processes by blocking database migrations.
### Dangerous example: third-party API calls
Consider the following example:
```ruby
member = Member.find(5)
Member.transaction do
member.update!(notification_email_sent: true)
member.send_notification_email
end
```
Here, we ensure that the `notification_email_sent` column is updated only when the
`send_notification_email` method succeeds. The `send_notification_email` method
executes a network request to an email sending service. If the underlying infrastructure
does not specify timeouts or the network call takes too long time, the database transaction
stays open.
Ideally, a transaction should only contain database statements.
Avoid doing in a `transaction` block:
- External network requests such as:
- Triggering Sidekiq jobs.
- Sending emails.
- HTTP API calls.
- Running database statements using a different connection.
- File system operations.
- Long, CPU intensive computation.
- Calling `sleep(n)`.
## Explicit model referencing
If a transaction modifies records from the same database table, we advise to use the
`Model.transaction` block:
```ruby
build_1 = Ci::Build.find(1)
build_2 = Ci::Build.find(2)
Ci::Build.transaction do
build_1.touch
build_2.touch
end
```
The transaction above uses the same database connection for the transaction as the models
in the `transaction` block. In a multi-database environment the following example is dangerous:
```ruby
# `ci_builds` table is located on another database
class Ci::Build < CiDatabase
end
build_1 = Ci::Build.find(1)
build_2 = Ci::Build.find(2)
ApplicationRecord.transaction do
build_1.touch
build_2.touch
end
```
The `ApplicationRecord` class uses a different database connection than the `Ci::Build` records.
The two statements in the transaction block are not part of the transaction and are not
rolled back in case something goes wrong. They act as third-party calls.
|
---
stage: Data Access
group: Database Frameworks
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: Transaction guidelines
breadcrumbs:
- doc
- development
- database
---
This document gives a few examples of the usage of database transactions in application code.
For further reference, check PostgreSQL documentation about [transactions](https://www.postgresql.org/docs/16/tutorial-transactions.html).
## Database decomposition and sharding
The [Tenant Scale group](https://handbook.gitlab.com/handbook/engineering/infrastructure-platforms/tenant-scale/) plans
to split the main GitLab database and move some of the database tables to other database servers.
We start decomposing the `ci_*`-related database tables first. To maintain the current application
development experience, we add tooling and static analyzers to the codebase to ensure correct
data access and data modification methods. By using the correct form for defining database transactions,
we can save significant refactoring work in the future.
## The transaction block
The `ActiveRecord` library provides a convenient way to group database statements into a transaction:
```ruby
issue = Issue.find(10)
project = issue.project
ApplicationRecord.transaction do
issue.update!(title: 'updated title')
project.update!(last_update_at: Time.now)
end
```
This transaction involves two database tables. In case of an error, each `UPDATE`
statement rolls back to the previous consistent state.
{{< alert type="note" >}}
Avoid referencing the `ActiveRecord::Base` class and use `ApplicationRecord` instead.
{{< /alert >}}
## Transaction and database locks
When a transaction block is opened, the database tries to acquire the necessary
locks on the resources. The type of locks depend on the actual database statements.
Consider a concurrent update scenario where the following code is executed at the
same time from two different processes:
```ruby
issue = Issue.find(10)
project = issue.project
ApplicationRecord.transaction do
issue.update!(title: 'updated title')
project.update!(last_update_at: Time.now)
end
```
The database tries to acquire the `FOR UPDATE` lock for the referenced `issue` and
`project` records. In our case, we have two competing transactions for these locks,
and only one of them successfully acquires them. The other transaction has
to wait in the lock queue until the first transaction finishes. The execution of the
second transaction is blocked at this point.
## Transaction speed
To prevent lock contention and maintain stable application performance, the transaction
block should finish as fast as possible. When a transaction acquires locks, it holds
on to them until the transaction finishes.
Apart from application performance, long-running transactions can also affect application
upgrade processes by blocking database migrations.
### Dangerous example: third-party API calls
Consider the following example:
```ruby
member = Member.find(5)
Member.transaction do
member.update!(notification_email_sent: true)
member.send_notification_email
end
```
Here, we ensure that the `notification_email_sent` column is updated only when the
`send_notification_email` method succeeds. The `send_notification_email` method
executes a network request to an email sending service. If the underlying infrastructure
does not specify timeouts or the network call takes too long time, the database transaction
stays open.
Ideally, a transaction should only contain database statements.
Avoid doing in a `transaction` block:
- External network requests such as:
- Triggering Sidekiq jobs.
- Sending emails.
- HTTP API calls.
- Running database statements using a different connection.
- File system operations.
- Long, CPU intensive computation.
- Calling `sleep(n)`.
## Explicit model referencing
If a transaction modifies records from the same database table, we advise to use the
`Model.transaction` block:
```ruby
build_1 = Ci::Build.find(1)
build_2 = Ci::Build.find(2)
Ci::Build.transaction do
build_1.touch
build_2.touch
end
```
The transaction above uses the same database connection for the transaction as the models
in the `transaction` block. In a multi-database environment the following example is dangerous:
```ruby
# `ci_builds` table is located on another database
class Ci::Build < CiDatabase
end
build_1 = Ci::Build.find(1)
build_2 = Ci::Build.find(2)
ApplicationRecord.transaction do
build_1.touch
build_2.touch
end
```
The `ApplicationRecord` class uses a different database connection than the `Ci::Build` records.
The two statements in the transaction block are not part of the transaction and are not
rolled back in case something goes wrong. They act as third-party calls.
|
https://docs.gitlab.com/development/dbmigrate_multi_version_upgrade_job
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/dbmigrate_multi_version_upgrade_job.md
|
2025-08-13
|
doc/development/database
|
[
"doc",
"development",
"database"
] |
dbmigrate_multi_version_upgrade_job.md
|
Data Access
|
Database
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
db:migrate:multi-version-upgrade job
| null |
{{< history >}}
- [Introduced](https://gitlab.com/groups/gitlab-org/quality/quality-engineering/-/epics/19) in GitLab 16.11.
{{< /history >}}
This job runs on the test stage of a merge request pipeline. It validates that migrations pass
for multi-version upgrade from the latest [required upgrade stop](../../update/upgrade_paths.md)
to the author's working branch. It achieves it by running `gitlab:db:configure` against PostgreSQL
dump created from the latest known [GitLab version stop](../../update/upgrade_paths.md) with test data.
The database dump is generated and maintained with [PostgreSQL Dump Generator](https://gitlab.com/gitlab-org/quality/pg-dump-generator).
To seed database with data, the tool uses Data Seeder with [`bulk_data.rb`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/ee/db/seeds/data_seeder/bulk_data.rb)
configuration to seed all factories and uses `db:seed_fu` to seed all [`db/fixtures`](../development_seed_files.md).
Latest dump is generated automatically in scheduled pipelines for the latest patch
release of the required stop.
## Troubleshooting
### Database reconfigure failures
This failure usually happens due to an actual migration error in your working branch.
To reproduce the failure locally follow [Migration upgrade testing](https://gitlab.com/gitlab-org/quality/pg-dump-generator#migration-upgrade-testing)
guidance. It outlines the steps how to import the latest PostgreSQL dump
in your local GitLab Development Kit or GitLab Docker instance.
For a real-life example, refer to
[this failed job](https://gitlab.com/gitlab-org/gitlab/-/jobs/6418619509#L4970).
#### Broken master
When a new required upgrade stop is added (every three or four milestones), it triggers the build of a new PostgreSQL Dump.
In some cases, this might cause the `db:migrate:multi-version-upgrade` job to fail in `master` pipeline.
For example, if new additional tables are seeded, it helps detect migration errors that might have been missed in older dumps without these seeded tables.
Workflow for the [broken master](https://handbook.gitlab.com/handbook/engineering/workflow/#broken-master) case:
1. Identify the root cause MR by searching for the migration that caused the error. For instance, [`db/migrate/20240416123401_add_security_policy_management_project_id_to_security_policies.rb` in failing job](https://gitlab.com/gitlab-org/gitlab-foss/-/jobs/6671417979#L1547)
- Debug locally if needed as described in the [Database reconfigure failures](#database-reconfigure-failures)
1. Reach out to the relevant team that introduced the migration to discuss whether the MR should be reverted or if a fix will be worked on
- If the team isn't available, post about it in the `#database` Slack channel
1. While a fix or revert is being worked on, `master` pipeline can be unblocked by disabling the job temporarily by setting `DISABLE_DB_MULTI_VERSION_UPGRADE=true` in [CI/CD Settings page](https://gitlab.com/gitlab-org/gitlab/-/settings/ci_cd)
- When disabling the job, announce it in the `#master-broken` Slack channel
1. Add a note to [job stability tracking issue#458402](https://gitlab.com/gitlab-org/gitlab/-/issues/458402)
1. Reinstate the job by removing `DISABLE_DB_MULTI_VERSION_UPGRADE` from CI/CD Settings
### Database import failures
If job is failing on setup stage prior to `gitlab:db:configure`
due to external dependencies, the job can be disabled by setting
`DISABLE_DB_MULTI_VERSION_UPGRADE=true` in GitLab project CI variables
to unblock the [broken master](https://handbook.gitlab.com/handbook/engineering/workflow/#broken-master).
Reach out to [Self-Managed Platform team](https://handbook.gitlab.com/handbook/engineering/infrastructure/test-platform/self-managed-platform-team/) to expedite debugging.
|
---
stage: Data Access
group: Database
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: db:migrate:multi-version-upgrade job
breadcrumbs:
- doc
- development
- database
---
{{< history >}}
- [Introduced](https://gitlab.com/groups/gitlab-org/quality/quality-engineering/-/epics/19) in GitLab 16.11.
{{< /history >}}
This job runs on the test stage of a merge request pipeline. It validates that migrations pass
for multi-version upgrade from the latest [required upgrade stop](../../update/upgrade_paths.md)
to the author's working branch. It achieves it by running `gitlab:db:configure` against PostgreSQL
dump created from the latest known [GitLab version stop](../../update/upgrade_paths.md) with test data.
The database dump is generated and maintained with [PostgreSQL Dump Generator](https://gitlab.com/gitlab-org/quality/pg-dump-generator).
To seed database with data, the tool uses Data Seeder with [`bulk_data.rb`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/ee/db/seeds/data_seeder/bulk_data.rb)
configuration to seed all factories and uses `db:seed_fu` to seed all [`db/fixtures`](../development_seed_files.md).
Latest dump is generated automatically in scheduled pipelines for the latest patch
release of the required stop.
## Troubleshooting
### Database reconfigure failures
This failure usually happens due to an actual migration error in your working branch.
To reproduce the failure locally follow [Migration upgrade testing](https://gitlab.com/gitlab-org/quality/pg-dump-generator#migration-upgrade-testing)
guidance. It outlines the steps how to import the latest PostgreSQL dump
in your local GitLab Development Kit or GitLab Docker instance.
For a real-life example, refer to
[this failed job](https://gitlab.com/gitlab-org/gitlab/-/jobs/6418619509#L4970).
#### Broken master
When a new required upgrade stop is added (every three or four milestones), it triggers the build of a new PostgreSQL Dump.
In some cases, this might cause the `db:migrate:multi-version-upgrade` job to fail in `master` pipeline.
For example, if new additional tables are seeded, it helps detect migration errors that might have been missed in older dumps without these seeded tables.
Workflow for the [broken master](https://handbook.gitlab.com/handbook/engineering/workflow/#broken-master) case:
1. Identify the root cause MR by searching for the migration that caused the error. For instance, [`db/migrate/20240416123401_add_security_policy_management_project_id_to_security_policies.rb` in failing job](https://gitlab.com/gitlab-org/gitlab-foss/-/jobs/6671417979#L1547)
- Debug locally if needed as described in the [Database reconfigure failures](#database-reconfigure-failures)
1. Reach out to the relevant team that introduced the migration to discuss whether the MR should be reverted or if a fix will be worked on
- If the team isn't available, post about it in the `#database` Slack channel
1. While a fix or revert is being worked on, `master` pipeline can be unblocked by disabling the job temporarily by setting `DISABLE_DB_MULTI_VERSION_UPGRADE=true` in [CI/CD Settings page](https://gitlab.com/gitlab-org/gitlab/-/settings/ci_cd)
- When disabling the job, announce it in the `#master-broken` Slack channel
1. Add a note to [job stability tracking issue#458402](https://gitlab.com/gitlab-org/gitlab/-/issues/458402)
1. Reinstate the job by removing `DISABLE_DB_MULTI_VERSION_UPGRADE` from CI/CD Settings
### Database import failures
If job is failing on setup stage prior to `gitlab:db:configure`
due to external dependencies, the job can be disabled by setting
`DISABLE_DB_MULTI_VERSION_UPGRADE=true` in GitLab project CI variables
to unblock the [broken master](https://handbook.gitlab.com/handbook/engineering/workflow/#broken-master).
Reach out to [Self-Managed Platform team](https://handbook.gitlab.com/handbook/engineering/infrastructure/test-platform/self-managed-platform-team/) to expedite debugging.
|
https://docs.gitlab.com/development/polymorphic_associations
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/polymorphic_associations.md
|
2025-08-13
|
doc/development/database
|
[
"doc",
"development",
"database"
] |
polymorphic_associations.md
|
Data Access
|
Database Frameworks
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Polymorphic Associations
| null |
**Summary**: always use separate tables instead of polymorphic associations.
Rails makes it possible to define so called "polymorphic associations". This
usually works by adding two columns to a table: a target type column, and a
target ID. For example, at the time of writing we have such a setup for
`members` with the following columns:
- `source_type`: a string defining the model to use, can be either `Project` or
`Namespace`.
- `source_id`: the ID of the row to retrieve based on `source_type`. For
example, when `source_type` is `Project` then `source_id` contains a
project ID.
While such a setup may appear to be useful, it comes with many drawbacks; enough
that you should avoid this at all costs.
## Space Wasted
Because this setup relies on string values to determine the model to use, it
wastes a lot of space. For example, for `Project` and `Namespace` the
maximum size is 9 bytes, plus 1 extra byte for every string when using
PostgreSQL. While this may only be 10 bytes per row, given enough tables and
rows using such a setup we can end up wasting quite a bit of disk space and
memory (for any indexes).
## Indexes
Because our associations are broken up into two columns this may result in
requiring composite indexes for queries to be performed efficiently. While
composite indexes are not wrong at all, they can be tricky to set up as the
ordering of columns in these indexes is important to ensure optimal performance.
## Consistency
One really big problem with polymorphic associations is being unable to enforce
data consistency on the database level using foreign keys. For consistency to be
enforced on the database level one would have to write their own foreign key
logic to support polymorphic associations.
Enforcing consistency on the database level is absolutely crucial for
maintaining a healthy environment, and thus is another reason to avoid
polymorphic associations.
## Query Overhead
When using polymorphic associations you always need to filter using both
columns. For example, you may end up writing a query like this:
```sql
SELECT *
FROM members
WHERE source_type = 'Project'
AND source_id = 13083;
```
Here PostgreSQL can perform the query quite efficiently if both columns are
indexed. As the query gets more complex, it may not be able to use these
indexes effectively.
## Mixed Responsibilities
Similar to functions and classes, a table should have a single responsibility:
storing data with a certain set of pre-defined columns. When using polymorphic
associations, you are storing different types of data (possibly with
different columns set) in the same table.
## The Solution
Fortunately, there is a solution to these problems: use a
separate table for every type you would otherwise store in the same table. Using
a separate table allows you to use everything a database may provide to ensure
consistency and query data efficiently, without any additional application logic
being necessary.
Consider a `members` table that stores approved and pending members for both projects and groups.
To determine if a member is pending, we check whether a value is set in the `requested_at` column.
Schema-wise, this configuration can waste space by only setting some indexes and columns for
certain rows. Querying this table also requires suboptimal queries. For example:
```sql
SELECT *
FROM members
WHERE requested_at IS NULL
AND source_type = 'GroupMember'
AND source_id = 4
```
Instead such a table should be broken up into separate tables. For example, you
may end up with 4 tables in this case:
- `project_members`
- `group_members`
- `pending_project_members`
- `pending_group_members`
This makes querying data trivial. For example, to get the members of a group
you'd run:
```sql
SELECT *
FROM group_members
WHERE group_id = 4
```
To get all the pending members of a group in turn you'd run:
```sql
SELECT *
FROM pending_group_members
WHERE group_id = 4
```
If you want to get both you can use a `UNION`, though you need to be explicit
about what columns you want to `SELECT` as otherwise the result set uses the
columns of the first query. For example:
```sql
SELECT id, 'Group' AS target_type, group_id AS target_id
FROM group_members
UNION ALL
SELECT id, 'Project' AS target_type, project_id AS target_id
FROM project_members
```
The above example is perhaps a bit silly, but it shows that there's nothing
stopping you from merging the data together and presenting it on the same page.
Selecting columns explicitly can also speed up queries as the database has to do
less work to get the data (compared to selecting all columns, even ones you're
not using).
Our schema also becomes easier. No longer do we need to both store and index the
`source_type` column, we can define foreign keys easily, and we don't need to
filter rows using the `IS NULL` condition.
To summarize: using separate tables allows us to use foreign keys effectively,
create indexes only where necessary, conserve space, query data more
efficiently, and scale these tables more easily (for example, by storing them on
separate disks). A nice side effect of this is that code can also become easier,
as a single model isn't responsible for handling different kinds of
data.
|
---
stage: Data Access
group: Database Frameworks
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: Polymorphic Associations
breadcrumbs:
- doc
- development
- database
---
**Summary**: always use separate tables instead of polymorphic associations.
Rails makes it possible to define so called "polymorphic associations". This
usually works by adding two columns to a table: a target type column, and a
target ID. For example, at the time of writing we have such a setup for
`members` with the following columns:
- `source_type`: a string defining the model to use, can be either `Project` or
`Namespace`.
- `source_id`: the ID of the row to retrieve based on `source_type`. For
example, when `source_type` is `Project` then `source_id` contains a
project ID.
While such a setup may appear to be useful, it comes with many drawbacks; enough
that you should avoid this at all costs.
## Space Wasted
Because this setup relies on string values to determine the model to use, it
wastes a lot of space. For example, for `Project` and `Namespace` the
maximum size is 9 bytes, plus 1 extra byte for every string when using
PostgreSQL. While this may only be 10 bytes per row, given enough tables and
rows using such a setup we can end up wasting quite a bit of disk space and
memory (for any indexes).
## Indexes
Because our associations are broken up into two columns this may result in
requiring composite indexes for queries to be performed efficiently. While
composite indexes are not wrong at all, they can be tricky to set up as the
ordering of columns in these indexes is important to ensure optimal performance.
## Consistency
One really big problem with polymorphic associations is being unable to enforce
data consistency on the database level using foreign keys. For consistency to be
enforced on the database level one would have to write their own foreign key
logic to support polymorphic associations.
Enforcing consistency on the database level is absolutely crucial for
maintaining a healthy environment, and thus is another reason to avoid
polymorphic associations.
## Query Overhead
When using polymorphic associations you always need to filter using both
columns. For example, you may end up writing a query like this:
```sql
SELECT *
FROM members
WHERE source_type = 'Project'
AND source_id = 13083;
```
Here PostgreSQL can perform the query quite efficiently if both columns are
indexed. As the query gets more complex, it may not be able to use these
indexes effectively.
## Mixed Responsibilities
Similar to functions and classes, a table should have a single responsibility:
storing data with a certain set of pre-defined columns. When using polymorphic
associations, you are storing different types of data (possibly with
different columns set) in the same table.
## The Solution
Fortunately, there is a solution to these problems: use a
separate table for every type you would otherwise store in the same table. Using
a separate table allows you to use everything a database may provide to ensure
consistency and query data efficiently, without any additional application logic
being necessary.
Consider a `members` table that stores approved and pending members for both projects and groups.
To determine if a member is pending, we check whether a value is set in the `requested_at` column.
Schema-wise, this configuration can waste space by only setting some indexes and columns for
certain rows. Querying this table also requires suboptimal queries. For example:
```sql
SELECT *
FROM members
WHERE requested_at IS NULL
AND source_type = 'GroupMember'
AND source_id = 4
```
Instead such a table should be broken up into separate tables. For example, you
may end up with 4 tables in this case:
- `project_members`
- `group_members`
- `pending_project_members`
- `pending_group_members`
This makes querying data trivial. For example, to get the members of a group
you'd run:
```sql
SELECT *
FROM group_members
WHERE group_id = 4
```
To get all the pending members of a group in turn you'd run:
```sql
SELECT *
FROM pending_group_members
WHERE group_id = 4
```
If you want to get both you can use a `UNION`, though you need to be explicit
about what columns you want to `SELECT` as otherwise the result set uses the
columns of the first query. For example:
```sql
SELECT id, 'Group' AS target_type, group_id AS target_id
FROM group_members
UNION ALL
SELECT id, 'Project' AS target_type, project_id AS target_id
FROM project_members
```
The above example is perhaps a bit silly, but it shows that there's nothing
stopping you from merging the data together and presenting it on the same page.
Selecting columns explicitly can also speed up queries as the database has to do
less work to get the data (compared to selecting all columns, even ones you're
not using).
Our schema also becomes easier. No longer do we need to both store and index the
`source_type` column, we can define foreign keys easily, and we don't need to
filter rows using the `IS NULL` condition.
To summarize: using separate tables allows us to use foreign keys effectively,
create indexes only where necessary, conserve space, query data more
efficiently, and scale these tables more easily (for example, by storing them on
separate disks). A nice side effect of this is that code can also become easier,
as a single model isn't responsible for handling different kinds of
data.
|
https://docs.gitlab.com/development/filtering_by_label
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/filtering_by_label.md
|
2025-08-13
|
doc/development/database
|
[
"doc",
"development",
"database"
] |
filtering_by_label.md
|
Plan
|
Project Management
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Filtering by label
| null |
## Introduction
GitLab has [labels](../../user/project/labels.md) that can be assigned to issues,
merge requests, and epics. Labels on those objects are a many-to-many relation
through the polymorphic `label_links` table.
To filter these objects by multiple labels - for instance, 'all open
issues with the label ~Plan and the label ~backend' - we generate a
query containing a `GROUP BY` clause. In a simple form, this looks like:
```sql
SELECT
issues.*
FROM
issues
INNER JOIN label_links ON label_links.target_id = issues.id
AND label_links.target_type = 'Issue'
INNER JOIN labels ON labels.id = label_links.label_id
WHERE
issues.project_id = 13083
AND (issues.state IN ('opened'))
AND labels.title IN ('Plan',
'backend')
GROUP BY
issues.id
HAVING (COUNT(DISTINCT labels.title) = 2)
ORDER BY
issues.updated_at DESC,
issues.id DESC
LIMIT 20 OFFSET 0
```
Specifically:
1. `GROUP BY issues.id` groups the results by issues.
1. `HAVING (COUNT(DISTINCT labels.title) = 2)` ensures that
all matched issues have both labels.
This is more complicated than is ideal. It makes the query construction more
prone to errors (such as
[issue #15557](https://gitlab.com/gitlab-org/gitlab-foss/-/issues/15557)).
## Attempt A: `WHERE EXISTS`
### Attempt A1: use multiple subqueries with `WHERE EXISTS`
In [issue #37137](https://gitlab.com/gitlab-org/gitlab-foss/-/issues/37137)
and its associated [merge request](https://gitlab.com/gitlab-org/gitlab-foss/-/merge_requests/14022),
we tried to replace the `GROUP BY` with multiple uses of `WHERE EXISTS`. For the
example above, this would give:
```sql
WHERE (EXISTS (
SELECT
TRUE
FROM
label_links
INNER JOIN labels ON labels.id = label_links.label_id
WHERE
labels.title = 'Plan'
AND target_type = 'Issue'
AND target_id = issues.id))
AND (EXISTS (
SELECT
TRUE
FROM
label_links
INNER JOIN labels ON labels.id = label_links.label_id
WHERE
labels.title = 'backend'
AND target_type = 'Issue'
AND target_id = issues.id))
```
While this worked without schema changes, and did improve readability somewhat,
it did not improve query performance.
### Attempt A2: use label IDs in the `WHERE EXISTS` clause
In [merge request #34503](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/34503), we followed a similar approach to A1. But this time, we
did a separate query to fetch the IDs of the labels used in the filter so that we avoid the `JOIN` in the `EXISTS` clause and filter directly by
`label_links.label_id`. We also added a new index on `label_links` for the `target_id`, `label_id`, and `target_type` columns to speed up this query.
Finding the label IDs wasn't straightforward because there could be multiple labels with the same title within a single root namespace. We solved
this by grouping the label IDs by title and then using the array of IDs in the `EXISTS` clauses.
This resulted in a significant performance improvement. However, this optimization could not be applied to the dashboard pages
where we do not have a project or group context. We could not easily search for the label IDs here because that would mean searching across all
projects and groups that the user has access to.
## Attempt B: Denormalize using an array column
We discussed denormalizing
the `label_links` table for querying in
[issue #49651](https://gitlab.com/gitlab-org/gitlab-foss/-/issues/49651),
with two options: label IDs and titles.
We can think of both of those as array columns on `issues`, `merge_requests`,
and `epics`: `issues.label_ids` would be an array column of label IDs, and
`issues.label_titles` would be an array of label titles.
These array columns can be complemented with
[GIN indexes](https://www.postgresql.org/docs/16/gin-intro.html) to improve
matching.
### Attempt B1: store label IDs for each object
This has some strong advantages over titles:
1. Unless a label is deleted, or a project is moved, we never need to
bulk-update the denormalized column.
1. It uses less storage than the titles.
Unfortunately, our application design makes this hard. If we were able to query
just by label ID easily, we wouldn't need the `INNER JOIN labels` in the initial
query at the start of this document. GitLab allows users to filter by label
title across projects and even across groups, so a filter by the label ~Plan may
include labels with multiple distinct IDs.
We do not want users to have to know about the different IDs, which means that
given this data set:
| Project | ~Plan label ID | ~backend label ID |
| ------- | -------------- | ----------------- |
| A | 11 | 12 |
| B | 21 | 22 |
| C | 31 | 32 |
We would need something like:
```sql
WHERE
label_ids @> ARRAY[11, 12]
OR label_ids @> ARRAY[21, 22]
OR label_ids @> ARRAY[31, 32]
```
This can get even more complicated when we consider that in some cases, there
might be two ~backend labels - with different IDs - that could apply to the same
object, so the number of combinations would balloon further.
### Attempt B2: store label titles for each object
From the perspective of updating the object, this is the worst
option. We have to bulk update the objects when:
1. The objects are moved from one project to another.
1. The project is moved from one group to another.
1. The label is renamed.
1. The label is deleted.
It also uses much more storage. Querying is simple, though:
```sql
WHERE
label_titles @> ARRAY['Plan', 'backend']
```
And our [tests in issue #49651](https://gitlab.com/gitlab-org/gitlab-foss/-/issues/49651#note_188777346)
showed that this could be fast.
However, at present, the disadvantages outweigh the advantages.
## Conclusion
We found a method A2 that does not need denormalization and improves the query performance significantly. This
did not apply to all cases, but we were able to apply method A1 to the rest of the cases so that we remove the
`GROUP BY` and `HAVING` clauses in all scenarios.
This simplified the query and improved the performance in the most common cases.
|
---
stage: Plan
group: Project Management
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: Filtering by label
breadcrumbs:
- doc
- development
- database
---
## Introduction
GitLab has [labels](../../user/project/labels.md) that can be assigned to issues,
merge requests, and epics. Labels on those objects are a many-to-many relation
through the polymorphic `label_links` table.
To filter these objects by multiple labels - for instance, 'all open
issues with the label ~Plan and the label ~backend' - we generate a
query containing a `GROUP BY` clause. In a simple form, this looks like:
```sql
SELECT
issues.*
FROM
issues
INNER JOIN label_links ON label_links.target_id = issues.id
AND label_links.target_type = 'Issue'
INNER JOIN labels ON labels.id = label_links.label_id
WHERE
issues.project_id = 13083
AND (issues.state IN ('opened'))
AND labels.title IN ('Plan',
'backend')
GROUP BY
issues.id
HAVING (COUNT(DISTINCT labels.title) = 2)
ORDER BY
issues.updated_at DESC,
issues.id DESC
LIMIT 20 OFFSET 0
```
Specifically:
1. `GROUP BY issues.id` groups the results by issues.
1. `HAVING (COUNT(DISTINCT labels.title) = 2)` ensures that
all matched issues have both labels.
This is more complicated than is ideal. It makes the query construction more
prone to errors (such as
[issue #15557](https://gitlab.com/gitlab-org/gitlab-foss/-/issues/15557)).
## Attempt A: `WHERE EXISTS`
### Attempt A1: use multiple subqueries with `WHERE EXISTS`
In [issue #37137](https://gitlab.com/gitlab-org/gitlab-foss/-/issues/37137)
and its associated [merge request](https://gitlab.com/gitlab-org/gitlab-foss/-/merge_requests/14022),
we tried to replace the `GROUP BY` with multiple uses of `WHERE EXISTS`. For the
example above, this would give:
```sql
WHERE (EXISTS (
SELECT
TRUE
FROM
label_links
INNER JOIN labels ON labels.id = label_links.label_id
WHERE
labels.title = 'Plan'
AND target_type = 'Issue'
AND target_id = issues.id))
AND (EXISTS (
SELECT
TRUE
FROM
label_links
INNER JOIN labels ON labels.id = label_links.label_id
WHERE
labels.title = 'backend'
AND target_type = 'Issue'
AND target_id = issues.id))
```
While this worked without schema changes, and did improve readability somewhat,
it did not improve query performance.
### Attempt A2: use label IDs in the `WHERE EXISTS` clause
In [merge request #34503](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/34503), we followed a similar approach to A1. But this time, we
did a separate query to fetch the IDs of the labels used in the filter so that we avoid the `JOIN` in the `EXISTS` clause and filter directly by
`label_links.label_id`. We also added a new index on `label_links` for the `target_id`, `label_id`, and `target_type` columns to speed up this query.
Finding the label IDs wasn't straightforward because there could be multiple labels with the same title within a single root namespace. We solved
this by grouping the label IDs by title and then using the array of IDs in the `EXISTS` clauses.
This resulted in a significant performance improvement. However, this optimization could not be applied to the dashboard pages
where we do not have a project or group context. We could not easily search for the label IDs here because that would mean searching across all
projects and groups that the user has access to.
## Attempt B: Denormalize using an array column
We discussed denormalizing
the `label_links` table for querying in
[issue #49651](https://gitlab.com/gitlab-org/gitlab-foss/-/issues/49651),
with two options: label IDs and titles.
We can think of both of those as array columns on `issues`, `merge_requests`,
and `epics`: `issues.label_ids` would be an array column of label IDs, and
`issues.label_titles` would be an array of label titles.
These array columns can be complemented with
[GIN indexes](https://www.postgresql.org/docs/16/gin-intro.html) to improve
matching.
### Attempt B1: store label IDs for each object
This has some strong advantages over titles:
1. Unless a label is deleted, or a project is moved, we never need to
bulk-update the denormalized column.
1. It uses less storage than the titles.
Unfortunately, our application design makes this hard. If we were able to query
just by label ID easily, we wouldn't need the `INNER JOIN labels` in the initial
query at the start of this document. GitLab allows users to filter by label
title across projects and even across groups, so a filter by the label ~Plan may
include labels with multiple distinct IDs.
We do not want users to have to know about the different IDs, which means that
given this data set:
| Project | ~Plan label ID | ~backend label ID |
| ------- | -------------- | ----------------- |
| A | 11 | 12 |
| B | 21 | 22 |
| C | 31 | 32 |
We would need something like:
```sql
WHERE
label_ids @> ARRAY[11, 12]
OR label_ids @> ARRAY[21, 22]
OR label_ids @> ARRAY[31, 32]
```
This can get even more complicated when we consider that in some cases, there
might be two ~backend labels - with different IDs - that could apply to the same
object, so the number of combinations would balloon further.
### Attempt B2: store label titles for each object
From the perspective of updating the object, this is the worst
option. We have to bulk update the objects when:
1. The objects are moved from one project to another.
1. The project is moved from one group to another.
1. The label is renamed.
1. The label is deleted.
It also uses much more storage. Querying is simple, though:
```sql
WHERE
label_titles @> ARRAY['Plan', 'backend']
```
And our [tests in issue #49651](https://gitlab.com/gitlab-org/gitlab-foss/-/issues/49651#note_188777346)
showed that this could be fast.
However, at present, the disadvantages outweigh the advantages.
## Conclusion
We found a method A2 that does not need denormalization and improves the query performance significantly. This
did not apply to all cases, but we were able to apply method A1 to the rest of the cases so that we remove the
`GROUP BY` and `HAVING` clauses in all scenarios.
This simplified the query and improved the performance in the most common cases.
|
https://docs.gitlab.com/development/not_null_constraints
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/not_null_constraints.md
|
2025-08-13
|
doc/development/database
|
[
"doc",
"development",
"database"
] |
not_null_constraints.md
|
Data Access
|
Database Frameworks
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
`NOT NULL` constraints
| null |
All attributes that should not have `NULL` as a value, should be defined as `NOT NULL`
columns in the database.
Depending on the application logic, `NOT NULL` columns should either have a [presence validation defined in their Model](#add-validation-to-the-model-next-release)
or have a default value as part of their database definition.
As an example, the latter can be true for boolean attributes that should always have a non-`NULL`
value, but have a well defined default value that the application does not need to enforce each
time (for example, `active=true`).
For foreign key columns that are part of a `belongs_to` association, prefer using `optional: false`
on the association instead of a separate `presence: true` validation. This approach is more
semantically correct and leverages Rails' built-in association validation. Note that GitLab has
[config.active_record.belongs_to_required_by_default = false](https://gitlab.com/gitlab-org/gitlab/blob/bb49c1beceb3615bcff8993085e5f2b89c844599/config/application.rb#L259-259)
in `config/application.rb`, so `belongs_to` associations are optional by default and must be explicitly marked as required.
## Create a new table with `NOT NULL` columns
When adding a new table, all `NOT NULL` columns should be defined as such directly inside `create_table`.
For example, consider a migration that creates a table with two `NOT NULL` columns,
`db/migrate/20200401000001_create_db_guides.rb`:
```ruby
class CreateDbGuides < Gitlab::Database::Migration[2.1]
def change
create_table :db_guides do |t|
t.bigint :stars, default: 0, null: false
t.bigint :guide, null: false
end
end
end
```
## Add a `NOT NULL` column to an existing table
With PostgreSQL 11 being the minimum version in GitLab, adding columns with `NULL` and/or
default values has become much easier and the standard `add_column` helper should be used in all cases.
For example, consider a migration that adds a new `NOT NULL` column `active` to table `db_guides`,
`db/migrate/20200501000001_add_active_to_db_guides.rb`:
```ruby
class AddExtendedTitleToSprints < Gitlab::Database::Migration[2.1]
def change
add_column :db_guides, :active, :boolean, default: true, null: false
end
end
```
## Add a `NOT NULL` constraint to an existing column
Adding `NOT NULL` to existing database columns usually requires multiple steps split into at least two
different releases. If your table is small enough that you don't need to
use a background migration, you can include all these in the same merge
request. We recommend to use separate migrations to reduce
transaction durations.
The steps required are:
1. Release `N.M` (current release)
1. Ensure $ATTRIBUTE value is being set at the application level.
1. If the attribute has a default value, add the default value to the model so the default value is set for new records.
1. Update all places in the code where the attribute would be set to `nil`, if any, for new and existing records. Note that
using ActiveRecord callbacks such as `before_save` and `before_validation` may not be sufficient, as some processes
skip these callbacks. `update_column`, `update_columns`, and bulk operations such as `insert_all` and `update_all` are some
examples of methods to look out for.
1. Add a post-deployment migration to fix the existing records.
{{< alert type="note" >}}
Depending on the size of the table, a background migration for cleanup could be required in the next release.
See the [`NOT NULL` constraints on large tables](not_null_constraints.md#not-null-constraints-on-large-tables) section for more information.
{{< /alert >}}
1. Release `N.M+1` (next release)
1. Make sure all existing records on GitLab.com have attribute set. If not, go back to step 1 from Release `N.M`.
1. If step 1 seems fine and the backfill from Release `N.M` was done via a batched background migration then add a
post-deployment migration to
[finalize the background migration](batched_background_migrations.md#depending-on-migrated-data).
1. Add a validation for the attribute in the model to prevent records with `nil` attribute as now all existing and new records should be valid.
1. Add a post-deployment migration to add the `NOT NULL` constraint.
### Example
Considering a given release milestone, such as 13.0.
After checking our production database, we know that there are `epics` with `NULL` descriptions,
so we cannot add and validate the constraint in one step.
{{< alert type="note" >}}
Even if we did not have any epic with a `NULL` description, another instance of GitLab could have
such records, so we would follow the same process either way.
{{< /alert >}}
#### Prevent new invalid records (current release)
Update all the code paths where the attribute is being set to `nil`, if any, to set the attribute to non-nil value
for new and existing records.
An attribute with default using the
[Rails attributes API](https://api.rubyonrails.org/classes/ActiveRecord/Attributes/ClassMethods.html) has been added in
`epic.rb` so that default value is set for new records:
```ruby
class Epic < ApplicationRecord
attribute :description, default: 'No description'
end
```
#### Data migration to fix existing records (current release)
The approach here depends on the data volume and the cleanup strategy. The number of records that
must be fixed on GitLab.com is a nice indicator that helps us decide whether to use a
post-deployment migration or a background data migration:
- If the data volume is less than `1000` records, then the data migration can be executed within the post-migration.
- If the data volume is higher than `1000` records, it's advised to create a background migration.
When unsure about which option to use, contact the Database team for advice.
Back to our example, the epics table is not considerably large nor frequently accessed,
so we add a post-deployment migration for the 13.0 milestone (current),
`db/post_migrate/20200501000002_cleanup_epics_with_null_description.rb`:
```ruby
class CleanupEpicsWithNullDescription < Gitlab::Database::Migration[2.1]
# With BATCH_SIZE=1000 and epics.count=29500 on GitLab.com
# - 30 iterations will be run
# - each requires on average ~150ms
# Expected total run time: ~5 seconds
BATCH_SIZE = 1000
disable_ddl_transaction!
class Epic < MigrationRecord
include EachBatch
self.table_name = 'epics'
end
def up
Epic.each_batch(of: BATCH_SIZE) do |relation|
relation.
where('description IS NULL').
update_all(description: 'No description')
end
end
def down
# no-op : can't go back to `NULL` without first dropping the `NOT NULL` constraint
end
end
```
#### Check if all records are fixed (next release)
Use postgres.ai to [create a thin clone](https://handbook.gitlab.com/handbook/engineering/infrastructure-platforms/data-access/database-framework/doc/gitlab-com-database/#use-postgresai-to-work-with-a-thin-clone-of-the-database-includes-direct-psql-access-to-the-thin-clone)
of the production database and check if all records on GitLab.com have the attribute set.
If not go back to [Prevent new invalid records](#prevent-new-invalid-records-current-release) step and figure out where
in the code the attribute is explicitly set to `nil`. Fix the code path then reschedule the migration to fix the existing
records and wait for the next release to do the following steps.
#### Finalize the background migration (next release)
If the migration was done using a background migration then [finalize the migration](batched_background_migrations.md#depending-on-migrated-data).
#### Add validation to the model (next release)
Add a validation for the attribute to the model to prevent records with `nil` attribute as now all existing and new records should be valid.
For foreign key columns that are part of a `belongs_to` association, prefer using `optional: false`:
```ruby
class Epic < ApplicationRecord
belongs_to :group, optional: false
end
```
This is preferred over:
```ruby
class Epic < ApplicationRecord
belongs_to :group
validates :group, presence: true
end
```
For regular attributes:
```ruby
class Epic < ApplicationRecord
validates :description, presence: true
end
```
#### Add the `NOT NULL` constraint (next release)
Adding the `NOT NULL` constraint scans the whole table and make sure that each record is correct.
Still in our example, for the 13.1 milestone (next), we run the `add_not_null_constraint`
migration helper in a final post-deployment migration:
```ruby
class AddNotNullConstraintToEpicsDescription < Gitlab::Database::Migration[2.1]
disable_ddl_transaction!
def up
# This will add the `NOT NULL` constraint and validate it
add_not_null_constraint :epics, :description
end
def down
# Down is required as `add_not_null_constraint` is not reversible
remove_not_null_constraint :epics, :description
end
end
```
## `NOT NULL` constraints on large tables
If you have to clean up a nullable column for a [high-traffic table](../migration_style_guide.md#high-traffic-tables)
(for example, the `artifacts` in `ci_builds`), your background migration goes on for a while and
it needs an additional [batched background migration cleaning up](batched_background_migrations.md#cleaning-up-a-batched-background-migration)
in the release after adding the data migration.
In this case the number of releases depends on the amount of time needed to migrate existing records. The cleanup is
scheduled after the background migration has completed, which could be several releases after the constraint was added.
1. Release `N.M`:
- Add the background-migration to fix the existing records:
```ruby
# db/post_migrate/
class QueueBackfillMergeRequestDiffsProjectId < Gitlab::Database::Migration[2.2]
milestone '16.7'
restrict_gitlab_migration gitlab_schema: :gitlab_main
MIGRATION = 'BackfillMergeRequestDiffsProjectId'
DELAY_INTERVAL = 2.minutes
def up
queue_batched_background_migration(
MIGRATION,
:merge_request_diffs,
:id
)
end
def down
delete_batched_background_migration(MIGRATION, :merge_request_diffs, :id, [])
end
end
```
1. Release `N.M+X`, where `X` is the number of releases the migration was running:
- [Verify that all existing records are fixed](#check-if-all-records-are-fixed-next-release).
- Cleanup the background migration:
```ruby
# db/post_migrate/
class FinalizeMergeRequestDiffsProjectIdBackfill < Gitlab::Database::Migration[2.2]
disable_ddl_transaction!
milestone '16.10'
restrict_gitlab_migration gitlab_schema: :gitlab_main
MIGRATION = 'BackfillMergeRequestDiffsProjectId'
def up
ensure_batched_background_migration_is_finished(
job_class_name: MIGRATION,
table_name: :merge_request_diffs,
column_name: :id,
job_arguments: [],
finalize: true
)
end
def down
# no-op
end
end
```
- Add the `NOT NULL` constraint:
```ruby
# db/post_migrate/
class AddMergeRequestDiffsProjectIdNotNullConstraint < Gitlab::Database::Migration[2.2]
disable_ddl_transaction!
milestone '16.7'
def up
add_not_null_constraint :merge_request_diffs, :project_id
end
def down
remove_not_null_constraint :merge_request_diffs, :project_id
end
end
```
- **Optional.** For very large tables, add an invalid `NOT NULL` constraint and schedule asynchronous validation:
```ruby
# db/post_migrate/
class AddMergeRequestDiffsProjectIdNotNullConstraint < Gitlab::Database::Migration[2.2]
disable_ddl_transaction!
milestone '16.7'
def up
add_not_null_constraint :merge_request_diffs, :project_id, validate: false
end
def down
remove_not_null_constraint :merge_request_diffs, :project_id
end
end
```
```ruby
# db/post_migrate/
class PrepareMergeRequestDiffsProjectIdNotNullValidation < Gitlab::Database::Migration[2.2]
milestone '16.10'
CONSTRAINT_NAME = 'check_11c5f029ad'
def up
prepare_async_check_constraint_validation :merge_request_diffs, name: CONSTRAINT_NAME
end
def down
unprepare_async_check_constraint_validation :merge_request_diffs, name: CONSTRAINT_NAME
end
end
```
- **Optional.** For partitioned table, use:
```ruby
# db/post_migrate/
PARTITIONED_TABLE_NAME = :p_ci_builds
CONSTRAINT_NAME = 'check_9aa9432137'
# Partitioned check constraint to be validated in https://gitlab.com/gitlab-org/gitlab/-/issues/XXXXX
def up
prepare_partitioned_async_check_constraint_validation PARTITIONED_TABLE_NAME, name: CONSTRAINT_NAME
end
def down
unprepare_partitioned_async_check_constraint_validation PARTITIONED_TABLE_NAME, name: CONSTRAINT_NAME
end
```
{{< alert type="note" >}}
`prepare_partitioned_async_check_constraint_validation` only validates the existing `NOT VALID` check constraint asynchronously for all the partitions.
It doesn't create or validate the check constraint for the partitioned table.
{{< /alert >}}
1. **Optional.** If the constraint was validated asynchronously, validate the `NOT NULL` constraint once validation is complete:
- Use [Database Lab](database_lab.md) to check if the validation was successful.
Run the command `\d+ table_name` and ensure that `NOT VALID` has been removed from the check constraint definition.
- Add the migration to validate the `NOT NULL` constraint:
```ruby
# db/post_migrate/
class ValidateMergeRequestDiffsProjectIdNullConstraint < Gitlab::Database::Migration[2.2]
milestone '16.10'
def up
validate_not_null_constraint :merge_request_diffs, :project_id
end
def down
# no-op
end
end
```
For these cases, consult the database team early in the update cycle. The `NOT NULL`
constraint may not be required or other options could exist that do not affect really large
or frequently accessed tables.
## `NOT NULL` constraints for multiple columns
Sometimes we want to ensure a set of columns contains a specific number of `NOT NULL` values. A common example
is a table that can belong to either a project or a group, and therefore `project_id` or `group_id` must
be present. To enforce this, follow the steps for your use case above, but instead use the
`add_multi_column_not_null_constraint` helper.
In this example, `labels` must belong to either a project or a group, but not both. We can add
a check constraint to enforce this:
```ruby
class AddLabelsNullConstraint < Gitlab::Database::Migration[2.2]
disable_ddl_transaction!
milestone '16.10'
def up
add_multi_column_not_null_constraint(:labels, :group_id, :project_id)
end
def down
remove_multi_column_not_null_constraint(:labels, :group_id, :project_id)
end
end
```
This will add the following constraint to `labels`:
```sql
CREATE TABLE labels (
...
CONSTRAINT check_45e873b2a8 CHECK ((num_nonnulls(group_id, project_id) = 1))
);
```
`num_nonnulls` returns the number of supplied arguments that are non-null. Checking this value
equals `1` in the constraint means that only one of `group_id` and `project_id` should contain
a non-null value in a row, but not both.
### Custom limits and operators
If we want to customize the number of non-nulls required, we can use a different `limit` and/or `operator`:
```ruby
class AddLabelsNullConstraint < Gitlab::Database::Migration[2.2]
disable_ddl_transaction!
milestone '16.10'
def up
add_multi_column_not_null_constraint(:labels, :group_id, :project_id, limit: 0, operator: '>')
end
def down
remove_multi_column_not_null_constraint(:labels, :group_id, :project_id)
end
end
```
This is then reflected in the constraint, allowing both `project_id` and `group_id` to be present:
```sql
CREATE TABLE labels (
...
CONSTRAINT check_45e873b2a8 CHECK ((num_nonnulls(group_id, project_id) > 0))
);
```
## Dropping a `NOT NULL` constraint on a column in an existing table
Dropping a `NOT NULL` constraint from an existing database column requires a multistep migration process:
1. A schema migration to drop the `NOT NULL` constraint.
1. A separate data migration to ensure data integrity after a potential rollback. This migration may:
- Remove invalid records.
- Update invalid records with a default value.
Multiple migrations are required as combining data modifications (DML) and schema changes (DDL) in a single migration is not
allowed.
### Dropping a `NOT NULL` constraint with a check constraint on the column
First, verify there's a constraint in place on the column. You can do this in several ways:
- Query the [`Gitlab::Database::PostgresConstraint`](https://gitlab.com/gitlab-org/gitlab/-/blob/71892a3c97f52ddcef819dd210ab32864e90c85c/lib/gitlab/database/postgres_constraint.rb) view in rails console
- Use `psql` to check the table itself: `\d+ table_name`
- Check `structure.sql`:
```sql
CREATE TABLE labels (
...
CONSTRAINT check_061f6f1c91 CHECK ((project_view IS NOT NULL))
);
```
#### Example
{{< alert type="note" >}}
The milestone number is just an example. Use the correct version.
{{< /alert >}}
```ruby
# frozen_string_literal: true
class DropNotNullConstraintFromLabelsProjectView< Gitlab::Database::Migration[2.2]
disable_ddl_transaction!
milestone '16.7'
def up
remove_not_null_constraint :labels, :project_view
end
def down
add_not_null_constraint :labels, :project_view
end
end
```
```ruby
# frozen_string_literal: true
class CleanupRecordsWithNullProjectViewValuesFromLabels < Gitlab::Database::Migration[2.2]
disable_ddl_transaction!
milestone '16.7'
BATCH_SIZE = 1000
class Label < MigrationRecord
include EachBatch
self.table_name = 'labels'
end
def up
# no-op - this migration is required to allow a rollback of `DropNotNullConstraintFromLabelsProjectView`
end
def down
Label.each_batch(of: BATCH_SIZE) do |relation|
relation.
where('project_view IS NULL').
delete_all
end
end
end
```
### Dropping a `NOT NULL` constraint without a check constraint on the column
If `NOT NULL` is just defined on the column and without a check constraint then we can use `change_column_null`.
Example in `structure.sql`:
```sql
CREATE TABLE labels (
...
projects_limit integer NOT NULL
);
```
#### Example
{{< alert type="note" >}}
The milestone number is just an example. Use the correct version.
{{< /alert >}}
```ruby
# frozen_string_literal: true
class DropNotNullConstraintFromLabelsProjectsLimit < Gitlab::Database::Migration[2.2]
milestone '16.7'
def up
change_column_null :labels, :projects_limit, true
end
def down
change_column_null :labels, :projects_limit, false
end
end
```
```ruby
# frozen_string_literal: true
class CleanupRecordsWithNullProjectsLimitValuesFromLabels < Gitlab::Database::Migration[2.2]
disable_ddl_transaction!
milestone '16.7'
BATCH_SIZE = 1000
class Label < MigrationRecord
include EachBatch
self.table_name = 'labels'
end
def up
# no-op - this migration is required to allow a rollback of `DropNotNullConstraintFromLabelsProjectsLimit`
end
def down
Label.each_batch(of: BATCH_SIZE) do |relation|
relation.
where('projects_limit IS NULL').
delete_all
end
end
end
```
### Dropping a `NOT NULL` constraint on a partition table
Important note: we cannot drop the `NOT NULL` constraint from an individual partition if it exists on the parent table because all the partitions inherit the constraint from the parent table. For this reason, we need to drop the constraint from the parent table instead which cascades to all the child partitions.
|
---
stage: Data Access
group: Database Frameworks
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: '`NOT NULL` constraints'
breadcrumbs:
- doc
- development
- database
---
All attributes that should not have `NULL` as a value, should be defined as `NOT NULL`
columns in the database.
Depending on the application logic, `NOT NULL` columns should either have a [presence validation defined in their Model](#add-validation-to-the-model-next-release)
or have a default value as part of their database definition.
As an example, the latter can be true for boolean attributes that should always have a non-`NULL`
value, but have a well defined default value that the application does not need to enforce each
time (for example, `active=true`).
For foreign key columns that are part of a `belongs_to` association, prefer using `optional: false`
on the association instead of a separate `presence: true` validation. This approach is more
semantically correct and leverages Rails' built-in association validation. Note that GitLab has
[config.active_record.belongs_to_required_by_default = false](https://gitlab.com/gitlab-org/gitlab/blob/bb49c1beceb3615bcff8993085e5f2b89c844599/config/application.rb#L259-259)
in `config/application.rb`, so `belongs_to` associations are optional by default and must be explicitly marked as required.
## Create a new table with `NOT NULL` columns
When adding a new table, all `NOT NULL` columns should be defined as such directly inside `create_table`.
For example, consider a migration that creates a table with two `NOT NULL` columns,
`db/migrate/20200401000001_create_db_guides.rb`:
```ruby
class CreateDbGuides < Gitlab::Database::Migration[2.1]
def change
create_table :db_guides do |t|
t.bigint :stars, default: 0, null: false
t.bigint :guide, null: false
end
end
end
```
## Add a `NOT NULL` column to an existing table
With PostgreSQL 11 being the minimum version in GitLab, adding columns with `NULL` and/or
default values has become much easier and the standard `add_column` helper should be used in all cases.
For example, consider a migration that adds a new `NOT NULL` column `active` to table `db_guides`,
`db/migrate/20200501000001_add_active_to_db_guides.rb`:
```ruby
class AddExtendedTitleToSprints < Gitlab::Database::Migration[2.1]
def change
add_column :db_guides, :active, :boolean, default: true, null: false
end
end
```
## Add a `NOT NULL` constraint to an existing column
Adding `NOT NULL` to existing database columns usually requires multiple steps split into at least two
different releases. If your table is small enough that you don't need to
use a background migration, you can include all these in the same merge
request. We recommend to use separate migrations to reduce
transaction durations.
The steps required are:
1. Release `N.M` (current release)
1. Ensure $ATTRIBUTE value is being set at the application level.
1. If the attribute has a default value, add the default value to the model so the default value is set for new records.
1. Update all places in the code where the attribute would be set to `nil`, if any, for new and existing records. Note that
using ActiveRecord callbacks such as `before_save` and `before_validation` may not be sufficient, as some processes
skip these callbacks. `update_column`, `update_columns`, and bulk operations such as `insert_all` and `update_all` are some
examples of methods to look out for.
1. Add a post-deployment migration to fix the existing records.
{{< alert type="note" >}}
Depending on the size of the table, a background migration for cleanup could be required in the next release.
See the [`NOT NULL` constraints on large tables](not_null_constraints.md#not-null-constraints-on-large-tables) section for more information.
{{< /alert >}}
1. Release `N.M+1` (next release)
1. Make sure all existing records on GitLab.com have attribute set. If not, go back to step 1 from Release `N.M`.
1. If step 1 seems fine and the backfill from Release `N.M` was done via a batched background migration then add a
post-deployment migration to
[finalize the background migration](batched_background_migrations.md#depending-on-migrated-data).
1. Add a validation for the attribute in the model to prevent records with `nil` attribute as now all existing and new records should be valid.
1. Add a post-deployment migration to add the `NOT NULL` constraint.
### Example
Considering a given release milestone, such as 13.0.
After checking our production database, we know that there are `epics` with `NULL` descriptions,
so we cannot add and validate the constraint in one step.
{{< alert type="note" >}}
Even if we did not have any epic with a `NULL` description, another instance of GitLab could have
such records, so we would follow the same process either way.
{{< /alert >}}
#### Prevent new invalid records (current release)
Update all the code paths where the attribute is being set to `nil`, if any, to set the attribute to non-nil value
for new and existing records.
An attribute with default using the
[Rails attributes API](https://api.rubyonrails.org/classes/ActiveRecord/Attributes/ClassMethods.html) has been added in
`epic.rb` so that default value is set for new records:
```ruby
class Epic < ApplicationRecord
attribute :description, default: 'No description'
end
```
#### Data migration to fix existing records (current release)
The approach here depends on the data volume and the cleanup strategy. The number of records that
must be fixed on GitLab.com is a nice indicator that helps us decide whether to use a
post-deployment migration or a background data migration:
- If the data volume is less than `1000` records, then the data migration can be executed within the post-migration.
- If the data volume is higher than `1000` records, it's advised to create a background migration.
When unsure about which option to use, contact the Database team for advice.
Back to our example, the epics table is not considerably large nor frequently accessed,
so we add a post-deployment migration for the 13.0 milestone (current),
`db/post_migrate/20200501000002_cleanup_epics_with_null_description.rb`:
```ruby
class CleanupEpicsWithNullDescription < Gitlab::Database::Migration[2.1]
# With BATCH_SIZE=1000 and epics.count=29500 on GitLab.com
# - 30 iterations will be run
# - each requires on average ~150ms
# Expected total run time: ~5 seconds
BATCH_SIZE = 1000
disable_ddl_transaction!
class Epic < MigrationRecord
include EachBatch
self.table_name = 'epics'
end
def up
Epic.each_batch(of: BATCH_SIZE) do |relation|
relation.
where('description IS NULL').
update_all(description: 'No description')
end
end
def down
# no-op : can't go back to `NULL` without first dropping the `NOT NULL` constraint
end
end
```
#### Check if all records are fixed (next release)
Use postgres.ai to [create a thin clone](https://handbook.gitlab.com/handbook/engineering/infrastructure-platforms/data-access/database-framework/doc/gitlab-com-database/#use-postgresai-to-work-with-a-thin-clone-of-the-database-includes-direct-psql-access-to-the-thin-clone)
of the production database and check if all records on GitLab.com have the attribute set.
If not go back to [Prevent new invalid records](#prevent-new-invalid-records-current-release) step and figure out where
in the code the attribute is explicitly set to `nil`. Fix the code path then reschedule the migration to fix the existing
records and wait for the next release to do the following steps.
#### Finalize the background migration (next release)
If the migration was done using a background migration then [finalize the migration](batched_background_migrations.md#depending-on-migrated-data).
#### Add validation to the model (next release)
Add a validation for the attribute to the model to prevent records with `nil` attribute as now all existing and new records should be valid.
For foreign key columns that are part of a `belongs_to` association, prefer using `optional: false`:
```ruby
class Epic < ApplicationRecord
belongs_to :group, optional: false
end
```
This is preferred over:
```ruby
class Epic < ApplicationRecord
belongs_to :group
validates :group, presence: true
end
```
For regular attributes:
```ruby
class Epic < ApplicationRecord
validates :description, presence: true
end
```
#### Add the `NOT NULL` constraint (next release)
Adding the `NOT NULL` constraint scans the whole table and make sure that each record is correct.
Still in our example, for the 13.1 milestone (next), we run the `add_not_null_constraint`
migration helper in a final post-deployment migration:
```ruby
class AddNotNullConstraintToEpicsDescription < Gitlab::Database::Migration[2.1]
disable_ddl_transaction!
def up
# This will add the `NOT NULL` constraint and validate it
add_not_null_constraint :epics, :description
end
def down
# Down is required as `add_not_null_constraint` is not reversible
remove_not_null_constraint :epics, :description
end
end
```
## `NOT NULL` constraints on large tables
If you have to clean up a nullable column for a [high-traffic table](../migration_style_guide.md#high-traffic-tables)
(for example, the `artifacts` in `ci_builds`), your background migration goes on for a while and
it needs an additional [batched background migration cleaning up](batched_background_migrations.md#cleaning-up-a-batched-background-migration)
in the release after adding the data migration.
In this case the number of releases depends on the amount of time needed to migrate existing records. The cleanup is
scheduled after the background migration has completed, which could be several releases after the constraint was added.
1. Release `N.M`:
- Add the background-migration to fix the existing records:
```ruby
# db/post_migrate/
class QueueBackfillMergeRequestDiffsProjectId < Gitlab::Database::Migration[2.2]
milestone '16.7'
restrict_gitlab_migration gitlab_schema: :gitlab_main
MIGRATION = 'BackfillMergeRequestDiffsProjectId'
DELAY_INTERVAL = 2.minutes
def up
queue_batched_background_migration(
MIGRATION,
:merge_request_diffs,
:id
)
end
def down
delete_batched_background_migration(MIGRATION, :merge_request_diffs, :id, [])
end
end
```
1. Release `N.M+X`, where `X` is the number of releases the migration was running:
- [Verify that all existing records are fixed](#check-if-all-records-are-fixed-next-release).
- Cleanup the background migration:
```ruby
# db/post_migrate/
class FinalizeMergeRequestDiffsProjectIdBackfill < Gitlab::Database::Migration[2.2]
disable_ddl_transaction!
milestone '16.10'
restrict_gitlab_migration gitlab_schema: :gitlab_main
MIGRATION = 'BackfillMergeRequestDiffsProjectId'
def up
ensure_batched_background_migration_is_finished(
job_class_name: MIGRATION,
table_name: :merge_request_diffs,
column_name: :id,
job_arguments: [],
finalize: true
)
end
def down
# no-op
end
end
```
- Add the `NOT NULL` constraint:
```ruby
# db/post_migrate/
class AddMergeRequestDiffsProjectIdNotNullConstraint < Gitlab::Database::Migration[2.2]
disable_ddl_transaction!
milestone '16.7'
def up
add_not_null_constraint :merge_request_diffs, :project_id
end
def down
remove_not_null_constraint :merge_request_diffs, :project_id
end
end
```
- **Optional.** For very large tables, add an invalid `NOT NULL` constraint and schedule asynchronous validation:
```ruby
# db/post_migrate/
class AddMergeRequestDiffsProjectIdNotNullConstraint < Gitlab::Database::Migration[2.2]
disable_ddl_transaction!
milestone '16.7'
def up
add_not_null_constraint :merge_request_diffs, :project_id, validate: false
end
def down
remove_not_null_constraint :merge_request_diffs, :project_id
end
end
```
```ruby
# db/post_migrate/
class PrepareMergeRequestDiffsProjectIdNotNullValidation < Gitlab::Database::Migration[2.2]
milestone '16.10'
CONSTRAINT_NAME = 'check_11c5f029ad'
def up
prepare_async_check_constraint_validation :merge_request_diffs, name: CONSTRAINT_NAME
end
def down
unprepare_async_check_constraint_validation :merge_request_diffs, name: CONSTRAINT_NAME
end
end
```
- **Optional.** For partitioned table, use:
```ruby
# db/post_migrate/
PARTITIONED_TABLE_NAME = :p_ci_builds
CONSTRAINT_NAME = 'check_9aa9432137'
# Partitioned check constraint to be validated in https://gitlab.com/gitlab-org/gitlab/-/issues/XXXXX
def up
prepare_partitioned_async_check_constraint_validation PARTITIONED_TABLE_NAME, name: CONSTRAINT_NAME
end
def down
unprepare_partitioned_async_check_constraint_validation PARTITIONED_TABLE_NAME, name: CONSTRAINT_NAME
end
```
{{< alert type="note" >}}
`prepare_partitioned_async_check_constraint_validation` only validates the existing `NOT VALID` check constraint asynchronously for all the partitions.
It doesn't create or validate the check constraint for the partitioned table.
{{< /alert >}}
1. **Optional.** If the constraint was validated asynchronously, validate the `NOT NULL` constraint once validation is complete:
- Use [Database Lab](database_lab.md) to check if the validation was successful.
Run the command `\d+ table_name` and ensure that `NOT VALID` has been removed from the check constraint definition.
- Add the migration to validate the `NOT NULL` constraint:
```ruby
# db/post_migrate/
class ValidateMergeRequestDiffsProjectIdNullConstraint < Gitlab::Database::Migration[2.2]
milestone '16.10'
def up
validate_not_null_constraint :merge_request_diffs, :project_id
end
def down
# no-op
end
end
```
For these cases, consult the database team early in the update cycle. The `NOT NULL`
constraint may not be required or other options could exist that do not affect really large
or frequently accessed tables.
## `NOT NULL` constraints for multiple columns
Sometimes we want to ensure a set of columns contains a specific number of `NOT NULL` values. A common example
is a table that can belong to either a project or a group, and therefore `project_id` or `group_id` must
be present. To enforce this, follow the steps for your use case above, but instead use the
`add_multi_column_not_null_constraint` helper.
In this example, `labels` must belong to either a project or a group, but not both. We can add
a check constraint to enforce this:
```ruby
class AddLabelsNullConstraint < Gitlab::Database::Migration[2.2]
disable_ddl_transaction!
milestone '16.10'
def up
add_multi_column_not_null_constraint(:labels, :group_id, :project_id)
end
def down
remove_multi_column_not_null_constraint(:labels, :group_id, :project_id)
end
end
```
This will add the following constraint to `labels`:
```sql
CREATE TABLE labels (
...
CONSTRAINT check_45e873b2a8 CHECK ((num_nonnulls(group_id, project_id) = 1))
);
```
`num_nonnulls` returns the number of supplied arguments that are non-null. Checking this value
equals `1` in the constraint means that only one of `group_id` and `project_id` should contain
a non-null value in a row, but not both.
### Custom limits and operators
If we want to customize the number of non-nulls required, we can use a different `limit` and/or `operator`:
```ruby
class AddLabelsNullConstraint < Gitlab::Database::Migration[2.2]
disable_ddl_transaction!
milestone '16.10'
def up
add_multi_column_not_null_constraint(:labels, :group_id, :project_id, limit: 0, operator: '>')
end
def down
remove_multi_column_not_null_constraint(:labels, :group_id, :project_id)
end
end
```
This is then reflected in the constraint, allowing both `project_id` and `group_id` to be present:
```sql
CREATE TABLE labels (
...
CONSTRAINT check_45e873b2a8 CHECK ((num_nonnulls(group_id, project_id) > 0))
);
```
## Dropping a `NOT NULL` constraint on a column in an existing table
Dropping a `NOT NULL` constraint from an existing database column requires a multistep migration process:
1. A schema migration to drop the `NOT NULL` constraint.
1. A separate data migration to ensure data integrity after a potential rollback. This migration may:
- Remove invalid records.
- Update invalid records with a default value.
Multiple migrations are required as combining data modifications (DML) and schema changes (DDL) in a single migration is not
allowed.
### Dropping a `NOT NULL` constraint with a check constraint on the column
First, verify there's a constraint in place on the column. You can do this in several ways:
- Query the [`Gitlab::Database::PostgresConstraint`](https://gitlab.com/gitlab-org/gitlab/-/blob/71892a3c97f52ddcef819dd210ab32864e90c85c/lib/gitlab/database/postgres_constraint.rb) view in rails console
- Use `psql` to check the table itself: `\d+ table_name`
- Check `structure.sql`:
```sql
CREATE TABLE labels (
...
CONSTRAINT check_061f6f1c91 CHECK ((project_view IS NOT NULL))
);
```
#### Example
{{< alert type="note" >}}
The milestone number is just an example. Use the correct version.
{{< /alert >}}
```ruby
# frozen_string_literal: true
class DropNotNullConstraintFromLabelsProjectView< Gitlab::Database::Migration[2.2]
disable_ddl_transaction!
milestone '16.7'
def up
remove_not_null_constraint :labels, :project_view
end
def down
add_not_null_constraint :labels, :project_view
end
end
```
```ruby
# frozen_string_literal: true
class CleanupRecordsWithNullProjectViewValuesFromLabels < Gitlab::Database::Migration[2.2]
disable_ddl_transaction!
milestone '16.7'
BATCH_SIZE = 1000
class Label < MigrationRecord
include EachBatch
self.table_name = 'labels'
end
def up
# no-op - this migration is required to allow a rollback of `DropNotNullConstraintFromLabelsProjectView`
end
def down
Label.each_batch(of: BATCH_SIZE) do |relation|
relation.
where('project_view IS NULL').
delete_all
end
end
end
```
### Dropping a `NOT NULL` constraint without a check constraint on the column
If `NOT NULL` is just defined on the column and without a check constraint then we can use `change_column_null`.
Example in `structure.sql`:
```sql
CREATE TABLE labels (
...
projects_limit integer NOT NULL
);
```
#### Example
{{< alert type="note" >}}
The milestone number is just an example. Use the correct version.
{{< /alert >}}
```ruby
# frozen_string_literal: true
class DropNotNullConstraintFromLabelsProjectsLimit < Gitlab::Database::Migration[2.2]
milestone '16.7'
def up
change_column_null :labels, :projects_limit, true
end
def down
change_column_null :labels, :projects_limit, false
end
end
```
```ruby
# frozen_string_literal: true
class CleanupRecordsWithNullProjectsLimitValuesFromLabels < Gitlab::Database::Migration[2.2]
disable_ddl_transaction!
milestone '16.7'
BATCH_SIZE = 1000
class Label < MigrationRecord
include EachBatch
self.table_name = 'labels'
end
def up
# no-op - this migration is required to allow a rollback of `DropNotNullConstraintFromLabelsProjectsLimit`
end
def down
Label.each_batch(of: BATCH_SIZE) do |relation|
relation.
where('projects_limit IS NULL').
delete_all
end
end
end
```
### Dropping a `NOT NULL` constraint on a partition table
Important note: we cannot drop the `NOT NULL` constraint from an individual partition if it exists on the parent table because all the partitions inherit the constraint from the parent table. For this reason, we need to drop the constraint from the parent table instead which cascades to all the child partitions.
|
https://docs.gitlab.com/development/required_stops
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/required_stops.md
|
2025-08-13
|
doc/development/database
|
[
"doc",
"development",
"database"
] |
required_stops.md
|
Data Access
|
Database
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Database required stops
| null |
This page describes which database changes require GitLab upgrade stops. If you're interested
about a comprehensive list of causes, refer to [causes of required stops](../avoiding_required_stops.md#causes-of-required-stops).
[Required stops](../../update/upgrade_paths.md) will now consistently land on minor versions X.2, X.5, X.8 and X.11. This is to ensure predictable upgrade paths for users. Any changes to the database that require a stop can make use of these releases. The instructions below are used to add required upgrade stops.
## Common database changes that require stops
### Long running migrations being finalized
If a migration takes a long time, it could cause a large number of customers to encounter timeouts
during upgrades. The increased support volume may cause us to introduce a required stop. While any
background migration may cause these issues with particularly large customers, we typically only
introduce stops when the impact is widespread.
- **Cause**: When an upgrade takes more than an hour, omnibus times out.
- **Mitigation**: Schedule finalization for the first minor version after the next required stop. By waiting for the
next required stop, we ensure the customers jumping between required stops will have an opportunity to run the
migrations in the background ensuring their services remain operational. Otherwise, finalizing migrations in the
required stop would force synchronous execution during upgrade from previous required stop, causing downtime if the
migration runtime exceed the maintenance window.
### Improperly finalized background migrations
You may need to introduce a required stop for mitigation when:
- A background migration is not finalized, and
- A migration is written that depends on that background migration.
- **Cause**: The dependent migration may fail if the background migration is incomplete.
- **Mitigation**: Ensure that all background migrations are finalized before authoring dependent migrations.
### Remove a migration
If a migration is removed, you may need to introduce a required stop to ensure customers
don't miss the required change.
- **Cause**: Dependent migrations may fail, or the application may not function, because a required
migration was removed.
- **Mitigation**: Ensure migrations are only removed after they've been a part of a planned
required stop.
### A migration timestamp is very old
If a migration timestamp is very old (> 3 weeks, or after a before the last stop),
these scenarios may cause issues:
- If the migration depends on another migration with a newer timestamp but introduced in a
previous release after a required stop, then the new migration may run sequentially sooner
than the prerequisite migration, and thus fail.
- If the migration timestamp ID is before the last, it may be inadvertently squashed when the
team squashes other migrations from the required stop.
- **Cause**: The migration may fail if it depends on a migration with a later timestamp introduced
in an earlier version. Or, the migration may be inadvertently squashed after a required stop.
- **Mitigation**: Aim for migration timestamps to fall inside the release dates and be sure that
they are not dated prior to the last required stop.
### Bugs in migration related tooling
In a few circumstances, bugs in migration related tooling has required us to introduce stops. While we aim
to prevent these in testing, sometimes they happen.
- **Cause**: There have been a few different causes where we recognized these too late.
- **Mitigation**: Typically we try to backport fixes for migrations, but in some cases this is not possible.
## Adding a required stop
If you plan to introduce a change the falls into one of the above scenarios,
see [adding required stops](../avoiding_required_stops.md#adding-required-stops).
|
---
stage: Data Access
group: Database
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: Database required stops
breadcrumbs:
- doc
- development
- database
---
This page describes which database changes require GitLab upgrade stops. If you're interested
about a comprehensive list of causes, refer to [causes of required stops](../avoiding_required_stops.md#causes-of-required-stops).
[Required stops](../../update/upgrade_paths.md) will now consistently land on minor versions X.2, X.5, X.8 and X.11. This is to ensure predictable upgrade paths for users. Any changes to the database that require a stop can make use of these releases. The instructions below are used to add required upgrade stops.
## Common database changes that require stops
### Long running migrations being finalized
If a migration takes a long time, it could cause a large number of customers to encounter timeouts
during upgrades. The increased support volume may cause us to introduce a required stop. While any
background migration may cause these issues with particularly large customers, we typically only
introduce stops when the impact is widespread.
- **Cause**: When an upgrade takes more than an hour, omnibus times out.
- **Mitigation**: Schedule finalization for the first minor version after the next required stop. By waiting for the
next required stop, we ensure the customers jumping between required stops will have an opportunity to run the
migrations in the background ensuring their services remain operational. Otherwise, finalizing migrations in the
required stop would force synchronous execution during upgrade from previous required stop, causing downtime if the
migration runtime exceed the maintenance window.
### Improperly finalized background migrations
You may need to introduce a required stop for mitigation when:
- A background migration is not finalized, and
- A migration is written that depends on that background migration.
- **Cause**: The dependent migration may fail if the background migration is incomplete.
- **Mitigation**: Ensure that all background migrations are finalized before authoring dependent migrations.
### Remove a migration
If a migration is removed, you may need to introduce a required stop to ensure customers
don't miss the required change.
- **Cause**: Dependent migrations may fail, or the application may not function, because a required
migration was removed.
- **Mitigation**: Ensure migrations are only removed after they've been a part of a planned
required stop.
### A migration timestamp is very old
If a migration timestamp is very old (> 3 weeks, or after a before the last stop),
these scenarios may cause issues:
- If the migration depends on another migration with a newer timestamp but introduced in a
previous release after a required stop, then the new migration may run sequentially sooner
than the prerequisite migration, and thus fail.
- If the migration timestamp ID is before the last, it may be inadvertently squashed when the
team squashes other migrations from the required stop.
- **Cause**: The migration may fail if it depends on a migration with a later timestamp introduced
in an earlier version. Or, the migration may be inadvertently squashed after a required stop.
- **Mitigation**: Aim for migration timestamps to fall inside the release dates and be sure that
they are not dated prior to the last required stop.
### Bugs in migration related tooling
In a few circumstances, bugs in migration related tooling has required us to introduce stops. While we aim
to prevent these in testing, sometimes they happen.
- **Cause**: There have been a few different causes where we recognized these too late.
- **Mitigation**: Typically we try to backport fixes for migrations, but in some cases this is not possible.
## Adding a required stop
If you plan to introduce a change the falls into one of the above scenarios,
see [adding required stops](../avoiding_required_stops.md#adding-required-stops).
|
https://docs.gitlab.com/development/pagination_performance_guidelines
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/pagination_performance_guidelines.md
|
2025-08-13
|
doc/development/database
|
[
"doc",
"development",
"database"
] |
pagination_performance_guidelines.md
|
Data Access
|
Database Frameworks
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Pagination performance guidelines
| null |
The following document gives a few ideas for improving the pagination (sorting) performance. These apply both on [offset](pagination_guidelines.md#offset-pagination) and [keyset](pagination_guidelines.md#keyset-pagination) pagination.
## Tie-breaker column
When ordering the columns it's advised to order by distinct columns only. Consider the following example:
| `id` | `created_at` |
|------|-----------------------|
| `1` | `2021-01-04 14:13:43` |
| `2` | `2021-01-05 19:03:12` |
| `3` | `2021-01-05 19:03:12` |
If we order by `created_at`, the result would likely depend on how the records are located on the disk.
Using the tie-breaker column is advised when the data is exposed via a well defined interface and its consumed
by an automated process, such as an API. Without the tie-breaker column, the order of the rows could change
(data is re-imported) which could cause problems that are hard to debug, such as:
- An integration comparing the rows to determine changes breaks.
- E-tag cache values change, which requires a complete re-download.
```sql
SELECT issues.* FROM issues ORDER BY created_at;
```
We can fix this by adding a second column to `ORDER BY`:
```sql
SELECT issues.* FROM issues ORDER BY created_at, id;
```
This change makes the order distinct so we have "stable" sorting.
{{< alert type="note" >}}
To make the query efficient, we need an index covering both columns: `(created_at, id)`. The order of the columns **should match** the columns in the `ORDER BY` clause.
{{< /alert >}}
### Incremental sorting
In PostgreSQL 13 incremental sorting was added which can help introducing a tie-breaker column to the `ORDER BY` clause without adding or replacing an index. Also, with incremental sorting, introducing a new keyset-paginated database query can happen before the new index is built (async indexes). Incremental sorting is enabled by default.
Consider the following database query:
```sql
SELECT *
FROM merge_requests
WHERE author_id = 1
ORDER BY created_at ASC
LIMIT 20
```
The query will read 20 rows using the following index:
```plaintext
"index_merge_requests_on_author_id_and_created_at" btree (author_id, created_at)
```
Using this query with keyset pagination is not possible because the `created_at` column is not unique. Let's add a tie-breaker column:
```sql
SELECT *
FROM merge_requests
WHERE author_id = 1
ORDER BY created_at ASC, id ASC
LIMIT 20
```
Execution plan:
```plaintext
Limit (cost=1.99..30.97 rows=20 width=910) (actual time=1.217..1.220 rows=20 loops=1)
Buffers: shared hit=33 read=2
I/O Timings: read=0.983 write=0.000
-> Incremental Sort (cost=1.99..919.33 rows=633 width=910) (actual time=1.215..1.216 rows=20 loops=1)
Sort Key: merge_requests.created_at, merge_requests.id
Buffers: shared hit=33 read=2
I/O Timings: read=0.983 write=0.000
-> Index Scan using index_merge_requests_on_author_id_and_created_at on public.merge_requests (cost=0.57..890.84 rows=633 width=910) (actual time=0.038..1.139 rows=22 loops=1)
Index Cond: (merge_requests.author_id = 1)
Buffers: shared hit=24 read=2
I/O Timings: read=0.983 write=0.000
```
As you can see the query read 22 rows using the same index. The database compared the 20th, 21th and 22th value of the `created_at` column and determined that the 22th value differ thus checking the next record is not needed. In this example the 20th and 21th column had the same `created_at` value.
Incremental sorting works well with timestamp columns where duplicated values are unlikely hence the incremental sorting will perform badly or won't be used at all when the column has very few distinct values (like an enum).
As an example, when incremental sorting is disabled, the database reads all merge requests records by the author and sorts data in memory.
```sql
set enable_incremental_sort=off;
```
```plaintext
Limit (cost=907.69..907.74 rows=20 width=910) (actual time=2.911..2.917 rows=20 loops=1)
Buffers: shared hit=1004
-> Sort (cost=907.69..909.27 rows=633 width=910) (actual time=2.908..2.911 rows=20 loops=1)
Sort Key: created_at, id
Sort Method: top-N heapsort Memory: 52kB
Buffers: shared hit=1004
-> Index Scan using index_merge_requests_on_author_id_and_created_at on merge_requests (cost=0.57..890.84 rows=633 width=910) (actual time=0.042..1.974 rows=1111 loops=1)
Index Cond: (author_id = 1)
Buffers: shared hit=1111
Planning Time: 0.386 ms
Execution Time: 3.000 ms
(11 rows)
```
In this example the database read 1111 rows and sorted the rows in memory.
## Ordering by joined table column
Oftentimes, we want to order the data by a column on a joined database table. The following example orders `issues` records by the `first_mentioned_in_commit_at` metric column:
```sql
SELECT issues.* FROM issues
INNER JOIN issue_metrics on issue_metrics.issue_id=issues.id
WHERE issues.project_id = 2
ORDER BY issue_metrics.first_mentioned_in_commit_at DESC, issues.id DESC
LIMIT 20
OFFSET 0
```
With PostgreSQL version 11, the planner first looks up all issues matching the `project_id` filter and then join all `issue_metrics` rows. The ordering of rows happens in memory. In case the joined relation is always present (1:1 relationship), the database reads `N * 2` rows where N is the number of rows matching the `project_id` filter.
For performance reasons, we should avoid mixing columns from different tables when specifying the `ORDER BY` clause.
In this particular case there is no simple way (like index creation) to improve the query. We might think that changing the `issues.id` column to `issue_metrics.issue_id` helps, however, this likely makes the query perform worse because it might force the database to process all rows in the `issue_metrics` table.
One idea to address this problem is denormalization. Adding the `project_id` column to the `issue_metrics` table makes the filtering and sorting efficient:
```sql
SELECT issues.* FROM issues
INNER JOIN issue_metrics on issue_metrics.issue_id=issues.id
WHERE issue_metrics.project_id = 2
ORDER BY issue_metrics.first_mentioned_in_commit_at DESC, issue_metrics.issue_id DESC
LIMIT 20
OFFSET 0
```
{{< alert type="note" >}}
The query requires an index on `issue_metrics` table with the following column configuration: `(project_id, first_mentioned_in_commit_at DESC, issue_id DESC)`.
{{< /alert >}}
## Filtering
### By project
Filtering by a project is a very common use case since we have many features on the project level. Examples: merge requests, issues, boards, iterations.
These features have a filter on `project_id` in their base query. Loading issues for a project:
```ruby
project = Project.find(5)
# order by internal id
issues = project.issues.order(:iid).page(1).per(20)
```
To make the base query efficient, there is usually a database index covering the `project_id` column. This significantly reduces the number of rows the database needs to scan. Without the index, the whole `issues` table would be read (full table scan) by the database.
Since `project_id` is a foreign key, we might have the following index available:
```sql
"index_issues_on_project_id" btree (project_id)
```
### By group
Unfortunately, there is no efficient way to sort and paginate on the group level. The database query execution time increases based on the number of records in the group.
Things get worse when group level actually means group and its subgroups. To load the first page, the database looks up the group hierarchy, finds all projects, and then looks up all issues.
The main reason behind the inefficient queries on the group level is the way our database schema is designed; our core domain models are associated with a project, and projects are associated with groups. This doesn't mean that the database structure is bad, it's just in a well-normalized form that is not optimized for efficient group level queries. We might need to look into denormalization in the long term.
Example: List issues in a group
```ruby
group = Group.find(9970)
Issue.where(project_id: group.projects).order(:iid).page(1).per(20)
```
The generated SQL query:
```sql
SELECT "issues".*
FROM "issues"
WHERE "issues"."project_id" IN
(SELECT "projects"."id"
FROM "projects"
WHERE "projects"."namespace_id" = 5)
ORDER BY "issues"."iid" ASC
LIMIT 20
OFFSET 0
```
The execution plan shows that we read significantly more rows than requested (20), and the rows are sorted in memory:
```plaintext
Limit (cost=10716.87..10716.92 rows=20 width=1300) (actual time=1472.305..1472.308 rows=20 loops=1)
-> Sort (cost=10716.87..10717.03 rows=61 width=1300) (actual time=1472.303..1472.305 rows=20 loops=1)
Sort Key: issues.iid
Sort Method: top-N heapsort Memory: 41kB
-> Nested Loop (cost=1.00..10715.25 rows=61 width=1300) (actual time=0.215..1331.647 rows=177267 loops=1)
-> Index Only Scan using index_projects_on_namespace_id_and_id on projects (cost=0.44..3.77 rows=19 width=4) (actual time=0.077..1.057 rows=270 loops=1)
Index Cond: (namespace_id = 9970)
Heap Fetches: 25
-> Index Scan using index_issues_on_project_id_and_iid on issues (cost=0.56..559.28 rows=448 width=1300) (actual time=0.101..4.781 rows=657 loops=270)
Index Cond: (project_id = projects.id)
Planning Time: 12.281 ms
Execution Time: 1472.391 ms
(12 rows)
```
#### Columns in the same database table
Filtering by columns located in the same database table can be improved with an index. In case we want to support filtering by the `state_id` column, we can add the following index:
```sql
"index_issues_on_project_id_and_state_id_and_iid" UNIQUE, btree (project_id, state_id, iid)
```
Example query in Rails:
```ruby
project = Project.find(5)
# order by internal id
issues = project.issues.opened.order(:iid).page(1).per(20)
```
SQL query:
```sql
SELECT "issues".*
FROM "issues"
WHERE
"issues"."project_id" = 5
AND ("issues"."state_id" IN (1))
ORDER BY "issues"."iid" ASC
LIMIT 20
OFFSET 0
```
The index above does not support the following project level query:
```sql
SELECT "issues".*
FROM "issues"
WHERE "issues"."project_id" = 5
ORDER BY "issues"."iid" ASC
LIMIT 20
OFFSET 0
```
#### Special case: confidential flag
In the `issues` table, we have a boolean field (`confidential`) that marks an issue confidential. This makes the issue invisible (filtered out) for non-member users.
Example SQL query:
```sql
SELECT "issues".*
FROM "issues"
WHERE "issues"."project_id" = 5
AND "issues"."confidential" = FALSE
ORDER BY "issues"."iid" ASC
LIMIT 20
OFFSET 0
```
We might be tempted to add an index on `project_id`, `confidential`, and `iid` to improve the database query, however, in this case it's probably unnecessary. Based on the data distribution in the table, confidential issues are rare. Filtering them out does not make the database query significantly slower. The database might read a few extra rows, the performance difference might not even be visible to the end-user.
On the other hand, if we implemented a special filter where we only show confidential issues, we need the index. Finding 20 confidential issues might require the database to scan hundreds of rows or, in the worst case, all issues in the project.
{{< alert type="note" >}}
Be aware of the data distribution and the table access patterns (how features work) when introducing a new database index. Sampling production data might be necessary to make the right decision.
{{< /alert >}}
#### Columns in a different database table
Example: filtering issues in a project by an assignee
```ruby
project = Project.find(5)
project
.issues
.joins(:issue_assignees)
.where(issue_assignees: { user_id: 10 })
.order(:iid)
.page(1)
.per(20)
```
```sql
SELECT "issues".*
FROM "issues"
INNER JOIN "issue_assignees" ON "issue_assignees"."issue_id" = "issues"."id"
WHERE "issues"."project_id" = 5
AND "issue_assignees"."user_id" = 10
ORDER BY "issues"."iid" ASC
LIMIT 20
OFFSET 0
```
Example database (oversimplified) execution plan:
1. The database parses the SQL query and detects the `JOIN`.
1. The database splits the query into two subqueries.
- `SELECT "issue_assignees".* FROM "issue_assignees" WHERE "issue_assignees"."user_id" = 10`
- `SELECT "issues".* FROM "issues" WHERE "issues"."project_id" = 5`
1. The database estimates the number of rows and the costs to run these queries.
1. The database executes the cheapest query first.
1. Using the query result, load the rows from the other table (from the other query) using the `JOIN` column and filter the rows further.
In this particular example, the `issue_assignees` query would likely be executed first.
Running the query in production for the GitLab project produces the following execution plan:
```plaintext
Limit (cost=411.20..411.21 rows=1 width=1300) (actual time=24.071..24.077 rows=20 loops=1)
-> Sort (cost=411.20..411.21 rows=1 width=1300) (actual time=24.070..24.073 rows=20 loops=1)
Sort Key: issues.iid
Sort Method: top-N heapsort Memory: 91kB
-> Nested Loop (cost=1.00..411.19 rows=1 width=1300) (actual time=0.826..23.705 rows=190 loops=1)
-> Index Scan using index_issue_assignees_on_user_id on issue_assignees (cost=0.44..81.37 rows=92 width=4) (actual time=0.741..13.202 rows=215 loops=1)
Index Cond: (user_id = 4156052)
-> Index Scan using issues_pkey on issues (cost=0.56..3.58 rows=1 width=1300) (actual time=0.048..0.048 rows=1 loops=215)
Index Cond: (id = issue_assignees.issue_id)
Filter: (project_id = 278964)
Rows Removed by Filter: 0
Planning Time: 1.141 ms
Execution Time: 24.170 ms
(13 rows)
```
The query looks up the `assignees` first, filtered by the `user_id` (`user_id = 4156052`) and it finds 215 rows. Using those 215 rows, the database looks up the 215 associated issue rows by the primary key. Notice that the filter on the `project_id` column is not backed by an index.
In most cases, joined relations do not return too many rows, and we end up with a relatively efficient database query that accesses a small number of rows. As the database grows, these queries might start to behave differently. For example, a user with a very high number of `issue_assignees` records might cause this join query to perform poorly and time out.
A similar problem could be a double join, where the filter exists in the 2nd `JOIN` query. Example: `Issue -> LabelLink -> Label(name=bug)`.
There is no easy way to fix these problems. Denormalization of data could help significantly, however, it has also negative effects (data duplication and keeping the data up to date).
Ideas for improving the `issue_assignees` filter:
- Add `project_id` column to the `issue_assignees` table so when performing the `JOIN`, the extra `project_id` filter further filters the rows. The sorting likely happens in memory:
```sql
SELECT "issues".*
FROM "issues"
INNER JOIN "issue_assignees" ON "issue_assignees"."issue_id" = "issues"."id"
WHERE "issues"."project_id" = 5
AND "issue_assignees"."user_id" = 10
AND "issue_assignees"."project_id" = 5
ORDER BY "issues"."iid" ASC
LIMIT 20
OFFSET 0
```
- Add the `iid` column to the `issue_assignees` table. Notice that the `ORDER BY` column is different and the `project_id` filter is gone from the `issues` table:
```sql
SELECT "issues".*
FROM "issues"
INNER JOIN "issue_assignees" ON "issue_assignees"."issue_id" = "issues"."id"
WHERE "issue_assignees"."user_id" = 10
AND "issue_assignees"."project_id" = 5
ORDER BY "issue_assignees"."iid" ASC
LIMIT 20
OFFSET 0
```
The query now performs well for any number of `issue_assignees` records, however, we pay a very high price for it:
- Two columns are duplicated which increases the database size.
- We need to keep the two columns in sync.
- We need more indexes on the `issue_assignees` table to support the query.
- The new database query is very specific to the assignee search and needs complex backend code to build it.
- If the assignee is filtered by the user, then order by a different column, remove the `project_id` filter, etc.
{{< alert type="note" >}}
Currently we're not doing these kinds of denormalization at GitLab.
{{< /alert >}}
|
---
stage: Data Access
group: Database Frameworks
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: Pagination performance guidelines
breadcrumbs:
- doc
- development
- database
---
The following document gives a few ideas for improving the pagination (sorting) performance. These apply both on [offset](pagination_guidelines.md#offset-pagination) and [keyset](pagination_guidelines.md#keyset-pagination) pagination.
## Tie-breaker column
When ordering the columns it's advised to order by distinct columns only. Consider the following example:
| `id` | `created_at` |
|------|-----------------------|
| `1` | `2021-01-04 14:13:43` |
| `2` | `2021-01-05 19:03:12` |
| `3` | `2021-01-05 19:03:12` |
If we order by `created_at`, the result would likely depend on how the records are located on the disk.
Using the tie-breaker column is advised when the data is exposed via a well defined interface and its consumed
by an automated process, such as an API. Without the tie-breaker column, the order of the rows could change
(data is re-imported) which could cause problems that are hard to debug, such as:
- An integration comparing the rows to determine changes breaks.
- E-tag cache values change, which requires a complete re-download.
```sql
SELECT issues.* FROM issues ORDER BY created_at;
```
We can fix this by adding a second column to `ORDER BY`:
```sql
SELECT issues.* FROM issues ORDER BY created_at, id;
```
This change makes the order distinct so we have "stable" sorting.
{{< alert type="note" >}}
To make the query efficient, we need an index covering both columns: `(created_at, id)`. The order of the columns **should match** the columns in the `ORDER BY` clause.
{{< /alert >}}
### Incremental sorting
In PostgreSQL 13 incremental sorting was added which can help introducing a tie-breaker column to the `ORDER BY` clause without adding or replacing an index. Also, with incremental sorting, introducing a new keyset-paginated database query can happen before the new index is built (async indexes). Incremental sorting is enabled by default.
Consider the following database query:
```sql
SELECT *
FROM merge_requests
WHERE author_id = 1
ORDER BY created_at ASC
LIMIT 20
```
The query will read 20 rows using the following index:
```plaintext
"index_merge_requests_on_author_id_and_created_at" btree (author_id, created_at)
```
Using this query with keyset pagination is not possible because the `created_at` column is not unique. Let's add a tie-breaker column:
```sql
SELECT *
FROM merge_requests
WHERE author_id = 1
ORDER BY created_at ASC, id ASC
LIMIT 20
```
Execution plan:
```plaintext
Limit (cost=1.99..30.97 rows=20 width=910) (actual time=1.217..1.220 rows=20 loops=1)
Buffers: shared hit=33 read=2
I/O Timings: read=0.983 write=0.000
-> Incremental Sort (cost=1.99..919.33 rows=633 width=910) (actual time=1.215..1.216 rows=20 loops=1)
Sort Key: merge_requests.created_at, merge_requests.id
Buffers: shared hit=33 read=2
I/O Timings: read=0.983 write=0.000
-> Index Scan using index_merge_requests_on_author_id_and_created_at on public.merge_requests (cost=0.57..890.84 rows=633 width=910) (actual time=0.038..1.139 rows=22 loops=1)
Index Cond: (merge_requests.author_id = 1)
Buffers: shared hit=24 read=2
I/O Timings: read=0.983 write=0.000
```
As you can see the query read 22 rows using the same index. The database compared the 20th, 21th and 22th value of the `created_at` column and determined that the 22th value differ thus checking the next record is not needed. In this example the 20th and 21th column had the same `created_at` value.
Incremental sorting works well with timestamp columns where duplicated values are unlikely hence the incremental sorting will perform badly or won't be used at all when the column has very few distinct values (like an enum).
As an example, when incremental sorting is disabled, the database reads all merge requests records by the author and sorts data in memory.
```sql
set enable_incremental_sort=off;
```
```plaintext
Limit (cost=907.69..907.74 rows=20 width=910) (actual time=2.911..2.917 rows=20 loops=1)
Buffers: shared hit=1004
-> Sort (cost=907.69..909.27 rows=633 width=910) (actual time=2.908..2.911 rows=20 loops=1)
Sort Key: created_at, id
Sort Method: top-N heapsort Memory: 52kB
Buffers: shared hit=1004
-> Index Scan using index_merge_requests_on_author_id_and_created_at on merge_requests (cost=0.57..890.84 rows=633 width=910) (actual time=0.042..1.974 rows=1111 loops=1)
Index Cond: (author_id = 1)
Buffers: shared hit=1111
Planning Time: 0.386 ms
Execution Time: 3.000 ms
(11 rows)
```
In this example the database read 1111 rows and sorted the rows in memory.
## Ordering by joined table column
Oftentimes, we want to order the data by a column on a joined database table. The following example orders `issues` records by the `first_mentioned_in_commit_at` metric column:
```sql
SELECT issues.* FROM issues
INNER JOIN issue_metrics on issue_metrics.issue_id=issues.id
WHERE issues.project_id = 2
ORDER BY issue_metrics.first_mentioned_in_commit_at DESC, issues.id DESC
LIMIT 20
OFFSET 0
```
With PostgreSQL version 11, the planner first looks up all issues matching the `project_id` filter and then join all `issue_metrics` rows. The ordering of rows happens in memory. In case the joined relation is always present (1:1 relationship), the database reads `N * 2` rows where N is the number of rows matching the `project_id` filter.
For performance reasons, we should avoid mixing columns from different tables when specifying the `ORDER BY` clause.
In this particular case there is no simple way (like index creation) to improve the query. We might think that changing the `issues.id` column to `issue_metrics.issue_id` helps, however, this likely makes the query perform worse because it might force the database to process all rows in the `issue_metrics` table.
One idea to address this problem is denormalization. Adding the `project_id` column to the `issue_metrics` table makes the filtering and sorting efficient:
```sql
SELECT issues.* FROM issues
INNER JOIN issue_metrics on issue_metrics.issue_id=issues.id
WHERE issue_metrics.project_id = 2
ORDER BY issue_metrics.first_mentioned_in_commit_at DESC, issue_metrics.issue_id DESC
LIMIT 20
OFFSET 0
```
{{< alert type="note" >}}
The query requires an index on `issue_metrics` table with the following column configuration: `(project_id, first_mentioned_in_commit_at DESC, issue_id DESC)`.
{{< /alert >}}
## Filtering
### By project
Filtering by a project is a very common use case since we have many features on the project level. Examples: merge requests, issues, boards, iterations.
These features have a filter on `project_id` in their base query. Loading issues for a project:
```ruby
project = Project.find(5)
# order by internal id
issues = project.issues.order(:iid).page(1).per(20)
```
To make the base query efficient, there is usually a database index covering the `project_id` column. This significantly reduces the number of rows the database needs to scan. Without the index, the whole `issues` table would be read (full table scan) by the database.
Since `project_id` is a foreign key, we might have the following index available:
```sql
"index_issues_on_project_id" btree (project_id)
```
### By group
Unfortunately, there is no efficient way to sort and paginate on the group level. The database query execution time increases based on the number of records in the group.
Things get worse when group level actually means group and its subgroups. To load the first page, the database looks up the group hierarchy, finds all projects, and then looks up all issues.
The main reason behind the inefficient queries on the group level is the way our database schema is designed; our core domain models are associated with a project, and projects are associated with groups. This doesn't mean that the database structure is bad, it's just in a well-normalized form that is not optimized for efficient group level queries. We might need to look into denormalization in the long term.
Example: List issues in a group
```ruby
group = Group.find(9970)
Issue.where(project_id: group.projects).order(:iid).page(1).per(20)
```
The generated SQL query:
```sql
SELECT "issues".*
FROM "issues"
WHERE "issues"."project_id" IN
(SELECT "projects"."id"
FROM "projects"
WHERE "projects"."namespace_id" = 5)
ORDER BY "issues"."iid" ASC
LIMIT 20
OFFSET 0
```
The execution plan shows that we read significantly more rows than requested (20), and the rows are sorted in memory:
```plaintext
Limit (cost=10716.87..10716.92 rows=20 width=1300) (actual time=1472.305..1472.308 rows=20 loops=1)
-> Sort (cost=10716.87..10717.03 rows=61 width=1300) (actual time=1472.303..1472.305 rows=20 loops=1)
Sort Key: issues.iid
Sort Method: top-N heapsort Memory: 41kB
-> Nested Loop (cost=1.00..10715.25 rows=61 width=1300) (actual time=0.215..1331.647 rows=177267 loops=1)
-> Index Only Scan using index_projects_on_namespace_id_and_id on projects (cost=0.44..3.77 rows=19 width=4) (actual time=0.077..1.057 rows=270 loops=1)
Index Cond: (namespace_id = 9970)
Heap Fetches: 25
-> Index Scan using index_issues_on_project_id_and_iid on issues (cost=0.56..559.28 rows=448 width=1300) (actual time=0.101..4.781 rows=657 loops=270)
Index Cond: (project_id = projects.id)
Planning Time: 12.281 ms
Execution Time: 1472.391 ms
(12 rows)
```
#### Columns in the same database table
Filtering by columns located in the same database table can be improved with an index. In case we want to support filtering by the `state_id` column, we can add the following index:
```sql
"index_issues_on_project_id_and_state_id_and_iid" UNIQUE, btree (project_id, state_id, iid)
```
Example query in Rails:
```ruby
project = Project.find(5)
# order by internal id
issues = project.issues.opened.order(:iid).page(1).per(20)
```
SQL query:
```sql
SELECT "issues".*
FROM "issues"
WHERE
"issues"."project_id" = 5
AND ("issues"."state_id" IN (1))
ORDER BY "issues"."iid" ASC
LIMIT 20
OFFSET 0
```
The index above does not support the following project level query:
```sql
SELECT "issues".*
FROM "issues"
WHERE "issues"."project_id" = 5
ORDER BY "issues"."iid" ASC
LIMIT 20
OFFSET 0
```
#### Special case: confidential flag
In the `issues` table, we have a boolean field (`confidential`) that marks an issue confidential. This makes the issue invisible (filtered out) for non-member users.
Example SQL query:
```sql
SELECT "issues".*
FROM "issues"
WHERE "issues"."project_id" = 5
AND "issues"."confidential" = FALSE
ORDER BY "issues"."iid" ASC
LIMIT 20
OFFSET 0
```
We might be tempted to add an index on `project_id`, `confidential`, and `iid` to improve the database query, however, in this case it's probably unnecessary. Based on the data distribution in the table, confidential issues are rare. Filtering them out does not make the database query significantly slower. The database might read a few extra rows, the performance difference might not even be visible to the end-user.
On the other hand, if we implemented a special filter where we only show confidential issues, we need the index. Finding 20 confidential issues might require the database to scan hundreds of rows or, in the worst case, all issues in the project.
{{< alert type="note" >}}
Be aware of the data distribution and the table access patterns (how features work) when introducing a new database index. Sampling production data might be necessary to make the right decision.
{{< /alert >}}
#### Columns in a different database table
Example: filtering issues in a project by an assignee
```ruby
project = Project.find(5)
project
.issues
.joins(:issue_assignees)
.where(issue_assignees: { user_id: 10 })
.order(:iid)
.page(1)
.per(20)
```
```sql
SELECT "issues".*
FROM "issues"
INNER JOIN "issue_assignees" ON "issue_assignees"."issue_id" = "issues"."id"
WHERE "issues"."project_id" = 5
AND "issue_assignees"."user_id" = 10
ORDER BY "issues"."iid" ASC
LIMIT 20
OFFSET 0
```
Example database (oversimplified) execution plan:
1. The database parses the SQL query and detects the `JOIN`.
1. The database splits the query into two subqueries.
- `SELECT "issue_assignees".* FROM "issue_assignees" WHERE "issue_assignees"."user_id" = 10`
- `SELECT "issues".* FROM "issues" WHERE "issues"."project_id" = 5`
1. The database estimates the number of rows and the costs to run these queries.
1. The database executes the cheapest query first.
1. Using the query result, load the rows from the other table (from the other query) using the `JOIN` column and filter the rows further.
In this particular example, the `issue_assignees` query would likely be executed first.
Running the query in production for the GitLab project produces the following execution plan:
```plaintext
Limit (cost=411.20..411.21 rows=1 width=1300) (actual time=24.071..24.077 rows=20 loops=1)
-> Sort (cost=411.20..411.21 rows=1 width=1300) (actual time=24.070..24.073 rows=20 loops=1)
Sort Key: issues.iid
Sort Method: top-N heapsort Memory: 91kB
-> Nested Loop (cost=1.00..411.19 rows=1 width=1300) (actual time=0.826..23.705 rows=190 loops=1)
-> Index Scan using index_issue_assignees_on_user_id on issue_assignees (cost=0.44..81.37 rows=92 width=4) (actual time=0.741..13.202 rows=215 loops=1)
Index Cond: (user_id = 4156052)
-> Index Scan using issues_pkey on issues (cost=0.56..3.58 rows=1 width=1300) (actual time=0.048..0.048 rows=1 loops=215)
Index Cond: (id = issue_assignees.issue_id)
Filter: (project_id = 278964)
Rows Removed by Filter: 0
Planning Time: 1.141 ms
Execution Time: 24.170 ms
(13 rows)
```
The query looks up the `assignees` first, filtered by the `user_id` (`user_id = 4156052`) and it finds 215 rows. Using those 215 rows, the database looks up the 215 associated issue rows by the primary key. Notice that the filter on the `project_id` column is not backed by an index.
In most cases, joined relations do not return too many rows, and we end up with a relatively efficient database query that accesses a small number of rows. As the database grows, these queries might start to behave differently. For example, a user with a very high number of `issue_assignees` records might cause this join query to perform poorly and time out.
A similar problem could be a double join, where the filter exists in the 2nd `JOIN` query. Example: `Issue -> LabelLink -> Label(name=bug)`.
There is no easy way to fix these problems. Denormalization of data could help significantly, however, it has also negative effects (data duplication and keeping the data up to date).
Ideas for improving the `issue_assignees` filter:
- Add `project_id` column to the `issue_assignees` table so when performing the `JOIN`, the extra `project_id` filter further filters the rows. The sorting likely happens in memory:
```sql
SELECT "issues".*
FROM "issues"
INNER JOIN "issue_assignees" ON "issue_assignees"."issue_id" = "issues"."id"
WHERE "issues"."project_id" = 5
AND "issue_assignees"."user_id" = 10
AND "issue_assignees"."project_id" = 5
ORDER BY "issues"."iid" ASC
LIMIT 20
OFFSET 0
```
- Add the `iid` column to the `issue_assignees` table. Notice that the `ORDER BY` column is different and the `project_id` filter is gone from the `issues` table:
```sql
SELECT "issues".*
FROM "issues"
INNER JOIN "issue_assignees" ON "issue_assignees"."issue_id" = "issues"."id"
WHERE "issue_assignees"."user_id" = 10
AND "issue_assignees"."project_id" = 5
ORDER BY "issue_assignees"."iid" ASC
LIMIT 20
OFFSET 0
```
The query now performs well for any number of `issue_assignees` records, however, we pay a very high price for it:
- Two columns are duplicated which increases the database size.
- We need to keep the two columns in sync.
- We need more indexes on the `issue_assignees` table to support the query.
- The new database query is very specific to the assignee search and needs complex backend code to build it.
- If the assignee is filtered by the user, then order by a different column, remove the `project_id` filter, etc.
{{< alert type="note" >}}
Currently we're not doing these kinds of denormalization at GitLab.
{{< /alert >}}
|
https://docs.gitlab.com/development/poc_tree_iterator
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/poc_tree_iterator.md
|
2025-08-13
|
doc/development/database
|
[
"doc",
"development",
"database"
] |
poc_tree_iterator.md
|
Data Access
|
Database Frameworks
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Batch iteration in a tree hierarchy (proof of concept)
| null |
The group hierarchy in GitLab is represented with a tree, where the root element
is the top-level namespace, and the child elements are the subgroups or the
recently introduced `Namespaces::ProjectNamespace` records.
The tree is implemented in the `namespaces` table ,via the `parent_id` column.
The column points to the parent namespace record. The top level namespace has no
`parent_id`.
Partial hierarchy of `gitlab-org`:
```mermaid
flowchart TD
A("gitlab-org (9979)") --- B("quality (2750817)")
B --- C("engineering-productivity (16947798)")
B --- D("performance-testing (9453799)")
A --- F("charts (5032027)")
A --- E("ruby (14018648)")
```
Efficiently iterating over the group hierarchy has several potential use cases.
This is true especially in background jobs, which need to perform queries on the group hierarchy,
where stable and safe execution is more important than fast runtime. Batch iteration
requires more network round-trips, but each batch provides similar performance
characteristics.
A few examples:
- For each subgroup, do something.
- For each project in the hierarchy, do something.
- For each issue in the hierarchy, do something.
## Problem statement
A group hierarchy could grow so big that a single query would not be able to load
it in time. The query would fail with statement timeout error.
Addressing scalability issues related to very large groups requires us to store
the same data in different formats (de-normalization). However, if we're unable
to load the group hierarchy, then de-normalization could not be implemented.
One de-normalization technique would be to store all descendant group IDs for a
given group. This would speed up queries where we need to load the group and its
subgroups. Example:
```mermaid
flowchart TD
A(1) --- B(2)
A --- C(3)
C --- D(4)
```
| GROUP_ID | DESCENDANT_GROUP_IDS |
|----------|------------------------|
| 1 | `[2,3,4]` |
| 2 | `[]` |
| 3 | `[4]` |
| 4 | `[]` |
With this structure, determining all the subgroups would require us to read only
one row from the database, instead of 4 rows. For a hierarchy as big as 1000 groups,
this could make a huge difference.
The reading of the hierarchy problem is solved with this de-normalization. However,
we still need to find a way to persist this data in a table. Because a group and
its hierarchy could grow very large, we cannot expect a single query to work here.
```sql
SELECT id FROM namespaces WHERE traversal_ids && ARRAY[9970]
```
The query above could time out for large groups, so we need to process the data in batches.
Implementing batching logic in a tree is not something we've looked at before,
and it's fairly complex to implement. An `EachBatch` or `find_in_batches` based
solution would not work because:
- The data (group IDs) are not sorted in the hierarchy.
- Groups in subgroups don't know about the top-level group ID.
## Algorithm
The batching query is implemented as a recursive CTE SQL query, where one batch
would read a maximum of N rows. Due to the tree structure, reading N rows might
not necessarily mean that we're reading N group IDs. If the tree is structured in
a non-optimal way, a batch could return less (but never more) group IDs.
The query implements a [depth-first](https://en.wikipedia.org/wiki/Depth-first_search)
tree walking logic, where the DB scans the first branch of the tree until the leaf
element. We're implementing depth-first algorithm because, when a batch is finished,
the query must return enough information for the next batch (cursor). In GitLab,
we limit the depth of the tree to 20, which means that in the worst case, the
query would return a cursor containing 19 elements.
Implementing a [breadth-first](https://en.wikipedia.org/wiki/Breadth-first_search)
tree walking algorithm would be impractical, because a group can have unbounded
number of descendants, thus we might end up with a huge cursor.
1. Create an initializer row that contains:
1. The currently processed group ID (top-level group ID)
1. Two arrays (tree depth and the collected IDs)
1. A counter for tracking the number of row reads in the query.
1. Recursively process the row and do one of the following (whenever the condition matches):
- Load the first child namespace and update the currently processed namespace
ID if we're not at the leaf node. (Walking down a branch)
- Load the next namespace record on the current depth if there are any rows left.
- Walk up one node and process rows at one level higher.
1. Continue the processing until the number of reads reaches our `LIMIT` (batch size).
1. Find the last processed row which contains the data for the cursor, and all the collected record IDs.
```sql
WITH RECURSIVE result AS (
(
SELECT
9970 AS current_id, /* current namespace id we're processing */
ARRAY[9970]::int[] AS depth, /* cursor */
ARRAY[9970]::int[] AS ids, /* collected ids */
1::bigint AS reads,
'initialize' AS action
) UNION ALL
(
WITH cte AS ( /* trick for referencing the result cte multiple times */
select * FROM result
)
SELECT * FROM (
(
SELECT /* walk down the branch */
namespaces.id,
cte.depth || namespaces.id,
cte.ids || namespaces.id,
cte.reads + 1,
'walkdown'
FROM namespaces, cte
WHERE
namespaces.parent_id = cte.current_id
ORDER BY namespaces.id ASC
LIMIT 1
) UNION ALL
(
SELECT /* find next element on the same level */
namespaces.id,
cte.depth[:array_length(cte.depth, 1) - 1] || namespaces.id,
cte.ids || namespaces.id,
cte.reads + 1,
'next'
FROM namespaces, cte
WHERE
namespaces.parent_id = cte.depth[array_length(cte.depth, 1) - 1] AND
namespaces.id > cte.depth[array_length(cte.depth, 1)]
ORDER BY namespaces.id ASC
LIMIT 1
) UNION ALL
(
SELECT /* jump up one node when finished with the current level */
cte.current_id,
cte.depth[:array_length(cte.depth, 1) - 1],
cte.ids,
cte.reads + 1,
'jump'
FROM cte
WHERE cte.depth <> ARRAY[]::int[]
LIMIT 1
)
) next_row LIMIT 1
)
)
SELECT current_id, depth, ids, action
FROM result
```
```plaintext
current_id | depth | ids | action
------------+--------------+------------------------+------------
24 | {24} | {24} | initialize
25 | {24,25} | {24,25} | walkdown
26 | {24,26} | {24,25,26} | next
112 | {24,112} | {24,25,26,112} | next
113 | {24,113} | {24,25,26,112,113} | next
114 | {24,113,114} | {24,25,26,112,113,114} | walkdown
114 | {24,113} | {24,25,26,112,113,114} | jump
114 | {24} | {24,25,26,112,113,114} | jump
114 | {} | {24,25,26,112,113,114} | jump
```
{{< alert type="note" >}}
Using this query to find all the namespace IDs in a group hierarchy is likely slower
than other querying methods, such as the current `self_and_descendants` implementation
based on the `traversal_ids` column. The query above should be only used when
implementing batch iteration over the group hierarchy.
{{< /alert >}}
Rudimentary batching implementation in Ruby:
```ruby
class NamespaceEachBatch
def initialize(namespace_id:, cursor: nil)
@namespace_id = namespace_id
@cursor = cursor || { current_id: namespace_id, depth: [namespace_id] }
end
def each_batch(of: 500)
current_cursor = cursor.dup
first_iteration = true
loop do
new_cursor, ids = load_batch(cursor: current_cursor, of: of, first_iteration: first_iteration)
first_iteration = false
current_cursor = new_cursor
yield ids
break if new_cursor[:depth].empty?
end
end
private
# yields array of namespace ids
def load_batch(cursor:, of:, first_iteration: false)
recursive_cte = Gitlab::SQL::RecursiveCTE.new(:result,
union_args: { remove_order: false, remove_duplicates: false })
ids = first_iteration ? namespace_id.to_s : ""
recursive_cte << Namespace.select(
Arel.sql(Integer(cursor.fetch(:current_id)).to_s).as('current_id'),
Arel.sql("ARRAY[#{cursor.fetch(:depth).join(',')}]::int[]").as('depth'),
Arel.sql("ARRAY[#{ids}]::int[]").as('ids'),
Arel.sql("1::bigint AS count")
).from('(VALUES (1)) AS does_not_matter').limit(1)
cte = Gitlab::SQL::CTE.new(:cte, Namespace.select('*').from('result'))
union_query = Namespace.with(cte.to_arel).from_union(
walk_down,
next_elements,
up_one_level,
remove_duplicates: false,
remove_order: false
).select('current_id', 'depth', 'ids', 'count').limit(1)
recursive_cte << union_query
scope = Namespace.with
.recursive(recursive_cte.to_arel)
.from(recursive_cte.alias_to(Namespace.arel_table))
.limit(of)
row = Namespace.from(scope.arel.as('namespaces')).order(count: :desc).limit(1).first
[
{ current_id: row[:current_id], depth: row[:depth] },
row[:ids]
]
end
attr_reader :namespace_id, :cursor
def walk_down
Namespace.select(
Arel.sql('namespaces.id').as('current_id'),
Arel.sql('cte.depth || namespaces.id').as('depth'),
Arel.sql('cte.ids || namespaces.id').as('ids'),
Arel.sql('cte.count + 1').as('count')
).from('cte, LATERAL (SELECT id FROM namespaces WHERE parent_id = cte.current_id ORDER BY id LIMIT 1) namespaces')
end
def next_elements
Namespace.select(
Arel.sql('namespaces.id').as('current_id'),
Arel.sql('cte.depth[:array_length(cte.depth, 1) - 1] || namespaces.id').as('depth'),
Arel.sql('cte.ids || namespaces.id').as('ids'),
Arel.sql('cte.count + 1').as('count')
).from('cte, LATERAL (SELECT id FROM namespaces WHERE namespaces.parent_id = cte.depth[array_length(cte.depth, 1) - 1] AND namespaces.id > cte.depth[array_length(cte.depth, 1)] ORDER BY id LIMIT 1) namespaces')
end
def up_one_level
Namespace.select(
Arel.sql('cte.current_id').as('current_id'),
Arel.sql('cte.depth[:array_length(cte.depth, 1) - 1]').as('depth'),
Arel.sql('cte.ids').as('ids'),
Arel.sql('cte.count + 1').as('count')
).from('cte')
.where('cte.depth <> ARRAY[]::int[]')
.limit(1)
end
end
iterator = NamespaceEachBatch.new(namespace_id: 9970)
all_ids = []
iterator.each_batch do |ids|
all_ids.concat(ids)
end
# Test
puts all_ids.count
puts all_ids.sort == Namespace.where('traversal_ids && ARRAY[9970]').pluck(:id).sort
```
Example batch query:
```sql
SELECT
"namespaces".*
FROM ( WITH RECURSIVE "result" AS ((
SELECT
15847356 AS current_id,
ARRAY[9970,
12061481,
12128714,
12445111,
15847356]::int[] AS depth,
ARRAY[]::int[] AS ids,
1::bigint AS count
FROM (
VALUES (1)) AS does_not_matter
LIMIT 1)
UNION ALL ( WITH "cte" AS MATERIALIZED (
SELECT
*
FROM
result
)
SELECT
current_id,
depth,
ids,
count
FROM ((
SELECT
namespaces.id AS current_id,
cte.depth || namespaces.id AS depth,
cte.ids || namespaces.id AS ids,
cte.count + 1 AS count
FROM
cte,
LATERAL (
SELECT
id
FROM
namespaces
WHERE
parent_id = cte.current_id
ORDER BY
id
LIMIT 1
) namespaces
)
UNION ALL (
SELECT
namespaces.id AS current_id,
cte.depth[:array_length(
cte.depth, 1
) - 1] || namespaces.id AS depth,
cte.ids || namespaces.id AS ids,
cte.count + 1 AS count
FROM
cte,
LATERAL (
SELECT
id
FROM
namespaces
WHERE
namespaces.parent_id = cte.depth[array_length(
cte.depth, 1
) - 1]
AND namespaces.id > cte.depth[array_length(
cte.depth, 1
)]
ORDER BY
id
LIMIT 1
) namespaces
)
UNION ALL (
SELECT
cte.current_id AS current_id,
cte.depth[:array_length(
cte.depth, 1
) - 1] AS depth,
cte.ids AS ids,
cte.count + 1 AS count
FROM
cte
WHERE (
cte.depth <> ARRAY[]::int[]
)
LIMIT 1
)
) namespaces
LIMIT 1
))
SELECT
"namespaces".*
FROM
"result" AS "namespaces"
LIMIT 500) namespaces
ORDER BY
"count" DESC
LIMIT 1
```
Execution plan:
```plaintext
Limit (cost=16.36..16.36 rows=1 width=76) (actual time=436.963..436.970 rows=1 loops=1)
Buffers: shared hit=3721 read=423 dirtied=8
I/O Timings: read=412.590 write=0.000
-> Sort (cost=16.36..16.39 rows=11 width=76) (actual time=436.961..436.968 rows=1 loops=1)
Sort Key: namespaces.count DESC
Sort Method: top-N heapsort Memory: 27kB
Buffers: shared hit=3721 read=423 dirtied=8
I/O Timings: read=412.590 write=0.000
-> Limit (cost=15.98..16.20 rows=11 width=76) (actual time=0.005..436.394 rows=500 loops=1)
Buffers: shared hit=3718 read=423 dirtied=8
I/O Timings: read=412.590 write=0.000
CTE result
-> Recursive Union (cost=0.00..15.98 rows=11 width=76) (actual time=0.003..432.924 rows=500 loops=1)
Buffers: shared hit=3718 read=423 dirtied=8
I/O Timings: read=412.590 write=0.000
-> Limit (cost=0.00..0.01 rows=1 width=76) (actual time=0.002..0.003 rows=1 loops=1)
I/O Timings: read=0.000 write=0.000
-> Result (cost=0.00..0.01 rows=1 width=76) (actual time=0.001..0.002 rows=1 loops=1)
I/O Timings: read=0.000 write=0.000
-> Limit (cost=0.76..1.57 rows=1 width=76) (actual time=0.862..0.862 rows=1 loops=499)
Buffers: shared hit=3718 read=423 dirtied=8
I/O Timings: read=412.590 write=0.000
CTE cte
-> WorkTable Scan on result (cost=0.00..0.20 rows=10 width=76) (actual time=0.000..0.000 rows=1 loops=499)
I/O Timings: read=0.000 write=0.000
-> Append (cost=0.56..17.57 rows=21 width=76) (actual time=0.862..0.862 rows=1 loops=499)
Buffers: shared hit=3718 read=423 dirtied=8
I/O Timings: read=412.590 write=0.000
-> Nested Loop (cost=0.56..7.77 rows=10 width=76) (actual time=0.675..0.675 rows=0 loops=499)
Buffers: shared hit=1693 read=357 dirtied=1
I/O Timings: read=327.812 write=0.000
-> CTE Scan on cte (cost=0.00..0.20 rows=10 width=76) (actual time=0.001..0.001 rows=1 loops=499)
I/O Timings: read=0.000 write=0.000
-> Limit (cost=0.56..0.73 rows=1 width=4) (actual time=0.672..0.672 rows=0 loops=499)
Buffers: shared hit=1693 read=357 dirtied=1
I/O Timings: read=327.812 write=0.000
-> Index Only Scan using index_namespaces_on_parent_id_and_id on public.namespaces namespaces_1 (cost=0.56..5.33 rows=29 width=4) (actual time=0.671..0.671 rows=0 loops=499)
Index Cond: (namespaces_1.parent_id = cte.current_id)
Heap Fetches: 7
Buffers: shared hit=1693 read=357 dirtied=1
I/O Timings: read=327.812 write=0.000
-> Nested Loop (cost=0.57..9.45 rows=10 width=76) (actual time=0.208..0.208 rows=1 loops=442)
Buffers: shared hit=2025 read=66 dirtied=7
I/O Timings: read=84.778 write=0.000
-> CTE Scan on cte cte_1 (cost=0.00..0.20 rows=10 width=72) (actual time=0.000..0.000 rows=1 loops=442)
I/O Timings: read=0.000 write=0.000
-> Limit (cost=0.57..0.89 rows=1 width=4) (actual time=0.203..0.203 rows=1 loops=442)
Buffers: shared hit=2025 read=66 dirtied=7
I/O Timings: read=84.778 write=0.000
-> Index Only Scan using index_namespaces_on_parent_id_and_id on public.namespaces namespaces_2 (cost=0.57..3.77 rows=10 width=4) (actual time=0.201..0.201 rows=1 loops=442)
Index Cond: ((namespaces_2.parent_id = (cte_1.depth)[(array_length(cte_1.depth, 1) - 1)]) AND (namespaces_2.id > (cte_1.depth)[array_length(cte_1.depth, 1)]))
Heap Fetches: 35
Buffers: shared hit=2025 read=66 dirtied=6
I/O Timings: read=84.778 write=0.000
-> Limit (cost=0.00..0.03 rows=1 width=76) (actual time=0.003..0.003 rows=1 loops=59)
I/O Timings: read=0.000 write=0.000
-> CTE Scan on cte cte_2 (cost=0.00..0.29 rows=9 width=76) (actual time=0.002..0.002 rows=1 loops=59)
Filter: (cte_2.depth <> '{}'::integer[])
Rows Removed by Filter: 0
I/O Timings: read=0.000 write=0.000
-> CTE Scan on result namespaces (cost=0.00..0.22 rows=11 width=76) (actual time=0.005..436.240 rows=500 loops=1)
Buffers: shared hit=3718 read=423 dirtied=8
I/O Timings: read=412.590 write=0.000
```
|
---
stage: Data Access
group: Database Frameworks
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: Batch iteration in a tree hierarchy (proof of concept)
breadcrumbs:
- doc
- development
- database
---
The group hierarchy in GitLab is represented with a tree, where the root element
is the top-level namespace, and the child elements are the subgroups or the
recently introduced `Namespaces::ProjectNamespace` records.
The tree is implemented in the `namespaces` table ,via the `parent_id` column.
The column points to the parent namespace record. The top level namespace has no
`parent_id`.
Partial hierarchy of `gitlab-org`:
```mermaid
flowchart TD
A("gitlab-org (9979)") --- B("quality (2750817)")
B --- C("engineering-productivity (16947798)")
B --- D("performance-testing (9453799)")
A --- F("charts (5032027)")
A --- E("ruby (14018648)")
```
Efficiently iterating over the group hierarchy has several potential use cases.
This is true especially in background jobs, which need to perform queries on the group hierarchy,
where stable and safe execution is more important than fast runtime. Batch iteration
requires more network round-trips, but each batch provides similar performance
characteristics.
A few examples:
- For each subgroup, do something.
- For each project in the hierarchy, do something.
- For each issue in the hierarchy, do something.
## Problem statement
A group hierarchy could grow so big that a single query would not be able to load
it in time. The query would fail with statement timeout error.
Addressing scalability issues related to very large groups requires us to store
the same data in different formats (de-normalization). However, if we're unable
to load the group hierarchy, then de-normalization could not be implemented.
One de-normalization technique would be to store all descendant group IDs for a
given group. This would speed up queries where we need to load the group and its
subgroups. Example:
```mermaid
flowchart TD
A(1) --- B(2)
A --- C(3)
C --- D(4)
```
| GROUP_ID | DESCENDANT_GROUP_IDS |
|----------|------------------------|
| 1 | `[2,3,4]` |
| 2 | `[]` |
| 3 | `[4]` |
| 4 | `[]` |
With this structure, determining all the subgroups would require us to read only
one row from the database, instead of 4 rows. For a hierarchy as big as 1000 groups,
this could make a huge difference.
The reading of the hierarchy problem is solved with this de-normalization. However,
we still need to find a way to persist this data in a table. Because a group and
its hierarchy could grow very large, we cannot expect a single query to work here.
```sql
SELECT id FROM namespaces WHERE traversal_ids && ARRAY[9970]
```
The query above could time out for large groups, so we need to process the data in batches.
Implementing batching logic in a tree is not something we've looked at before,
and it's fairly complex to implement. An `EachBatch` or `find_in_batches` based
solution would not work because:
- The data (group IDs) are not sorted in the hierarchy.
- Groups in subgroups don't know about the top-level group ID.
## Algorithm
The batching query is implemented as a recursive CTE SQL query, where one batch
would read a maximum of N rows. Due to the tree structure, reading N rows might
not necessarily mean that we're reading N group IDs. If the tree is structured in
a non-optimal way, a batch could return less (but never more) group IDs.
The query implements a [depth-first](https://en.wikipedia.org/wiki/Depth-first_search)
tree walking logic, where the DB scans the first branch of the tree until the leaf
element. We're implementing depth-first algorithm because, when a batch is finished,
the query must return enough information for the next batch (cursor). In GitLab,
we limit the depth of the tree to 20, which means that in the worst case, the
query would return a cursor containing 19 elements.
Implementing a [breadth-first](https://en.wikipedia.org/wiki/Breadth-first_search)
tree walking algorithm would be impractical, because a group can have unbounded
number of descendants, thus we might end up with a huge cursor.
1. Create an initializer row that contains:
1. The currently processed group ID (top-level group ID)
1. Two arrays (tree depth and the collected IDs)
1. A counter for tracking the number of row reads in the query.
1. Recursively process the row and do one of the following (whenever the condition matches):
- Load the first child namespace and update the currently processed namespace
ID if we're not at the leaf node. (Walking down a branch)
- Load the next namespace record on the current depth if there are any rows left.
- Walk up one node and process rows at one level higher.
1. Continue the processing until the number of reads reaches our `LIMIT` (batch size).
1. Find the last processed row which contains the data for the cursor, and all the collected record IDs.
```sql
WITH RECURSIVE result AS (
(
SELECT
9970 AS current_id, /* current namespace id we're processing */
ARRAY[9970]::int[] AS depth, /* cursor */
ARRAY[9970]::int[] AS ids, /* collected ids */
1::bigint AS reads,
'initialize' AS action
) UNION ALL
(
WITH cte AS ( /* trick for referencing the result cte multiple times */
select * FROM result
)
SELECT * FROM (
(
SELECT /* walk down the branch */
namespaces.id,
cte.depth || namespaces.id,
cte.ids || namespaces.id,
cte.reads + 1,
'walkdown'
FROM namespaces, cte
WHERE
namespaces.parent_id = cte.current_id
ORDER BY namespaces.id ASC
LIMIT 1
) UNION ALL
(
SELECT /* find next element on the same level */
namespaces.id,
cte.depth[:array_length(cte.depth, 1) - 1] || namespaces.id,
cte.ids || namespaces.id,
cte.reads + 1,
'next'
FROM namespaces, cte
WHERE
namespaces.parent_id = cte.depth[array_length(cte.depth, 1) - 1] AND
namespaces.id > cte.depth[array_length(cte.depth, 1)]
ORDER BY namespaces.id ASC
LIMIT 1
) UNION ALL
(
SELECT /* jump up one node when finished with the current level */
cte.current_id,
cte.depth[:array_length(cte.depth, 1) - 1],
cte.ids,
cte.reads + 1,
'jump'
FROM cte
WHERE cte.depth <> ARRAY[]::int[]
LIMIT 1
)
) next_row LIMIT 1
)
)
SELECT current_id, depth, ids, action
FROM result
```
```plaintext
current_id | depth | ids | action
------------+--------------+------------------------+------------
24 | {24} | {24} | initialize
25 | {24,25} | {24,25} | walkdown
26 | {24,26} | {24,25,26} | next
112 | {24,112} | {24,25,26,112} | next
113 | {24,113} | {24,25,26,112,113} | next
114 | {24,113,114} | {24,25,26,112,113,114} | walkdown
114 | {24,113} | {24,25,26,112,113,114} | jump
114 | {24} | {24,25,26,112,113,114} | jump
114 | {} | {24,25,26,112,113,114} | jump
```
{{< alert type="note" >}}
Using this query to find all the namespace IDs in a group hierarchy is likely slower
than other querying methods, such as the current `self_and_descendants` implementation
based on the `traversal_ids` column. The query above should be only used when
implementing batch iteration over the group hierarchy.
{{< /alert >}}
Rudimentary batching implementation in Ruby:
```ruby
class NamespaceEachBatch
def initialize(namespace_id:, cursor: nil)
@namespace_id = namespace_id
@cursor = cursor || { current_id: namespace_id, depth: [namespace_id] }
end
def each_batch(of: 500)
current_cursor = cursor.dup
first_iteration = true
loop do
new_cursor, ids = load_batch(cursor: current_cursor, of: of, first_iteration: first_iteration)
first_iteration = false
current_cursor = new_cursor
yield ids
break if new_cursor[:depth].empty?
end
end
private
# yields array of namespace ids
def load_batch(cursor:, of:, first_iteration: false)
recursive_cte = Gitlab::SQL::RecursiveCTE.new(:result,
union_args: { remove_order: false, remove_duplicates: false })
ids = first_iteration ? namespace_id.to_s : ""
recursive_cte << Namespace.select(
Arel.sql(Integer(cursor.fetch(:current_id)).to_s).as('current_id'),
Arel.sql("ARRAY[#{cursor.fetch(:depth).join(',')}]::int[]").as('depth'),
Arel.sql("ARRAY[#{ids}]::int[]").as('ids'),
Arel.sql("1::bigint AS count")
).from('(VALUES (1)) AS does_not_matter').limit(1)
cte = Gitlab::SQL::CTE.new(:cte, Namespace.select('*').from('result'))
union_query = Namespace.with(cte.to_arel).from_union(
walk_down,
next_elements,
up_one_level,
remove_duplicates: false,
remove_order: false
).select('current_id', 'depth', 'ids', 'count').limit(1)
recursive_cte << union_query
scope = Namespace.with
.recursive(recursive_cte.to_arel)
.from(recursive_cte.alias_to(Namespace.arel_table))
.limit(of)
row = Namespace.from(scope.arel.as('namespaces')).order(count: :desc).limit(1).first
[
{ current_id: row[:current_id], depth: row[:depth] },
row[:ids]
]
end
attr_reader :namespace_id, :cursor
def walk_down
Namespace.select(
Arel.sql('namespaces.id').as('current_id'),
Arel.sql('cte.depth || namespaces.id').as('depth'),
Arel.sql('cte.ids || namespaces.id').as('ids'),
Arel.sql('cte.count + 1').as('count')
).from('cte, LATERAL (SELECT id FROM namespaces WHERE parent_id = cte.current_id ORDER BY id LIMIT 1) namespaces')
end
def next_elements
Namespace.select(
Arel.sql('namespaces.id').as('current_id'),
Arel.sql('cte.depth[:array_length(cte.depth, 1) - 1] || namespaces.id').as('depth'),
Arel.sql('cte.ids || namespaces.id').as('ids'),
Arel.sql('cte.count + 1').as('count')
).from('cte, LATERAL (SELECT id FROM namespaces WHERE namespaces.parent_id = cte.depth[array_length(cte.depth, 1) - 1] AND namespaces.id > cte.depth[array_length(cte.depth, 1)] ORDER BY id LIMIT 1) namespaces')
end
def up_one_level
Namespace.select(
Arel.sql('cte.current_id').as('current_id'),
Arel.sql('cte.depth[:array_length(cte.depth, 1) - 1]').as('depth'),
Arel.sql('cte.ids').as('ids'),
Arel.sql('cte.count + 1').as('count')
).from('cte')
.where('cte.depth <> ARRAY[]::int[]')
.limit(1)
end
end
iterator = NamespaceEachBatch.new(namespace_id: 9970)
all_ids = []
iterator.each_batch do |ids|
all_ids.concat(ids)
end
# Test
puts all_ids.count
puts all_ids.sort == Namespace.where('traversal_ids && ARRAY[9970]').pluck(:id).sort
```
Example batch query:
```sql
SELECT
"namespaces".*
FROM ( WITH RECURSIVE "result" AS ((
SELECT
15847356 AS current_id,
ARRAY[9970,
12061481,
12128714,
12445111,
15847356]::int[] AS depth,
ARRAY[]::int[] AS ids,
1::bigint AS count
FROM (
VALUES (1)) AS does_not_matter
LIMIT 1)
UNION ALL ( WITH "cte" AS MATERIALIZED (
SELECT
*
FROM
result
)
SELECT
current_id,
depth,
ids,
count
FROM ((
SELECT
namespaces.id AS current_id,
cte.depth || namespaces.id AS depth,
cte.ids || namespaces.id AS ids,
cte.count + 1 AS count
FROM
cte,
LATERAL (
SELECT
id
FROM
namespaces
WHERE
parent_id = cte.current_id
ORDER BY
id
LIMIT 1
) namespaces
)
UNION ALL (
SELECT
namespaces.id AS current_id,
cte.depth[:array_length(
cte.depth, 1
) - 1] || namespaces.id AS depth,
cte.ids || namespaces.id AS ids,
cte.count + 1 AS count
FROM
cte,
LATERAL (
SELECT
id
FROM
namespaces
WHERE
namespaces.parent_id = cte.depth[array_length(
cte.depth, 1
) - 1]
AND namespaces.id > cte.depth[array_length(
cte.depth, 1
)]
ORDER BY
id
LIMIT 1
) namespaces
)
UNION ALL (
SELECT
cte.current_id AS current_id,
cte.depth[:array_length(
cte.depth, 1
) - 1] AS depth,
cte.ids AS ids,
cte.count + 1 AS count
FROM
cte
WHERE (
cte.depth <> ARRAY[]::int[]
)
LIMIT 1
)
) namespaces
LIMIT 1
))
SELECT
"namespaces".*
FROM
"result" AS "namespaces"
LIMIT 500) namespaces
ORDER BY
"count" DESC
LIMIT 1
```
Execution plan:
```plaintext
Limit (cost=16.36..16.36 rows=1 width=76) (actual time=436.963..436.970 rows=1 loops=1)
Buffers: shared hit=3721 read=423 dirtied=8
I/O Timings: read=412.590 write=0.000
-> Sort (cost=16.36..16.39 rows=11 width=76) (actual time=436.961..436.968 rows=1 loops=1)
Sort Key: namespaces.count DESC
Sort Method: top-N heapsort Memory: 27kB
Buffers: shared hit=3721 read=423 dirtied=8
I/O Timings: read=412.590 write=0.000
-> Limit (cost=15.98..16.20 rows=11 width=76) (actual time=0.005..436.394 rows=500 loops=1)
Buffers: shared hit=3718 read=423 dirtied=8
I/O Timings: read=412.590 write=0.000
CTE result
-> Recursive Union (cost=0.00..15.98 rows=11 width=76) (actual time=0.003..432.924 rows=500 loops=1)
Buffers: shared hit=3718 read=423 dirtied=8
I/O Timings: read=412.590 write=0.000
-> Limit (cost=0.00..0.01 rows=1 width=76) (actual time=0.002..0.003 rows=1 loops=1)
I/O Timings: read=0.000 write=0.000
-> Result (cost=0.00..0.01 rows=1 width=76) (actual time=0.001..0.002 rows=1 loops=1)
I/O Timings: read=0.000 write=0.000
-> Limit (cost=0.76..1.57 rows=1 width=76) (actual time=0.862..0.862 rows=1 loops=499)
Buffers: shared hit=3718 read=423 dirtied=8
I/O Timings: read=412.590 write=0.000
CTE cte
-> WorkTable Scan on result (cost=0.00..0.20 rows=10 width=76) (actual time=0.000..0.000 rows=1 loops=499)
I/O Timings: read=0.000 write=0.000
-> Append (cost=0.56..17.57 rows=21 width=76) (actual time=0.862..0.862 rows=1 loops=499)
Buffers: shared hit=3718 read=423 dirtied=8
I/O Timings: read=412.590 write=0.000
-> Nested Loop (cost=0.56..7.77 rows=10 width=76) (actual time=0.675..0.675 rows=0 loops=499)
Buffers: shared hit=1693 read=357 dirtied=1
I/O Timings: read=327.812 write=0.000
-> CTE Scan on cte (cost=0.00..0.20 rows=10 width=76) (actual time=0.001..0.001 rows=1 loops=499)
I/O Timings: read=0.000 write=0.000
-> Limit (cost=0.56..0.73 rows=1 width=4) (actual time=0.672..0.672 rows=0 loops=499)
Buffers: shared hit=1693 read=357 dirtied=1
I/O Timings: read=327.812 write=0.000
-> Index Only Scan using index_namespaces_on_parent_id_and_id on public.namespaces namespaces_1 (cost=0.56..5.33 rows=29 width=4) (actual time=0.671..0.671 rows=0 loops=499)
Index Cond: (namespaces_1.parent_id = cte.current_id)
Heap Fetches: 7
Buffers: shared hit=1693 read=357 dirtied=1
I/O Timings: read=327.812 write=0.000
-> Nested Loop (cost=0.57..9.45 rows=10 width=76) (actual time=0.208..0.208 rows=1 loops=442)
Buffers: shared hit=2025 read=66 dirtied=7
I/O Timings: read=84.778 write=0.000
-> CTE Scan on cte cte_1 (cost=0.00..0.20 rows=10 width=72) (actual time=0.000..0.000 rows=1 loops=442)
I/O Timings: read=0.000 write=0.000
-> Limit (cost=0.57..0.89 rows=1 width=4) (actual time=0.203..0.203 rows=1 loops=442)
Buffers: shared hit=2025 read=66 dirtied=7
I/O Timings: read=84.778 write=0.000
-> Index Only Scan using index_namespaces_on_parent_id_and_id on public.namespaces namespaces_2 (cost=0.57..3.77 rows=10 width=4) (actual time=0.201..0.201 rows=1 loops=442)
Index Cond: ((namespaces_2.parent_id = (cte_1.depth)[(array_length(cte_1.depth, 1) - 1)]) AND (namespaces_2.id > (cte_1.depth)[array_length(cte_1.depth, 1)]))
Heap Fetches: 35
Buffers: shared hit=2025 read=66 dirtied=6
I/O Timings: read=84.778 write=0.000
-> Limit (cost=0.00..0.03 rows=1 width=76) (actual time=0.003..0.003 rows=1 loops=59)
I/O Timings: read=0.000 write=0.000
-> CTE Scan on cte cte_2 (cost=0.00..0.29 rows=9 width=76) (actual time=0.002..0.002 rows=1 loops=59)
Filter: (cte_2.depth <> '{}'::integer[])
Rows Removed by Filter: 0
I/O Timings: read=0.000 write=0.000
-> CTE Scan on result namespaces (cost=0.00..0.22 rows=11 width=76) (actual time=0.005..436.240 rows=500 loops=1)
Buffers: shared hit=3718 read=423 dirtied=8
I/O Timings: read=412.590 write=0.000
```
|
https://docs.gitlab.com/development/query_performance
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/query_performance.md
|
2025-08-13
|
doc/development/database
|
[
"doc",
"development",
"database"
] |
query_performance.md
|
Data Access
|
Database Frameworks
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Query performance guidelines
| null |
This document describes various guidelines to follow when optimizing SQL queries.
When you are optimizing your SQL queries, there are two dimensions to pay attention to:
1. The query execution time. This is paramount as it reflects how the user experiences GitLab.
1. The query plan. Optimizing the query plan is important in allowing queries to independently scale over time. Realizing that an index keeps a query performing well as the table grows before the query degrades is an example of why we analyze these plans.
## Timing guidelines for queries
| Query Type | Maximum Query Time | Notes |
|-------------------------------------------|--------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| General queries | `100ms` | This is not a hard limit, but if a query is getting above it, it is important to spend time understanding why it can or cannot be optimized. |
| Queries in a migration | `100ms` | This is different than the total [migration time](../migration_style_guide.md#how-long-a-migration-should-take). |
| Concurrent operations in a migration | `5min` | Concurrent operations do not block the database, but they block the GitLab update. This includes operations such as `add_concurrent_index`, `add_concurrent_foreign_key`, and validate constraint (e.g. adding text limit via `add_text_limit`). |
| Concurrent operations in a post migration | `20min` | Concurrent operations do not block the database, but they block the GitLab post update process. This includes operations such as `add_concurrent_index`, `add_concurrent_foreign_key`, and validate constraint (e.g. adding text limit via `add_text_limit`). If index creation exceeds 20 minutes, consider [async index creation](adding_database_indexes.md#create-indexes-asynchronously). |
| Background migrations | `1s` | |
| Service Ping | `1s` | See the [Metrics Instrumentation docs](../internal_analytics/metrics/metrics_instrumentation.md#database-metrics) for more details. |
- When analyzing your query's performance, pay attention to if the time you are seeing is on a [cold or warm cache](#cold-and-warm-cache). These guidelines apply for both cache types.
- When working with batched queries, change the range and batch size to see how it effects the query timing and caching.
- If an existing query is not performing well, make an effort to improve it. If it is too complex or would stall development, create a follow-up so it can be addressed in a timely manner. You can always ask the database reviewer or maintainer for help and guidance.
## Cold and warm cache
When evaluating query performance it is important to understand the difference between
cold and warm cached queries.
The first time a query is made, it is made on a "cold cache". Meaning it needs
to read from disk. If you run the query again, the data can be read from the
cache, or what PostgreSQL calls shared buffers. This is the "warm cache" query.
When analyzing an [`EXPLAIN` plan](understanding_explain_plans.md), you can see
the difference not only in the timing, but by looking at the output for `Buffers`
by running your explain with `EXPLAIN(analyze, buffers)`. [Database Lab](understanding_explain_plans.md#database-lab-engine)
automatically includes these options.
If you are making a warm cache query, you see only the `shared hits`.
For example, using [Database Lab](database_lab.md):
```plaintext
Shared buffers:
- hits: 36467 (~284.90 MiB) from the buffer pool
- reads: 0 from the OS file cache, including disk I/O
```
Or in the explain plan from `psql`:
```sql
Buffers: shared hit=7323
```
If the cache is cold, you also see `reads`.
Using [Database Lab](database_lab.md):
```plaintext
Shared buffers:
- hits: 17204 (~134.40 MiB) from the buffer pool
- reads: 15229 (~119.00 MiB) from the OS file cache, including disk I/O
```
In `psql`:
```sql
Buffers: shared hit=7202 read=121
```
## Slow list views and APIs
We often build filtered list views and APIs in GitLab which need to have many
different filter and sorting options. All these options are usually
encapsulated in finders and exposed by API/GraphQL arguments. While we have many possible
[pagination performance optimizations](pagination_performance_guidelines.md)
, there is
often no way to make all combinations of sorting and filtering performant.
Attempts to make many options performant might involve
[adding too many indexes](adding_database_indexes.md)
which sacrifices performance of our primary database. This is only justified
for common use cases and should not be considered as a way to make all
permutations of filter and sort performant. What this means practically is that
there will likely be filtered views and API requests that timeout when certain
sorting or filtering options are applied. We still allow them to be added by
teams where they benefit certain customers with specific combinations of
filtering/sorting, but we need to accept that they will timeout for some users.
|
---
stage: Data Access
group: Database Frameworks
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: Query performance guidelines
breadcrumbs:
- doc
- development
- database
---
This document describes various guidelines to follow when optimizing SQL queries.
When you are optimizing your SQL queries, there are two dimensions to pay attention to:
1. The query execution time. This is paramount as it reflects how the user experiences GitLab.
1. The query plan. Optimizing the query plan is important in allowing queries to independently scale over time. Realizing that an index keeps a query performing well as the table grows before the query degrades is an example of why we analyze these plans.
## Timing guidelines for queries
| Query Type | Maximum Query Time | Notes |
|-------------------------------------------|--------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| General queries | `100ms` | This is not a hard limit, but if a query is getting above it, it is important to spend time understanding why it can or cannot be optimized. |
| Queries in a migration | `100ms` | This is different than the total [migration time](../migration_style_guide.md#how-long-a-migration-should-take). |
| Concurrent operations in a migration | `5min` | Concurrent operations do not block the database, but they block the GitLab update. This includes operations such as `add_concurrent_index`, `add_concurrent_foreign_key`, and validate constraint (e.g. adding text limit via `add_text_limit`). |
| Concurrent operations in a post migration | `20min` | Concurrent operations do not block the database, but they block the GitLab post update process. This includes operations such as `add_concurrent_index`, `add_concurrent_foreign_key`, and validate constraint (e.g. adding text limit via `add_text_limit`). If index creation exceeds 20 minutes, consider [async index creation](adding_database_indexes.md#create-indexes-asynchronously). |
| Background migrations | `1s` | |
| Service Ping | `1s` | See the [Metrics Instrumentation docs](../internal_analytics/metrics/metrics_instrumentation.md#database-metrics) for more details. |
- When analyzing your query's performance, pay attention to if the time you are seeing is on a [cold or warm cache](#cold-and-warm-cache). These guidelines apply for both cache types.
- When working with batched queries, change the range and batch size to see how it effects the query timing and caching.
- If an existing query is not performing well, make an effort to improve it. If it is too complex or would stall development, create a follow-up so it can be addressed in a timely manner. You can always ask the database reviewer or maintainer for help and guidance.
## Cold and warm cache
When evaluating query performance it is important to understand the difference between
cold and warm cached queries.
The first time a query is made, it is made on a "cold cache". Meaning it needs
to read from disk. If you run the query again, the data can be read from the
cache, or what PostgreSQL calls shared buffers. This is the "warm cache" query.
When analyzing an [`EXPLAIN` plan](understanding_explain_plans.md), you can see
the difference not only in the timing, but by looking at the output for `Buffers`
by running your explain with `EXPLAIN(analyze, buffers)`. [Database Lab](understanding_explain_plans.md#database-lab-engine)
automatically includes these options.
If you are making a warm cache query, you see only the `shared hits`.
For example, using [Database Lab](database_lab.md):
```plaintext
Shared buffers:
- hits: 36467 (~284.90 MiB) from the buffer pool
- reads: 0 from the OS file cache, including disk I/O
```
Or in the explain plan from `psql`:
```sql
Buffers: shared hit=7323
```
If the cache is cold, you also see `reads`.
Using [Database Lab](database_lab.md):
```plaintext
Shared buffers:
- hits: 17204 (~134.40 MiB) from the buffer pool
- reads: 15229 (~119.00 MiB) from the OS file cache, including disk I/O
```
In `psql`:
```sql
Buffers: shared hit=7202 read=121
```
## Slow list views and APIs
We often build filtered list views and APIs in GitLab which need to have many
different filter and sorting options. All these options are usually
encapsulated in finders and exposed by API/GraphQL arguments. While we have many possible
[pagination performance optimizations](pagination_performance_guidelines.md)
, there is
often no way to make all combinations of sorting and filtering performant.
Attempts to make many options performant might involve
[adding too many indexes](adding_database_indexes.md)
which sacrifices performance of our primary database. This is only justified
for common use cases and should not be considered as a way to make all
permutations of filter and sort performant. What this means practically is that
there will likely be filtered views and API requests that timeout when certain
sorting or filtering options are applied. We still allow them to be added by
teams where they benefit certain customers with specific combinations of
filtering/sorting, but we need to accept that they will timeout for some users.
|
https://docs.gitlab.com/development/load_balancing
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/load_balancing.md
|
2025-08-13
|
doc/development/database
|
[
"doc",
"development",
"database"
] |
load_balancing.md
|
Data Access
|
Database Frameworks
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Database load balancing
| null |
With database load balancing, read-only queries can be distributed across multiple
PostgreSQL nodes to increase performance.
This documentation provides a technical overview on how database load balancing
is implemented in GitLab Rails and Sidekiq.
## Nomenclature
1. **Host**: Each database host. It could be a primary or a replica.
1. **Primary**: Primary PostgreSQL host that is used for write-only and read-and-write operations.
1. **Replica**: Secondary PostgreSQL hosts that are used for read-only operations.
1. **Workload**: a Rails request or a Sidekiq job that requires database connections.
## Components
A few Ruby classes are involved in the load balancing process. All of them are
in the namespace `Gitlab::Database::LoadBalancing`:
1. `Host`
1. `LoadBalancer`
1. `ConnectionProxy`
1. `Session`
Each workload begins with a new instance of `Gitlab::Database::LoadBalancing::Session`.
The `Session` keeps track of the database operations that have been performed. It then
determines if the workload requires a connection to either the primary host or a replica host.
When the workload requires a database connection through `ActiveRecord`,
`ConnectionProxy` first redirects the connection request to `LoadBalancer`.
`ConnectionProxy` requests either a `read` or `read_write` connection from the `LoadBalancer`
depending on a few criteria:
1. Whether the query is a read-only or it requires write.
1. Whether the `Session` has recorded a write operation previously.
1. Whether any special blocks have been used to prefer primary or replica, such as:
- `use_primary`
- `ignore_writes`
- `use_replicas_for_read_queries`
- `fallback_to_replicas_for_ambiguous_queries`
`LoadBalancer` then yields the requested connection from the respective database connection pool.
It yields either:
- A `read_write` connection from the primary's connection pool.
- A `read` connection from the replicas' connection pools.
When responding to a request for a `read` connection, `LoadBalancer` would
first attempt to load balance the connection across the replica hosts.
It looks for the next `online` replica host and yields a connection from the host's connection pool.
A replica host is considered `online` if it is up-to-date with the primary, based on
either the replication lag size or time. The thresholds for these requirements are configurable.
## Deployment Strategy
When rolling out changes via feature flag, consider deploying exclusively to Sidekiq pods initially to minimize risk.
Why Sidekiq-first deployment:
- Keeps the API pods stable ensuring ChatOps remains available to disable feature flags in worst case scenario.
- Background jobs can retry automatically without any intervention.
Implementation example:
```ruby
if feature_flag_enabled? && Gitlab::Runtime.sidekiq?
new_changes
else
existing_changes
end
```
|
---
stage: Data Access
group: Database Frameworks
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: Database load balancing
breadcrumbs:
- doc
- development
- database
---
With database load balancing, read-only queries can be distributed across multiple
PostgreSQL nodes to increase performance.
This documentation provides a technical overview on how database load balancing
is implemented in GitLab Rails and Sidekiq.
## Nomenclature
1. **Host**: Each database host. It could be a primary or a replica.
1. **Primary**: Primary PostgreSQL host that is used for write-only and read-and-write operations.
1. **Replica**: Secondary PostgreSQL hosts that are used for read-only operations.
1. **Workload**: a Rails request or a Sidekiq job that requires database connections.
## Components
A few Ruby classes are involved in the load balancing process. All of them are
in the namespace `Gitlab::Database::LoadBalancing`:
1. `Host`
1. `LoadBalancer`
1. `ConnectionProxy`
1. `Session`
Each workload begins with a new instance of `Gitlab::Database::LoadBalancing::Session`.
The `Session` keeps track of the database operations that have been performed. It then
determines if the workload requires a connection to either the primary host or a replica host.
When the workload requires a database connection through `ActiveRecord`,
`ConnectionProxy` first redirects the connection request to `LoadBalancer`.
`ConnectionProxy` requests either a `read` or `read_write` connection from the `LoadBalancer`
depending on a few criteria:
1. Whether the query is a read-only or it requires write.
1. Whether the `Session` has recorded a write operation previously.
1. Whether any special blocks have been used to prefer primary or replica, such as:
- `use_primary`
- `ignore_writes`
- `use_replicas_for_read_queries`
- `fallback_to_replicas_for_ambiguous_queries`
`LoadBalancer` then yields the requested connection from the respective database connection pool.
It yields either:
- A `read_write` connection from the primary's connection pool.
- A `read` connection from the replicas' connection pools.
When responding to a request for a `read` connection, `LoadBalancer` would
first attempt to load balance the connection across the replica hosts.
It looks for the next `online` replica host and yields a connection from the host's connection pool.
A replica host is considered `online` if it is up-to-date with the primary, based on
either the replication lag size or time. The thresholds for these requirements are configurable.
## Deployment Strategy
When rolling out changes via feature flag, consider deploying exclusively to Sidekiq pods initially to minimize risk.
Why Sidekiq-first deployment:
- Keeps the API pods stable ensuring ChatOps remains available to disable feature flags in worst case scenario.
- Background jobs can retry automatically without any intervention.
Implementation example:
```ruby
if feature_flag_enabled? && Gitlab::Runtime.sidekiq?
new_changes
else
existing_changes
end
```
|
https://docs.gitlab.com/development/pg_upgrade_timeline
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/pg_upgrade_timeline.md
|
2025-08-13
|
doc/development/database
|
[
"doc",
"development",
"database"
] |
pg_upgrade_timeline.md
|
Data Access
|
Database Frameworks
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
PostgreSQL upgrade timeline
| null |
GitLab implements annual PostgreSQL database version upgrades to maximize operational efficiency and capitalize on enhanced functionality. This critical infrastructure update impacts multiple teams and requires coordination to ensure minimal disruption to our production environment.
This document establishes a comprehensive framework outlining the responsibilities of each team involved in the PostgreSQL upgrade process at GitLab. By clearly defining ownership of specific tasks and establishing a timeline for completion, we aim to standardize our approach, mitigate risks, and ensure successful implementation across all database environments.
The timeline detailed in this document serves as a roadmap for our PostgreSQL upgrade journey, ensuring that all necessary steps are properly sequenced and executed. By following this structured approach, we can deliver the best possible experience to our customers, minimizing downtime and maintaining the high level of service they expect from GitLab.
The following sections detail the specific responsibilities assigned to each team, along with the recommended sequence of activities. This framework will serve as the standard operating procedure for all future PostgreSQL version upgrades.
## Timeline and Team Responsibilities
### January: Team Awareness and Preparation
**Owner: All Cross-functional Teams**
Teams: [Database Operations Team](https://handbook.gitlab.com/handbook/engineering/infrastructure-platforms/data-access/database-operations/), [Database Frameworks Team](https://handbook.gitlab.com/handbook/engineering/infrastructure-platforms/data-access/database-framework/),
Build Team, [Durability Team](https://handbook.gitlab.com/handbook/engineering/infrastructure-platforms/data-access/durability/), [Geo Team](https://handbook.gitlab.com/handbook/engineering/infrastructure-platforms/tenant-scale/geo/),
[Dedicated Team](https://handbook.gitlab.com/handbook/engineering/infrastructure/team/gitlab-dedicated/)
This foundational phase initiates the mobilization of resources, with all teams conducting strategic planning for the forthcoming PostgreSQL version implementation.
Team Tasks: All teams to prepare their work and to allocate team resources for the upcoming PostgreSQL update.
### February-April: GitLab.com Platform Compatibility Assurance
#### Strategic Upgrade Cycle Planning
Analyze and propose the new PostgreSQL version for [GitLab](https://gitlab.com/).
**Owner: Database Operations Team**
Team Tasks:
1. Formulate a high-level summary of the implementation strategy;
1. Document the purpose and expected benefits for GitLab in the upgrade epic, following the [New Project template](https://gitlab.com/gitlab-com/gl-infra/data-access/team/-/blob/main/.gitlab/issue_templates/New_Project.md);
1. Invite stakeholders and cross-functional teams to collaborate and comment directly in the Epic;
#### PostgreSQL test compatibility and performance
Ensure the compatibility of [GitLab.com](https://gitlab.com) to the new proposed PostgreSQL version.
**Owner: Database Frameworks Team**
Team Tasks:
1. Integrate the new PostgreSQL version into nightly specs;
1. Ensure the compatibility with the new PostgreSQL version;
1. Document and communicate PostgreSQL inconsistencies, technical findings, and nightly specs results through an issue linked to the upgrade epic;
1. Document and communicate to cross-functional teams that comprehensive testing confirms GitLab is fully functional with the new PostgreSQL version in the upgrade epic;
#### Cloud managed PostgreSQL test compatibility
Ensure the compatibility of [GitLab Dedicated](https://about.gitlab.com/dedicated/) cloud-managed PostgreSQL to the stable version used by GitLab.com.
**Owner: Dedicated Team**
Team Tasks:
1. Review available RDS and CloudSQL upgrade documentation for the stable supported PostgreSQL version;
1. Test the upgrade with the current stable PostgreSQL version for AWS and GPC;
1. Document the rollout schedule and customer communication plan. Link the rollout schedule in the upgrade epic;
#### Geo Upgrade Preparation
**Owner: Geo Team**
Team Tasks: Verify the upgrade procedure for the PostgreSQL new version on Geo installations;
### May-July: Bundled Postgres Compatibility Assurance
Validates the bundled PostgreSQL upgrade based on [GitLab.com](https://gitlab.com) production-stable version. This usually happens on a major release only, around May every year.
#### Validate bundled PostgreSQL upgrades for supported deployment methods
**Owner: Build Team**
Team Tasks:
1. Conduct deployment-specific testing to ensure PostgreSQL compatibility with Docker, Kubernetes, and Omnibus
1. Test auto-upgrade paths thoroughly;
#### Provide optional support for bundled PostgreSQL upgrade
**Owner: Build Team**
Team Tasks:
1. Document the upgrade procedures for different deployment methods in the installation guide;
1. Existing installations will gain access to a validated upgrade pathway via the `pg-upgrade` utility tool, allowing for planned and controlled PostgreSQL upgrades;
### August-October: Pre-prod Preparation and GitLab.com Upgrade
Upgrade [GitLab.com](https://gitlab.com) environments.
**Owner: Database Operations Team**
Team Tasks:
1. Upgrade two STG databases and two PRD databases, typically CI + SEC or Registry. The specific databases may vary year to year;
1. Upgrade the remaining two STG databases and two PRD databases. The specific databases may vary from year to year;
1. Communicate to cross-functional teams that GitLab has successfully transitioned to a new PostgreSQL version;
### November-January: Stable Release Integration
Proceed with updating the tooling based on the stable production version of [GitLab.com](https://gitlab.com).
This upgrade migrates customers to the new PostgreSQL version, thereby discontinuing support for the current version they are using.
#### Auto upgrade self-managed single node Omnibus instances
**Owner: Build Team**
Team Tasks: Auto-upgrade the PostgreSQL version for non-high availability environments;
#### Make the new version of bundled PostgreSQL as default
**Owner: Build Team**
Team Tasks:
1. The stable bundled PostgreSQL version will become the default database version for all new installations;
1. Monitor customer adoption and address any issues that arise;
1. Document any related issues in the upgrade epic;
#### Cloud managed PostgreSQL update
Proceed with [GitLab Dedicated](https://about.gitlab.com/dedicated/) cloud-managed upgrade.
**Owner: Dedicated Team**
Team Tasks:
1. Upgrade UATs: USPubSec and Commercial Dedicated environments upgraded;
1. Upgrade production tenants: Production USPubSec and Commercial Dedicated environments upgraded;
1. Code cleanup and Post Rollout: Update the default PostgreSQL version for Instrumentor;
|
---
stage: Data Access
group: Database Frameworks
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: PostgreSQL upgrade timeline
breadcrumbs:
- doc
- development
- database
---
GitLab implements annual PostgreSQL database version upgrades to maximize operational efficiency and capitalize on enhanced functionality. This critical infrastructure update impacts multiple teams and requires coordination to ensure minimal disruption to our production environment.
This document establishes a comprehensive framework outlining the responsibilities of each team involved in the PostgreSQL upgrade process at GitLab. By clearly defining ownership of specific tasks and establishing a timeline for completion, we aim to standardize our approach, mitigate risks, and ensure successful implementation across all database environments.
The timeline detailed in this document serves as a roadmap for our PostgreSQL upgrade journey, ensuring that all necessary steps are properly sequenced and executed. By following this structured approach, we can deliver the best possible experience to our customers, minimizing downtime and maintaining the high level of service they expect from GitLab.
The following sections detail the specific responsibilities assigned to each team, along with the recommended sequence of activities. This framework will serve as the standard operating procedure for all future PostgreSQL version upgrades.
## Timeline and Team Responsibilities
### January: Team Awareness and Preparation
**Owner: All Cross-functional Teams**
Teams: [Database Operations Team](https://handbook.gitlab.com/handbook/engineering/infrastructure-platforms/data-access/database-operations/), [Database Frameworks Team](https://handbook.gitlab.com/handbook/engineering/infrastructure-platforms/data-access/database-framework/),
Build Team, [Durability Team](https://handbook.gitlab.com/handbook/engineering/infrastructure-platforms/data-access/durability/), [Geo Team](https://handbook.gitlab.com/handbook/engineering/infrastructure-platforms/tenant-scale/geo/),
[Dedicated Team](https://handbook.gitlab.com/handbook/engineering/infrastructure/team/gitlab-dedicated/)
This foundational phase initiates the mobilization of resources, with all teams conducting strategic planning for the forthcoming PostgreSQL version implementation.
Team Tasks: All teams to prepare their work and to allocate team resources for the upcoming PostgreSQL update.
### February-April: GitLab.com Platform Compatibility Assurance
#### Strategic Upgrade Cycle Planning
Analyze and propose the new PostgreSQL version for [GitLab](https://gitlab.com/).
**Owner: Database Operations Team**
Team Tasks:
1. Formulate a high-level summary of the implementation strategy;
1. Document the purpose and expected benefits for GitLab in the upgrade epic, following the [New Project template](https://gitlab.com/gitlab-com/gl-infra/data-access/team/-/blob/main/.gitlab/issue_templates/New_Project.md);
1. Invite stakeholders and cross-functional teams to collaborate and comment directly in the Epic;
#### PostgreSQL test compatibility and performance
Ensure the compatibility of [GitLab.com](https://gitlab.com) to the new proposed PostgreSQL version.
**Owner: Database Frameworks Team**
Team Tasks:
1. Integrate the new PostgreSQL version into nightly specs;
1. Ensure the compatibility with the new PostgreSQL version;
1. Document and communicate PostgreSQL inconsistencies, technical findings, and nightly specs results through an issue linked to the upgrade epic;
1. Document and communicate to cross-functional teams that comprehensive testing confirms GitLab is fully functional with the new PostgreSQL version in the upgrade epic;
#### Cloud managed PostgreSQL test compatibility
Ensure the compatibility of [GitLab Dedicated](https://about.gitlab.com/dedicated/) cloud-managed PostgreSQL to the stable version used by GitLab.com.
**Owner: Dedicated Team**
Team Tasks:
1. Review available RDS and CloudSQL upgrade documentation for the stable supported PostgreSQL version;
1. Test the upgrade with the current stable PostgreSQL version for AWS and GPC;
1. Document the rollout schedule and customer communication plan. Link the rollout schedule in the upgrade epic;
#### Geo Upgrade Preparation
**Owner: Geo Team**
Team Tasks: Verify the upgrade procedure for the PostgreSQL new version on Geo installations;
### May-July: Bundled Postgres Compatibility Assurance
Validates the bundled PostgreSQL upgrade based on [GitLab.com](https://gitlab.com) production-stable version. This usually happens on a major release only, around May every year.
#### Validate bundled PostgreSQL upgrades for supported deployment methods
**Owner: Build Team**
Team Tasks:
1. Conduct deployment-specific testing to ensure PostgreSQL compatibility with Docker, Kubernetes, and Omnibus
1. Test auto-upgrade paths thoroughly;
#### Provide optional support for bundled PostgreSQL upgrade
**Owner: Build Team**
Team Tasks:
1. Document the upgrade procedures for different deployment methods in the installation guide;
1. Existing installations will gain access to a validated upgrade pathway via the `pg-upgrade` utility tool, allowing for planned and controlled PostgreSQL upgrades;
### August-October: Pre-prod Preparation and GitLab.com Upgrade
Upgrade [GitLab.com](https://gitlab.com) environments.
**Owner: Database Operations Team**
Team Tasks:
1. Upgrade two STG databases and two PRD databases, typically CI + SEC or Registry. The specific databases may vary year to year;
1. Upgrade the remaining two STG databases and two PRD databases. The specific databases may vary from year to year;
1. Communicate to cross-functional teams that GitLab has successfully transitioned to a new PostgreSQL version;
### November-January: Stable Release Integration
Proceed with updating the tooling based on the stable production version of [GitLab.com](https://gitlab.com).
This upgrade migrates customers to the new PostgreSQL version, thereby discontinuing support for the current version they are using.
#### Auto upgrade self-managed single node Omnibus instances
**Owner: Build Team**
Team Tasks: Auto-upgrade the PostgreSQL version for non-high availability environments;
#### Make the new version of bundled PostgreSQL as default
**Owner: Build Team**
Team Tasks:
1. The stable bundled PostgreSQL version will become the default database version for all new installations;
1. Monitor customer adoption and address any issues that arise;
1. Document any related issues in the upgrade epic;
#### Cloud managed PostgreSQL update
Proceed with [GitLab Dedicated](https://about.gitlab.com/dedicated/) cloud-managed upgrade.
**Owner: Dedicated Team**
Team Tasks:
1. Upgrade UATs: USPubSec and Commercial Dedicated environments upgraded;
1. Upgrade production tenants: Production USPubSec and Commercial Dedicated environments upgraded;
1. Code cleanup and Post Rollout: Update the default PostgreSQL version for Instrumentor;
|
https://docs.gitlab.com/development/creating_enums
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/creating_enums.md
|
2025-08-13
|
doc/development/database
|
[
"doc",
"development",
"database"
] |
creating_enums.md
|
Data Access
|
Database Frameworks
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Creating enums
| null |
When creating a new enum, it should use the database type `SMALLINT`.
The `SMALLINT` type size is 2 bytes, which is sufficient for an enum.
This would help to save space in the database.
To use this type, add `limit: 2` to the migration that creates the column.
Example:
```ruby
def change
add_column :ci_job_artifacts, :file_format, :integer, limit: 2
end
```
## All of the key/value pairs should be defined in FOSS
**Summary**: All enums needs to be defined in FOSS, if a model is also part of the FOSS.
```ruby
class Model < ApplicationRecord
enum platform: {
aws: 0,
gcp: 1 # EE-only
}
end
```
When you add a new key/value pair to a `enum` and if it's EE-specific, you might be
tempted to organize the `enum` as the following:
```ruby
# Define `failure_reason` enum in `Pipeline` model:
class Pipeline < ApplicationRecord
enum failure_reason: Enums::Pipeline.failure_reasons
end
```
```ruby
# Define key/value pairs that used in FOSS and EE:
module Enums
module Pipeline
def self.failure_reasons
{ unknown_failure: 0, config_error: 1 }
end
end
end
Enums::Pipeline.prepend_mod_with('Enums::Pipeline')
```
```ruby
# Define key/value pairs that used in EE only:
module EE
module Enums
module Pipeline
override :failure_reasons
def failure_reasons
super.merge(job_activity_limit_exceeded: 2)
end
end
end
end
```
This works as-is, however, it has a couple of downside that:
- Someone could define a key/value pair in EE that is **conflicted** with a value defined in FOSS.
For example, define `job_activity_limit_exceeded: 1` in `EE::Enums::Pipeline`.
- When it happens, the feature works totally different.
For example, we cannot figure out `failure_reason` is either `config_error` or `job_activity_limit_exceeded`.
- When it happens, we have to ship a database migration to fix the data integrity,
which might be impossible if you cannot recover the original value.
Also, you might observe a workaround for this concern by setting an offset in the `EE` module's values.
For example, this example sets `1000` as the offset:
```ruby
module EE
module Enums
module Pipeline
override :failure_reasons
def failure_reasons
super.merge(job_activity_limit_exceeded: 1_000, size_limit_exceeded: 1_001)
end
end
end
end
```
This looks working as a workaround, however, this approach has some downsides that:
- Features could move from EE to FOSS or vice versa. Therefore, the offset might be mixed between FOSS and EE in the future.
For example, when you move `job_activity_limit_exceeded` to FOSS, you see `{ unknown_failure: 0, config_error: 1, job_activity_limit_exceeded: 1_000 }`.
- The integer column for the `enum` is likely created as `SMALLINT`.
Therefore, you need to be careful of that the offset doesn't exceed the maximum value of 2 bytes integer.
As a conclusion, you should define all of the key/value pairs in FOSS.
For example, you can write the following code in the above case:
```ruby
class Pipeline < ApplicationRecord
enum failure_reason: {
unknown_failure: 0,
config_error: 1,
job_activity_limit_exceeded: 2
}
end
```
## Add new values in the gap
After merging some EE and FOSS enums, there might be a gap between the two groups of values:
```ruby
module Enums
module Ci
module CommitStatus
def self.failure_reasons
{
# ...
data_integrity_failure: 12,
forward_deployment_failure: 13,
insufficient_bridge_permissions: 1_001,
downstream_bridge_project_not_found: 1_002,
# ...
}
end
end
end
end
```
To add new values, you should fill the gap first.
In the example above add `14` instead of `1_003`:
```ruby
{
# ...
data_integrity_failure: 12,
forward_deployment_failure: 13,
a_new_value: 14,
insufficient_bridge_permissions: 1_001,
downstream_bridge_project_not_found: 1_002,
# ...
}
```
|
---
stage: Data Access
group: Database Frameworks
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: Creating enums
breadcrumbs:
- doc
- development
- database
---
When creating a new enum, it should use the database type `SMALLINT`.
The `SMALLINT` type size is 2 bytes, which is sufficient for an enum.
This would help to save space in the database.
To use this type, add `limit: 2` to the migration that creates the column.
Example:
```ruby
def change
add_column :ci_job_artifacts, :file_format, :integer, limit: 2
end
```
## All of the key/value pairs should be defined in FOSS
**Summary**: All enums needs to be defined in FOSS, if a model is also part of the FOSS.
```ruby
class Model < ApplicationRecord
enum platform: {
aws: 0,
gcp: 1 # EE-only
}
end
```
When you add a new key/value pair to a `enum` and if it's EE-specific, you might be
tempted to organize the `enum` as the following:
```ruby
# Define `failure_reason` enum in `Pipeline` model:
class Pipeline < ApplicationRecord
enum failure_reason: Enums::Pipeline.failure_reasons
end
```
```ruby
# Define key/value pairs that used in FOSS and EE:
module Enums
module Pipeline
def self.failure_reasons
{ unknown_failure: 0, config_error: 1 }
end
end
end
Enums::Pipeline.prepend_mod_with('Enums::Pipeline')
```
```ruby
# Define key/value pairs that used in EE only:
module EE
module Enums
module Pipeline
override :failure_reasons
def failure_reasons
super.merge(job_activity_limit_exceeded: 2)
end
end
end
end
```
This works as-is, however, it has a couple of downside that:
- Someone could define a key/value pair in EE that is **conflicted** with a value defined in FOSS.
For example, define `job_activity_limit_exceeded: 1` in `EE::Enums::Pipeline`.
- When it happens, the feature works totally different.
For example, we cannot figure out `failure_reason` is either `config_error` or `job_activity_limit_exceeded`.
- When it happens, we have to ship a database migration to fix the data integrity,
which might be impossible if you cannot recover the original value.
Also, you might observe a workaround for this concern by setting an offset in the `EE` module's values.
For example, this example sets `1000` as the offset:
```ruby
module EE
module Enums
module Pipeline
override :failure_reasons
def failure_reasons
super.merge(job_activity_limit_exceeded: 1_000, size_limit_exceeded: 1_001)
end
end
end
end
```
This looks working as a workaround, however, this approach has some downsides that:
- Features could move from EE to FOSS or vice versa. Therefore, the offset might be mixed between FOSS and EE in the future.
For example, when you move `job_activity_limit_exceeded` to FOSS, you see `{ unknown_failure: 0, config_error: 1, job_activity_limit_exceeded: 1_000 }`.
- The integer column for the `enum` is likely created as `SMALLINT`.
Therefore, you need to be careful of that the offset doesn't exceed the maximum value of 2 bytes integer.
As a conclusion, you should define all of the key/value pairs in FOSS.
For example, you can write the following code in the above case:
```ruby
class Pipeline < ApplicationRecord
enum failure_reason: {
unknown_failure: 0,
config_error: 1,
job_activity_limit_exceeded: 2
}
end
```
## Add new values in the gap
After merging some EE and FOSS enums, there might be a gap between the two groups of values:
```ruby
module Enums
module Ci
module CommitStatus
def self.failure_reasons
{
# ...
data_integrity_failure: 12,
forward_deployment_failure: 13,
insufficient_bridge_permissions: 1_001,
downstream_bridge_project_not_found: 1_002,
# ...
}
end
end
end
end
```
To add new values, you should fill the gap first.
In the example above add `14` instead of `1_003`:
```ruby
{
# ...
data_integrity_failure: 12,
forward_deployment_failure: 13,
a_new_value: 14,
insufficient_bridge_permissions: 1_001,
downstream_bridge_project_not_found: 1_002,
# ...
}
```
|
https://docs.gitlab.com/development/maintenance_operations
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/maintenance_operations.md
|
2025-08-13
|
doc/development/database
|
[
"doc",
"development",
"database"
] |
maintenance_operations.md
|
Data Access
|
Database Frameworks
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Maintenance operations
| null |
This page details various database related operations that may relate to development.
## Disabling an index is not safe
{{< alert type="warning" >}}
Previously, this section described a procedure to mark the index as invalid before removing it.
It's no longer recommended, as [it is not safe](https://gitlab.com/groups/gitlab-org/-/epics/11543#note_1570734906).
{{< /alert >}}
There are certain situations in which you might want to disable an index before removing it:
- The index is on a large table and rebuilding it in the case of a revert would take a long time.
- It is uncertain whether or not the index is being used in ways that are not fully visible.
In such situations, the index was disabled in a coordinated manner with
the infrastructure team and the database team
by opening a [production infrastructure issue](https://gitlab.com/gitlab-com/gl-infra/production/-/issues/new)
with the "Production Change" template and
then running the following commands:
```sql
-- Disable the index then run an EXPLAIN command known to use the index:
UPDATE pg_index SET indisvalid = false WHERE indexrelid = 'index_issues_on_foo'::regclass;
-- Verify the index is invalid on replicas:
SELECT indisvalid FROM pg_index WHERE indexrelid = 'index_issues_on_foo'::regclass;
-- Rollback the invalidation:
UPDATE pg_index SET indisvalid = true WHERE indexrelid = 'index_issues_on_foo'::regclass;
```
See this [example infrastructure issue](https://gitlab.com/gitlab-com/gl-infra/production/-/issues/2795) for reference.
|
---
stage: Data Access
group: Database Frameworks
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: Maintenance operations
breadcrumbs:
- doc
- development
- database
---
This page details various database related operations that may relate to development.
## Disabling an index is not safe
{{< alert type="warning" >}}
Previously, this section described a procedure to mark the index as invalid before removing it.
It's no longer recommended, as [it is not safe](https://gitlab.com/groups/gitlab-org/-/epics/11543#note_1570734906).
{{< /alert >}}
There are certain situations in which you might want to disable an index before removing it:
- The index is on a large table and rebuilding it in the case of a revert would take a long time.
- It is uncertain whether or not the index is being used in ways that are not fully visible.
In such situations, the index was disabled in a coordinated manner with
the infrastructure team and the database team
by opening a [production infrastructure issue](https://gitlab.com/gitlab-com/gl-infra/production/-/issues/new)
with the "Production Change" template and
then running the following commands:
```sql
-- Disable the index then run an EXPLAIN command known to use the index:
UPDATE pg_index SET indisvalid = false WHERE indexrelid = 'index_issues_on_foo'::regclass;
-- Verify the index is invalid on replicas:
SELECT indisvalid FROM pg_index WHERE indexrelid = 'index_issues_on_foo'::regclass;
-- Rollback the invalidation:
UPDATE pg_index SET indisvalid = true WHERE indexrelid = 'index_issues_on_foo'::regclass;
```
See this [example infrastructure issue](https://gitlab.com/gitlab-com/gl-infra/production/-/issues/2795) for reference.
|
https://docs.gitlab.com/development/new_database_migration_version
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/new_database_migration_version.md
|
2025-08-13
|
doc/development/database
|
[
"doc",
"development",
"database"
] |
new_database_migration_version.md
|
Data Access
|
Database Frameworks
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Introducing a new database migration version
| null |
At GitLab we've added many helpers for the database migrations to help developers manipulate
the schema and data of tables on a large scale like on GitLab.com. To avoid the repetitive task
of including the helpers into each database migration, we use a subclass of the Rails `ActiveRecord::Migration`
class that we use for all of our database migrations. This subclass is `Gitlab::Database::Migration`, and it already
includes all the helpers that developers can use. You can see many use cases of helpers built
in-house in [Avoiding downtime in migrations](avoiding_downtime_in_migrations.md).
Sometimes, we need to add or modify existing a helper's functionality without having a reverse effect on all the
previous database migrations. That's why we introduced versioning to `Gitlab::Database::Migration`. Now,
each database migration can inherit the latest version of this class at the time of the writing the database migration.
After we add a new feature, those old database migrations are no longer affected. We usually
refer to the version using `Gitlab::Database::Migration[2.1]`, where `2.1` is the current version.
Because we are chasing a moving target, adding a new migration and deprecating older versions
can be challenging. Database migrations are introduced every day, and this can break the pipeline.
In this document, we explain a two-step method to add a new database migration version.
1. [Introduce a new version, and keep the older version allowed](#introduce-a-new-version-and-keep-the-older-version-allowed)
1. [Prevent the usage of the older database migration version](#prevent-the-usage-of-the-older-database-migration-version)
## Introduce a new version, and keep the older version allowed
1. The new version can be added to the
[`migration.rb`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/lib/gitlab/database/migration.rb)
class, along with any new helpers that should be included in the new version.
Make sure that `current_version` refers to this new version. For example:
```ruby
class V2_2 < V2_1 # rubocop:disable Naming/ClassAndModuleCamelCase
include Gitlab::Database::MigrationHelpers::ANY_NEW_HELPER
end
def self.current_version
2.2
end
```
1. Update all the examples in the documentation to refer to the new database
migration version `Gitlab::Database::Migration[2.2]`.
1. Make sure that [`migration_spec.rb`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/spec/db/migration_spec.rb)
doesn't fail for the new database migrations by adding an open date rate for
the **new database version**.
## Prevent the usage of the older database migration version
After some time passes, and ensuring all developers are using the
new database migration version in their merge requests, prevent the older
version from being used:
1. Close the date range in [`migration_spec.rb`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/spec/db/migration_spec.rb)
for the older database version.
1. Modify the
[`RuboCop::Cop::Migration::VersionedMigrationClass`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/rubocop/cop/migration/versioned_migration_class.rb)
and [its owned tests](https://gitlab.com/gitlab-org/gitlab/-/blob/master/spec/rubocop/cop/migration/versioned_migration_class_spec.rb).
1. Communicate this change on our Slack `#backend` and `#database` channels and
[Engineering Week-in-Review document](https://handbook.gitlab.com/handbook/engineering/engineering-comms/#keeping-yourself-informed).
|
---
stage: Data Access
group: Database Frameworks
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: Introducing a new database migration version
breadcrumbs:
- doc
- development
- database
---
At GitLab we've added many helpers for the database migrations to help developers manipulate
the schema and data of tables on a large scale like on GitLab.com. To avoid the repetitive task
of including the helpers into each database migration, we use a subclass of the Rails `ActiveRecord::Migration`
class that we use for all of our database migrations. This subclass is `Gitlab::Database::Migration`, and it already
includes all the helpers that developers can use. You can see many use cases of helpers built
in-house in [Avoiding downtime in migrations](avoiding_downtime_in_migrations.md).
Sometimes, we need to add or modify existing a helper's functionality without having a reverse effect on all the
previous database migrations. That's why we introduced versioning to `Gitlab::Database::Migration`. Now,
each database migration can inherit the latest version of this class at the time of the writing the database migration.
After we add a new feature, those old database migrations are no longer affected. We usually
refer to the version using `Gitlab::Database::Migration[2.1]`, where `2.1` is the current version.
Because we are chasing a moving target, adding a new migration and deprecating older versions
can be challenging. Database migrations are introduced every day, and this can break the pipeline.
In this document, we explain a two-step method to add a new database migration version.
1. [Introduce a new version, and keep the older version allowed](#introduce-a-new-version-and-keep-the-older-version-allowed)
1. [Prevent the usage of the older database migration version](#prevent-the-usage-of-the-older-database-migration-version)
## Introduce a new version, and keep the older version allowed
1. The new version can be added to the
[`migration.rb`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/lib/gitlab/database/migration.rb)
class, along with any new helpers that should be included in the new version.
Make sure that `current_version` refers to this new version. For example:
```ruby
class V2_2 < V2_1 # rubocop:disable Naming/ClassAndModuleCamelCase
include Gitlab::Database::MigrationHelpers::ANY_NEW_HELPER
end
def self.current_version
2.2
end
```
1. Update all the examples in the documentation to refer to the new database
migration version `Gitlab::Database::Migration[2.2]`.
1. Make sure that [`migration_spec.rb`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/spec/db/migration_spec.rb)
doesn't fail for the new database migrations by adding an open date rate for
the **new database version**.
## Prevent the usage of the older database migration version
After some time passes, and ensuring all developers are using the
new database migration version in their merge requests, prevent the older
version from being used:
1. Close the date range in [`migration_spec.rb`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/spec/db/migration_spec.rb)
for the older database version.
1. Modify the
[`RuboCop::Cop::Migration::VersionedMigrationClass`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/rubocop/cop/migration/versioned_migration_class.rb)
and [its owned tests](https://gitlab.com/gitlab-org/gitlab/-/blob/master/spec/rubocop/cop/migration/versioned_migration_class_spec.rb).
1. Communicate this change on our Slack `#backend` and `#database` channels and
[Engineering Week-in-Review document](https://handbook.gitlab.com/handbook/engineering/engineering-comms/#keeping-yourself-informed).
|
https://docs.gitlab.com/development/migration_squashing
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/migration_squashing.md
|
2025-08-13
|
doc/development/database
|
[
"doc",
"development",
"database"
] |
migration_squashing.md
|
Data Access
|
Database
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Migration Squashing
| null |
## Migration squashing
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/105553) in GitLab 16.3.
{{< /history >}}
Migration squashing combines multiple database migrations into a single schema definition to improve database setup performance and maintain a manageable migration history.
## When to use migration squashing
Use migration squashing at the following times:
- At the start of each major release cycle
- After a required stop
- When the number of migrations has grown significantly (typically more than 200 migrations)
## Squash migrations
To squash migrations from a previous version (such as 16.10), run:
```shell
bundle exec rake "gitlab:db:squash[origin/16-10-stable-ee]"
```
This Rake task:
1. Removes all migrations from the previous version
1. Updates the schema version references in relevant files
1. Cleans up finalized batched background migrations
1. Updates CI configuration for database rollbacks
### Parameters
| Parameter | Description |
|-----------|-------------|
| `[origin/16-10-stable-ee]` | The Git reference to use as a baseline for migration squashing. This should be the stable branch of the previous version. |
## Troubleshooting
### Missing schema references
If you encounter errors related to missing schema references, check:
- Migration spec files that might reference old migrations
- Background migration files that might need manual updates
- Documentation that references specific migration versions
## Related documentation
- [Migration style guide](../migration_style_guide.md)
- [Required stops](required_stops.md)
|
---
stage: Data Access
group: Database
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: Migration Squashing
breadcrumbs:
- doc
- development
- database
---
## Migration squashing
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/105553) in GitLab 16.3.
{{< /history >}}
Migration squashing combines multiple database migrations into a single schema definition to improve database setup performance and maintain a manageable migration history.
## When to use migration squashing
Use migration squashing at the following times:
- At the start of each major release cycle
- After a required stop
- When the number of migrations has grown significantly (typically more than 200 migrations)
## Squash migrations
To squash migrations from a previous version (such as 16.10), run:
```shell
bundle exec rake "gitlab:db:squash[origin/16-10-stable-ee]"
```
This Rake task:
1. Removes all migrations from the previous version
1. Updates the schema version references in relevant files
1. Cleans up finalized batched background migrations
1. Updates CI configuration for database rollbacks
### Parameters
| Parameter | Description |
|-----------|-------------|
| `[origin/16-10-stable-ee]` | The Git reference to use as a baseline for migration squashing. This should be the stable branch of the previous version. |
## Troubleshooting
### Missing schema references
If you encounter errors related to missing schema references, check:
- Migration spec files that might reference old migrations
- Background migration files that might need manual updates
- Documentation that references specific migration versions
## Related documentation
- [Migration style guide](../migration_style_guide.md)
- [Required stops](required_stops.md)
|
https://docs.gitlab.com/development/db_dump
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/db_dump.md
|
2025-08-13
|
doc/development/database
|
[
"doc",
"development",
"database"
] |
db_dump.md
|
Data Access
|
Database Frameworks
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Importing a database dump into a staging environment
| null |
Sometimes it is useful to import the database from a production environment
into a staging environment for testing. The procedure below assumes you have
SSH and `sudo` access to both the production environment and the staging VM.
**Destroy your staging VM** when you are done with it. It is important to avoid
data leaks.
On the staging VM, add the following line to `/etc/gitlab/gitlab.rb` to speed up
large database imports.
```shell
# On STAGING
echo "postgresql['checkpoint_segments'] = 64" | sudo tee -a /etc/gitlab/gitlab.rb
sudo touch /etc/gitlab/skip-auto-reconfigure
sudo gitlab-ctl reconfigure
sudo gitlab-ctl stop puma
sudo gitlab-ctl stop sidekiq
```
Next, we let the production environment stream a compressed SQL dump to our
local machine via SSH, and redirect this stream to a `psql` client on the staging
VM.
```shell
# On LOCAL MACHINE
ssh -C gitlab.example.com sudo -u gitlab-psql /opt/gitlab/embedded/bin/pg_dump -Cc gitlabhq_production |\
ssh -C staging-vm sudo -u gitlab-psql /opt/gitlab/embedded/bin/psql -d template1
```
## Recreating directory structure
If you need to re-create some directory structure on the staging server you can
use this procedure.
First, on the production server, create a list of directories you want to
re-create.
```shell
# On PRODUCTION
(umask 077; sudo find /var/opt/gitlab/git-data/repositories -maxdepth 1 -type d -print0 > directories.txt)
```
Copy `directories.txt` to the staging server and create the directories there.
```shell
# On STAGING
sudo -u git xargs -0 mkdir -p < directories.txt
```
|
---
stage: Data Access
group: Database Frameworks
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: Importing a database dump into a staging environment
breadcrumbs:
- doc
- development
- database
---
Sometimes it is useful to import the database from a production environment
into a staging environment for testing. The procedure below assumes you have
SSH and `sudo` access to both the production environment and the staging VM.
**Destroy your staging VM** when you are done with it. It is important to avoid
data leaks.
On the staging VM, add the following line to `/etc/gitlab/gitlab.rb` to speed up
large database imports.
```shell
# On STAGING
echo "postgresql['checkpoint_segments'] = 64" | sudo tee -a /etc/gitlab/gitlab.rb
sudo touch /etc/gitlab/skip-auto-reconfigure
sudo gitlab-ctl reconfigure
sudo gitlab-ctl stop puma
sudo gitlab-ctl stop sidekiq
```
Next, we let the production environment stream a compressed SQL dump to our
local machine via SSH, and redirect this stream to a `psql` client on the staging
VM.
```shell
# On LOCAL MACHINE
ssh -C gitlab.example.com sudo -u gitlab-psql /opt/gitlab/embedded/bin/pg_dump -Cc gitlabhq_production |\
ssh -C staging-vm sudo -u gitlab-psql /opt/gitlab/embedded/bin/psql -d template1
```
## Recreating directory structure
If you need to re-create some directory structure on the staging server you can
use this procedure.
First, on the production server, create a list of directories you want to
re-create.
```shell
# On PRODUCTION
(umask 077; sudo find /var/opt/gitlab/git-data/repositories -maxdepth 1 -type d -print0 > directories.txt)
```
Copy `directories.txt` to the staging server and create the directories there.
```shell
# On STAGING
sudo -u git xargs -0 mkdir -p < directories.txt
```
|
https://docs.gitlab.com/development/dbcheck-migrations-job
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/dbcheck-migrations-job.md
|
2025-08-13
|
doc/development/database
|
[
"doc",
"development",
"database"
] |
dbcheck-migrations-job.md
|
Data Access
|
Database Frameworks
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
db:check-migrations job
| null |
This job runs on the test stage of a merge request pipeline. It checks:
1. A schema dump comparison between the author's working branch and the target branch,
after executing a rollback of your new migrations. This check validates that the
schema properly resets to what it was before executing this new migration.
1. A schema dump comparison between the author's working branch and the `db/structure.sql`
file that the author committed. This check validates that it contains all the expected changes
in the migration.
1. A Git diff between the `db/schema_migrations` that the author committed and the
one that the script generated after running migrations. This check validates that everything
was properly committed.
## Troubleshooting
### False positives
This job is not allowed to fail, but it can throw some false positives.
For example, when we drop a column and then roll back, this column is always
re-added at the end of the list of columns. If the column was previously in
the middle of the list, the rollback can't return the schema back exactly to
its previous state. In such cases apply the `pipeline:skip-check-migrations`
label to skip this check.
For a real-life example, refer to
[this failed job](https://gitlab.com/gitlab-org/gitlab/-/jobs/2006544972#L138).
Here, the author dropped the `position` column.
### Schema dump comparison fails after rollback
This failure often happens if your working branch is behind the target branch.
A real scenario:
```mermaid
graph LR
Main((main<br>commit A)) ===> |remove constraint<br>fk_rails_dbebdaa8fe| MainB((main<br>commit B))
Main((main<br>commit A)) --> |checkout<br>dev| DevA((dev<br>commit A)):::dev
DevA((dev<br>commit A)) --> |add column<br>dependency_proxy_size| DevC((dev<br>commit C)):::dev
DevC -.-> |CI pipeline<br>executes| JOB-FAILED((JOB FAILED!)):::error
classDef main fill:#f4f0ff,stroke:#7b58cf
classDef dev fill:#e9f3fc,stroke:#1f75cb
classDef error fill:#f15146,stroke:#d4121a
```
1. You check out the `dev` working branch from the `main` target branch. At this point,
each branch has their `HEAD` at commit A.
1. Someone works on the `main` branch and drops the `fk_rails_dbebdaa8fe` constraint,
thus creating commit B on `main`.
1. You add column `dependency_proxy_size` to your `dev` branch.
1. The `db:check-migrations` job fails for your `dev` branch's CI/CD pipeline, because
the `structure.sql` file did not rollback to its expected state.
This happened because branch `dev` contained commits A and C, not B. Its database schema
did not know about the removal of the `fk_rails_dbebdaa8fe` constraint. When comparing the two
schemas, the `dev` branch contained this constraint while the `main` branch didn't.
This example really happened. Read the [job failure logs](https://gitlab.com/gitlab-org/gitlab/-/jobs/1992050890).
To fix these kind of issues, rebase the working branch onto the target branch to get the latest changes.
|
---
stage: Data Access
group: Database Frameworks
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: db:check-migrations job
breadcrumbs:
- doc
- development
- database
---
This job runs on the test stage of a merge request pipeline. It checks:
1. A schema dump comparison between the author's working branch and the target branch,
after executing a rollback of your new migrations. This check validates that the
schema properly resets to what it was before executing this new migration.
1. A schema dump comparison between the author's working branch and the `db/structure.sql`
file that the author committed. This check validates that it contains all the expected changes
in the migration.
1. A Git diff between the `db/schema_migrations` that the author committed and the
one that the script generated after running migrations. This check validates that everything
was properly committed.
## Troubleshooting
### False positives
This job is not allowed to fail, but it can throw some false positives.
For example, when we drop a column and then roll back, this column is always
re-added at the end of the list of columns. If the column was previously in
the middle of the list, the rollback can't return the schema back exactly to
its previous state. In such cases apply the `pipeline:skip-check-migrations`
label to skip this check.
For a real-life example, refer to
[this failed job](https://gitlab.com/gitlab-org/gitlab/-/jobs/2006544972#L138).
Here, the author dropped the `position` column.
### Schema dump comparison fails after rollback
This failure often happens if your working branch is behind the target branch.
A real scenario:
```mermaid
graph LR
Main((main<br>commit A)) ===> |remove constraint<br>fk_rails_dbebdaa8fe| MainB((main<br>commit B))
Main((main<br>commit A)) --> |checkout<br>dev| DevA((dev<br>commit A)):::dev
DevA((dev<br>commit A)) --> |add column<br>dependency_proxy_size| DevC((dev<br>commit C)):::dev
DevC -.-> |CI pipeline<br>executes| JOB-FAILED((JOB FAILED!)):::error
classDef main fill:#f4f0ff,stroke:#7b58cf
classDef dev fill:#e9f3fc,stroke:#1f75cb
classDef error fill:#f15146,stroke:#d4121a
```
1. You check out the `dev` working branch from the `main` target branch. At this point,
each branch has their `HEAD` at commit A.
1. Someone works on the `main` branch and drops the `fk_rails_dbebdaa8fe` constraint,
thus creating commit B on `main`.
1. You add column `dependency_proxy_size` to your `dev` branch.
1. The `db:check-migrations` job fails for your `dev` branch's CI/CD pipeline, because
the `structure.sql` file did not rollback to its expected state.
This happened because branch `dev` contained commits A and C, not B. Its database schema
did not know about the removal of the `fk_rails_dbebdaa8fe` constraint. When comparing the two
schemas, the `dev` branch contained this constraint while the `main` branch didn't.
This example really happened. Read the [job failure logs](https://gitlab.com/gitlab-org/gitlab/-/jobs/1992050890).
To fix these kind of issues, rebase the working branch onto the target branch to get the latest changes.
|
https://docs.gitlab.com/development/efficient_in_operator_queries
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/efficient_in_operator_queries.md
|
2025-08-13
|
doc/development/database
|
[
"doc",
"development",
"database"
] |
efficient_in_operator_queries.md
|
Data Access
|
Database
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Efficient `IN` operator queries
| null |
This document describes a technique for building efficient ordered database queries with the `IN`
SQL operator and the usage of a GitLab utility module to help apply the technique.
{{< alert type="note" >}}
The described technique makes heavy use of
[keyset pagination](pagination_guidelines.md#keyset-pagination).
It's advised to get familiar with the topic first.
{{< /alert >}}
## Motivation
In GitLab, many domain objects like `Issue` live under nested hierarchies of projects and groups.
To fetch nested database records for domain objects at the group-level,
we often perform queries with the `IN` SQL operator.
We are usually interested in ordering the records by some attributes
and limiting the number of records using `ORDER BY` and `LIMIT` clauses for performance.
Pagination may be used to fetch subsequent records.
Example tasks requiring querying nested domain objects from the group level:
- Show first 20 issues by creation date or due date from the group `gitlab-org`.
- Show first 20 merge requests by merged at date from the group `gitlab-com`.
Unfortunately, ordered group-level queries typically perform badly
as their executions require heavy I/O, memory, and computations.
Let's do an in-depth examination of executing one such query.
### Performance problems with `IN` queries
Consider the task of fetching the twenty oldest created issues
from the group `gitlab-org` with the following query:
```sql
SELECT "issues".*
FROM "issues"
WHERE "issues"."project_id" IN
(SELECT "projects"."id"
FROM "projects"
WHERE "projects"."namespace_id" IN
(SELECT traversal_ids[array_length(traversal_ids, 1)] AS id
FROM "namespaces"
WHERE (traversal_ids @> ('{9970}'))))
ORDER BY "issues"."created_at" ASC,
"issues"."id" ASC
LIMIT 20
```
{{< alert type="note" >}}
For pagination, ordering by the `created_at` column is not enough,
we must add the `id` column as a
[tie-breaker](pagination_performance_guidelines.md#tie-breaker-column).
{{< /alert >}}
The execution of the query can be largely broken down into three steps:
1. The database accesses both `namespaces` and `projects` tables
to find all projects from all groups in the group hierarchy.
1. The database retrieves `issues` records for each project causing heavy disk I/O.
Ideally, an appropriate index configuration should optimize this process.
1. The database sorts the `issues` rows in memory by `created_at` and returns `LIMIT 20` rows to
the end-user. For large groups, this final step requires both large memory and CPU resources.
Execution plan for this DB query:
```sql
Limit (cost=90170.07..90170.12 rows=20 width=1329) (actual time=967.597..967.607 rows=20 loops=1)
Buffers: shared hit=239127 read=3060
I/O Timings: read=336.879
-> Sort (cost=90170.07..90224.02 rows=21578 width=1329) (actual time=967.596..967.603 rows=20 loops=1)
Sort Key: issues.created_at, issues.id
Sort Method: top-N heapsort Memory: 74kB
Buffers: shared hit=239127 read=3060
I/O Timings: read=336.879
-> Nested Loop (cost=1305.66..89595.89 rows=21578 width=1329) (actual time=4.709..797.659 rows=241534 loops=1)
Buffers: shared hit=239121 read=3060
I/O Timings: read=336.879
-> HashAggregate (cost=1305.10..1360.22 rows=5512 width=4) (actual time=4.657..5.370 rows=1528 loops=1)
Group Key: projects.id
Buffers: shared hit=2597
-> Nested Loop (cost=576.76..1291.32 rows=5512 width=4) (actual time=2.427..4.244 rows=1528 loops=1)
Buffers: shared hit=2597
-> HashAggregate (cost=576.32..579.06 rows=274 width=25) (actual time=2.406..2.447 rows=265 loops=1)
Group Key: namespaces.traversal_ids[array_length(namespaces.traversal_ids, 1)]
Buffers: shared hit=334
-> Bitmap Heap Scan on namespaces (cost=141.62..575.63 rows=274 width=25) (actual time=1.933..2.330 rows=265 loops=1)
Recheck Cond: (traversal_ids @> '{9970}'::integer[])
Heap Blocks: exact=243
Buffers: shared hit=334
-> Bitmap Index Scan on index_namespaces_on_traversal_ids (cost=0.00..141.55 rows=274 width=0) (actual time=1.897..1.898 rows=265 loops=1)
Index Cond: (traversal_ids @> '{9970}'::integer[])
Buffers: shared hit=91
-> Index Only Scan using index_projects_on_namespace_id_and_id on projects (cost=0.44..2.40 rows=20 width=8) (actual time=0.004..0.006 rows=6 loops=265)
Index Cond: (namespace_id = (namespaces.traversal_ids)[array_length(namespaces.traversal_ids, 1)])
Heap Fetches: 51
Buffers: shared hit=2263
-> Index Scan using index_issues_on_project_id_and_iid on issues (cost=0.57..10.57 rows=544 width=1329) (actual time=0.114..0.484 rows=158 loops=1528)
Index Cond: (project_id = projects.id)
Buffers: shared hit=236524 read=3060
I/O Timings: read=336.879
Planning Time: 7.750 ms
Execution Time: 967.973 ms
(36 rows)
```
The performance of the query depends on the number of rows in the database.
On average, we can say the following:
- Number of groups in the group-hierarchy: less than 1 000
- Number of projects: less than 5 000
- Number of issues: less than 100 000
From the list, it's apparent that the number of `issues` records has
the largest impact on the performance.
As per typical usage, we can say that the number of issue records grows
at a faster rate than the `namespaces` and the `projects` records.
This problem affects most of our group-level features where records are listed
in a specific order, such as group-level issues, merge requests pages, and APIs.
For very large groups the database queries can easily time out, causing HTTP 500 errors.
## Optimizing ordered `IN` queries
In the talk ["How to teach an elephant to dance rock and roll"](https://www.youtube.com/watch?v=Ha38lcjVyhQ),
Maxim Boguk demonstrated a technique to optimize a special class of ordered `IN` queries,
such as our ordered group-level queries.
A typical ordered `IN` query may look like this:
```sql
SELECT t.* FROM t
WHERE t.fkey IN (value_set)
ORDER BY t.pkey
LIMIT N;
```
Here's the key insight used in the technique: we need at most `|value_set| + N` record lookups,
rather than retrieving all records satisfying the condition `t.fkey IN value_set` (`|value_set|`
is the number of values in `value_set`).
We adopted and generalized the technique for use in GitLab by implementing utilities in the
`Gitlab::Pagination::Keyset::InOperatorOptimization` class to facilitate building efficient `IN`
queries.
### Requirements
The technique is not a drop-in replacement for the existing group-level queries using `IN` operator.
The technique can only optimize `IN` queries that satisfy the following requirements:
- `LIMIT` is present, which usually means that the query is paginated
(offset or keyset pagination).
- The column used with the `IN` query and the columns in the `ORDER BY`
clause are covered with a database index. The columns in the index must be
in the following order: `column_for_the_in_query`, `order by column 1`, and
`order by column 2`.
- The columns in the `ORDER BY` clause are distinct
(the combination of the columns uniquely identifies one particular row in the table).
{{< alert type="warning" >}}
This technique does not improve the performance of the `COUNT(*)` queries.
{{< /alert >}}
## The `InOperatorOptimization` module
The `Gitlab::Pagination::Keyset::InOperatorOptimization` module implements utilities for applying a generalized version of
the efficient `IN` query technique described in the previous section.
To build optimized, ordered `IN` queries that meet [the requirements](#requirements),
use the utility class `QueryBuilder` from the module.
{{< alert type="note" >}}
The generic keyset pagination module introduced in the merge request
[51481](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/51481)
plays a fundamental role in the generalized implementation of the technique
in `Gitlab::Pagination::Keyset::InOperatorOptimization`.
{{< /alert >}}
### Basic usage of `QueryBuilder`
To illustrate a basic usage, we build a query that
fetches 20 issues with the oldest `created_at` from the group `gitlab-org`.
The following ActiveRecord query would produce a query similar to
[the unoptimized query](#performance-problems-with-in-queries) that we examined earlier:
```ruby
scope = Issue
.where(project_id: Group.find(9970).all_projects.select(:id)) # `gitlab-org` group and its subgroups
.order(:created_at, :id)
.limit(20)
```
Instead, use the query builder `InOperatorOptimization::QueryBuilder` to produce an optimized
version:
```ruby
scope = Issue.order(:created_at, :id)
array_scope = Group.find(9970).all_projects.select(:id)
array_mapping_scope = -> (id_expression) { Issue.where(Issue.arel_table[:project_id].eq(id_expression)) }
finder_query = -> (created_at_expression, id_expression) { Issue.where(Issue.arel_table[:id].eq(id_expression)) }
Gitlab::Pagination::Keyset::InOperatorOptimization::QueryBuilder.new(
scope: scope,
array_scope: array_scope,
array_mapping_scope: array_mapping_scope,
finder_query: finder_query
).execute.limit(20)
```
- `scope` represents the original `ActiveRecord::Relation` object without the `IN` query. The
relation should define an order which must be supported by the
[keyset pagination library](keyset_pagination.md#usage).
- `array_scope` contains the `ActiveRecord::Relation` object, which represents the original
`IN (subquery)`. The select values must contain the columns by which the subquery is "connected"
to the main query: the `id` of the project record.
- `array_mapping_scope` defines a lambda returning an `ActiveRecord::Relation` object. The lambda
matches (`=`) single select values from the `array_scope`. The lambda yields as many
arguments as the select values defined in the `array_scope`. The arguments are Arel SQL expressions.
- `finder_query` loads the actual record row from the database. It must also be a lambda, where
the order by column expressions is available for locating the record. In this example, the
yielded values are `created_at` and `id` SQL expressions. Finding a record is very fast via the
primary key, so we don't use the `created_at` value. Providing the `finder_query` lambda is optional.
If it's not given, the `IN` operator optimization only makes the `ORDER BY` columns available to
the end-user and not the full database row.
The following database index on the `issues` table must be present
to make the query execute efficiently:
```sql
"idx_issues_on_project_id_and_created_at_and_id" btree (project_id, created_at, id)
```
The SQL query:
```sql
SELECT "issues".*
FROM
(WITH RECURSIVE "array_cte" AS MATERIALIZED
(SELECT "projects"."id"
FROM "projects"
WHERE "projects"."namespace_id" IN
(SELECT traversal_ids[array_length(traversal_ids, 1)] AS id
FROM "namespaces"
WHERE (traversal_ids @> ('{9970}')))),
"recursive_keyset_cte" AS ( -- initializer row start
(SELECT NULL::issues AS records,
array_cte_id_array,
issues_created_at_array,
issues_id_array,
0::bigint AS COUNT
FROM
(SELECT ARRAY_AGG("array_cte"."id") AS array_cte_id_array,
ARRAY_AGG("issues"."created_at") AS issues_created_at_array,
ARRAY_AGG("issues"."id") AS issues_id_array
FROM
(SELECT "array_cte"."id"
FROM array_cte) array_cte
LEFT JOIN LATERAL
(SELECT "issues"."created_at",
"issues"."id"
FROM "issues"
WHERE "issues"."project_id" = "array_cte"."id"
ORDER BY "issues"."created_at" ASC, "issues"."id" ASC
LIMIT 1) issues ON TRUE
WHERE "issues"."created_at" IS NOT NULL
AND "issues"."id" IS NOT NULL) array_scope_lateral_query
LIMIT 1)
-- initializer row finished
UNION ALL
(SELECT
-- result row start
(SELECT issues -- record finder query as the first column
FROM "issues"
WHERE "issues"."id" = recursive_keyset_cte.issues_id_array[position]
LIMIT 1),
array_cte_id_array,
recursive_keyset_cte.issues_created_at_array[:position_query.position-1]||next_cursor_values.created_at||recursive_keyset_cte.issues_created_at_array[position_query.position+1:],
recursive_keyset_cte.issues_id_array[:position_query.position-1]||next_cursor_values.id||recursive_keyset_cte.issues_id_array[position_query.position+1:],
recursive_keyset_cte.count + 1
-- result row finished
FROM recursive_keyset_cte,
LATERAL
-- finding the cursor values of the next record start
(SELECT created_at,
id,
position
FROM UNNEST(issues_created_at_array, issues_id_array) WITH
ORDINALITY AS u(created_at, id, position)
WHERE created_at IS NOT NULL
AND id IS NOT NULL
ORDER BY "created_at" ASC, "id" ASC
LIMIT 1) AS position_query,
-- finding the cursor values of the next record end
-- finding the next cursor values (next_cursor_values_query) start
LATERAL
(SELECT "record"."created_at",
"record"."id"
FROM (
VALUES (NULL,
NULL)) AS nulls
LEFT JOIN
(SELECT "issues"."created_at",
"issues"."id"
FROM (
(SELECT "issues"."created_at",
"issues"."id"
FROM "issues"
WHERE "issues"."project_id" = recursive_keyset_cte.array_cte_id_array[position]
AND recursive_keyset_cte.issues_created_at_array[position] IS NULL
AND "issues"."created_at" IS NULL
AND "issues"."id" > recursive_keyset_cte.issues_id_array[position]
ORDER BY "issues"."created_at" ASC, "issues"."id" ASC)
UNION ALL
(SELECT "issues"."created_at",
"issues"."id"
FROM "issues"
WHERE "issues"."project_id" = recursive_keyset_cte.array_cte_id_array[position]
AND recursive_keyset_cte.issues_created_at_array[position] IS NOT NULL
AND "issues"."created_at" IS NULL
ORDER BY "issues"."created_at" ASC, "issues"."id" ASC)
UNION ALL
(SELECT "issues"."created_at",
"issues"."id"
FROM "issues"
WHERE "issues"."project_id" = recursive_keyset_cte.array_cte_id_array[position]
AND recursive_keyset_cte.issues_created_at_array[position] IS NOT NULL
AND "issues"."created_at" > recursive_keyset_cte.issues_created_at_array[position]
ORDER BY "issues"."created_at" ASC, "issues"."id" ASC)
UNION ALL
(SELECT "issues"."created_at",
"issues"."id"
FROM "issues"
WHERE "issues"."project_id" = recursive_keyset_cte.array_cte_id_array[position]
AND recursive_keyset_cte.issues_created_at_array[position] IS NOT NULL
AND "issues"."created_at" = recursive_keyset_cte.issues_created_at_array[position]
AND "issues"."id" > recursive_keyset_cte.issues_id_array[position]
ORDER BY "issues"."created_at" ASC, "issues"."id" ASC)) issues
ORDER BY "issues"."created_at" ASC, "issues"."id" ASC
LIMIT 1) record ON TRUE
LIMIT 1) AS next_cursor_values))
-- finding the next cursor values (next_cursor_values_query) END
SELECT (records).*
FROM "recursive_keyset_cte" AS "issues"
WHERE (COUNT <> 0)) issues -- filtering out the initializer row
LIMIT 20
```
### Using the `IN` query optimization
#### Adding more filters
In this example, let's add an extra filter by `milestone_id`.
Be careful when adding extra filters to the query. If the column is not covered by the same index,
then the query might perform worse than the non-optimized query. The `milestone_id` column in the
`issues` table is currently covered by a different index:
```sql
"index_issues_on_milestone_id" btree (milestone_id)
```
Adding the `milestone_id = X` filter to the `scope` argument or to the optimized scope causes bad performance.
Example (bad):
```ruby
Gitlab::Pagination::Keyset::InOperatorOptimization::QueryBuilder.new(
scope: scope,
array_scope: array_scope,
array_mapping_scope: array_mapping_scope,
finder_query: finder_query
).execute
.where(milestone_id: 5)
.limit(20)
```
To address this concern, we could define another index:
```sql
"idx_issues_on_project_id_and_milestone_id_and_created_at_and_id" btree (project_id, milestone_id, created_at, id)
```
Adding more indexes to the `issues` table could significantly affect the performance of
the `UPDATE` queries. In this case, it's better to rely on the original query. It means that if we
want to use the optimization for the unfiltered page we need to add extra logic in the application code:
```ruby
if optimization_possible? # no extra params or params covered with the same index as the ORDER BY clause
run_optimized_query
else
run_normal_in_query
end
```
#### Multiple `IN` queries
Let's assume that we want to extend the group-level queries to include only incident and test case
issue types.
The original ActiveRecord query would look like this:
```ruby
scope = Issue
.where(project_id: Group.find(9970).all_projects.select(:id)) # `gitlab-org` group and its subgroups
.where(issue_type: [:incident, :test_case]) # 1, 2
.order(:created_at, :id)
.limit(20)
```
To construct the array scope, we need to take the Cartesian product of the `project_id IN` and
the `issue_type IN` queries. `issue_type` is an ActiveRecord enum, so we need to
construct the following table:
| `project_id` | `issue_type_value` |
| ------------ | ------------------ |
| 2 | 1 |
| 2 | 2 |
| 5 | 1 |
| 5 | 2 |
| 10 | 1 |
| 10 | 2 |
| 9 | 1 |
| 9 | 2 |
For the `issue_types` query we can construct a value list without querying a table:
```ruby
value_list = Arel::Nodes::ValuesList.new([[WorkItems::Type.base_types[:incident]],[WorkItems::Type.base_types[:test_case]]])
issue_type_values = Arel::Nodes::Grouping.new(value_list).as('issue_type_values (value)').to_sql
array_scope = Group
.find(9970)
.all_projects
.from("#{Project.table_name}, #{issue_type_values}")
.select(:id, :value)
```
Building the `array_mapping_scope` query requires two arguments: `id` and `issue_type_value`:
```ruby
array_mapping_scope = -> (id_expression, issue_type_value_expression) { Issue.where(Issue.arel_table[:project_id].eq(id_expression)).where(Issue.arel_table[:issue_type].eq(issue_type_value_expression)) }
```
The `scope` and the `finder` queries don't change:
```ruby
scope = Issue.order(:created_at, :id)
finder_query = -> (created_at_expression, id_expression) { Issue.where(Issue.arel_table[:id].eq(id_expression)) }
Gitlab::Pagination::Keyset::InOperatorOptimization::QueryBuilder.new(
scope: scope,
array_scope: array_scope,
array_mapping_scope: array_mapping_scope,
finder_query: finder_query
).execute.limit(20)
```
The SQL query:
```sql
SELECT "issues".*
FROM
(WITH RECURSIVE "array_cte" AS MATERIALIZED
(SELECT "projects"."id", "value"
FROM projects, (
VALUES (1), (2)) AS issue_type_values (value)
WHERE "projects"."namespace_id" IN
(WITH RECURSIVE "base_and_descendants" AS (
(SELECT "namespaces".*
FROM "namespaces"
WHERE "namespaces"."type" = 'Group'
AND "namespaces"."id" = 9970)
UNION
(SELECT "namespaces".*
FROM "namespaces", "base_and_descendants"
WHERE "namespaces"."type" = 'Group'
AND "namespaces"."parent_id" = "base_and_descendants"."id")) SELECT "id"
FROM "base_and_descendants" AS "namespaces")),
"recursive_keyset_cte" AS (
(SELECT NULL::issues AS records,
array_cte_id_array,
array_cte_value_array,
issues_created_at_array,
issues_id_array,
0::bigint AS COUNT
FROM
(SELECT ARRAY_AGG("array_cte"."id") AS array_cte_id_array,
ARRAY_AGG("array_cte"."value") AS array_cte_value_array,
ARRAY_AGG("issues"."created_at") AS issues_created_at_array,
ARRAY_AGG("issues"."id") AS issues_id_array
FROM
(SELECT "array_cte"."id",
"array_cte"."value"
FROM array_cte) array_cte
LEFT JOIN LATERAL
(SELECT "issues"."created_at",
"issues"."id"
FROM "issues"
WHERE "issues"."project_id" = "array_cte"."id"
AND "issues"."issue_type" = "array_cte"."value"
ORDER BY "issues"."created_at" ASC, "issues"."id" ASC
LIMIT 1) issues ON TRUE
WHERE "issues"."created_at" IS NOT NULL
AND "issues"."id" IS NOT NULL) array_scope_lateral_query
LIMIT 1)
UNION ALL
(SELECT
(SELECT issues
FROM "issues"
WHERE "issues"."id" = recursive_keyset_cte.issues_id_array[POSITION]
LIMIT 1), array_cte_id_array,
array_cte_value_array,
recursive_keyset_cte.issues_created_at_array[:position_query.position-1]||next_cursor_values.created_at||recursive_keyset_cte.issues_created_at_array[position_query.position+1:], recursive_keyset_cte.issues_id_array[:position_query.position-1]||next_cursor_values.id||recursive_keyset_cte.issues_id_array[position_query.position+1:], recursive_keyset_cte.count + 1
FROM recursive_keyset_cte,
LATERAL
(SELECT created_at,
id,
POSITION
FROM UNNEST(issues_created_at_array, issues_id_array) WITH
ORDINALITY AS u(created_at, id, POSITION)
WHERE created_at IS NOT NULL
AND id IS NOT NULL
ORDER BY "created_at" ASC, "id" ASC
LIMIT 1) AS position_query,
LATERAL
(SELECT "record"."created_at",
"record"."id"
FROM (
VALUES (NULL,
NULL)) AS nulls
LEFT JOIN
(SELECT "issues"."created_at",
"issues"."id"
FROM (
(SELECT "issues"."created_at",
"issues"."id"
FROM "issues"
WHERE "issues"."project_id" = recursive_keyset_cte.array_cte_id_array[POSITION]
AND "issues"."issue_type" = recursive_keyset_cte.array_cte_value_array[POSITION]
AND recursive_keyset_cte.issues_created_at_array[POSITION] IS NULL
AND "issues"."created_at" IS NULL
AND "issues"."id" > recursive_keyset_cte.issues_id_array[POSITION]
ORDER BY "issues"."created_at" ASC, "issues"."id" ASC)
UNION ALL
(SELECT "issues"."created_at",
"issues"."id"
FROM "issues"
WHERE "issues"."project_id" = recursive_keyset_cte.array_cte_id_array[POSITION]
AND "issues"."issue_type" = recursive_keyset_cte.array_cte_value_array[POSITION]
AND recursive_keyset_cte.issues_created_at_array[POSITION] IS NOT NULL
AND "issues"."created_at" IS NULL
ORDER BY "issues"."created_at" ASC, "issues"."id" ASC)
UNION ALL
(SELECT "issues"."created_at",
"issues"."id"
FROM "issues"
WHERE "issues"."project_id" = recursive_keyset_cte.array_cte_id_array[POSITION]
AND "issues"."issue_type" = recursive_keyset_cte.array_cte_value_array[POSITION]
AND recursive_keyset_cte.issues_created_at_array[POSITION] IS NOT NULL
AND "issues"."created_at" > recursive_keyset_cte.issues_created_at_array[POSITION]
ORDER BY "issues"."created_at" ASC, "issues"."id" ASC)
UNION ALL
(SELECT "issues"."created_at",
"issues"."id"
FROM "issues"
WHERE "issues"."project_id" = recursive_keyset_cte.array_cte_id_array[POSITION]
AND "issues"."issue_type" = recursive_keyset_cte.array_cte_value_array[POSITION]
AND recursive_keyset_cte.issues_created_at_array[POSITION] IS NOT NULL
AND "issues"."created_at" = recursive_keyset_cte.issues_created_at_array[POSITION]
AND "issues"."id" > recursive_keyset_cte.issues_id_array[POSITION]
ORDER BY "issues"."created_at" ASC, "issues"."id" ASC)) issues
ORDER BY "issues"."created_at" ASC, "issues"."id" ASC
LIMIT 1) record ON TRUE
LIMIT 1) AS next_cursor_values)) SELECT (records).*
FROM "recursive_keyset_cte" AS "issues"
WHERE (COUNT <> 0)) issues
LIMIT 20
```
{{< alert type="note" >}}
To make the query efficient, the following columns need to be covered with an index: `project_id`, `issue_type`, `created_at`, and `id`.
{{< /alert >}}
#### Using calculated `ORDER BY` expression
The following example orders epic records by the duration between the creation time and closed
time. It is calculated with the following formula:
```sql
SELECT EXTRACT('epoch' FROM epics.closed_at - epics.created_at) FROM epics
```
The query above returns the duration in seconds (`double precision`) between the two timestamp
columns in seconds. To order the records by this expression, you must reference it
in the `ORDER BY` clause:
```sql
SELECT EXTRACT('epoch' FROM epics.closed_at - epics.created_at)
FROM epics
ORDER BY EXTRACT('epoch' FROM epics.closed_at - epics.created_at) DESC
```
To make this ordering efficient on the group-level with the in-operator optimization, use a
custom `ORDER BY` configuration. Since the duration is not a distinct value (no unique index
present), you must add a tie-breaker column (`id`).
The following example shows the final `ORDER BY` clause:
```sql
ORDER BY extract('epoch' FROM epics.closed_at - epics.created_at) DESC, epics.id DESC
```
Snippet for loading records ordered by the calculated duration:
```ruby
arel_table = Epic.arel_table
order = Gitlab::Pagination::Keyset::Order.build([
Gitlab::Pagination::Keyset::ColumnOrderDefinition.new(
attribute_name: 'duration_in_seconds',
order_expression: Arel.sql('EXTRACT(EPOCH FROM epics.closed_at - epics.created_at)').desc,
sql_type: 'double precision' # important for calculated SQL expressions
),
Gitlab::Pagination::Keyset::ColumnOrderDefinition.new(
attribute_name: 'id',
order_expression: arel_table[:id].desc
)
])
records = Gitlab::Pagination::Keyset::InOperatorOptimization::QueryBuilder.new(
scope: Epic.where.not(closed_at: nil).reorder(order), # filter out NULL values
array_scope: Group.find(9970).self_and_descendants.select(:id),
array_mapping_scope: -> (id_expression) { Epic.where(Epic.arel_table[:group_id].eq(id_expression)) }
).execute.limit(20)
puts records.pluck(:duration_in_seconds, :id) # other columns are not available
```
Building the query requires quite a bit of configuration. For the order configuration you
can find more information within the
[complex order configuration](keyset_pagination.md#complex-order-configuration)
section for keyset paginated database queries.
The query requires a specialized database index:
```sql
CREATE INDEX index_epics_on_duration ON epics USING btree (group_id, EXTRACT(EPOCH FROM epics.closed_at - epics.created_at) DESC, id DESC) WHERE (closed_at IS NOT NULL);
```
Notice that the `finder_query` parameter is not used. The query only returns the `ORDER BY` columns
which are the `duration_in_seconds` (calculated column) and the `id` columns. This is a limitation
of the feature, defining the `finder_query` with calculated `ORDER BY` expressions is not supported.
To get the complete database records, an extra query can be invoked by the returned `id` column:
```ruby
records_by_id = records.index_by(&:id)
complete_records = Epic.where(id: records_by_id.keys).index_by(&:id)
# Printing the complete records according to the `ORDER BY` clause
records_by_id.each do |id, _|
puts complete_records[id].attributes
end
```
#### Ordering by `JOIN` columns
Ordering records by mixed columns where one or more columns are coming from `JOIN` tables
works with limitations. It requires extra configuration via Common Table Expression (CTE). The trick is to use a
non-materialized CTE to act as a "fake" table which exposes all required columns.
{{< alert type="note" >}}
The query performance might not improve compared to the standard `IN` query. Always
check the query plan.
{{< /alert >}}
Example: order issues by `projects.name, issues.id` within the group hierarchy
The first step is to create a CTE, where all required columns are collected in the `SELECT`
clause.
```ruby
cte_query = Issue
.select('issues.id AS id', 'issues.project_id AS project_id', 'projects.name AS projects_name')
.joins(:project)
cte = Gitlab::SQL::CTE.new(:issue_with_projects, cte_query, materialized: false)
```
Custom order object configuration:
```ruby
order = Gitlab::Pagination::Keyset::Order.build([
Gitlab::Pagination::Keyset::ColumnOrderDefinition.new(
attribute_name: 'projects_name',
order_expression: Issue.arel_table[:projects_name].asc,
sql_type: 'character varying',
nullable: :nulls_last
),
Gitlab::Pagination::Keyset::ColumnOrderDefinition.new(
attribute_name: :id,
order_expression: Issue.arel_table[:id].asc
)
])
```
Generate the query:
```ruby
scope = cte.apply_to(Issue.where({}).reorder(order))
opts = {
scope: scope,
array_scope: Project.where(namespace_id: top_level_group.self_and_descendants.select(:id)).select(:id),
array_mapping_scope: -> (id_expression) { Issue.where(Issue.arel_table[:project_id].eq(id_expression)) }
}
records = Gitlab::Pagination::Keyset::InOperatorOptimization::QueryBuilder
.new(**opts)
.execute
.limit(20)
```
#### Batch iteration
Batch iteration over the records is possible via the keyset `Iterator` class.
```ruby
scope = Issue.order(:created_at, :id)
array_scope = Group.find(9970).all_projects.select(:id)
array_mapping_scope = -> (id_expression) { Issue.where(Issue.arel_table[:project_id].eq(id_expression)) }
finder_query = -> (created_at_expression, id_expression) { Issue.where(Issue.arel_table[:id].eq(id_expression)) }
opts = {
in_operator_optimization_options: {
array_scope: array_scope,
array_mapping_scope: array_mapping_scope,
finder_query: finder_query
}
}
Gitlab::Pagination::Keyset::Iterator.new(scope: scope, **opts).each_batch(of: 100) do |records|
puts records.select(:id).map { |r| [r.id] }
end
```
{{< alert type="note" >}}
The query loads complete database rows from the disk. This may cause increased I/O and slower
database queries. Depending on the use case, the primary key is often only
needed for the batch query to invoke additional statements. For example, `UPDATE` or `DELETE`. The
`id` column is included in the `ORDER BY` columns (`created_at` and `id`) and is already
loaded. In this case, you can omit the `finder_query` parameter.
{{< /alert >}}
Example for loading the `ORDER BY` columns only:
```ruby
scope = Issue.order(:created_at, :id)
array_scope = Group.find(9970).all_projects.select(:id)
array_mapping_scope = -> (id_expression) { Issue.where(Issue.arel_table[:project_id].eq(id_expression)) }
opts = {
in_operator_optimization_options: {
array_scope: array_scope,
array_mapping_scope: array_mapping_scope
}
}
Gitlab::Pagination::Keyset::Iterator.new(scope: scope, **opts).each_batch(of: 100) do |records|
puts records.select(:id).map { |r| [r.id] } # only id and created_at are available
end
```
#### Keyset pagination
The optimization works out of the box with GraphQL and the `keyset_paginate` helper method.
Read more about [keyset pagination](keyset_pagination.md).
```ruby
array_scope = Group.find(9970).all_projects.select(:id)
array_mapping_scope = -> (id_expression) { Issue.where(Issue.arel_table[:project_id].eq(id_expression)) }
finder_query = -> (created_at_expression, id_expression) { Issue.where(Issue.arel_table[:id].eq(id_expression)) }
opts = {
in_operator_optimization_options: {
array_scope: array_scope,
array_mapping_scope: array_mapping_scope,
finder_query: finder_query
}
}
issues = Issue
.order(:created_at, :id)
.keyset_paginate(per_page: 20, keyset_order_options: opts)
.records
```
#### Offset pagination with Kaminari
The `ActiveRecord` scope produced by the `InOperatorOptimization` class can be used in
[offset-paginated](pagination_guidelines.md#offset-pagination)
queries.
```ruby
Gitlab::Pagination::Keyset::InOperatorOptimization::QueryBuilder
.new(...)
.execute
.page(1)
.per(20)
.without_count
```
## Generalized `IN` optimization technique
Let's dive into how `QueryBuilder` builds the optimized query
to fetch the twenty oldest created issues from the group `gitlab-org`
using the generalized `IN` optimization technique.
### Array CTE
As the first step, we use a Common Table Expression (CTE) for collecting the `projects.id` values.
This is done by wrapping the incoming `array_scope` ActiveRecord relation parameter with a CTE.
```sql
WITH array_cte AS MATERIALIZED (
SELECT "projects"."id"
FROM "projects"
WHERE "projects"."namespace_id" IN
(SELECT traversal_ids[array_length(traversal_ids, 1)] AS id
FROM "namespaces"
WHERE (traversal_ids @> ('{9970}')))
)
```
This query produces the following result set with only one column (`projects.id`):
| ID |
| --- |
| 9 |
| 2 |
| 5 |
| 10 |
### Array mapping
For each project (that is, each record storing a project ID in `array_cte`),
we fetch the cursor value identifying the first issue respecting the `ORDER BY` clause.
As an example, let's pick the first record `ID=9` from `array_cte`.
The following query should fetch the cursor value `(created_at, id)` identifying
the first issue record respecting the `ORDER BY` clause for the project with `ID=9`:
```sql
SELECT "issues"."created_at", "issues"."id"
FROM "issues"."project_id"=9
ORDER BY "issues"."created_at" ASC, "issues"."id" ASC
LIMIT 1;
```
We use `LATERAL JOIN` to loop over the records in the `array_cte` and find the
cursor value for each project. The query would be built using the `array_mapping_scope` lambda
function.
```sql
SELECT ARRAY_AGG("array_cte"."id") AS array_cte_id_array,
ARRAY_AGG("issues"."created_at") AS issues_created_at_array,
ARRAY_AGG("issues"."id") AS issues_id_array
FROM (
SELECT "array_cte"."id" FROM array_cte
) array_cte
LEFT JOIN LATERAL
(
SELECT "issues"."created_at", "issues"."id"
FROM "issues"
WHERE "issues"."project_id" = "array_cte"."id"
ORDER BY "issues"."created_at" ASC, "issues"."id" ASC
LIMIT 1
) issues ON TRUE
```
Since we have an index on `project_id`, `created_at`, and `id`,
index-only scans should quickly locate all the cursor values.
This is how the query could be translated to Ruby:
```ruby
created_at_values = []
id_values = []
project_ids.map do |project_id|
created_at, id = Issue.select(:created_at, :id).where(project_id: project_id).order(:created_at, :id).limit(1).first # N+1 but it's fast
created_at_values << created_at
id_values << id
end
```
This is what the result set would look like:
| `project_ids` | `created_at_values` | `id_values` |
| ------------- | ------------------- | ----------- |
| 2 | 2020-01-10 | 5 |
| 5 | 2020-01-05 | 4 |
| 10 | 2020-01-15 | 7 |
| 9 | 2020-01-05 | 3 |
The table shows the cursor values (`created_at, id`) of the first record for each project
respecting the `ORDER BY` clause.
At this point, we have the initial data. To start collecting the actual records from the database,
we use a recursive CTE query where each recursion locates one row until
the `LIMIT` is reached or no more data can be found.
Here's an outline of the steps we take in the recursive CTE query
(expressing the steps in SQL is non-trivial but is explained next):
1. Sort the initial `resultset` according to the `ORDER BY` clause.
1. Pick the top cursor to fetch the record, this is our first record. In the example,
this cursor would be (`2020-01-05`, `3`) for `project_id=9`.
1. We can use (`2020-01-05`, `3`) to fetch the next issue respecting the `ORDER BY` clause
`project_id=9` filter. This produces an updated `resultset`.
| `project_ids` | `created_at_values` | `id_values` |
| ------------- | ------------------- | ----------- |
| 2 | 2020-01-10 | 5 |
| 5 | 2020-01-05 | 4 |
| 10 | 2020-01-15 | 7 |
| **9** | **2020-01-06** | **6** |
1. Repeat 1 to 3 with the updated `resultset` until we have fetched `N=20` records.
### Initializing the recursive CTE query
For the initial recursive query, we need to produce exactly one row, we call this the
initializer query (`initializer_query`).
Use `ARRAY_AGG` function to compact the initial result set into a single row
and use the row as the initial value for the recursive CTE query:
Example initializer row:
| `records` | `project_ids` | `created_at_values` | `id_values` | `Count` | `Position` |
| -------------- | --------------- | ------------------- | ----------- | ------- | ---------- |
| `NULL::issues` | `[9, 2, 5, 10]` | `[...]` | `[...]` | `0` | `NULL` |
- The `records` column contains our sorted database records, and the initializer query sets the
first value to `NULL`, which is filtered out later.
- The `count` column tracks the number of records found. We use this column to filter out the
initializer row from the result set.
### Recursive portion of the CTE query
The result row is produced with the following steps:
1. [Order the keyset arrays.](#order-the-keyset-arrays)
1. [Find the next cursor.](#find-the-next-cursor)
1. [Produce a new row.](#produce-a-new-row)
#### Order the keyset arrays
Order the keyset arrays according to the original `ORDER BY` clause with `LIMIT 1` using the
`UNNEST [] WITH ORDINALITY` table function. The function locates the "lowest" keyset cursor
values and gives us the array position. These cursor values are used to locate the record.
{{< alert type="note" >}}
At this point, we haven't read anything from the database tables, because we relied on
fast index-only scans.
{{< /alert >}}
| `project_ids` | `created_at_values` | `id_values` |
| ------------- | ------------------- | ----------- |
| 2 | 2020-01-10 | 5 |
| 5 | 2020-01-05 | 4 |
| 10 | 2020-01-15 | 7 |
| 9 | 2020-01-05 | 3 |
The first row is the 4th one (`position = 4`), because it has the lowest `created_at` and
`id` values. The `UNNEST` function also exposes the position using an extra column (note:
PostgreSQL uses 1-based index).
Demonstration of the `UNNEST [] WITH ORDINALITY` table function:
```sql
SELECT position FROM unnest('{2020-01-10, 2020-01-05, 2020-01-15, 2020-01-05}'::timestamp[], '{5, 4, 7, 3}'::int[])
WITH ORDINALITY AS t(created_at, id, position) ORDER BY created_at ASC, id ASC LIMIT 1;
```
Result:
```sql
position
----------
4
(1 row)
```
#### Find the next cursor
Now, let's find the next cursor values (`next_cursor_values_query`) for the project with `id = 9`.
To do that, we build a keyset pagination SQL query. Find the next row after
`created_at = 2020-01-05` and `id = 3`. Because we order by two database columns, there can be two
cases:
- There are rows with `created_at = 2020-01-05` and `id > 3`.
- There are rows with `created_at > 2020-01-05`.
Generating this query is done by the generic keyset pagination library. After the query is done,
we have a temporary table with the next cursor values:
| `created_at` | ID |
| ------------ | --- |
| 2020-01-06 | 6 |
#### Produce a new row
As the final step, we need to produce a new row by manipulating the initializer row
(`data_collector_query` method). Two things happen here:
- Read the full row from the DB and return it in the `records` columns. (`result_collector_columns`
method)
- Replace the cursor values at the current position with the results from the keyset query.
Reading the full row from the database is only one index scan by the primary key. We use the
ActiveRecord query passed as the `finder_query`:
```sql
(SELECT "issues".* FROM issues WHERE id = id_values[position] LIMIT 1)
```
By adding parentheses, the result row can be put into the `records` column.
Replacing the cursor values at `position` can be done via standard PostgreSQL array operators:
```sql
-- created_at_values column value
created_at_values[:position-1]||next_cursor_values.created_at||created_at_values[position+1:]
-- id_values column value
id_values[:position-1]||next_cursor_values.id||id_values[position+1:]
```
The Ruby equivalent would be the following:
```ruby
id_values[0..(position - 1)] + [next_cursor_values.id] + id_values[(position + 1)..-1]
```
After this, the recursion starts again by finding the next lowest cursor value.
### Finalizing the query
For producing the final `issues` rows, we wrap the query with another `SELECT` statement:
```sql
SELECT "issues".*
FROM (
SELECT (records).* -- similar to ruby splat operator
FROM recursive_keyset_cte
WHERE recursive_keyset_cte.count <> 0 -- filter out the initializer row
) AS issues
```
### Performance comparison
Assuming that we have the correct database index in place, we can compare the query performance by
looking at the number of database rows accessed by the query.
- Number of groups: 100
- Number of projects: 500
- Number of issues (in the group hierarchy): 50 000
Standard `IN` query:
| Query | Entries read from index | Rows read from the table | Rows sorted in memory |
| ------------------------ | ----------------------- | ------------------------ | --------------------- |
| group hierarchy subquery | 100 | 0 | 0 |
| project lookup query | 500 | 0 | 0 |
| issue lookup query | 50 000 | 20 | 50 000 |
Optimized `IN` query:
| Query | Entries read from index | Rows read from the table | Rows sorted in memory |
| ------------------------ | ----------------------- | ------------------------ | --------------------- |
| group hierarchy subquery | 100 | 0 | 0 |
| project lookup query | 500 | 0 | 0 |
| issue lookup query | 519 | 20 | 10 000 |
The group and project queries are not using sorting, the necessary columns are read from database
indexes. These values are accessed frequently so it's very likely that most of the data is
in the PostgreSQL's buffer cache.
The optimized `IN` query reads maximum 519 entries (cursor values) from the index:
- 500 index-only scans for populating the arrays for each project. The cursor values of the first
record is here.
- Maximum 19 additional index-only scans for the consecutive records.
The optimized `IN` query sorts the array (cursor values per project array) 20 times, which
means we sort 20 x 500 rows. However, this might be a less memory-intensive task than
sorting 10 000 rows at once.
Performance comparison for the `gitlab-org` group:
| Query | Number of 8K Buffers involved | Uncached execution time | Cached execution time |
| -------------------- | ----------------------------- | ----------------------- | --------------------- |
| `IN` query | 240833 | 1.2s | 660ms |
| Optimized `IN` query | 9783 | 450ms | 22ms |
{{< alert type="note" >}}
Before taking measurements, the group lookup query was executed separately to make
the group data available in the buffer cache. Since it's a frequently called query, it
hits many shared buffers during the query execution in the production environment.
{{< /alert >}}
|
---
stage: Data Access
group: Database
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: Efficient `IN` operator queries
breadcrumbs:
- doc
- development
- database
---
This document describes a technique for building efficient ordered database queries with the `IN`
SQL operator and the usage of a GitLab utility module to help apply the technique.
{{< alert type="note" >}}
The described technique makes heavy use of
[keyset pagination](pagination_guidelines.md#keyset-pagination).
It's advised to get familiar with the topic first.
{{< /alert >}}
## Motivation
In GitLab, many domain objects like `Issue` live under nested hierarchies of projects and groups.
To fetch nested database records for domain objects at the group-level,
we often perform queries with the `IN` SQL operator.
We are usually interested in ordering the records by some attributes
and limiting the number of records using `ORDER BY` and `LIMIT` clauses for performance.
Pagination may be used to fetch subsequent records.
Example tasks requiring querying nested domain objects from the group level:
- Show first 20 issues by creation date or due date from the group `gitlab-org`.
- Show first 20 merge requests by merged at date from the group `gitlab-com`.
Unfortunately, ordered group-level queries typically perform badly
as their executions require heavy I/O, memory, and computations.
Let's do an in-depth examination of executing one such query.
### Performance problems with `IN` queries
Consider the task of fetching the twenty oldest created issues
from the group `gitlab-org` with the following query:
```sql
SELECT "issues".*
FROM "issues"
WHERE "issues"."project_id" IN
(SELECT "projects"."id"
FROM "projects"
WHERE "projects"."namespace_id" IN
(SELECT traversal_ids[array_length(traversal_ids, 1)] AS id
FROM "namespaces"
WHERE (traversal_ids @> ('{9970}'))))
ORDER BY "issues"."created_at" ASC,
"issues"."id" ASC
LIMIT 20
```
{{< alert type="note" >}}
For pagination, ordering by the `created_at` column is not enough,
we must add the `id` column as a
[tie-breaker](pagination_performance_guidelines.md#tie-breaker-column).
{{< /alert >}}
The execution of the query can be largely broken down into three steps:
1. The database accesses both `namespaces` and `projects` tables
to find all projects from all groups in the group hierarchy.
1. The database retrieves `issues` records for each project causing heavy disk I/O.
Ideally, an appropriate index configuration should optimize this process.
1. The database sorts the `issues` rows in memory by `created_at` and returns `LIMIT 20` rows to
the end-user. For large groups, this final step requires both large memory and CPU resources.
Execution plan for this DB query:
```sql
Limit (cost=90170.07..90170.12 rows=20 width=1329) (actual time=967.597..967.607 rows=20 loops=1)
Buffers: shared hit=239127 read=3060
I/O Timings: read=336.879
-> Sort (cost=90170.07..90224.02 rows=21578 width=1329) (actual time=967.596..967.603 rows=20 loops=1)
Sort Key: issues.created_at, issues.id
Sort Method: top-N heapsort Memory: 74kB
Buffers: shared hit=239127 read=3060
I/O Timings: read=336.879
-> Nested Loop (cost=1305.66..89595.89 rows=21578 width=1329) (actual time=4.709..797.659 rows=241534 loops=1)
Buffers: shared hit=239121 read=3060
I/O Timings: read=336.879
-> HashAggregate (cost=1305.10..1360.22 rows=5512 width=4) (actual time=4.657..5.370 rows=1528 loops=1)
Group Key: projects.id
Buffers: shared hit=2597
-> Nested Loop (cost=576.76..1291.32 rows=5512 width=4) (actual time=2.427..4.244 rows=1528 loops=1)
Buffers: shared hit=2597
-> HashAggregate (cost=576.32..579.06 rows=274 width=25) (actual time=2.406..2.447 rows=265 loops=1)
Group Key: namespaces.traversal_ids[array_length(namespaces.traversal_ids, 1)]
Buffers: shared hit=334
-> Bitmap Heap Scan on namespaces (cost=141.62..575.63 rows=274 width=25) (actual time=1.933..2.330 rows=265 loops=1)
Recheck Cond: (traversal_ids @> '{9970}'::integer[])
Heap Blocks: exact=243
Buffers: shared hit=334
-> Bitmap Index Scan on index_namespaces_on_traversal_ids (cost=0.00..141.55 rows=274 width=0) (actual time=1.897..1.898 rows=265 loops=1)
Index Cond: (traversal_ids @> '{9970}'::integer[])
Buffers: shared hit=91
-> Index Only Scan using index_projects_on_namespace_id_and_id on projects (cost=0.44..2.40 rows=20 width=8) (actual time=0.004..0.006 rows=6 loops=265)
Index Cond: (namespace_id = (namespaces.traversal_ids)[array_length(namespaces.traversal_ids, 1)])
Heap Fetches: 51
Buffers: shared hit=2263
-> Index Scan using index_issues_on_project_id_and_iid on issues (cost=0.57..10.57 rows=544 width=1329) (actual time=0.114..0.484 rows=158 loops=1528)
Index Cond: (project_id = projects.id)
Buffers: shared hit=236524 read=3060
I/O Timings: read=336.879
Planning Time: 7.750 ms
Execution Time: 967.973 ms
(36 rows)
```
The performance of the query depends on the number of rows in the database.
On average, we can say the following:
- Number of groups in the group-hierarchy: less than 1 000
- Number of projects: less than 5 000
- Number of issues: less than 100 000
From the list, it's apparent that the number of `issues` records has
the largest impact on the performance.
As per typical usage, we can say that the number of issue records grows
at a faster rate than the `namespaces` and the `projects` records.
This problem affects most of our group-level features where records are listed
in a specific order, such as group-level issues, merge requests pages, and APIs.
For very large groups the database queries can easily time out, causing HTTP 500 errors.
## Optimizing ordered `IN` queries
In the talk ["How to teach an elephant to dance rock and roll"](https://www.youtube.com/watch?v=Ha38lcjVyhQ),
Maxim Boguk demonstrated a technique to optimize a special class of ordered `IN` queries,
such as our ordered group-level queries.
A typical ordered `IN` query may look like this:
```sql
SELECT t.* FROM t
WHERE t.fkey IN (value_set)
ORDER BY t.pkey
LIMIT N;
```
Here's the key insight used in the technique: we need at most `|value_set| + N` record lookups,
rather than retrieving all records satisfying the condition `t.fkey IN value_set` (`|value_set|`
is the number of values in `value_set`).
We adopted and generalized the technique for use in GitLab by implementing utilities in the
`Gitlab::Pagination::Keyset::InOperatorOptimization` class to facilitate building efficient `IN`
queries.
### Requirements
The technique is not a drop-in replacement for the existing group-level queries using `IN` operator.
The technique can only optimize `IN` queries that satisfy the following requirements:
- `LIMIT` is present, which usually means that the query is paginated
(offset or keyset pagination).
- The column used with the `IN` query and the columns in the `ORDER BY`
clause are covered with a database index. The columns in the index must be
in the following order: `column_for_the_in_query`, `order by column 1`, and
`order by column 2`.
- The columns in the `ORDER BY` clause are distinct
(the combination of the columns uniquely identifies one particular row in the table).
{{< alert type="warning" >}}
This technique does not improve the performance of the `COUNT(*)` queries.
{{< /alert >}}
## The `InOperatorOptimization` module
The `Gitlab::Pagination::Keyset::InOperatorOptimization` module implements utilities for applying a generalized version of
the efficient `IN` query technique described in the previous section.
To build optimized, ordered `IN` queries that meet [the requirements](#requirements),
use the utility class `QueryBuilder` from the module.
{{< alert type="note" >}}
The generic keyset pagination module introduced in the merge request
[51481](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/51481)
plays a fundamental role in the generalized implementation of the technique
in `Gitlab::Pagination::Keyset::InOperatorOptimization`.
{{< /alert >}}
### Basic usage of `QueryBuilder`
To illustrate a basic usage, we build a query that
fetches 20 issues with the oldest `created_at` from the group `gitlab-org`.
The following ActiveRecord query would produce a query similar to
[the unoptimized query](#performance-problems-with-in-queries) that we examined earlier:
```ruby
scope = Issue
.where(project_id: Group.find(9970).all_projects.select(:id)) # `gitlab-org` group and its subgroups
.order(:created_at, :id)
.limit(20)
```
Instead, use the query builder `InOperatorOptimization::QueryBuilder` to produce an optimized
version:
```ruby
scope = Issue.order(:created_at, :id)
array_scope = Group.find(9970).all_projects.select(:id)
array_mapping_scope = -> (id_expression) { Issue.where(Issue.arel_table[:project_id].eq(id_expression)) }
finder_query = -> (created_at_expression, id_expression) { Issue.where(Issue.arel_table[:id].eq(id_expression)) }
Gitlab::Pagination::Keyset::InOperatorOptimization::QueryBuilder.new(
scope: scope,
array_scope: array_scope,
array_mapping_scope: array_mapping_scope,
finder_query: finder_query
).execute.limit(20)
```
- `scope` represents the original `ActiveRecord::Relation` object without the `IN` query. The
relation should define an order which must be supported by the
[keyset pagination library](keyset_pagination.md#usage).
- `array_scope` contains the `ActiveRecord::Relation` object, which represents the original
`IN (subquery)`. The select values must contain the columns by which the subquery is "connected"
to the main query: the `id` of the project record.
- `array_mapping_scope` defines a lambda returning an `ActiveRecord::Relation` object. The lambda
matches (`=`) single select values from the `array_scope`. The lambda yields as many
arguments as the select values defined in the `array_scope`. The arguments are Arel SQL expressions.
- `finder_query` loads the actual record row from the database. It must also be a lambda, where
the order by column expressions is available for locating the record. In this example, the
yielded values are `created_at` and `id` SQL expressions. Finding a record is very fast via the
primary key, so we don't use the `created_at` value. Providing the `finder_query` lambda is optional.
If it's not given, the `IN` operator optimization only makes the `ORDER BY` columns available to
the end-user and not the full database row.
The following database index on the `issues` table must be present
to make the query execute efficiently:
```sql
"idx_issues_on_project_id_and_created_at_and_id" btree (project_id, created_at, id)
```
The SQL query:
```sql
SELECT "issues".*
FROM
(WITH RECURSIVE "array_cte" AS MATERIALIZED
(SELECT "projects"."id"
FROM "projects"
WHERE "projects"."namespace_id" IN
(SELECT traversal_ids[array_length(traversal_ids, 1)] AS id
FROM "namespaces"
WHERE (traversal_ids @> ('{9970}')))),
"recursive_keyset_cte" AS ( -- initializer row start
(SELECT NULL::issues AS records,
array_cte_id_array,
issues_created_at_array,
issues_id_array,
0::bigint AS COUNT
FROM
(SELECT ARRAY_AGG("array_cte"."id") AS array_cte_id_array,
ARRAY_AGG("issues"."created_at") AS issues_created_at_array,
ARRAY_AGG("issues"."id") AS issues_id_array
FROM
(SELECT "array_cte"."id"
FROM array_cte) array_cte
LEFT JOIN LATERAL
(SELECT "issues"."created_at",
"issues"."id"
FROM "issues"
WHERE "issues"."project_id" = "array_cte"."id"
ORDER BY "issues"."created_at" ASC, "issues"."id" ASC
LIMIT 1) issues ON TRUE
WHERE "issues"."created_at" IS NOT NULL
AND "issues"."id" IS NOT NULL) array_scope_lateral_query
LIMIT 1)
-- initializer row finished
UNION ALL
(SELECT
-- result row start
(SELECT issues -- record finder query as the first column
FROM "issues"
WHERE "issues"."id" = recursive_keyset_cte.issues_id_array[position]
LIMIT 1),
array_cte_id_array,
recursive_keyset_cte.issues_created_at_array[:position_query.position-1]||next_cursor_values.created_at||recursive_keyset_cte.issues_created_at_array[position_query.position+1:],
recursive_keyset_cte.issues_id_array[:position_query.position-1]||next_cursor_values.id||recursive_keyset_cte.issues_id_array[position_query.position+1:],
recursive_keyset_cte.count + 1
-- result row finished
FROM recursive_keyset_cte,
LATERAL
-- finding the cursor values of the next record start
(SELECT created_at,
id,
position
FROM UNNEST(issues_created_at_array, issues_id_array) WITH
ORDINALITY AS u(created_at, id, position)
WHERE created_at IS NOT NULL
AND id IS NOT NULL
ORDER BY "created_at" ASC, "id" ASC
LIMIT 1) AS position_query,
-- finding the cursor values of the next record end
-- finding the next cursor values (next_cursor_values_query) start
LATERAL
(SELECT "record"."created_at",
"record"."id"
FROM (
VALUES (NULL,
NULL)) AS nulls
LEFT JOIN
(SELECT "issues"."created_at",
"issues"."id"
FROM (
(SELECT "issues"."created_at",
"issues"."id"
FROM "issues"
WHERE "issues"."project_id" = recursive_keyset_cte.array_cte_id_array[position]
AND recursive_keyset_cte.issues_created_at_array[position] IS NULL
AND "issues"."created_at" IS NULL
AND "issues"."id" > recursive_keyset_cte.issues_id_array[position]
ORDER BY "issues"."created_at" ASC, "issues"."id" ASC)
UNION ALL
(SELECT "issues"."created_at",
"issues"."id"
FROM "issues"
WHERE "issues"."project_id" = recursive_keyset_cte.array_cte_id_array[position]
AND recursive_keyset_cte.issues_created_at_array[position] IS NOT NULL
AND "issues"."created_at" IS NULL
ORDER BY "issues"."created_at" ASC, "issues"."id" ASC)
UNION ALL
(SELECT "issues"."created_at",
"issues"."id"
FROM "issues"
WHERE "issues"."project_id" = recursive_keyset_cte.array_cte_id_array[position]
AND recursive_keyset_cte.issues_created_at_array[position] IS NOT NULL
AND "issues"."created_at" > recursive_keyset_cte.issues_created_at_array[position]
ORDER BY "issues"."created_at" ASC, "issues"."id" ASC)
UNION ALL
(SELECT "issues"."created_at",
"issues"."id"
FROM "issues"
WHERE "issues"."project_id" = recursive_keyset_cte.array_cte_id_array[position]
AND recursive_keyset_cte.issues_created_at_array[position] IS NOT NULL
AND "issues"."created_at" = recursive_keyset_cte.issues_created_at_array[position]
AND "issues"."id" > recursive_keyset_cte.issues_id_array[position]
ORDER BY "issues"."created_at" ASC, "issues"."id" ASC)) issues
ORDER BY "issues"."created_at" ASC, "issues"."id" ASC
LIMIT 1) record ON TRUE
LIMIT 1) AS next_cursor_values))
-- finding the next cursor values (next_cursor_values_query) END
SELECT (records).*
FROM "recursive_keyset_cte" AS "issues"
WHERE (COUNT <> 0)) issues -- filtering out the initializer row
LIMIT 20
```
### Using the `IN` query optimization
#### Adding more filters
In this example, let's add an extra filter by `milestone_id`.
Be careful when adding extra filters to the query. If the column is not covered by the same index,
then the query might perform worse than the non-optimized query. The `milestone_id` column in the
`issues` table is currently covered by a different index:
```sql
"index_issues_on_milestone_id" btree (milestone_id)
```
Adding the `milestone_id = X` filter to the `scope` argument or to the optimized scope causes bad performance.
Example (bad):
```ruby
Gitlab::Pagination::Keyset::InOperatorOptimization::QueryBuilder.new(
scope: scope,
array_scope: array_scope,
array_mapping_scope: array_mapping_scope,
finder_query: finder_query
).execute
.where(milestone_id: 5)
.limit(20)
```
To address this concern, we could define another index:
```sql
"idx_issues_on_project_id_and_milestone_id_and_created_at_and_id" btree (project_id, milestone_id, created_at, id)
```
Adding more indexes to the `issues` table could significantly affect the performance of
the `UPDATE` queries. In this case, it's better to rely on the original query. It means that if we
want to use the optimization for the unfiltered page we need to add extra logic in the application code:
```ruby
if optimization_possible? # no extra params or params covered with the same index as the ORDER BY clause
run_optimized_query
else
run_normal_in_query
end
```
#### Multiple `IN` queries
Let's assume that we want to extend the group-level queries to include only incident and test case
issue types.
The original ActiveRecord query would look like this:
```ruby
scope = Issue
.where(project_id: Group.find(9970).all_projects.select(:id)) # `gitlab-org` group and its subgroups
.where(issue_type: [:incident, :test_case]) # 1, 2
.order(:created_at, :id)
.limit(20)
```
To construct the array scope, we need to take the Cartesian product of the `project_id IN` and
the `issue_type IN` queries. `issue_type` is an ActiveRecord enum, so we need to
construct the following table:
| `project_id` | `issue_type_value` |
| ------------ | ------------------ |
| 2 | 1 |
| 2 | 2 |
| 5 | 1 |
| 5 | 2 |
| 10 | 1 |
| 10 | 2 |
| 9 | 1 |
| 9 | 2 |
For the `issue_types` query we can construct a value list without querying a table:
```ruby
value_list = Arel::Nodes::ValuesList.new([[WorkItems::Type.base_types[:incident]],[WorkItems::Type.base_types[:test_case]]])
issue_type_values = Arel::Nodes::Grouping.new(value_list).as('issue_type_values (value)').to_sql
array_scope = Group
.find(9970)
.all_projects
.from("#{Project.table_name}, #{issue_type_values}")
.select(:id, :value)
```
Building the `array_mapping_scope` query requires two arguments: `id` and `issue_type_value`:
```ruby
array_mapping_scope = -> (id_expression, issue_type_value_expression) { Issue.where(Issue.arel_table[:project_id].eq(id_expression)).where(Issue.arel_table[:issue_type].eq(issue_type_value_expression)) }
```
The `scope` and the `finder` queries don't change:
```ruby
scope = Issue.order(:created_at, :id)
finder_query = -> (created_at_expression, id_expression) { Issue.where(Issue.arel_table[:id].eq(id_expression)) }
Gitlab::Pagination::Keyset::InOperatorOptimization::QueryBuilder.new(
scope: scope,
array_scope: array_scope,
array_mapping_scope: array_mapping_scope,
finder_query: finder_query
).execute.limit(20)
```
The SQL query:
```sql
SELECT "issues".*
FROM
(WITH RECURSIVE "array_cte" AS MATERIALIZED
(SELECT "projects"."id", "value"
FROM projects, (
VALUES (1), (2)) AS issue_type_values (value)
WHERE "projects"."namespace_id" IN
(WITH RECURSIVE "base_and_descendants" AS (
(SELECT "namespaces".*
FROM "namespaces"
WHERE "namespaces"."type" = 'Group'
AND "namespaces"."id" = 9970)
UNION
(SELECT "namespaces".*
FROM "namespaces", "base_and_descendants"
WHERE "namespaces"."type" = 'Group'
AND "namespaces"."parent_id" = "base_and_descendants"."id")) SELECT "id"
FROM "base_and_descendants" AS "namespaces")),
"recursive_keyset_cte" AS (
(SELECT NULL::issues AS records,
array_cte_id_array,
array_cte_value_array,
issues_created_at_array,
issues_id_array,
0::bigint AS COUNT
FROM
(SELECT ARRAY_AGG("array_cte"."id") AS array_cte_id_array,
ARRAY_AGG("array_cte"."value") AS array_cte_value_array,
ARRAY_AGG("issues"."created_at") AS issues_created_at_array,
ARRAY_AGG("issues"."id") AS issues_id_array
FROM
(SELECT "array_cte"."id",
"array_cte"."value"
FROM array_cte) array_cte
LEFT JOIN LATERAL
(SELECT "issues"."created_at",
"issues"."id"
FROM "issues"
WHERE "issues"."project_id" = "array_cte"."id"
AND "issues"."issue_type" = "array_cte"."value"
ORDER BY "issues"."created_at" ASC, "issues"."id" ASC
LIMIT 1) issues ON TRUE
WHERE "issues"."created_at" IS NOT NULL
AND "issues"."id" IS NOT NULL) array_scope_lateral_query
LIMIT 1)
UNION ALL
(SELECT
(SELECT issues
FROM "issues"
WHERE "issues"."id" = recursive_keyset_cte.issues_id_array[POSITION]
LIMIT 1), array_cte_id_array,
array_cte_value_array,
recursive_keyset_cte.issues_created_at_array[:position_query.position-1]||next_cursor_values.created_at||recursive_keyset_cte.issues_created_at_array[position_query.position+1:], recursive_keyset_cte.issues_id_array[:position_query.position-1]||next_cursor_values.id||recursive_keyset_cte.issues_id_array[position_query.position+1:], recursive_keyset_cte.count + 1
FROM recursive_keyset_cte,
LATERAL
(SELECT created_at,
id,
POSITION
FROM UNNEST(issues_created_at_array, issues_id_array) WITH
ORDINALITY AS u(created_at, id, POSITION)
WHERE created_at IS NOT NULL
AND id IS NOT NULL
ORDER BY "created_at" ASC, "id" ASC
LIMIT 1) AS position_query,
LATERAL
(SELECT "record"."created_at",
"record"."id"
FROM (
VALUES (NULL,
NULL)) AS nulls
LEFT JOIN
(SELECT "issues"."created_at",
"issues"."id"
FROM (
(SELECT "issues"."created_at",
"issues"."id"
FROM "issues"
WHERE "issues"."project_id" = recursive_keyset_cte.array_cte_id_array[POSITION]
AND "issues"."issue_type" = recursive_keyset_cte.array_cte_value_array[POSITION]
AND recursive_keyset_cte.issues_created_at_array[POSITION] IS NULL
AND "issues"."created_at" IS NULL
AND "issues"."id" > recursive_keyset_cte.issues_id_array[POSITION]
ORDER BY "issues"."created_at" ASC, "issues"."id" ASC)
UNION ALL
(SELECT "issues"."created_at",
"issues"."id"
FROM "issues"
WHERE "issues"."project_id" = recursive_keyset_cte.array_cte_id_array[POSITION]
AND "issues"."issue_type" = recursive_keyset_cte.array_cte_value_array[POSITION]
AND recursive_keyset_cte.issues_created_at_array[POSITION] IS NOT NULL
AND "issues"."created_at" IS NULL
ORDER BY "issues"."created_at" ASC, "issues"."id" ASC)
UNION ALL
(SELECT "issues"."created_at",
"issues"."id"
FROM "issues"
WHERE "issues"."project_id" = recursive_keyset_cte.array_cte_id_array[POSITION]
AND "issues"."issue_type" = recursive_keyset_cte.array_cte_value_array[POSITION]
AND recursive_keyset_cte.issues_created_at_array[POSITION] IS NOT NULL
AND "issues"."created_at" > recursive_keyset_cte.issues_created_at_array[POSITION]
ORDER BY "issues"."created_at" ASC, "issues"."id" ASC)
UNION ALL
(SELECT "issues"."created_at",
"issues"."id"
FROM "issues"
WHERE "issues"."project_id" = recursive_keyset_cte.array_cte_id_array[POSITION]
AND "issues"."issue_type" = recursive_keyset_cte.array_cte_value_array[POSITION]
AND recursive_keyset_cte.issues_created_at_array[POSITION] IS NOT NULL
AND "issues"."created_at" = recursive_keyset_cte.issues_created_at_array[POSITION]
AND "issues"."id" > recursive_keyset_cte.issues_id_array[POSITION]
ORDER BY "issues"."created_at" ASC, "issues"."id" ASC)) issues
ORDER BY "issues"."created_at" ASC, "issues"."id" ASC
LIMIT 1) record ON TRUE
LIMIT 1) AS next_cursor_values)) SELECT (records).*
FROM "recursive_keyset_cte" AS "issues"
WHERE (COUNT <> 0)) issues
LIMIT 20
```
{{< alert type="note" >}}
To make the query efficient, the following columns need to be covered with an index: `project_id`, `issue_type`, `created_at`, and `id`.
{{< /alert >}}
#### Using calculated `ORDER BY` expression
The following example orders epic records by the duration between the creation time and closed
time. It is calculated with the following formula:
```sql
SELECT EXTRACT('epoch' FROM epics.closed_at - epics.created_at) FROM epics
```
The query above returns the duration in seconds (`double precision`) between the two timestamp
columns in seconds. To order the records by this expression, you must reference it
in the `ORDER BY` clause:
```sql
SELECT EXTRACT('epoch' FROM epics.closed_at - epics.created_at)
FROM epics
ORDER BY EXTRACT('epoch' FROM epics.closed_at - epics.created_at) DESC
```
To make this ordering efficient on the group-level with the in-operator optimization, use a
custom `ORDER BY` configuration. Since the duration is not a distinct value (no unique index
present), you must add a tie-breaker column (`id`).
The following example shows the final `ORDER BY` clause:
```sql
ORDER BY extract('epoch' FROM epics.closed_at - epics.created_at) DESC, epics.id DESC
```
Snippet for loading records ordered by the calculated duration:
```ruby
arel_table = Epic.arel_table
order = Gitlab::Pagination::Keyset::Order.build([
Gitlab::Pagination::Keyset::ColumnOrderDefinition.new(
attribute_name: 'duration_in_seconds',
order_expression: Arel.sql('EXTRACT(EPOCH FROM epics.closed_at - epics.created_at)').desc,
sql_type: 'double precision' # important for calculated SQL expressions
),
Gitlab::Pagination::Keyset::ColumnOrderDefinition.new(
attribute_name: 'id',
order_expression: arel_table[:id].desc
)
])
records = Gitlab::Pagination::Keyset::InOperatorOptimization::QueryBuilder.new(
scope: Epic.where.not(closed_at: nil).reorder(order), # filter out NULL values
array_scope: Group.find(9970).self_and_descendants.select(:id),
array_mapping_scope: -> (id_expression) { Epic.where(Epic.arel_table[:group_id].eq(id_expression)) }
).execute.limit(20)
puts records.pluck(:duration_in_seconds, :id) # other columns are not available
```
Building the query requires quite a bit of configuration. For the order configuration you
can find more information within the
[complex order configuration](keyset_pagination.md#complex-order-configuration)
section for keyset paginated database queries.
The query requires a specialized database index:
```sql
CREATE INDEX index_epics_on_duration ON epics USING btree (group_id, EXTRACT(EPOCH FROM epics.closed_at - epics.created_at) DESC, id DESC) WHERE (closed_at IS NOT NULL);
```
Notice that the `finder_query` parameter is not used. The query only returns the `ORDER BY` columns
which are the `duration_in_seconds` (calculated column) and the `id` columns. This is a limitation
of the feature, defining the `finder_query` with calculated `ORDER BY` expressions is not supported.
To get the complete database records, an extra query can be invoked by the returned `id` column:
```ruby
records_by_id = records.index_by(&:id)
complete_records = Epic.where(id: records_by_id.keys).index_by(&:id)
# Printing the complete records according to the `ORDER BY` clause
records_by_id.each do |id, _|
puts complete_records[id].attributes
end
```
#### Ordering by `JOIN` columns
Ordering records by mixed columns where one or more columns are coming from `JOIN` tables
works with limitations. It requires extra configuration via Common Table Expression (CTE). The trick is to use a
non-materialized CTE to act as a "fake" table which exposes all required columns.
{{< alert type="note" >}}
The query performance might not improve compared to the standard `IN` query. Always
check the query plan.
{{< /alert >}}
Example: order issues by `projects.name, issues.id` within the group hierarchy
The first step is to create a CTE, where all required columns are collected in the `SELECT`
clause.
```ruby
cte_query = Issue
.select('issues.id AS id', 'issues.project_id AS project_id', 'projects.name AS projects_name')
.joins(:project)
cte = Gitlab::SQL::CTE.new(:issue_with_projects, cte_query, materialized: false)
```
Custom order object configuration:
```ruby
order = Gitlab::Pagination::Keyset::Order.build([
Gitlab::Pagination::Keyset::ColumnOrderDefinition.new(
attribute_name: 'projects_name',
order_expression: Issue.arel_table[:projects_name].asc,
sql_type: 'character varying',
nullable: :nulls_last
),
Gitlab::Pagination::Keyset::ColumnOrderDefinition.new(
attribute_name: :id,
order_expression: Issue.arel_table[:id].asc
)
])
```
Generate the query:
```ruby
scope = cte.apply_to(Issue.where({}).reorder(order))
opts = {
scope: scope,
array_scope: Project.where(namespace_id: top_level_group.self_and_descendants.select(:id)).select(:id),
array_mapping_scope: -> (id_expression) { Issue.where(Issue.arel_table[:project_id].eq(id_expression)) }
}
records = Gitlab::Pagination::Keyset::InOperatorOptimization::QueryBuilder
.new(**opts)
.execute
.limit(20)
```
#### Batch iteration
Batch iteration over the records is possible via the keyset `Iterator` class.
```ruby
scope = Issue.order(:created_at, :id)
array_scope = Group.find(9970).all_projects.select(:id)
array_mapping_scope = -> (id_expression) { Issue.where(Issue.arel_table[:project_id].eq(id_expression)) }
finder_query = -> (created_at_expression, id_expression) { Issue.where(Issue.arel_table[:id].eq(id_expression)) }
opts = {
in_operator_optimization_options: {
array_scope: array_scope,
array_mapping_scope: array_mapping_scope,
finder_query: finder_query
}
}
Gitlab::Pagination::Keyset::Iterator.new(scope: scope, **opts).each_batch(of: 100) do |records|
puts records.select(:id).map { |r| [r.id] }
end
```
{{< alert type="note" >}}
The query loads complete database rows from the disk. This may cause increased I/O and slower
database queries. Depending on the use case, the primary key is often only
needed for the batch query to invoke additional statements. For example, `UPDATE` or `DELETE`. The
`id` column is included in the `ORDER BY` columns (`created_at` and `id`) and is already
loaded. In this case, you can omit the `finder_query` parameter.
{{< /alert >}}
Example for loading the `ORDER BY` columns only:
```ruby
scope = Issue.order(:created_at, :id)
array_scope = Group.find(9970).all_projects.select(:id)
array_mapping_scope = -> (id_expression) { Issue.where(Issue.arel_table[:project_id].eq(id_expression)) }
opts = {
in_operator_optimization_options: {
array_scope: array_scope,
array_mapping_scope: array_mapping_scope
}
}
Gitlab::Pagination::Keyset::Iterator.new(scope: scope, **opts).each_batch(of: 100) do |records|
puts records.select(:id).map { |r| [r.id] } # only id and created_at are available
end
```
#### Keyset pagination
The optimization works out of the box with GraphQL and the `keyset_paginate` helper method.
Read more about [keyset pagination](keyset_pagination.md).
```ruby
array_scope = Group.find(9970).all_projects.select(:id)
array_mapping_scope = -> (id_expression) { Issue.where(Issue.arel_table[:project_id].eq(id_expression)) }
finder_query = -> (created_at_expression, id_expression) { Issue.where(Issue.arel_table[:id].eq(id_expression)) }
opts = {
in_operator_optimization_options: {
array_scope: array_scope,
array_mapping_scope: array_mapping_scope,
finder_query: finder_query
}
}
issues = Issue
.order(:created_at, :id)
.keyset_paginate(per_page: 20, keyset_order_options: opts)
.records
```
#### Offset pagination with Kaminari
The `ActiveRecord` scope produced by the `InOperatorOptimization` class can be used in
[offset-paginated](pagination_guidelines.md#offset-pagination)
queries.
```ruby
Gitlab::Pagination::Keyset::InOperatorOptimization::QueryBuilder
.new(...)
.execute
.page(1)
.per(20)
.without_count
```
## Generalized `IN` optimization technique
Let's dive into how `QueryBuilder` builds the optimized query
to fetch the twenty oldest created issues from the group `gitlab-org`
using the generalized `IN` optimization technique.
### Array CTE
As the first step, we use a Common Table Expression (CTE) for collecting the `projects.id` values.
This is done by wrapping the incoming `array_scope` ActiveRecord relation parameter with a CTE.
```sql
WITH array_cte AS MATERIALIZED (
SELECT "projects"."id"
FROM "projects"
WHERE "projects"."namespace_id" IN
(SELECT traversal_ids[array_length(traversal_ids, 1)] AS id
FROM "namespaces"
WHERE (traversal_ids @> ('{9970}')))
)
```
This query produces the following result set with only one column (`projects.id`):
| ID |
| --- |
| 9 |
| 2 |
| 5 |
| 10 |
### Array mapping
For each project (that is, each record storing a project ID in `array_cte`),
we fetch the cursor value identifying the first issue respecting the `ORDER BY` clause.
As an example, let's pick the first record `ID=9` from `array_cte`.
The following query should fetch the cursor value `(created_at, id)` identifying
the first issue record respecting the `ORDER BY` clause for the project with `ID=9`:
```sql
SELECT "issues"."created_at", "issues"."id"
FROM "issues"."project_id"=9
ORDER BY "issues"."created_at" ASC, "issues"."id" ASC
LIMIT 1;
```
We use `LATERAL JOIN` to loop over the records in the `array_cte` and find the
cursor value for each project. The query would be built using the `array_mapping_scope` lambda
function.
```sql
SELECT ARRAY_AGG("array_cte"."id") AS array_cte_id_array,
ARRAY_AGG("issues"."created_at") AS issues_created_at_array,
ARRAY_AGG("issues"."id") AS issues_id_array
FROM (
SELECT "array_cte"."id" FROM array_cte
) array_cte
LEFT JOIN LATERAL
(
SELECT "issues"."created_at", "issues"."id"
FROM "issues"
WHERE "issues"."project_id" = "array_cte"."id"
ORDER BY "issues"."created_at" ASC, "issues"."id" ASC
LIMIT 1
) issues ON TRUE
```
Since we have an index on `project_id`, `created_at`, and `id`,
index-only scans should quickly locate all the cursor values.
This is how the query could be translated to Ruby:
```ruby
created_at_values = []
id_values = []
project_ids.map do |project_id|
created_at, id = Issue.select(:created_at, :id).where(project_id: project_id).order(:created_at, :id).limit(1).first # N+1 but it's fast
created_at_values << created_at
id_values << id
end
```
This is what the result set would look like:
| `project_ids` | `created_at_values` | `id_values` |
| ------------- | ------------------- | ----------- |
| 2 | 2020-01-10 | 5 |
| 5 | 2020-01-05 | 4 |
| 10 | 2020-01-15 | 7 |
| 9 | 2020-01-05 | 3 |
The table shows the cursor values (`created_at, id`) of the first record for each project
respecting the `ORDER BY` clause.
At this point, we have the initial data. To start collecting the actual records from the database,
we use a recursive CTE query where each recursion locates one row until
the `LIMIT` is reached or no more data can be found.
Here's an outline of the steps we take in the recursive CTE query
(expressing the steps in SQL is non-trivial but is explained next):
1. Sort the initial `resultset` according to the `ORDER BY` clause.
1. Pick the top cursor to fetch the record, this is our first record. In the example,
this cursor would be (`2020-01-05`, `3`) for `project_id=9`.
1. We can use (`2020-01-05`, `3`) to fetch the next issue respecting the `ORDER BY` clause
`project_id=9` filter. This produces an updated `resultset`.
| `project_ids` | `created_at_values` | `id_values` |
| ------------- | ------------------- | ----------- |
| 2 | 2020-01-10 | 5 |
| 5 | 2020-01-05 | 4 |
| 10 | 2020-01-15 | 7 |
| **9** | **2020-01-06** | **6** |
1. Repeat 1 to 3 with the updated `resultset` until we have fetched `N=20` records.
### Initializing the recursive CTE query
For the initial recursive query, we need to produce exactly one row, we call this the
initializer query (`initializer_query`).
Use `ARRAY_AGG` function to compact the initial result set into a single row
and use the row as the initial value for the recursive CTE query:
Example initializer row:
| `records` | `project_ids` | `created_at_values` | `id_values` | `Count` | `Position` |
| -------------- | --------------- | ------------------- | ----------- | ------- | ---------- |
| `NULL::issues` | `[9, 2, 5, 10]` | `[...]` | `[...]` | `0` | `NULL` |
- The `records` column contains our sorted database records, and the initializer query sets the
first value to `NULL`, which is filtered out later.
- The `count` column tracks the number of records found. We use this column to filter out the
initializer row from the result set.
### Recursive portion of the CTE query
The result row is produced with the following steps:
1. [Order the keyset arrays.](#order-the-keyset-arrays)
1. [Find the next cursor.](#find-the-next-cursor)
1. [Produce a new row.](#produce-a-new-row)
#### Order the keyset arrays
Order the keyset arrays according to the original `ORDER BY` clause with `LIMIT 1` using the
`UNNEST [] WITH ORDINALITY` table function. The function locates the "lowest" keyset cursor
values and gives us the array position. These cursor values are used to locate the record.
{{< alert type="note" >}}
At this point, we haven't read anything from the database tables, because we relied on
fast index-only scans.
{{< /alert >}}
| `project_ids` | `created_at_values` | `id_values` |
| ------------- | ------------------- | ----------- |
| 2 | 2020-01-10 | 5 |
| 5 | 2020-01-05 | 4 |
| 10 | 2020-01-15 | 7 |
| 9 | 2020-01-05 | 3 |
The first row is the 4th one (`position = 4`), because it has the lowest `created_at` and
`id` values. The `UNNEST` function also exposes the position using an extra column (note:
PostgreSQL uses 1-based index).
Demonstration of the `UNNEST [] WITH ORDINALITY` table function:
```sql
SELECT position FROM unnest('{2020-01-10, 2020-01-05, 2020-01-15, 2020-01-05}'::timestamp[], '{5, 4, 7, 3}'::int[])
WITH ORDINALITY AS t(created_at, id, position) ORDER BY created_at ASC, id ASC LIMIT 1;
```
Result:
```sql
position
----------
4
(1 row)
```
#### Find the next cursor
Now, let's find the next cursor values (`next_cursor_values_query`) for the project with `id = 9`.
To do that, we build a keyset pagination SQL query. Find the next row after
`created_at = 2020-01-05` and `id = 3`. Because we order by two database columns, there can be two
cases:
- There are rows with `created_at = 2020-01-05` and `id > 3`.
- There are rows with `created_at > 2020-01-05`.
Generating this query is done by the generic keyset pagination library. After the query is done,
we have a temporary table with the next cursor values:
| `created_at` | ID |
| ------------ | --- |
| 2020-01-06 | 6 |
#### Produce a new row
As the final step, we need to produce a new row by manipulating the initializer row
(`data_collector_query` method). Two things happen here:
- Read the full row from the DB and return it in the `records` columns. (`result_collector_columns`
method)
- Replace the cursor values at the current position with the results from the keyset query.
Reading the full row from the database is only one index scan by the primary key. We use the
ActiveRecord query passed as the `finder_query`:
```sql
(SELECT "issues".* FROM issues WHERE id = id_values[position] LIMIT 1)
```
By adding parentheses, the result row can be put into the `records` column.
Replacing the cursor values at `position` can be done via standard PostgreSQL array operators:
```sql
-- created_at_values column value
created_at_values[:position-1]||next_cursor_values.created_at||created_at_values[position+1:]
-- id_values column value
id_values[:position-1]||next_cursor_values.id||id_values[position+1:]
```
The Ruby equivalent would be the following:
```ruby
id_values[0..(position - 1)] + [next_cursor_values.id] + id_values[(position + 1)..-1]
```
After this, the recursion starts again by finding the next lowest cursor value.
### Finalizing the query
For producing the final `issues` rows, we wrap the query with another `SELECT` statement:
```sql
SELECT "issues".*
FROM (
SELECT (records).* -- similar to ruby splat operator
FROM recursive_keyset_cte
WHERE recursive_keyset_cte.count <> 0 -- filter out the initializer row
) AS issues
```
### Performance comparison
Assuming that we have the correct database index in place, we can compare the query performance by
looking at the number of database rows accessed by the query.
- Number of groups: 100
- Number of projects: 500
- Number of issues (in the group hierarchy): 50 000
Standard `IN` query:
| Query | Entries read from index | Rows read from the table | Rows sorted in memory |
| ------------------------ | ----------------------- | ------------------------ | --------------------- |
| group hierarchy subquery | 100 | 0 | 0 |
| project lookup query | 500 | 0 | 0 |
| issue lookup query | 50 000 | 20 | 50 000 |
Optimized `IN` query:
| Query | Entries read from index | Rows read from the table | Rows sorted in memory |
| ------------------------ | ----------------------- | ------------------------ | --------------------- |
| group hierarchy subquery | 100 | 0 | 0 |
| project lookup query | 500 | 0 | 0 |
| issue lookup query | 519 | 20 | 10 000 |
The group and project queries are not using sorting, the necessary columns are read from database
indexes. These values are accessed frequently so it's very likely that most of the data is
in the PostgreSQL's buffer cache.
The optimized `IN` query reads maximum 519 entries (cursor values) from the index:
- 500 index-only scans for populating the arrays for each project. The cursor values of the first
record is here.
- Maximum 19 additional index-only scans for the consecutive records.
The optimized `IN` query sorts the array (cursor values per project array) 20 times, which
means we sort 20 x 500 rows. However, this might be a less memory-intensive task than
sorting 10 000 rows at once.
Performance comparison for the `gitlab-org` group:
| Query | Number of 8K Buffers involved | Uncached execution time | Cached execution time |
| -------------------- | ----------------------------- | ----------------------- | --------------------- |
| `IN` query | 240833 | 1.2s | 660ms |
| Optimized `IN` query | 9783 | 450ms | 22ms |
{{< alert type="note" >}}
Before taking measurements, the group lookup query was executed separately to make
the group data available in the buffer cache. Since it's a frequently called query, it
hits many shared buffers during the query execution in the production environment.
{{< /alert >}}
|
https://docs.gitlab.com/development/ci_mirrored_tables
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/ci_mirrored_tables.md
|
2025-08-13
|
doc/development/database
|
[
"doc",
"development",
"database"
] |
ci_mirrored_tables.md
|
Data Access
|
Database Frameworks
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
CI mirrored tables
| null |
## Problem statement
As part of the database [decomposition work](https://gitlab.com/groups/gitlab-org/-/epics/6168),
which had the goal of splitting the single database GitLab is using, into two databases: `main` and
`ci`, came the big challenge of
[removing all joins between the `main` and the `ci` tables](multiple_databases.md#removing-joins-between-main-and-non-main-tables).
That is because PostgreSQL doesn't support joins between tables that belong to different databases.
However, some core application models in the main database are queried very often by the CI side.
For example:
- `Namespace`, in the `namespaces` table.
- `Project`, in the `projects` table.
Not being able to do `joins` on these tables brings a great challenge. The team chose to perform logical
replication of those tables from the main database to the CI database, in the new tables:
- `ci_namespace_mirrors`, as a mirror of the `namespaces` table
- `ci_project_mirrors`, as a mirror of the `projects` table
This logical replication means two things:
1. The `main` database tables can be queried and joined to the `namespaces` and `projects` tables.
1. The `ci` database tables can be joined with the `ci_namespace_mirrors` and `ci_project_mirrors` tables.
```mermaid
graph LR
subgraph "Main database (tables)"
A[namespaces] -->|updates| B[namespaces_sync_events]
A -->|deletes| C[loose_foreign_keys_deleted_records]
D[projects] -->|deletes| C
D -->|updates| E[projects_sync_events]
end
B --> F
C --> G
E --> H
subgraph "Sidekiq worker jobs"
F[Namespaces::ProcessSyncEventsWorker]
G[LooseForeignKeys::CleanupWorker]
H[Projects::ProcessSyncEventsWorker]
end
F -->|do update| I
G -->|delete records| I
G -->|delete records| J
H -->|do update| J
subgraph "CI database (tables)"
I[ci_namespace_mirrors]
J[ci_project_mirrors]
end
```
This replication was restricted only to a few attributes that are needed from each model:
- From `Namespace` we replicate `traversal_ids`.
- From `Project` we replicate only the `namespace_id`, which represents the group which the project belongs to.
## Keeping the CI mirrored tables in sync with the source tables
We must care about two type 3 events to keep
the source and the target tables in sync:
1. Creation of new namespaces or projects.
1. Updating the namespaces or projects.
1. Deleting namespaces/projects.
```mermaid
graph LR
subgraph CI["CI Tables"]
E[other CI tables]
F{queries with joins allowed}
G[ci_project_mirrors]
H[ci_namespace_mirrors]
E---F
F---G
F---H
end
Main["Main Tables"]---L["⛔ ← Joins are not allowed → ⛔"]
L---CI
subgraph Main["Main Tables"]
A[other main tables]
B{queries with joins allowed}
C[projects]
D[namespaces]
A---B
B---C
B---D
end
```
### Create and update
Syncing the data of newly created or updated namespaces or projects happens in this
order:
1. **On the `main` database**: Any `INSERT` or `UPDATE` on the `namespaces` or `projects` tables
adds an entry to the tables `namespaces_sync_events`, and `projects_sync_events`. These tables
also exist on the `main` database. These entries are added by triggers on both of the tables.
1. **On the model level**: After a commit happens on either of the source models `Namespace` or
`Project`, it schedules the corresponding Sidekiq jobs `Namespaces::ProcessSyncEventsWorker`
or `Projects::ProcessSyncEventsWorker` to run.
1. These workers then:
1. Read the entries from the tables `(namespaces/project)_sync_events`
from the `main` database, to check which namespaces or projects to sync.
1. Copy the data for any updated records into the target
tables `ci_namespace_mirrors`, `ci_project_mirrors`.
### Delete
When any of `namespaces` or `projects` are deleted, the target records on the mirrored
CI tables are deleted using the [loose foreign keys](loose_foreign_keys.md) (LFK) mechanism.
By having these items in the `config/gitlab_loose_foreign_keys.yml`, the LFK mechanism
was already working as expected. It deleted any records on the CI mirrored
tables that mapped to deleted `namespaces` or `projects` in the `main` database.
```yaml
ci_namespace_mirrors:
- table: namespaces
column: namespace_id
on_delete: async_delete
ci_project_mirrors:
- table: projects
column: project_id
on_delete: async_delete
```
## Consistency Checking
To make sure that both syncing mechanisms work as expected, we deploy
two extra worker jobs, triggered by cron jobs every few minutes:
1. `Database::CiNamespaceMirrorsConsistencyCheckWorker`
1. `Database::CiProjectMirrorsConsistencyCheckWorker`
These jobs:
1. Scan both of the source tables on the `main` database, using a cursor.
1. Compare the items in the `namespaces` and `projects` with the target tables on the `ci` database.
1. Report the items that are not in sync to Kibana and Prometheus.
1. Corrects any discrepancies.
|
---
stage: Data Access
group: Database Frameworks
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: CI mirrored tables
breadcrumbs:
- doc
- development
- database
---
## Problem statement
As part of the database [decomposition work](https://gitlab.com/groups/gitlab-org/-/epics/6168),
which had the goal of splitting the single database GitLab is using, into two databases: `main` and
`ci`, came the big challenge of
[removing all joins between the `main` and the `ci` tables](multiple_databases.md#removing-joins-between-main-and-non-main-tables).
That is because PostgreSQL doesn't support joins between tables that belong to different databases.
However, some core application models in the main database are queried very often by the CI side.
For example:
- `Namespace`, in the `namespaces` table.
- `Project`, in the `projects` table.
Not being able to do `joins` on these tables brings a great challenge. The team chose to perform logical
replication of those tables from the main database to the CI database, in the new tables:
- `ci_namespace_mirrors`, as a mirror of the `namespaces` table
- `ci_project_mirrors`, as a mirror of the `projects` table
This logical replication means two things:
1. The `main` database tables can be queried and joined to the `namespaces` and `projects` tables.
1. The `ci` database tables can be joined with the `ci_namespace_mirrors` and `ci_project_mirrors` tables.
```mermaid
graph LR
subgraph "Main database (tables)"
A[namespaces] -->|updates| B[namespaces_sync_events]
A -->|deletes| C[loose_foreign_keys_deleted_records]
D[projects] -->|deletes| C
D -->|updates| E[projects_sync_events]
end
B --> F
C --> G
E --> H
subgraph "Sidekiq worker jobs"
F[Namespaces::ProcessSyncEventsWorker]
G[LooseForeignKeys::CleanupWorker]
H[Projects::ProcessSyncEventsWorker]
end
F -->|do update| I
G -->|delete records| I
G -->|delete records| J
H -->|do update| J
subgraph "CI database (tables)"
I[ci_namespace_mirrors]
J[ci_project_mirrors]
end
```
This replication was restricted only to a few attributes that are needed from each model:
- From `Namespace` we replicate `traversal_ids`.
- From `Project` we replicate only the `namespace_id`, which represents the group which the project belongs to.
## Keeping the CI mirrored tables in sync with the source tables
We must care about two type 3 events to keep
the source and the target tables in sync:
1. Creation of new namespaces or projects.
1. Updating the namespaces or projects.
1. Deleting namespaces/projects.
```mermaid
graph LR
subgraph CI["CI Tables"]
E[other CI tables]
F{queries with joins allowed}
G[ci_project_mirrors]
H[ci_namespace_mirrors]
E---F
F---G
F---H
end
Main["Main Tables"]---L["⛔ ← Joins are not allowed → ⛔"]
L---CI
subgraph Main["Main Tables"]
A[other main tables]
B{queries with joins allowed}
C[projects]
D[namespaces]
A---B
B---C
B---D
end
```
### Create and update
Syncing the data of newly created or updated namespaces or projects happens in this
order:
1. **On the `main` database**: Any `INSERT` or `UPDATE` on the `namespaces` or `projects` tables
adds an entry to the tables `namespaces_sync_events`, and `projects_sync_events`. These tables
also exist on the `main` database. These entries are added by triggers on both of the tables.
1. **On the model level**: After a commit happens on either of the source models `Namespace` or
`Project`, it schedules the corresponding Sidekiq jobs `Namespaces::ProcessSyncEventsWorker`
or `Projects::ProcessSyncEventsWorker` to run.
1. These workers then:
1. Read the entries from the tables `(namespaces/project)_sync_events`
from the `main` database, to check which namespaces or projects to sync.
1. Copy the data for any updated records into the target
tables `ci_namespace_mirrors`, `ci_project_mirrors`.
### Delete
When any of `namespaces` or `projects` are deleted, the target records on the mirrored
CI tables are deleted using the [loose foreign keys](loose_foreign_keys.md) (LFK) mechanism.
By having these items in the `config/gitlab_loose_foreign_keys.yml`, the LFK mechanism
was already working as expected. It deleted any records on the CI mirrored
tables that mapped to deleted `namespaces` or `projects` in the `main` database.
```yaml
ci_namespace_mirrors:
- table: namespaces
column: namespace_id
on_delete: async_delete
ci_project_mirrors:
- table: projects
column: project_id
on_delete: async_delete
```
## Consistency Checking
To make sure that both syncing mechanisms work as expected, we deploy
two extra worker jobs, triggered by cron jobs every few minutes:
1. `Database::CiNamespaceMirrorsConsistencyCheckWorker`
1. `Database::CiProjectMirrorsConsistencyCheckWorker`
These jobs:
1. Scan both of the source tables on the `main` database, using a cursor.
1. Compare the items in the `namespaces` and `projects` with the target tables on the `ci` database.
1. Report the items that are not in sync to Kibana and Prometheus.
1. Corrects any discrepancies.
|
https://docs.gitlab.com/development/keyset_pagination
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/keyset_pagination.md
|
2025-08-13
|
doc/development/database
|
[
"doc",
"development",
"database"
] |
keyset_pagination.md
|
Data Access
|
Database Frameworks
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Keyset pagination
| null |
The keyset pagination library can be used in HAML-based views and the REST API within the GitLab project.
You can read about keyset pagination and how it compares to the offset based pagination on our [pagination guidelines](pagination_guidelines.md) page.
## API overview
### Synopsis
Keyset pagination with `ActiveRecord` in Rails controllers:
```ruby
cursor = params[:cursor] # this is nil when the first page is requested
paginator = Project.order(:created_at).keyset_paginate(cursor: cursor, per_page: 20)
paginator.each do |project|
puts project.name # prints maximum 20 projects
end
```
### Usage
This library adds a single method to ActiveRecord relations: [`#keyset_paginate`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/config/initializers/active_record_keyset_pagination.rb).
This is similar in spirit (but not in implementation) to Kaminari's `paginate` method.
Keyset pagination works without any configuration for simple ActiveRecord queries:
- Order by one column.
- Order by two columns, where the last column is the primary key.
The library detects nullable and non-distinct columns and based on these, adds extra ordering
using the primary key. This is necessary because keyset pagination expects distinct order by values:
```ruby
Project.order(:created_at).keyset_paginate.records # ORDER BY created_at, id
Project.order(:name).keyset_paginate.records # ORDER BY name, id
Project.order(:created_at, id: :desc).keyset_paginate.records # ORDER BY created_at, id
Project.order(created_at: :asc, id: :desc).keyset_paginate.records # ORDER BY created_at, id DESC
```
The `keyset_paginate` method returns [a special paginator object](https://gitlab.com/gitlab-org/gitlab/-/blob/master/lib/gitlab/pagination/keyset/paginator.rb) which contains the loaded records and additional information for requesting various pages.
The method accepts the following keyword arguments:
- `cursor` - Encoded order by column values for requesting the next page (can be `nil`).
- `per_page` - Number of records to load per page (default 20).
- `keyset_order_options` - Extra options for building the keyset paginated database query, see an example for `UNION` queries in the performance section (optional).
The paginator object has the following methods:
- `records` - Returns the records for the current page.
- `has_next_page?` - Tells whether there is a next page.
- `has_previous_page?` - Tells whether there is a previous page.
- `cursor_for_next_page` - Encoded values as `String` for requesting the next page (can be `nil`).
- `cursor_for_previous_page` - Encoded values as `String` for requesting the previous page (can be `nil`).
- `cursor_for_first_page` - Encoded values as `String` for requesting the first page.
- `cursor_for_last_page` - Encoded values as `String` for requesting the last page.
- The paginator objects includes the `Enumerable` module and delegates the enumerable functionality to the `records` method/array.
Example for getting the first and the second page:
```ruby
paginator = Project.order(:name).keyset_paginate
paginator.to_a # same as .records
cursor = paginator.cursor_for_next_page # encoded column attributes for the next page
paginator = Project.order(:name).keyset_paginate(cursor: cursor).records # loading the next page
```
Because keyset pagination does not support page numbers, we are restricted to go to the following pages:
- Next page
- Previous page
- Last page
- First page
#### Usage in REST API with `paginate_with_strategies`
For the REST API, the `paginate_with_strategies` helper can be used on a relation in order to use either keyset pagination or offset pagination.
```ruby
desc 'Get the things related to a project' do
detail 'This feature was introduced in GitLab 16.1'
success code: 200, model: ::API::Entities::Thing
failure [
{ code: 401, message: 'Unauthorized' },
{ code: 403, message: 'Forbidden' },
{ code: 404, message: 'Not Found' }
]
end
params do
use :pagination
requires :project_id, type: Integer, desc: 'The ID of the project'
optional :cursor, type: String, desc: 'Cursor for obtaining the next set of records'
optional :order_by, type: String, values: %w[id name], default: 'id',
desc: 'Attribute to sort by'
optional :sort, type: String, values: %w[asc desc], default: 'desc', desc: 'Order of sorting'
end
route_setting :authentication
get ':project_id/things' do
project = Project.find_by_id(params[:project_id])
not_found! if project.blank?
things = project.things
present paginate_with_strategies(things), with: ::API::Entities::Thing
end
```
In order for keyset pagination to be used, the following conditions must be met:
1. `params[:pagination]` must return `'keyset'`
1. `params[:order_by]` and `params[:sort]` must both appear in the object returned by the
`supported_keyset_orderings` class method on the model. In the following example, `Thing`
supports keyset pagination when ordering by ID in either ascending or descending order.
```ruby
class Thing < ApplicationRecord
def self.supported_keyset_orderings
{ id: [:asc, :desc] }
end
end
```
#### Usage in Rails with HAML views
Consider the following controller action, where we list the projects ordered by name:
```ruby
def index
@projects = Project.order(:name).keyset_paginate(cursor: params[:cursor])
end
```
In the HAML file, we can render the records:
```ruby
- if @projects.any?
- @projects.each do |project|
.project-container
= project.name
= keyset_paginate @projects
```
## Performance
The performance of the keyset pagination depends on the database index configuration and the number of columns we use in the `ORDER BY` clause.
In case we order by the primary key (`id`), then the generated queries are efficient because
the primary key is covered by a database index.
When two or more columns are used in the `ORDER BY` clause, it's advised to check the generated database query and make sure that the correct index configuration is used. More information can be found on the [pagination guideline page](pagination_guidelines.md#index-coverage).
{{< alert type="note" >}}
While the query performance of the first page might look good, the second page (where the cursor attributes are used in the query) might yield poor performance. It's advised to always verify the performance of both queries: first page and second page.
{{< /alert >}}
Example database query with tie-breaker (`id`) column:
```sql
SELECT "issues".*
FROM "issues"
WHERE (("issues"."id" > 99
AND "issues"."created_at" = '2021-02-16 11:26:17.408466')
OR ("issues"."created_at" > '2021-02-16 11:26:17.408466')
OR ("issues"."created_at" IS NULL))
ORDER BY "issues"."created_at" DESC NULLS LAST, "issues"."id" DESC
LIMIT 20
```
`OR` queries are difficult to optimize in PostgreSQL, we generally advise using [`UNION` queries](../sql.md#use-unions) instead. The keyset pagination library can generate efficient `UNION` when multiple columns are present in the `ORDER BY` clause. This is triggered when we specify the `use_union_optimization: true` option in the options passed to `Relation#keyset_paginate`.
Example:
```ruby
# Triggers a simple query for the first page.
paginator1 = Project.order(:created_at, id: :desc).keyset_paginate(per_page: 2, keyset_order_options: { use_union_optimization: true })
cursor = paginator1.cursor_for_next_page
# Triggers UNION query for the second page
paginator2 = Project.order(:created_at, id: :desc).keyset_paginate(per_page: 2, cursor: cursor, keyset_order_options: { use_union_optimization: true })
puts paginator2.records.to_a # UNION query
```
## Complex order configuration
Common `ORDER BY` configurations are handled by the `keyset_paginate` method automatically
so no manual configuration is needed. There are a few edge cases where order object
configuration is necessary:
- `NULLS LAST` ordering.
- Function-based ordering.
- Ordering with a custom tie-breaker column, like `iid`.
These order objects can be defined in the model classes as standard ActiveRecord scopes, there is no special behavior that prevents using these scopes elsewhere (Kaminari, background jobs).
### `NULLS LAST` ordering
Consider the following scope:
```ruby
scope = Issue.where(project_id: 10).order(Issue.arel_table[:relative_position].desc.nulls_last)
# SELECT "issues".* FROM "issues" WHERE "issues"."project_id" = 10 ORDER BY relative_position DESC NULLS LAST
scope.keyset_paginate # raises: Gitlab::Pagination::Keyset::UnsupportedScopeOrder: The order on the scope does not support keyset pagination
```
The `keyset_paginate` method raises an error because the order value on the query is a custom SQL string and not an [`Arel`](https://www.rubydoc.info/gems/arel) AST node. The keyset library cannot automatically infer configuration values from these kinds of queries.
To make keyset pagination work, we must configure custom order objects, to do so, we must
collect information about the order columns:
- `relative_position` can have duplicated values because no unique index is present.
- `relative_position` can have null values because we don't have a not null constraint on the column. For this, we must determine where we see `NULL` values, at the beginning of the result set, or the end (`NULLS LAST`).
- Keyset pagination requires distinct order columns, so we must add the primary key (`id`) to make the order distinct.
- Jumping to the last page and paginating backwards actually reverses the `ORDER BY` clause. For this, we must provide the reversed `ORDER BY` clause.
Example:
```ruby
order = Gitlab::Pagination::Keyset::Order.build([
# The attributes are documented in the `lib/gitlab/pagination/keyset/column_order_definition.rb` file
Gitlab::Pagination::Keyset::ColumnOrderDefinition.new(
attribute_name: 'relative_position',
column_expression: Issue.arel_table[:relative_position],
order_expression: Issue.arel_table[:relative_position].desc.nulls_last,
reversed_order_expression: Issue.arel_table[:relative_position].asc.nulls_first,
nullable: :nulls_last,
order_direction: :desc
),
Gitlab::Pagination::Keyset::ColumnOrderDefinition.new(
attribute_name: 'id',
order_expression: Issue.arel_table[:id].asc,
nullable: :not_nullable
)
])
scope = Issue.where(project_id: 10).order(order) # or reorder()
scope.keyset_paginate.records # works
```
### Function-based ordering
In the following example, we multiply the `id` by 10 and order by that value. Because the `id`
column is unique, we define only one column:
```ruby
order = Gitlab::Pagination::Keyset::Order.build([
Gitlab::Pagination::Keyset::ColumnOrderDefinition.new(
attribute_name: 'id_times_ten',
order_expression: Arel.sql('id * 10').asc,
nullable: :not_nullable,
order_direction: :asc,
add_to_projections: true
)
])
paginator = Issue.where(project_id: 10).order(order).keyset_paginate(per_page: 5)
puts paginator.records.map(&:id_times_ten)
cursor = paginator.cursor_for_next_page
paginator = Issue.where(project_id: 10).order(order).keyset_paginate(cursor: cursor, per_page: 5)
puts paginator.records.map(&:id_times_ten)
```
The `add_to_projections` flag tells the paginator to expose the column expression in the `SELECT` clause. This is necessary because the keyset pagination needs to somehow extract the last value from the records to request the next page.
### `iid` based ordering
When ordering issues, the database ensures that we have distinct `iid` values in a project.
Ordering by one column is enough to make the pagination work if the `project_id` filter is present:
```ruby
order = Gitlab::Pagination::Keyset::Order.build([
Gitlab::Pagination::Keyset::ColumnOrderDefinition.new(
attribute_name: 'iid',
order_expression: Issue.arel_table[:iid].asc,
nullable: :not_nullable
)
])
scope = Issue.where(project_id: 10).order(order)
scope.keyset_paginate.records # works
```
|
---
stage: Data Access
group: Database Frameworks
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: Keyset pagination
breadcrumbs:
- doc
- development
- database
---
The keyset pagination library can be used in HAML-based views and the REST API within the GitLab project.
You can read about keyset pagination and how it compares to the offset based pagination on our [pagination guidelines](pagination_guidelines.md) page.
## API overview
### Synopsis
Keyset pagination with `ActiveRecord` in Rails controllers:
```ruby
cursor = params[:cursor] # this is nil when the first page is requested
paginator = Project.order(:created_at).keyset_paginate(cursor: cursor, per_page: 20)
paginator.each do |project|
puts project.name # prints maximum 20 projects
end
```
### Usage
This library adds a single method to ActiveRecord relations: [`#keyset_paginate`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/config/initializers/active_record_keyset_pagination.rb).
This is similar in spirit (but not in implementation) to Kaminari's `paginate` method.
Keyset pagination works without any configuration for simple ActiveRecord queries:
- Order by one column.
- Order by two columns, where the last column is the primary key.
The library detects nullable and non-distinct columns and based on these, adds extra ordering
using the primary key. This is necessary because keyset pagination expects distinct order by values:
```ruby
Project.order(:created_at).keyset_paginate.records # ORDER BY created_at, id
Project.order(:name).keyset_paginate.records # ORDER BY name, id
Project.order(:created_at, id: :desc).keyset_paginate.records # ORDER BY created_at, id
Project.order(created_at: :asc, id: :desc).keyset_paginate.records # ORDER BY created_at, id DESC
```
The `keyset_paginate` method returns [a special paginator object](https://gitlab.com/gitlab-org/gitlab/-/blob/master/lib/gitlab/pagination/keyset/paginator.rb) which contains the loaded records and additional information for requesting various pages.
The method accepts the following keyword arguments:
- `cursor` - Encoded order by column values for requesting the next page (can be `nil`).
- `per_page` - Number of records to load per page (default 20).
- `keyset_order_options` - Extra options for building the keyset paginated database query, see an example for `UNION` queries in the performance section (optional).
The paginator object has the following methods:
- `records` - Returns the records for the current page.
- `has_next_page?` - Tells whether there is a next page.
- `has_previous_page?` - Tells whether there is a previous page.
- `cursor_for_next_page` - Encoded values as `String` for requesting the next page (can be `nil`).
- `cursor_for_previous_page` - Encoded values as `String` for requesting the previous page (can be `nil`).
- `cursor_for_first_page` - Encoded values as `String` for requesting the first page.
- `cursor_for_last_page` - Encoded values as `String` for requesting the last page.
- The paginator objects includes the `Enumerable` module and delegates the enumerable functionality to the `records` method/array.
Example for getting the first and the second page:
```ruby
paginator = Project.order(:name).keyset_paginate
paginator.to_a # same as .records
cursor = paginator.cursor_for_next_page # encoded column attributes for the next page
paginator = Project.order(:name).keyset_paginate(cursor: cursor).records # loading the next page
```
Because keyset pagination does not support page numbers, we are restricted to go to the following pages:
- Next page
- Previous page
- Last page
- First page
#### Usage in REST API with `paginate_with_strategies`
For the REST API, the `paginate_with_strategies` helper can be used on a relation in order to use either keyset pagination or offset pagination.
```ruby
desc 'Get the things related to a project' do
detail 'This feature was introduced in GitLab 16.1'
success code: 200, model: ::API::Entities::Thing
failure [
{ code: 401, message: 'Unauthorized' },
{ code: 403, message: 'Forbidden' },
{ code: 404, message: 'Not Found' }
]
end
params do
use :pagination
requires :project_id, type: Integer, desc: 'The ID of the project'
optional :cursor, type: String, desc: 'Cursor for obtaining the next set of records'
optional :order_by, type: String, values: %w[id name], default: 'id',
desc: 'Attribute to sort by'
optional :sort, type: String, values: %w[asc desc], default: 'desc', desc: 'Order of sorting'
end
route_setting :authentication
get ':project_id/things' do
project = Project.find_by_id(params[:project_id])
not_found! if project.blank?
things = project.things
present paginate_with_strategies(things), with: ::API::Entities::Thing
end
```
In order for keyset pagination to be used, the following conditions must be met:
1. `params[:pagination]` must return `'keyset'`
1. `params[:order_by]` and `params[:sort]` must both appear in the object returned by the
`supported_keyset_orderings` class method on the model. In the following example, `Thing`
supports keyset pagination when ordering by ID in either ascending or descending order.
```ruby
class Thing < ApplicationRecord
def self.supported_keyset_orderings
{ id: [:asc, :desc] }
end
end
```
#### Usage in Rails with HAML views
Consider the following controller action, where we list the projects ordered by name:
```ruby
def index
@projects = Project.order(:name).keyset_paginate(cursor: params[:cursor])
end
```
In the HAML file, we can render the records:
```ruby
- if @projects.any?
- @projects.each do |project|
.project-container
= project.name
= keyset_paginate @projects
```
## Performance
The performance of the keyset pagination depends on the database index configuration and the number of columns we use in the `ORDER BY` clause.
In case we order by the primary key (`id`), then the generated queries are efficient because
the primary key is covered by a database index.
When two or more columns are used in the `ORDER BY` clause, it's advised to check the generated database query and make sure that the correct index configuration is used. More information can be found on the [pagination guideline page](pagination_guidelines.md#index-coverage).
{{< alert type="note" >}}
While the query performance of the first page might look good, the second page (where the cursor attributes are used in the query) might yield poor performance. It's advised to always verify the performance of both queries: first page and second page.
{{< /alert >}}
Example database query with tie-breaker (`id`) column:
```sql
SELECT "issues".*
FROM "issues"
WHERE (("issues"."id" > 99
AND "issues"."created_at" = '2021-02-16 11:26:17.408466')
OR ("issues"."created_at" > '2021-02-16 11:26:17.408466')
OR ("issues"."created_at" IS NULL))
ORDER BY "issues"."created_at" DESC NULLS LAST, "issues"."id" DESC
LIMIT 20
```
`OR` queries are difficult to optimize in PostgreSQL, we generally advise using [`UNION` queries](../sql.md#use-unions) instead. The keyset pagination library can generate efficient `UNION` when multiple columns are present in the `ORDER BY` clause. This is triggered when we specify the `use_union_optimization: true` option in the options passed to `Relation#keyset_paginate`.
Example:
```ruby
# Triggers a simple query for the first page.
paginator1 = Project.order(:created_at, id: :desc).keyset_paginate(per_page: 2, keyset_order_options: { use_union_optimization: true })
cursor = paginator1.cursor_for_next_page
# Triggers UNION query for the second page
paginator2 = Project.order(:created_at, id: :desc).keyset_paginate(per_page: 2, cursor: cursor, keyset_order_options: { use_union_optimization: true })
puts paginator2.records.to_a # UNION query
```
## Complex order configuration
Common `ORDER BY` configurations are handled by the `keyset_paginate` method automatically
so no manual configuration is needed. There are a few edge cases where order object
configuration is necessary:
- `NULLS LAST` ordering.
- Function-based ordering.
- Ordering with a custom tie-breaker column, like `iid`.
These order objects can be defined in the model classes as standard ActiveRecord scopes, there is no special behavior that prevents using these scopes elsewhere (Kaminari, background jobs).
### `NULLS LAST` ordering
Consider the following scope:
```ruby
scope = Issue.where(project_id: 10).order(Issue.arel_table[:relative_position].desc.nulls_last)
# SELECT "issues".* FROM "issues" WHERE "issues"."project_id" = 10 ORDER BY relative_position DESC NULLS LAST
scope.keyset_paginate # raises: Gitlab::Pagination::Keyset::UnsupportedScopeOrder: The order on the scope does not support keyset pagination
```
The `keyset_paginate` method raises an error because the order value on the query is a custom SQL string and not an [`Arel`](https://www.rubydoc.info/gems/arel) AST node. The keyset library cannot automatically infer configuration values from these kinds of queries.
To make keyset pagination work, we must configure custom order objects, to do so, we must
collect information about the order columns:
- `relative_position` can have duplicated values because no unique index is present.
- `relative_position` can have null values because we don't have a not null constraint on the column. For this, we must determine where we see `NULL` values, at the beginning of the result set, or the end (`NULLS LAST`).
- Keyset pagination requires distinct order columns, so we must add the primary key (`id`) to make the order distinct.
- Jumping to the last page and paginating backwards actually reverses the `ORDER BY` clause. For this, we must provide the reversed `ORDER BY` clause.
Example:
```ruby
order = Gitlab::Pagination::Keyset::Order.build([
# The attributes are documented in the `lib/gitlab/pagination/keyset/column_order_definition.rb` file
Gitlab::Pagination::Keyset::ColumnOrderDefinition.new(
attribute_name: 'relative_position',
column_expression: Issue.arel_table[:relative_position],
order_expression: Issue.arel_table[:relative_position].desc.nulls_last,
reversed_order_expression: Issue.arel_table[:relative_position].asc.nulls_first,
nullable: :nulls_last,
order_direction: :desc
),
Gitlab::Pagination::Keyset::ColumnOrderDefinition.new(
attribute_name: 'id',
order_expression: Issue.arel_table[:id].asc,
nullable: :not_nullable
)
])
scope = Issue.where(project_id: 10).order(order) # or reorder()
scope.keyset_paginate.records # works
```
### Function-based ordering
In the following example, we multiply the `id` by 10 and order by that value. Because the `id`
column is unique, we define only one column:
```ruby
order = Gitlab::Pagination::Keyset::Order.build([
Gitlab::Pagination::Keyset::ColumnOrderDefinition.new(
attribute_name: 'id_times_ten',
order_expression: Arel.sql('id * 10').asc,
nullable: :not_nullable,
order_direction: :asc,
add_to_projections: true
)
])
paginator = Issue.where(project_id: 10).order(order).keyset_paginate(per_page: 5)
puts paginator.records.map(&:id_times_ten)
cursor = paginator.cursor_for_next_page
paginator = Issue.where(project_id: 10).order(order).keyset_paginate(cursor: cursor, per_page: 5)
puts paginator.records.map(&:id_times_ten)
```
The `add_to_projections` flag tells the paginator to expose the column expression in the `SELECT` clause. This is necessary because the keyset pagination needs to somehow extract the last value from the records to request the next page.
### `iid` based ordering
When ordering issues, the database ensures that we have distinct `iid` values in a project.
Ordering by one column is enough to make the pagination work if the `project_id` filter is present:
```ruby
order = Gitlab::Pagination::Keyset::Order.build([
Gitlab::Pagination::Keyset::ColumnOrderDefinition.new(
attribute_name: 'iid',
order_expression: Issue.arel_table[:iid].asc,
nullable: :not_nullable
)
])
scope = Issue.where(project_id: 10).order(order)
scope.keyset_paginate.records # works
```
|
https://docs.gitlab.com/development/namespaces_storage_statistics
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/namespaces_storage_statistics.md
|
2025-08-13
|
doc/development/database
|
[
"doc",
"development",
"database"
] |
namespaces_storage_statistics.md
|
none
|
unassigned
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Database case study: Namespaces storage statistics
| null |
## Introduction
On [Storage and limits management for groups](https://gitlab.com/groups/gitlab-org/-/epics/886),
we want to facilitate a method for easily viewing the amount of
storage consumed by a group, and allow easy management.
## Proposal
1. Create a new ActiveRecord model to hold the namespaces' statistics in an aggregated form (only for root [namespaces](../../user/namespace/_index.md)).
1. Refresh the statistics in this model every time a project belonging to this namespace is changed.
## Problem
In GitLab, we update the project storage statistics through a
[callback](https://gitlab.com/gitlab-org/gitlab/-/blob/4ab54c2233e91f60a80e5b6fa2181e6899fdcc3e/app/models/project.rb#L97)
every time the project is saved.
The summary of those statistics per namespace is then retrieved
by [`Namespaces#with_statistics`](https://gitlab.com/gitlab-org/gitlab/-/blob/4ab54c2233e91f60a80e5b6fa2181e6899fdcc3e/app/models/namespace.rb#L70) scope. Analyzing this query we noticed that:
- It takes up to `1.2` seconds for namespaces with over `15k` projects.
- It can't be analyzed with [ChatOps](../chatops_on_gitlabcom.md), as it times out.
Additionally, the pattern that is currently used to update the project statistics
(the callback) doesn't scale adequately. It is currently one of the largest
[database queries transactions on production](https://gitlab.com/gitlab-org/gitlab/-/issues/29070)
that takes the most time overall. We can't add one more query to it as
it increases the transaction's length.
Because of all of the above, we can't apply the same pattern to store
and update the namespaces statistics, as the `namespaces` table is one
of the largest tables on GitLab.com. Therefore we needed to find a performant and
alternative method.
## Attempts
### Attempt A: PostgreSQL materialized view
Model can be updated through a refresh strategy based on a project routes SQL and a [materialized view](https://www.postgresql.org/docs/16/rules-materializedviews.html):
```sql
SELECT split_part("rs".path, '/', 1) as root_path,
COALESCE(SUM(ps.storage_size), 0) AS storage_size,
COALESCE(SUM(ps.repository_size), 0) AS repository_size,
COALESCE(SUM(ps.wiki_size), 0) AS wiki_size,
COALESCE(SUM(ps.lfs_objects_size), 0) AS lfs_objects_size,
COALESCE(SUM(ps.build_artifacts_size), 0) AS build_artifacts_size,
COALESCE(SUM(ps.pipeline_artifacts_size), 0) AS pipeline_artifacts_size,
COALESCE(SUM(ps.packages_size), 0) AS packages_size,
COALESCE(SUM(ps.snippets_size), 0) AS snippets_size,
COALESCE(SUM(ps.uploads_size), 0) AS uploads_size
FROM "projects"
INNER JOIN routes rs ON rs.source_id = projects.id AND rs.source_type = 'Project'
INNER JOIN project_statistics ps ON ps.project_id = projects.id
GROUP BY root_path
```
We could then execute the query with:
```sql
REFRESH MATERIALIZED VIEW root_namespace_storage_statistics;
```
While this implied a single query update (and probably a fast one), it has some downsides:
- Materialized views syntax varies from PostgreSQL and MySQL. While this feature was worked on, MySQL was still supported by GitLab.
- Rails does not have native support for materialized views. We'd need to use a specialized gem to take care of the management of the database views, which implies additional work.
### Attempt B: An update through a CTE
Similar to Attempt A: Model update done through a refresh strategy with a [Common Table Expression](https://www.postgresql.org/docs/9.1/queries-with.html)
```sql
WITH refresh AS (
SELECT split_part("rs".path, '/', 1) as root_path,
COALESCE(SUM(ps.storage_size), 0) AS storage_size,
COALESCE(SUM(ps.repository_size), 0) AS repository_size,
COALESCE(SUM(ps.wiki_size), 0) AS wiki_size,
COALESCE(SUM(ps.lfs_objects_size), 0) AS lfs_objects_size,
COALESCE(SUM(ps.build_artifacts_size), 0) AS build_artifacts_size,
COALESCE(SUM(ps.pipeline_artifacts_size), 0) AS pipeline_artifacts_size,
COALESCE(SUM(ps.packages_size), 0) AS packages_size,
COALESCE(SUM(ps.snippets_size), 0) AS snippets_size,
COALESCE(SUM(ps.uploads_size), 0) AS uploads_size
FROM "projects"
INNER JOIN routes rs ON rs.source_id = projects.id AND rs.source_type = 'Project'
INNER JOIN project_statistics ps ON ps.project_id = projects.id
GROUP BY root_path)
UPDATE namespace_storage_statistics
SET storage_size = refresh.storage_size,
repository_size = refresh.repository_size,
wiki_size = refresh.wiki_size,
lfs_objects_size = refresh.lfs_objects_size,
build_artifacts_size = refresh.build_artifacts_size,
pipeline_artifacts_size = refresh.pipeline_artifacts_size,
packages_size = refresh.packages_size,
snippets_size = refresh.snippets_size,
uploads_size = refresh.uploads_size
FROM refresh
INNER JOIN routes rs ON rs.path = refresh.root_path AND rs.source_type = 'Namespace'
WHERE namespace_storage_statistics.namespace_id = rs.source_id
```
Same benefits and downsides as attempt A.
### Attempt C: Get rid of the model and store the statistics on Redis
We could get rid of the model that stores the statistics in aggregated form and instead use a Redis Set.
This would be the [boring solution](https://handbook.gitlab.com/handbook/values/#boring-solutions) and the fastest one
to implement, as GitLab already includes Redis as part of its [Architecture](../architecture.md#redis).
The downside of this approach is that Redis does not provide the same persistence/consistency guarantees as PostgreSQL,
and this is information we can't afford to lose in a Redis failure.
### Attempt D: Tag the root namespace and its child namespaces
Directly relate the root namespace to its child namespaces, so
whenever a namespace is created without a parent, this one is tagged
with the root namespace ID:
| ID | root ID | parent ID |
|:---|:--------|:----------|
| 1 | 1 | NULL |
| 2 | 1 | 1 |
| 3 | 1 | 2 |
To aggregate the statistics inside a namespace we'd execute something like:
```sql
SELECT COUNT(...)
FROM projects
WHERE namespace_id IN (
SELECT id
FROM namespaces
WHERE root_id = X
)
```
Even though this approach would make aggregating much easier, it has some major downsides:
- We'd have to migrate **all namespaces** by adding and filling a new column. Because of the size of the table, dealing with time/cost would be significant. The background migration would take approximately `153h`, see <https://gitlab.com/gitlab-org/gitlab-foss/-/merge_requests/29772>.
- Background migration has to be shipped one release before, delaying the functionality by another milestone.
### Attempt E (final): Update the namespace storage statistics asynchronously
This approach consists of continuing to use the incremental statistics updates we already have,
but we refresh them through Sidekiq jobs and in different transactions:
1. Create a second table (`namespace_aggregation_schedules`) with two columns `id` and `namespace_id`.
1. Whenever the statistics of a project changes, insert a row into `namespace_aggregation_schedules`
- We don't insert a new row if there's already one related to the root namespace.
- Keeping in mind the length of the transaction that involves updating `project_statistics`(<https://gitlab.com/gitlab-org/gitlab/-/issues/29070>), the insertion should be done in a different transaction and through a Sidekiq Job.
1. After inserting the row, we schedule another worker to be executed asynchronously at two different moments:
- One enqueued for immediate execution and another one scheduled in `1.5h` hours.
- We only schedule the jobs, if we can obtain a `1.5h` lease on Redis on a key based on the root namespace ID.
- If we can't obtain the lease, it indicates there's another aggregation already in progress, or scheduled in no more than `1.5h`.
1. This worker will:
- Update the root namespace storage statistics by querying all the namespaces through a service.
- Delete the related `namespace_aggregation_schedules` after the update.
1. Another Sidekiq job is also included to traverse any remaining rows on the `namespace_aggregation_schedules` table and schedule jobs for every pending row.
- This job is scheduled with cron to run every night (UTC).
This implementation has the following benefits:
- All the updates are done asynchronously, so we're not increasing the length of the transactions for `project_statistics`.
- We're doing the update in a single SQL query.
- It is compatible with PostgreSQL and MySQL.
- No background migration required.
The only downside of this approach is that namespaces' statistics are updated up to `1.5` hours after the change is done,
which means there's a time window in which the statistics are inaccurate. Because we're still not
[enforcing storage limits](https://gitlab.com/gitlab-org/gitlab/-/issues/17664), this is not a major problem.
## Conclusion
Updating the storage statistics asynchronously, was the less problematic and
performant approach of aggregating the root namespaces.
All the details regarding this use case can be found on:
- <https://gitlab.com/gitlab-org/gitlab-foss/-/issues/62214>
- Merge request with the implementation: <https://gitlab.com/gitlab-org/gitlab-foss/-/merge_requests/28996>
Performance of the namespace storage statistics were measured in staging and production (GitLab.com). All results were posted
on <https://gitlab.com/gitlab-org/gitlab-foss/-/issues/64092>: No problem has been reported so far.
|
---
stage: none
group: unassigned
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: 'Database case study: Namespaces storage statistics'
breadcrumbs:
- doc
- development
- database
---
## Introduction
On [Storage and limits management for groups](https://gitlab.com/groups/gitlab-org/-/epics/886),
we want to facilitate a method for easily viewing the amount of
storage consumed by a group, and allow easy management.
## Proposal
1. Create a new ActiveRecord model to hold the namespaces' statistics in an aggregated form (only for root [namespaces](../../user/namespace/_index.md)).
1. Refresh the statistics in this model every time a project belonging to this namespace is changed.
## Problem
In GitLab, we update the project storage statistics through a
[callback](https://gitlab.com/gitlab-org/gitlab/-/blob/4ab54c2233e91f60a80e5b6fa2181e6899fdcc3e/app/models/project.rb#L97)
every time the project is saved.
The summary of those statistics per namespace is then retrieved
by [`Namespaces#with_statistics`](https://gitlab.com/gitlab-org/gitlab/-/blob/4ab54c2233e91f60a80e5b6fa2181e6899fdcc3e/app/models/namespace.rb#L70) scope. Analyzing this query we noticed that:
- It takes up to `1.2` seconds for namespaces with over `15k` projects.
- It can't be analyzed with [ChatOps](../chatops_on_gitlabcom.md), as it times out.
Additionally, the pattern that is currently used to update the project statistics
(the callback) doesn't scale adequately. It is currently one of the largest
[database queries transactions on production](https://gitlab.com/gitlab-org/gitlab/-/issues/29070)
that takes the most time overall. We can't add one more query to it as
it increases the transaction's length.
Because of all of the above, we can't apply the same pattern to store
and update the namespaces statistics, as the `namespaces` table is one
of the largest tables on GitLab.com. Therefore we needed to find a performant and
alternative method.
## Attempts
### Attempt A: PostgreSQL materialized view
Model can be updated through a refresh strategy based on a project routes SQL and a [materialized view](https://www.postgresql.org/docs/16/rules-materializedviews.html):
```sql
SELECT split_part("rs".path, '/', 1) as root_path,
COALESCE(SUM(ps.storage_size), 0) AS storage_size,
COALESCE(SUM(ps.repository_size), 0) AS repository_size,
COALESCE(SUM(ps.wiki_size), 0) AS wiki_size,
COALESCE(SUM(ps.lfs_objects_size), 0) AS lfs_objects_size,
COALESCE(SUM(ps.build_artifacts_size), 0) AS build_artifacts_size,
COALESCE(SUM(ps.pipeline_artifacts_size), 0) AS pipeline_artifacts_size,
COALESCE(SUM(ps.packages_size), 0) AS packages_size,
COALESCE(SUM(ps.snippets_size), 0) AS snippets_size,
COALESCE(SUM(ps.uploads_size), 0) AS uploads_size
FROM "projects"
INNER JOIN routes rs ON rs.source_id = projects.id AND rs.source_type = 'Project'
INNER JOIN project_statistics ps ON ps.project_id = projects.id
GROUP BY root_path
```
We could then execute the query with:
```sql
REFRESH MATERIALIZED VIEW root_namespace_storage_statistics;
```
While this implied a single query update (and probably a fast one), it has some downsides:
- Materialized views syntax varies from PostgreSQL and MySQL. While this feature was worked on, MySQL was still supported by GitLab.
- Rails does not have native support for materialized views. We'd need to use a specialized gem to take care of the management of the database views, which implies additional work.
### Attempt B: An update through a CTE
Similar to Attempt A: Model update done through a refresh strategy with a [Common Table Expression](https://www.postgresql.org/docs/9.1/queries-with.html)
```sql
WITH refresh AS (
SELECT split_part("rs".path, '/', 1) as root_path,
COALESCE(SUM(ps.storage_size), 0) AS storage_size,
COALESCE(SUM(ps.repository_size), 0) AS repository_size,
COALESCE(SUM(ps.wiki_size), 0) AS wiki_size,
COALESCE(SUM(ps.lfs_objects_size), 0) AS lfs_objects_size,
COALESCE(SUM(ps.build_artifacts_size), 0) AS build_artifacts_size,
COALESCE(SUM(ps.pipeline_artifacts_size), 0) AS pipeline_artifacts_size,
COALESCE(SUM(ps.packages_size), 0) AS packages_size,
COALESCE(SUM(ps.snippets_size), 0) AS snippets_size,
COALESCE(SUM(ps.uploads_size), 0) AS uploads_size
FROM "projects"
INNER JOIN routes rs ON rs.source_id = projects.id AND rs.source_type = 'Project'
INNER JOIN project_statistics ps ON ps.project_id = projects.id
GROUP BY root_path)
UPDATE namespace_storage_statistics
SET storage_size = refresh.storage_size,
repository_size = refresh.repository_size,
wiki_size = refresh.wiki_size,
lfs_objects_size = refresh.lfs_objects_size,
build_artifacts_size = refresh.build_artifacts_size,
pipeline_artifacts_size = refresh.pipeline_artifacts_size,
packages_size = refresh.packages_size,
snippets_size = refresh.snippets_size,
uploads_size = refresh.uploads_size
FROM refresh
INNER JOIN routes rs ON rs.path = refresh.root_path AND rs.source_type = 'Namespace'
WHERE namespace_storage_statistics.namespace_id = rs.source_id
```
Same benefits and downsides as attempt A.
### Attempt C: Get rid of the model and store the statistics on Redis
We could get rid of the model that stores the statistics in aggregated form and instead use a Redis Set.
This would be the [boring solution](https://handbook.gitlab.com/handbook/values/#boring-solutions) and the fastest one
to implement, as GitLab already includes Redis as part of its [Architecture](../architecture.md#redis).
The downside of this approach is that Redis does not provide the same persistence/consistency guarantees as PostgreSQL,
and this is information we can't afford to lose in a Redis failure.
### Attempt D: Tag the root namespace and its child namespaces
Directly relate the root namespace to its child namespaces, so
whenever a namespace is created without a parent, this one is tagged
with the root namespace ID:
| ID | root ID | parent ID |
|:---|:--------|:----------|
| 1 | 1 | NULL |
| 2 | 1 | 1 |
| 3 | 1 | 2 |
To aggregate the statistics inside a namespace we'd execute something like:
```sql
SELECT COUNT(...)
FROM projects
WHERE namespace_id IN (
SELECT id
FROM namespaces
WHERE root_id = X
)
```
Even though this approach would make aggregating much easier, it has some major downsides:
- We'd have to migrate **all namespaces** by adding and filling a new column. Because of the size of the table, dealing with time/cost would be significant. The background migration would take approximately `153h`, see <https://gitlab.com/gitlab-org/gitlab-foss/-/merge_requests/29772>.
- Background migration has to be shipped one release before, delaying the functionality by another milestone.
### Attempt E (final): Update the namespace storage statistics asynchronously
This approach consists of continuing to use the incremental statistics updates we already have,
but we refresh them through Sidekiq jobs and in different transactions:
1. Create a second table (`namespace_aggregation_schedules`) with two columns `id` and `namespace_id`.
1. Whenever the statistics of a project changes, insert a row into `namespace_aggregation_schedules`
- We don't insert a new row if there's already one related to the root namespace.
- Keeping in mind the length of the transaction that involves updating `project_statistics`(<https://gitlab.com/gitlab-org/gitlab/-/issues/29070>), the insertion should be done in a different transaction and through a Sidekiq Job.
1. After inserting the row, we schedule another worker to be executed asynchronously at two different moments:
- One enqueued for immediate execution and another one scheduled in `1.5h` hours.
- We only schedule the jobs, if we can obtain a `1.5h` lease on Redis on a key based on the root namespace ID.
- If we can't obtain the lease, it indicates there's another aggregation already in progress, or scheduled in no more than `1.5h`.
1. This worker will:
- Update the root namespace storage statistics by querying all the namespaces through a service.
- Delete the related `namespace_aggregation_schedules` after the update.
1. Another Sidekiq job is also included to traverse any remaining rows on the `namespace_aggregation_schedules` table and schedule jobs for every pending row.
- This job is scheduled with cron to run every night (UTC).
This implementation has the following benefits:
- All the updates are done asynchronously, so we're not increasing the length of the transactions for `project_statistics`.
- We're doing the update in a single SQL query.
- It is compatible with PostgreSQL and MySQL.
- No background migration required.
The only downside of this approach is that namespaces' statistics are updated up to `1.5` hours after the change is done,
which means there's a time window in which the statistics are inaccurate. Because we're still not
[enforcing storage limits](https://gitlab.com/gitlab-org/gitlab/-/issues/17664), this is not a major problem.
## Conclusion
Updating the storage statistics asynchronously, was the less problematic and
performant approach of aggregating the root namespaces.
All the details regarding this use case can be found on:
- <https://gitlab.com/gitlab-org/gitlab-foss/-/issues/62214>
- Merge request with the implementation: <https://gitlab.com/gitlab-org/gitlab-foss/-/merge_requests/28996>
Performance of the namespace storage statistics were measured in staging and production (GitLab.com). All results were posted
on <https://gitlab.com/gitlab-org/gitlab-foss/-/issues/64092>: No problem has been reported so far.
|
https://docs.gitlab.com/development/database_reviewer_guidelines
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/database_reviewer_guidelines.md
|
2025-08-13
|
doc/development/database
|
[
"doc",
"development",
"database"
] |
database_reviewer_guidelines.md
|
Data Access
|
Database Frameworks
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Database Reviewer Guidelines
| null |
This page includes introductory material for new database reviewers.
If you are interested in getting an application update reviewed,
check the [database review guidelines](../database_review.md).
## Scope of work done by a database reviewer
Database reviewers are domain experts who have substantial experience with databases,
`SQL`, and query performance optimization.
A database review is required whenever an application update [touches the database](../database_review.md#general-process).
The database reviewer is tasked with reviewing the database specific updates and
making sure that any queries or modifications perform without issues
at the scale of GitLab.com.
For more information on the database review process, check the [database review guidelines](../database_review.md).
## How to apply for becoming a database reviewer
Team members are encouraged to self-identify as database domain experts, by adding it
to your profile YAML file:
1. Make a merge request using the
[`Database reviewer` template](https://gitlab.com/gitlab-com/www-gitlab-com/-/blob/master/.gitlab/merge_request_templates/Database%20reviewer.md).
1. Add your database expertise to your YAML file:
```yaml
projects:
gitlab:
- reviewer database
```
1. Create the merge request
[using the "Database reviewer" template](https://gitlab.com/gitlab-com/www-gitlab-com/-/blob/master/.gitlab/merge_request_templates/Database%20reviewer.md).
1. Assign to a database maintainer or the
[Database Team's Engineering Manager](https://handbook.gitlab.com/handbook/engineering/infrastructure-platforms/data-access/database-framework/).
After the `team.yml` update is merged, the [Reviewer roulette](../code_review.md#reviewer-roulette)
may recommend you as a database reviewer.
## Resources for database reviewers
As a database reviewer, join the internal `#database` Slack channel and ask questions or discuss
database related issues with other database reviewers and maintainers.
Get familiar with using [Database Lab from postgres.ai](database_lab.md), a bot that
provides developers with their own clone of the production database.
Understanding and efficiently using `EXPLAIN` plans is at the core of the database review process.
The following guides provide a quick introduction and links to follow on more advanced topics:
- Guide on [understanding EXPLAIN plans](understanding_explain_plans.md).
- [Explaining the unexplainable series in `depesz`](https://www.depesz.com/tag/unexplainable/).
We also have licensed access to The Art of PostgreSQL. If you are interested in getting access, GitLab team
members can check out the issue here: `https://gitlab.com/gitlab-org/database-team/team-tasks/-/issues/23`.
Finally, you can find various guides in the [Database guides](_index.md) page that cover more specific
topics and use cases. The most frequently required during database reviewing are the following:
- [Migrations style guide](../migration_style_guide.md) for creating safe SQL migrations.
- [Avoiding downtime in migrations](avoiding_downtime_in_migrations.md).
- [SQL guidelines](../sql.md) for working with SQL queries.
- [Guidelines for JiHu contributions with database migrations](https://handbook.gitlab.com/handbook/ceo/office-of-the-ceo/jihu-support/jihu-database-change-process/)
## How to apply to become a database maintainer
Becoming a database maintainer uses the same process as the other projects.
[Follow the general process documented here](https://handbook.gitlab.com/handbook/engineering/workflow/code-review/#how-to-become-a-project-maintainer).
For database specific requirements, see [`Project maintainer process for gitlab-database`](https://handbook.gitlab.com/handbook/engineering/workflow/code-review/#project-maintainer-process-for-gitlab-database)
## What to do if you feel overwhelmed
Similar to all types of reviews, [unblocking others is always a top priority](https://handbook.gitlab.com/handbook/values/#global-optimization).
Database reviewers are expected to [review assigned merge requests in a timely manner](https://handbook.gitlab.com/handbook/engineering/workflow/code-review/#review-turnaround-time)
or let the author know as soon as possible and help them find another reviewer or maintainer.
We are doing reviews to help the rest of the GitLab team and, at the same time, get exposed
to more use cases, get a lot of insights and hone our database and data management skills.
If you are feeling overwhelmed, think you are at capacity, and are unable to accept any more
reviews until some have been completed, communicate this through your GitLab status by setting
the `:red_circle:` emoji and mentioning that you are at capacity in the status text.
|
---
stage: Data Access
group: Database Frameworks
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: Database Reviewer Guidelines
breadcrumbs:
- doc
- development
- database
---
This page includes introductory material for new database reviewers.
If you are interested in getting an application update reviewed,
check the [database review guidelines](../database_review.md).
## Scope of work done by a database reviewer
Database reviewers are domain experts who have substantial experience with databases,
`SQL`, and query performance optimization.
A database review is required whenever an application update [touches the database](../database_review.md#general-process).
The database reviewer is tasked with reviewing the database specific updates and
making sure that any queries or modifications perform without issues
at the scale of GitLab.com.
For more information on the database review process, check the [database review guidelines](../database_review.md).
## How to apply for becoming a database reviewer
Team members are encouraged to self-identify as database domain experts, by adding it
to your profile YAML file:
1. Make a merge request using the
[`Database reviewer` template](https://gitlab.com/gitlab-com/www-gitlab-com/-/blob/master/.gitlab/merge_request_templates/Database%20reviewer.md).
1. Add your database expertise to your YAML file:
```yaml
projects:
gitlab:
- reviewer database
```
1. Create the merge request
[using the "Database reviewer" template](https://gitlab.com/gitlab-com/www-gitlab-com/-/blob/master/.gitlab/merge_request_templates/Database%20reviewer.md).
1. Assign to a database maintainer or the
[Database Team's Engineering Manager](https://handbook.gitlab.com/handbook/engineering/infrastructure-platforms/data-access/database-framework/).
After the `team.yml` update is merged, the [Reviewer roulette](../code_review.md#reviewer-roulette)
may recommend you as a database reviewer.
## Resources for database reviewers
As a database reviewer, join the internal `#database` Slack channel and ask questions or discuss
database related issues with other database reviewers and maintainers.
Get familiar with using [Database Lab from postgres.ai](database_lab.md), a bot that
provides developers with their own clone of the production database.
Understanding and efficiently using `EXPLAIN` plans is at the core of the database review process.
The following guides provide a quick introduction and links to follow on more advanced topics:
- Guide on [understanding EXPLAIN plans](understanding_explain_plans.md).
- [Explaining the unexplainable series in `depesz`](https://www.depesz.com/tag/unexplainable/).
We also have licensed access to The Art of PostgreSQL. If you are interested in getting access, GitLab team
members can check out the issue here: `https://gitlab.com/gitlab-org/database-team/team-tasks/-/issues/23`.
Finally, you can find various guides in the [Database guides](_index.md) page that cover more specific
topics and use cases. The most frequently required during database reviewing are the following:
- [Migrations style guide](../migration_style_guide.md) for creating safe SQL migrations.
- [Avoiding downtime in migrations](avoiding_downtime_in_migrations.md).
- [SQL guidelines](../sql.md) for working with SQL queries.
- [Guidelines for JiHu contributions with database migrations](https://handbook.gitlab.com/handbook/ceo/office-of-the-ceo/jihu-support/jihu-database-change-process/)
## How to apply to become a database maintainer
Becoming a database maintainer uses the same process as the other projects.
[Follow the general process documented here](https://handbook.gitlab.com/handbook/engineering/workflow/code-review/#how-to-become-a-project-maintainer).
For database specific requirements, see [`Project maintainer process for gitlab-database`](https://handbook.gitlab.com/handbook/engineering/workflow/code-review/#project-maintainer-process-for-gitlab-database)
## What to do if you feel overwhelmed
Similar to all types of reviews, [unblocking others is always a top priority](https://handbook.gitlab.com/handbook/values/#global-optimization).
Database reviewers are expected to [review assigned merge requests in a timely manner](https://handbook.gitlab.com/handbook/engineering/workflow/code-review/#review-turnaround-time)
or let the author know as soon as possible and help them find another reviewer or maintainer.
We are doing reviews to help the rest of the GitLab team and, at the same time, get exposed
to more use cases, get a lot of insights and hone our database and data management skills.
If you are feeling overwhelmed, think you are at capacity, and are unable to accept any more
reviews until some have been completed, communicate this through your GitLab status by setting
the `:red_circle:` emoji and mentioning that you are at capacity in the status text.
|
https://docs.gitlab.com/development/understanding_explain_plans
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/development/understanding_explain_plans.md
|
2025-08-13
|
doc/development/database
|
[
"doc",
"development",
"database"
] |
understanding_explain_plans.md
|
Data Access
|
Database Frameworks
|
Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
|
Understanding EXPLAIN plans
| null |
PostgreSQL allows you to obtain query plans using the `EXPLAIN` command. This
command can be invaluable when trying to determine how a query performs.
You can use this command directly in your SQL query, as long as the query starts
with it:
```sql
EXPLAIN
SELECT COUNT(*)
FROM projects
WHERE visibility_level IN (0, 20);
```
When running this on GitLab.com, we are presented with the following output:
```sql
Aggregate (cost=922411.76..922411.77 rows=1 width=8)
-> Seq Scan on projects (cost=0.00..908044.47 rows=5746914 width=0)
Filter: (visibility_level = ANY ('{0,20}'::integer[]))
```
When using _just_ `EXPLAIN`, PostgreSQL does not actually execute our query,
instead it produces an _estimated_ execution plan based on the available
statistics. This means the actual plan can differ quite a bit. Fortunately,
PostgreSQL provides us with the option to execute the query as well. To do so,
we need to use `EXPLAIN ANALYZE` instead of just `EXPLAIN`:
```sql
EXPLAIN ANALYZE
SELECT COUNT(*)
FROM projects
WHERE visibility_level IN (0, 20);
```
This produces:
```sql
Aggregate (cost=922420.60..922420.61 rows=1 width=8) (actual time=3428.535..3428.535 rows=1 loops=1)
-> Seq Scan on projects (cost=0.00..908053.18 rows=5746969 width=0) (actual time=0.041..2987.606 rows=5746940 loops=1)
Filter: (visibility_level = ANY ('{0,20}'::integer[]))
Rows Removed by Filter: 65677
Planning time: 2.861 ms
Execution time: 3428.596 ms
```
As we can see this plan is quite different, and includes a lot more data. Let's
discuss this step by step.
Because `EXPLAIN ANALYZE` executes the query, care should be taken when using a
query that writes data or might time out. If the query modifies data,
consider wrapping it in a transaction that rolls back automatically like so:
```sql
BEGIN;
EXPLAIN ANALYZE
DELETE FROM users WHERE id = 1;
ROLLBACK;
```
The `EXPLAIN` command also takes additional options, such as `BUFFERS`:
```sql
EXPLAIN (ANALYZE, BUFFERS)
SELECT COUNT(*)
FROM projects
WHERE visibility_level IN (0, 20);
```
This then produces:
```sql
Aggregate (cost=922420.60..922420.61 rows=1 width=8) (actual time=3428.535..3428.535 rows=1 loops=1)
Buffers: shared hit=208846
-> Seq Scan on projects (cost=0.00..908053.18 rows=5746969 width=0) (actual time=0.041..2987.606 rows=5746940 loops=1)
Filter: (visibility_level = ANY ('{0,20}'::integer[]))
Rows Removed by Filter: 65677
Buffers: shared hit=208846
Planning time: 2.861 ms
Execution time: 3428.596 ms
```
For more information, refer to the official
[`EXPLAIN` documentation](https://www.postgresql.org/docs/16/sql-explain.html)
and [using `EXPLAIN` guide](https://www.postgresql.org/docs/16/using-explain.html).
## Nodes
Every query plan consists of nodes. Nodes can be nested, and are executed from
the inside out. This means that the innermost node is executed before an outer
node. This can be best thought of as nested function calls, returning their
results as they unwind. For example, a plan starting with an `Aggregate`
followed by a `Nested Loop`, followed by an `Index Only scan` can be thought of
as the following Ruby code:
```ruby
aggregate(
nested_loop(
index_only_scan()
index_only_scan()
)
)
```
Nodes are indicated using a `->` followed by the type of node taken. For
example:
```sql
Aggregate (cost=922411.76..922411.77 rows=1 width=8)
-> Seq Scan on projects (cost=0.00..908044.47 rows=5746914 width=0)
Filter: (visibility_level = ANY ('{0,20}'::integer[]))
```
Here the first node executed is `Seq scan on projects`. The `Filter:` is an
additional filter applied to the results of the node. A filter is very similar
to Ruby's `Array#select`: it takes the input rows, applies the filter, and
produces a new list of rows. After the node is done, we perform the `Aggregate`
above it.
Nested nodes look like this:
```sql
Aggregate (cost=176.97..176.98 rows=1 width=8) (actual time=0.252..0.252 rows=1 loops=1)
Buffers: shared hit=155
-> Nested Loop (cost=0.86..176.75 rows=87 width=0) (actual time=0.035..0.249 rows=36 loops=1)
Buffers: shared hit=155
-> Index Only Scan using users_pkey on users users_1 (cost=0.43..4.95 rows=87 width=4) (actual time=0.029..0.123 rows=36 loops=1)
Index Cond: (id < 100)
Heap Fetches: 0
-> Index Only Scan using users_pkey on users (cost=0.43..1.96 rows=1 width=4) (actual time=0.003..0.003 rows=1 loops=36)
Index Cond: (id = users_1.id)
Heap Fetches: 0
Planning time: 2.585 ms
Execution time: 0.310 ms
```
Here we first perform two separate "Index Only" scans, followed by performing a
"Nested Loop" on the result of these two scans.
## Node statistics
Each node in a plan has a set of associated statistics, such as the cost, the
number of rows produced, the number of loops performed, and more. For example:
```sql
Seq Scan on projects (cost=0.00..908044.47 rows=5746914 width=0)
```
Here we can see that our cost ranges from `0.00..908044.47` (we cover this in
a moment), and we estimate (since we're using `EXPLAIN` and not `EXPLAIN
ANALYZE`) a total of 5,746,914 rows to be produced by this node. The `width`
statistics describes the estimated width of each row, in bytes.
The `costs` field specifies how expensive a node was. The cost is measured in
arbitrary units determined by the query planner's cost parameters. What
influences the costs depends on a variety of settings, such as `seq_page_cost`,
`cpu_tuple_cost`, and various others.
The format of the costs field is as follows:
```sql
STARTUP COST..TOTAL COST
```
The startup cost states how expensive it was to start the node, with the total
cost describing how expensive the entire node was. In general: the greater the
values, the more expensive the node.
When using `EXPLAIN ANALYZE`, these statistics also include the actual time
(in milliseconds) spent, and other runtime statistics (for example, the actual number of
produced rows):
```sql
Seq Scan on projects (cost=0.00..908053.18 rows=5746969 width=0) (actual time=0.041..2987.606 rows=5746940 loops=1)
```
Here we can see we estimated 5,746,969 rows to be returned, but in reality we
returned 5,746,940 rows. We can also see that _just_ this sequential scan took
2.98 seconds to run.
Using `EXPLAIN (ANALYZE, BUFFERS)` also gives us information about the
number of rows removed by a filter, the number of buffers used, and more. For
example:
```sql
Seq Scan on projects (cost=0.00..908053.18 rows=5746969 width=0) (actual time=0.041..2987.606 rows=5746940 loops=1)
Filter: (visibility_level = ANY ('{0,20}'::integer[]))
Rows Removed by Filter: 65677
Buffers: shared hit=208846
```
Here we can see that our filter has to remove 65,677 rows, and that we use
208,846 buffers. Each buffer in PostgreSQL is 8 KB (8192 bytes), meaning our
above node uses *1.6 GB of buffers*. That's a lot!
Keep in mind that some statistics are per-loop averages, while others are total values:
| Field name | Value type |
| --- | --- |
| Actual Total Time | per-loop average |
| Actual Rows | per-loop average |
| Buffers Shared Hit | total value |
| Buffers Shared Read | total value |
| Buffers Shared Dirtied | total value |
| Buffers Shared Written | total value |
| I/O Read Time | total value |
| I/O Read Write | total value |
For example:
```sql
-> Index Scan using users_pkey on public.users (cost=0.43..3.44 rows=1 width=1318) (actual time=0.025..0.025 rows=1 loops=888)
Index Cond: (users.id = issues.author_id)
Buffers: shared hit=3543 read=9
I/O Timings: read=17.760 write=0.000
```
Here we can see that this node used 3552 buffers (3543 + 9), returned 888 rows (`888 * 1`), and the actual duration was 22.2 milliseconds (`888 * 0.025`).
17.76 milliseconds of the total duration was spent in reading from disk, to retrieve data that was not in the cache.
## Node types
There are quite a few different types of nodes, so we only cover some of the
more common ones here.
A full list of all the available nodes and their descriptions can be found in
the [PostgreSQL source file `plannodes.h`](https://gitlab.com/postgres/postgres/blob/master/src/include/nodes/plannodes.h).
The `pgMustard` [EXPLAIN documentation](https://www.pgmustard.com/docs/explain) also offers detailed look into nodes and their fields.
### Seq Scan
A sequential scan over (a chunk of) a database table. This is like using
`Array#each`, but on a database table. Sequential scans can be quite slow when
retrieving lots of rows, so it's best to avoid these for large tables.
### Index Only Scan
A scan on an index that did not require fetching anything from the table. In
certain cases an index only scan may still fetch data from the table, in this
case the node includes a `Heap Fetches:` statistic.
### Index Scan
A scan on an index that required retrieving some data from the table.
### Bitmap Index Scan and Bitmap Heap scan
Bitmap scans fall between sequential scans and index scans. These are typically
used when we would read too much data from an index scan, but too little to
perform a sequential scan. A bitmap scan uses what is known as a
[bitmap index](https://en.wikipedia.org/wiki/Bitmap_index) to perform its work.
The [source code of PostgreSQL](https://gitlab.com/postgres/postgres/blob/REL_11_STABLE/src/include/nodes/plannodes.h#L441)
states the following on bitmap scans:
> Bitmap Index Scan delivers a bitmap of potential tuple locations; it does not
> access the heap itself. The bitmap is used by an ancestor Bitmap Heap Scan
> node, possibly after passing through intermediate Bitmap Or and/or Bitmap And
> nodes to combine it with the results of other Bitmap Index Scans.
### Limit
Applies a `LIMIT` on the input rows.
### Sort
Sorts the input rows as specified using an `ORDER BY` statement.
### Nested Loop
A nested loop executes its child nodes for every row produced by a node that
precedes it. For example:
```sql
-> Nested Loop (cost=0.86..176.75 rows=87 width=0) (actual time=0.035..0.249 rows=36 loops=1)
Buffers: shared hit=155
-> Index Only Scan using users_pkey on users users_1 (cost=0.43..4.95 rows=87 width=4) (actual time=0.029..0.123 rows=36 loops=1)
Index Cond: (id < 100)
Heap Fetches: 0
-> Index Only Scan using users_pkey on users (cost=0.43..1.96 rows=1 width=4) (actual time=0.003..0.003 rows=1 loops=36)
Index Cond: (id = users_1.id)
Heap Fetches: 0
```
Here the first child node (`Index Only Scan using users_pkey on users users_1`)
produces 36 rows, and is executed once (`rows=36 loops=1`). The next node
produces 1 row (`rows=1`), but is repeated 36 times (`loops=36`). This is
because the previous node produced 36 rows.
This means that nested loops can quickly slow the query down if the various
child nodes keep producing many rows.
## Optimizing queries
With that out of the way, let's see how we can optimize a query. Let's use the
following query as an example:
```sql
SELECT COUNT(*)
FROM users
WHERE twitter != '';
```
This query counts the number of users that have a Twitter profile set.
Let's run this using `EXPLAIN (ANALYZE, BUFFERS)`:
```sql
EXPLAIN (ANALYZE, BUFFERS)
SELECT COUNT(*)
FROM users
WHERE twitter != '';
```
This produces the following plan:
```sql
Aggregate (cost=845110.21..845110.22 rows=1 width=8) (actual time=1271.157..1271.158 rows=1 loops=1)
Buffers: shared hit=202662
-> Seq Scan on users (cost=0.00..844969.99 rows=56087 width=0) (actual time=0.019..1265.883 rows=51833 loops=1)
Filter: ((twitter)::text <> ''::text)
Rows Removed by Filter: 2487813
Buffers: shared hit=202662
Planning time: 0.390 ms
Execution time: 1271.180 ms
```
From this query plan we can see the following:
1. We need to perform a sequential scan on the `users` table.
1. This sequential scan filters out 2,487,813 rows using a `Filter`.
1. We use 202,622 buffers, which equals 1.58 GB of memory.
1. It takes us 1.2 seconds to do all of this.
Considering we are just counting users, that's quite expensive!
Before we start making any changes, let's see if there are any existing indexes
on the `users` table that we might be able to use. We can obtain this
information by running `\d users` in a `psql` console, then scrolling down to
the `Indexes:` section:
```sql
Indexes:
"users_pkey" PRIMARY KEY, btree (id)
"index_users_on_confirmation_token" UNIQUE, btree (confirmation_token)
"index_users_on_email" UNIQUE, btree (email)
"index_users_on_reset_password_token" UNIQUE, btree (reset_password_token)
"index_users_on_static_object_token" UNIQUE, btree (static_object_token)
"index_users_on_unlock_token" UNIQUE, btree (unlock_token)
"index_on_users_name_lower" btree (lower(name::text))
"index_users_on_admin" btree (admin)
"index_users_on_created_at" btree (created_at)
"index_users_on_email_trigram" gin (email gin_trgm_ops)
"index_users_on_feed_token" btree (feed_token)
"index_users_on_group_view" btree (group_view)
"index_users_on_incoming_email_token" btree (incoming_email_token)
"index_users_on_managing_group_id" btree (managing_group_id)
"index_users_on_name" btree (name)
"index_users_on_name_trigram" gin (name gin_trgm_ops)
"index_users_on_public_email" btree (public_email) WHERE public_email::text <> ''::text
"index_users_on_state" btree (state)
"index_users_on_state_and_user_type" btree (state, user_type)
"index_users_on_unconfirmed_email" btree (unconfirmed_email) WHERE unconfirmed_email IS NOT NULL
"index_users_on_user_type" btree (user_type)
"index_users_on_username" btree (username)
"index_users_on_username_trigram" gin (username gin_trgm_ops)
"tmp_idx_on_user_id_where_bio_is_filled" btree (id) WHERE COALESCE(bio, ''::character varying)::text IS DISTINCT FROM ''::text
```
Here we can see there is no index on the `twitter` column, which means
PostgreSQL has to perform a sequential scan in this case. Let's try to fix this
by adding the following index:
```sql
CREATE INDEX CONCURRENTLY twitter_test ON users (twitter);
```
If we now re-run our query using `EXPLAIN (ANALYZE, BUFFERS)` we get the
following plan:
```sql
Aggregate (cost=61002.82..61002.83 rows=1 width=8) (actual time=297.311..297.312 rows=1 loops=1)
Buffers: shared hit=51854 dirtied=19
-> Index Only Scan using twitter_test on users (cost=0.43..60873.13 rows=51877 width=0) (actual time=279.184..293.532 rows=51833 loops=1)
Filter: ((twitter)::text <> ''::text)
Rows Removed by Filter: 2487830
Heap Fetches: 26037
Buffers: shared hit=51854 dirtied=19
Planning time: 0.191 ms
Execution time: 297.334 ms
```
Now it takes just under 300 milliseconds to get our data, instead of 1.2
seconds. However, we still use 51,854 buffers, which is about 400 MB of memory.
300 milliseconds is also quite slow for such a simple query. To understand why
this query is still expensive, let's take a look at the following:
```sql
Index Only Scan using twitter_test on users (cost=0.43..60873.13 rows=51877 width=0) (actual time=279.184..293.532 rows=51833 loops=1)
Filter: ((twitter)::text <> ''::text)
Rows Removed by Filter: 2487830
```
We start with an index only scan on our index, but we somehow still apply a
`Filter` that filters out 2,487,830 rows. Why is that? Well, let's look at how
we created the index:
```sql
CREATE INDEX CONCURRENTLY twitter_test ON users (twitter);
```
We told PostgreSQL to index all possible values of the `twitter` column,
even empty strings. Our query in turn uses `WHERE twitter != ''`. This means
that the index does improve things, as we don't need to do a sequential scan,
but we may still encounter empty strings. This means PostgreSQL _has_ to apply a
Filter on the index results to get rid of those values.
Fortunately, we can improve this even further using "partial indexes". Partial
indexes are indexes with a `WHERE` condition that is applied when indexing data.
For example:
```sql
CREATE INDEX CONCURRENTLY some_index ON users (email) WHERE id < 100
```
This index would only index the `email` value of rows that match `WHERE id < 100`.
We can use partial indexes to change our Twitter index to the following:
```sql
CREATE INDEX CONCURRENTLY twitter_test ON users (twitter) WHERE twitter != '';
```
After being created, if we run our query again we are given the following plan:
```sql
Aggregate (cost=1608.26..1608.27 rows=1 width=8) (actual time=19.821..19.821 rows=1 loops=1)
Buffers: shared hit=44036
-> Index Only Scan using twitter_test on users (cost=0.41..1479.71 rows=51420 width=0) (actual time=0.023..15.514 rows=51833 loops=1)
Heap Fetches: 1208
Buffers: shared hit=44036
Planning time: 0.123 ms
Execution time: 19.848 ms
```
That's _a lot_ better! Now it only takes 20 milliseconds to get the data, and we
only use about 344 MB of buffers (instead of the original 1.58 GB). The reason
this works is that now PostgreSQL no longer needs to apply a `Filter`, as the
index only contains `twitter` values that are not empty.
Keep in mind that you shouldn't just add partial indexes every time you want to
optimize a query. Every index has to be updated for every write, and they may
require quite a bit of space, depending on the amount of indexed data. As a
result, first check if there are any existing indexes you may be able to reuse.
If there aren't any, check if you can perhaps slightly change an existing one to
fit both the existing and new queries. Only add a new index if none of the
existing indexes can be used in any way.
When comparing execution plans, don't take timing as the only important metric.
Good timing is the main goal of any optimization, but it can be too volatile to
be used for comparison (for example, it depends a lot on the state of cache).
When optimizing a query, we usually need to reduce the amount of data we're
dealing with. Indexes are the way to work with fewer pages (buffers) to get the
result, so, during optimization, look at the number of buffers used (read and hit),
and work on reducing these numbers. Reduced timing is the consequence of reduced
buffer numbers. [Database Lab Engine](#database-lab-engine) guarantees that the plan is structurally
identical to production (and overall number of buffers is the same as on production),
but difference in cache state and I/O speed may lead to different timings.
## Queries that can't be optimized
Now that we have seen how to optimize a query, let's look at another query that
we might not be able to optimize:
```sql
EXPLAIN (ANALYZE, BUFFERS)
SELECT COUNT(*)
FROM projects
WHERE visibility_level IN (0, 20);
```
The output of `EXPLAIN (ANALYZE, BUFFERS)` is as follows:
```sql
Aggregate (cost=922420.60..922420.61 rows=1 width=8) (actual time=3428.535..3428.535 rows=1 loops=1)
Buffers: shared hit=208846
-> Seq Scan on projects (cost=0.00..908053.18 rows=5746969 width=0) (actual time=0.041..2987.606 rows=5746940 loops=1)
Filter: (visibility_level = ANY ('{0,20}'::integer[]))
Rows Removed by Filter: 65677
Buffers: shared hit=208846
Planning time: 2.861 ms
Execution time: 3428.596 ms
```
Looking at the output we see the following Filter:
```sql
Filter: (visibility_level = ANY ('{0,20}'::integer[]))
Rows Removed by Filter: 65677
```
Looking at the number of rows removed by the filter, we may be tempted to add an
index on `projects.visibility_level` to somehow turn this Sequential scan +
filter into an index-only scan.
Unfortunately, doing so is unlikely to improve anything. Contrary to what some
might believe, an index being present _does not guarantee_ that PostgreSQL
actually uses it. For example, when doing a `SELECT * FROM projects` it is much
cheaper to just scan the entire table, instead of using an index and then
fetching data from the table. In such cases PostgreSQL may decide to not use an
index.
Second, let's think for a moment what our query does: it gets all projects with
visibility level 0 or 20. In the above plan we can see this produces quite a lot
of rows (5,745,940), but how much is that relative to the total? Let's find out
by running the following query:
```sql
SELECT visibility_level, count(*) AS amount
FROM projects
GROUP BY visibility_level
ORDER BY visibility_level ASC;
```
For GitLab.com this produces:
```sql
visibility_level | amount
------------------+---------
0 | 5071325
10 | 65678
20 | 674801
```
Here the total number of projects is 5,811,804, and 5,746,126 of those are of
level 0 or 20. That's 98% of the entire table!
So no matter what we do, this query retrieves 98% of the entire table. Since
most time is spent doing exactly that, there isn't really much we can do to
improve this query, other than _not_ running it at all.
What is important here is that while some may recommend to straight up add an
index the moment you see a sequential scan, it is _much more important_ to first
understand what your query does, how much data it retrieves, and so on. After
all, you cannot optimize something you do not understand.
### Cardinality and selectivity
Earlier we saw that our query had to retrieve 98% of the rows in the table.
There are two terms commonly used for databases: cardinality, and selectivity.
Cardinality refers to the number of unique values in a particular column in a
table.
Selectivity is the number of unique values produced by an operation (for example, an
index scan or filter), relative to the total number of rows. The higher the
selectivity, the more likely PostgreSQL is able to use an index.
In the above example, there are only 3 unique values: 0, 10, and 20. This means
the cardinality is 3. The selectivity in turn is also very low: 0.0000003% (2 /
5,811,804), because our `Filter` only filters using two values (`0` and `20`).
With such a low selectivity value it's not surprising that PostgreSQL decides
using an index is not worth it, because it would produce almost no unique rows.
## Rewriting queries
So the above query can't really be optimized as-is, or at least not much. But
what if we slightly change the purpose of it? What if instead of retrieving all
projects with `visibility_level` 0 or 20, we retrieve those that a user
interacted with somehow?
Prior to GitLab 16.7, GitLab used a table named `user_interacted_projects` to track user interactions with projects.
This table had the following schema:
```sql
Table "public.user_interacted_projects"
Column | Type | Modifiers
------------+---------+-----------
user_id | integer | not null
project_id | integer | not null
Indexes:
"index_user_interacted_projects_on_project_id_and_user_id" UNIQUE, btree (project_id, user_id)
"index_user_interacted_projects_on_user_id" btree (user_id)
Foreign-key constraints:
"fk_rails_0894651f08" FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
"fk_rails_722ceba4f7" FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE
```
Let's rewrite our query to `JOIN` this table onto our projects, and get the
projects for a specific user:
```sql
EXPLAIN ANALYZE
SELECT COUNT(*)
FROM projects
INNER JOIN user_interacted_projects ON user_interacted_projects.project_id = projects.id
WHERE projects.visibility_level IN (0, 20)
AND user_interacted_projects.user_id = 1;
```
What we do here is the following:
1. Get our projects.
1. `INNER JOIN` `user_interacted_projects`, meaning we're only left with rows in
`projects` that have a corresponding row in `user_interacted_projects`.
1. Limit this to the projects with `visibility_level` of 0 or 20, and to
projects that the user with ID 1 interacted with.
If we run this query we get the following plan:
```sql
Aggregate (cost=871.03..871.04 rows=1 width=8) (actual time=9.763..9.763 rows=1 loops=1)
-> Nested Loop (cost=0.86..870.52 rows=203 width=0) (actual time=1.072..9.748 rows=143 loops=1)
-> Index Scan using index_user_interacted_projects_on_user_id on user_interacted_projects (cost=0.43..160.71 rows=205 width=4) (actual time=0.939..2.508 rows=145 loops=1)
Index Cond: (user_id = 1)
-> Index Scan using projects_pkey on projects (cost=0.43..3.45 rows=1 width=4) (actual time=0.049..0.050 rows=1 loops=145)
Index Cond: (id = user_interacted_projects.project_id)
Filter: (visibility_level = ANY ('{0,20}'::integer[]))
Rows Removed by Filter: 0
Planning time: 2.614 ms
Execution time: 9.809 ms
```
Here it only took us just under 10 milliseconds to get the data. We can also see
we're retrieving far fewer projects:
```sql
Index Scan using projects_pkey on projects (cost=0.43..3.45 rows=1 width=4) (actual time=0.049..0.050 rows=1 loops=145)
Index Cond: (id = user_interacted_projects.project_id)
Filter: (visibility_level = ANY ('{0,20}'::integer[]))
Rows Removed by Filter: 0
```
Here we see we perform 145 loops (`loops=145`), with every loop producing 1 row
(`rows=1`). This is much less than before, and our query performs much better!
If we look at the plan we also see our costs are very low:
```sql
Index Scan using projects_pkey on projects (cost=0.43..3.45 rows=1 width=4) (actual time=0.049..0.050 rows=1 loops=145)
```
Here our cost is only 3.45, and it takes us 7.25 milliseconds to do so (0.05 * 145).
The next index scan is a bit more expensive:
```sql
Index Scan using index_user_interacted_projects_on_user_id on user_interacted_projects (cost=0.43..160.71 rows=205 width=4) (actual time=0.939..2.508 rows=145 loops=1)
```
Here the cost is 160.71 (`cost=0.43..160.71`), taking about 2.5 milliseconds
(based on the output of `actual time=....`).
The most expensive part here is the "Nested Loop" that acts upon the result of
these two index scans:
```sql
Nested Loop (cost=0.86..870.52 rows=203 width=0) (actual time=1.072..9.748 rows=143 loops=1)
```
Here we had to perform 870.52 disk page fetches for 203 rows, 9.748
milliseconds, producing 143 rows in a single loop.
The key takeaway here is that sometimes you have to rewrite (parts of) a query
to make it better. Sometimes that means having to slightly change your feature
to accommodate for better performance.
## What makes a bad plan
This is a bit of a difficult question to answer, because the definition of "bad"
is relative to the problem you are trying to solve. However, some patterns are
best avoided in most cases, such as:
- Sequential scans on large tables
- Filters that remove a lot of rows
- Performing a certain step that requires _a lot_ of
buffers (for example, an index scan for GitLab.com that requires more than 512 MB).
As a general guideline, aim for a query that:
1. Takes no more than 10 milliseconds. Our target time spent in SQL per request
is around 100 milliseconds, so every query should be as fast as possible.
1. Does not use an excessive number of buffers, relative to the workload. For
example, retrieving ten rows shouldn't require 1 GB of buffers.
1. Does not spend a long amount of time performing disk IO operations. The
setting `track_io_timing` must be enabled for this data to be included in the
output of `EXPLAIN ANALYZE`.
1. Applies a `LIMIT` when retrieving rows without aggregating them, such as
`SELECT * FROM users`.
1. Doesn't use a `Filter` to filter out too many rows, especially if the query
does not use a `LIMIT` to limit the number of returned rows. Filters can
usually be removed by adding a (partial) index.
These are _guidelines_ and not hard requirements, as different needs may require
different queries. The only _rule_ is that you _must always measure_ your query
(preferably using a production-like database) using `EXPLAIN (ANALYZE, BUFFERS)`
and related tools such as:
- [`explain.depesz.com`](https://explain.depesz.com/).
- [`explain.dalibo.com/`](https://explain.dalibo.com/).
## Producing query plans
There are a few ways to get the output of a query plan. Of course you
can directly run the `EXPLAIN` query in the `psql` console, or you can
follow one of the other options below.
### Database Lab Engine
GitLab team members can use [Database Lab Engine](https://gitlab.com/postgres-ai/database-lab), and the companion
SQL optimization tool - [Joe Bot](https://gitlab.com/postgres-ai/joe).
Database Lab Engine provides developers with their own clone of the production database, while Joe Bot helps with exploring execution plans.
Joe Bot is available through its [web interface](https://console.postgres.ai/gitlab/joe-instances).
With Joe Bot you can execute DDL statements (like creating indexes, tables, and columns) and get query plans for `SELECT`, `UPDATE`, and `DELETE` statements.
For example, to test new index on a column that is not existing on production yet, you can do the following:
Create the column:
```sql
exec ALTER TABLE projects ADD COLUMN last_at timestamp without time zone
```
Create the index:
```sql
exec CREATE INDEX index_projects_last_activity ON projects (last_activity_at) WHERE last_activity_at IS NOT NULL
```
Analyze the table to update its statistics:
```sql
exec ANALYZE projects
```
Get the query plan:
```sql
explain SELECT * FROM projects WHERE last_activity_at < CURRENT_DATE
```
Once done you can rollback your changes:
```sql
reset
```
For more information about the available options, run:
```sql
help
```
The web interface comes with the following execution plan visualizers included:
- [Depesz](https://explain.depesz.com/)
- [PEV2](https://github.com/dalibo/pev2)
- [FlameGraph](https://github.com/mgartner/pg_flame)
#### Tips & Tricks
The database connection is now maintained during your whole session, so you can use `exec set ...` for any session variables (such as `enable_seqscan` or `work_mem`). These settings are applied to all subsequent commands until you reset them. For example you can disable parallel queries with
```sql
exec SET max_parallel_workers_per_gather = 0
```
### Rails console
Using the Rails 7.1 [explain method](https://guides.rubyonrails.org/active_record_querying.html#explain-options)
you can directly generate the query plan from the Rails console:
```ruby
pry(main)> Project.where('build_timeout > ?', 3600).explain(:analyze, :buffers, :verbose)
Project Load (1.9ms) SELECT "projects".* FROM "projects" WHERE (build_timeout > 3600)
↳ (pry):12
=> EXPLAIN for: SELECT "projects".* FROM "projects" WHERE (build_timeout > 3600)
Seq Scan on public.projects (cost=0.00..2.17 rows=1 width=742) (actual time=0.040..0.041 rows=0 loops=1)
Output: id, name, path, description, created_at, updated_at, creator_id, namespace_id, ...
Filter: (projects.build_timeout > 3600)
Rows Removed by Filter: 16
Buffers: shared hit=1
Planning:
Buffers: shared hit=6
Planning Time: 0.230 ms
Execution Time: 0.033 ms
(9 rows)
```
## Further reading
A more extensive guide on understanding query plans can be found in
the [presentation](https://public.dalibo.com/exports/conferences/_archives/_2012/201211_explain/understanding_explain.pdf)
from [Dalibo.org](https://www.dalibo.com/en/).
The Depesz blog also has a good [section](https://www.depesz.com/tag/unexplainable/) dedicated to query plans.
|
---
stage: Data Access
group: Database Frameworks
info: Any user with at least the Maintainer role can merge updates to this content.
For details, see https://docs.gitlab.com/development/development_processes/#development-guidelines-review.
title: Understanding EXPLAIN plans
breadcrumbs:
- doc
- development
- database
---
PostgreSQL allows you to obtain query plans using the `EXPLAIN` command. This
command can be invaluable when trying to determine how a query performs.
You can use this command directly in your SQL query, as long as the query starts
with it:
```sql
EXPLAIN
SELECT COUNT(*)
FROM projects
WHERE visibility_level IN (0, 20);
```
When running this on GitLab.com, we are presented with the following output:
```sql
Aggregate (cost=922411.76..922411.77 rows=1 width=8)
-> Seq Scan on projects (cost=0.00..908044.47 rows=5746914 width=0)
Filter: (visibility_level = ANY ('{0,20}'::integer[]))
```
When using _just_ `EXPLAIN`, PostgreSQL does not actually execute our query,
instead it produces an _estimated_ execution plan based on the available
statistics. This means the actual plan can differ quite a bit. Fortunately,
PostgreSQL provides us with the option to execute the query as well. To do so,
we need to use `EXPLAIN ANALYZE` instead of just `EXPLAIN`:
```sql
EXPLAIN ANALYZE
SELECT COUNT(*)
FROM projects
WHERE visibility_level IN (0, 20);
```
This produces:
```sql
Aggregate (cost=922420.60..922420.61 rows=1 width=8) (actual time=3428.535..3428.535 rows=1 loops=1)
-> Seq Scan on projects (cost=0.00..908053.18 rows=5746969 width=0) (actual time=0.041..2987.606 rows=5746940 loops=1)
Filter: (visibility_level = ANY ('{0,20}'::integer[]))
Rows Removed by Filter: 65677
Planning time: 2.861 ms
Execution time: 3428.596 ms
```
As we can see this plan is quite different, and includes a lot more data. Let's
discuss this step by step.
Because `EXPLAIN ANALYZE` executes the query, care should be taken when using a
query that writes data or might time out. If the query modifies data,
consider wrapping it in a transaction that rolls back automatically like so:
```sql
BEGIN;
EXPLAIN ANALYZE
DELETE FROM users WHERE id = 1;
ROLLBACK;
```
The `EXPLAIN` command also takes additional options, such as `BUFFERS`:
```sql
EXPLAIN (ANALYZE, BUFFERS)
SELECT COUNT(*)
FROM projects
WHERE visibility_level IN (0, 20);
```
This then produces:
```sql
Aggregate (cost=922420.60..922420.61 rows=1 width=8) (actual time=3428.535..3428.535 rows=1 loops=1)
Buffers: shared hit=208846
-> Seq Scan on projects (cost=0.00..908053.18 rows=5746969 width=0) (actual time=0.041..2987.606 rows=5746940 loops=1)
Filter: (visibility_level = ANY ('{0,20}'::integer[]))
Rows Removed by Filter: 65677
Buffers: shared hit=208846
Planning time: 2.861 ms
Execution time: 3428.596 ms
```
For more information, refer to the official
[`EXPLAIN` documentation](https://www.postgresql.org/docs/16/sql-explain.html)
and [using `EXPLAIN` guide](https://www.postgresql.org/docs/16/using-explain.html).
## Nodes
Every query plan consists of nodes. Nodes can be nested, and are executed from
the inside out. This means that the innermost node is executed before an outer
node. This can be best thought of as nested function calls, returning their
results as they unwind. For example, a plan starting with an `Aggregate`
followed by a `Nested Loop`, followed by an `Index Only scan` can be thought of
as the following Ruby code:
```ruby
aggregate(
nested_loop(
index_only_scan()
index_only_scan()
)
)
```
Nodes are indicated using a `->` followed by the type of node taken. For
example:
```sql
Aggregate (cost=922411.76..922411.77 rows=1 width=8)
-> Seq Scan on projects (cost=0.00..908044.47 rows=5746914 width=0)
Filter: (visibility_level = ANY ('{0,20}'::integer[]))
```
Here the first node executed is `Seq scan on projects`. The `Filter:` is an
additional filter applied to the results of the node. A filter is very similar
to Ruby's `Array#select`: it takes the input rows, applies the filter, and
produces a new list of rows. After the node is done, we perform the `Aggregate`
above it.
Nested nodes look like this:
```sql
Aggregate (cost=176.97..176.98 rows=1 width=8) (actual time=0.252..0.252 rows=1 loops=1)
Buffers: shared hit=155
-> Nested Loop (cost=0.86..176.75 rows=87 width=0) (actual time=0.035..0.249 rows=36 loops=1)
Buffers: shared hit=155
-> Index Only Scan using users_pkey on users users_1 (cost=0.43..4.95 rows=87 width=4) (actual time=0.029..0.123 rows=36 loops=1)
Index Cond: (id < 100)
Heap Fetches: 0
-> Index Only Scan using users_pkey on users (cost=0.43..1.96 rows=1 width=4) (actual time=0.003..0.003 rows=1 loops=36)
Index Cond: (id = users_1.id)
Heap Fetches: 0
Planning time: 2.585 ms
Execution time: 0.310 ms
```
Here we first perform two separate "Index Only" scans, followed by performing a
"Nested Loop" on the result of these two scans.
## Node statistics
Each node in a plan has a set of associated statistics, such as the cost, the
number of rows produced, the number of loops performed, and more. For example:
```sql
Seq Scan on projects (cost=0.00..908044.47 rows=5746914 width=0)
```
Here we can see that our cost ranges from `0.00..908044.47` (we cover this in
a moment), and we estimate (since we're using `EXPLAIN` and not `EXPLAIN
ANALYZE`) a total of 5,746,914 rows to be produced by this node. The `width`
statistics describes the estimated width of each row, in bytes.
The `costs` field specifies how expensive a node was. The cost is measured in
arbitrary units determined by the query planner's cost parameters. What
influences the costs depends on a variety of settings, such as `seq_page_cost`,
`cpu_tuple_cost`, and various others.
The format of the costs field is as follows:
```sql
STARTUP COST..TOTAL COST
```
The startup cost states how expensive it was to start the node, with the total
cost describing how expensive the entire node was. In general: the greater the
values, the more expensive the node.
When using `EXPLAIN ANALYZE`, these statistics also include the actual time
(in milliseconds) spent, and other runtime statistics (for example, the actual number of
produced rows):
```sql
Seq Scan on projects (cost=0.00..908053.18 rows=5746969 width=0) (actual time=0.041..2987.606 rows=5746940 loops=1)
```
Here we can see we estimated 5,746,969 rows to be returned, but in reality we
returned 5,746,940 rows. We can also see that _just_ this sequential scan took
2.98 seconds to run.
Using `EXPLAIN (ANALYZE, BUFFERS)` also gives us information about the
number of rows removed by a filter, the number of buffers used, and more. For
example:
```sql
Seq Scan on projects (cost=0.00..908053.18 rows=5746969 width=0) (actual time=0.041..2987.606 rows=5746940 loops=1)
Filter: (visibility_level = ANY ('{0,20}'::integer[]))
Rows Removed by Filter: 65677
Buffers: shared hit=208846
```
Here we can see that our filter has to remove 65,677 rows, and that we use
208,846 buffers. Each buffer in PostgreSQL is 8 KB (8192 bytes), meaning our
above node uses *1.6 GB of buffers*. That's a lot!
Keep in mind that some statistics are per-loop averages, while others are total values:
| Field name | Value type |
| --- | --- |
| Actual Total Time | per-loop average |
| Actual Rows | per-loop average |
| Buffers Shared Hit | total value |
| Buffers Shared Read | total value |
| Buffers Shared Dirtied | total value |
| Buffers Shared Written | total value |
| I/O Read Time | total value |
| I/O Read Write | total value |
For example:
```sql
-> Index Scan using users_pkey on public.users (cost=0.43..3.44 rows=1 width=1318) (actual time=0.025..0.025 rows=1 loops=888)
Index Cond: (users.id = issues.author_id)
Buffers: shared hit=3543 read=9
I/O Timings: read=17.760 write=0.000
```
Here we can see that this node used 3552 buffers (3543 + 9), returned 888 rows (`888 * 1`), and the actual duration was 22.2 milliseconds (`888 * 0.025`).
17.76 milliseconds of the total duration was spent in reading from disk, to retrieve data that was not in the cache.
## Node types
There are quite a few different types of nodes, so we only cover some of the
more common ones here.
A full list of all the available nodes and their descriptions can be found in
the [PostgreSQL source file `plannodes.h`](https://gitlab.com/postgres/postgres/blob/master/src/include/nodes/plannodes.h).
The `pgMustard` [EXPLAIN documentation](https://www.pgmustard.com/docs/explain) also offers detailed look into nodes and their fields.
### Seq Scan
A sequential scan over (a chunk of) a database table. This is like using
`Array#each`, but on a database table. Sequential scans can be quite slow when
retrieving lots of rows, so it's best to avoid these for large tables.
### Index Only Scan
A scan on an index that did not require fetching anything from the table. In
certain cases an index only scan may still fetch data from the table, in this
case the node includes a `Heap Fetches:` statistic.
### Index Scan
A scan on an index that required retrieving some data from the table.
### Bitmap Index Scan and Bitmap Heap scan
Bitmap scans fall between sequential scans and index scans. These are typically
used when we would read too much data from an index scan, but too little to
perform a sequential scan. A bitmap scan uses what is known as a
[bitmap index](https://en.wikipedia.org/wiki/Bitmap_index) to perform its work.
The [source code of PostgreSQL](https://gitlab.com/postgres/postgres/blob/REL_11_STABLE/src/include/nodes/plannodes.h#L441)
states the following on bitmap scans:
> Bitmap Index Scan delivers a bitmap of potential tuple locations; it does not
> access the heap itself. The bitmap is used by an ancestor Bitmap Heap Scan
> node, possibly after passing through intermediate Bitmap Or and/or Bitmap And
> nodes to combine it with the results of other Bitmap Index Scans.
### Limit
Applies a `LIMIT` on the input rows.
### Sort
Sorts the input rows as specified using an `ORDER BY` statement.
### Nested Loop
A nested loop executes its child nodes for every row produced by a node that
precedes it. For example:
```sql
-> Nested Loop (cost=0.86..176.75 rows=87 width=0) (actual time=0.035..0.249 rows=36 loops=1)
Buffers: shared hit=155
-> Index Only Scan using users_pkey on users users_1 (cost=0.43..4.95 rows=87 width=4) (actual time=0.029..0.123 rows=36 loops=1)
Index Cond: (id < 100)
Heap Fetches: 0
-> Index Only Scan using users_pkey on users (cost=0.43..1.96 rows=1 width=4) (actual time=0.003..0.003 rows=1 loops=36)
Index Cond: (id = users_1.id)
Heap Fetches: 0
```
Here the first child node (`Index Only Scan using users_pkey on users users_1`)
produces 36 rows, and is executed once (`rows=36 loops=1`). The next node
produces 1 row (`rows=1`), but is repeated 36 times (`loops=36`). This is
because the previous node produced 36 rows.
This means that nested loops can quickly slow the query down if the various
child nodes keep producing many rows.
## Optimizing queries
With that out of the way, let's see how we can optimize a query. Let's use the
following query as an example:
```sql
SELECT COUNT(*)
FROM users
WHERE twitter != '';
```
This query counts the number of users that have a Twitter profile set.
Let's run this using `EXPLAIN (ANALYZE, BUFFERS)`:
```sql
EXPLAIN (ANALYZE, BUFFERS)
SELECT COUNT(*)
FROM users
WHERE twitter != '';
```
This produces the following plan:
```sql
Aggregate (cost=845110.21..845110.22 rows=1 width=8) (actual time=1271.157..1271.158 rows=1 loops=1)
Buffers: shared hit=202662
-> Seq Scan on users (cost=0.00..844969.99 rows=56087 width=0) (actual time=0.019..1265.883 rows=51833 loops=1)
Filter: ((twitter)::text <> ''::text)
Rows Removed by Filter: 2487813
Buffers: shared hit=202662
Planning time: 0.390 ms
Execution time: 1271.180 ms
```
From this query plan we can see the following:
1. We need to perform a sequential scan on the `users` table.
1. This sequential scan filters out 2,487,813 rows using a `Filter`.
1. We use 202,622 buffers, which equals 1.58 GB of memory.
1. It takes us 1.2 seconds to do all of this.
Considering we are just counting users, that's quite expensive!
Before we start making any changes, let's see if there are any existing indexes
on the `users` table that we might be able to use. We can obtain this
information by running `\d users` in a `psql` console, then scrolling down to
the `Indexes:` section:
```sql
Indexes:
"users_pkey" PRIMARY KEY, btree (id)
"index_users_on_confirmation_token" UNIQUE, btree (confirmation_token)
"index_users_on_email" UNIQUE, btree (email)
"index_users_on_reset_password_token" UNIQUE, btree (reset_password_token)
"index_users_on_static_object_token" UNIQUE, btree (static_object_token)
"index_users_on_unlock_token" UNIQUE, btree (unlock_token)
"index_on_users_name_lower" btree (lower(name::text))
"index_users_on_admin" btree (admin)
"index_users_on_created_at" btree (created_at)
"index_users_on_email_trigram" gin (email gin_trgm_ops)
"index_users_on_feed_token" btree (feed_token)
"index_users_on_group_view" btree (group_view)
"index_users_on_incoming_email_token" btree (incoming_email_token)
"index_users_on_managing_group_id" btree (managing_group_id)
"index_users_on_name" btree (name)
"index_users_on_name_trigram" gin (name gin_trgm_ops)
"index_users_on_public_email" btree (public_email) WHERE public_email::text <> ''::text
"index_users_on_state" btree (state)
"index_users_on_state_and_user_type" btree (state, user_type)
"index_users_on_unconfirmed_email" btree (unconfirmed_email) WHERE unconfirmed_email IS NOT NULL
"index_users_on_user_type" btree (user_type)
"index_users_on_username" btree (username)
"index_users_on_username_trigram" gin (username gin_trgm_ops)
"tmp_idx_on_user_id_where_bio_is_filled" btree (id) WHERE COALESCE(bio, ''::character varying)::text IS DISTINCT FROM ''::text
```
Here we can see there is no index on the `twitter` column, which means
PostgreSQL has to perform a sequential scan in this case. Let's try to fix this
by adding the following index:
```sql
CREATE INDEX CONCURRENTLY twitter_test ON users (twitter);
```
If we now re-run our query using `EXPLAIN (ANALYZE, BUFFERS)` we get the
following plan:
```sql
Aggregate (cost=61002.82..61002.83 rows=1 width=8) (actual time=297.311..297.312 rows=1 loops=1)
Buffers: shared hit=51854 dirtied=19
-> Index Only Scan using twitter_test on users (cost=0.43..60873.13 rows=51877 width=0) (actual time=279.184..293.532 rows=51833 loops=1)
Filter: ((twitter)::text <> ''::text)
Rows Removed by Filter: 2487830
Heap Fetches: 26037
Buffers: shared hit=51854 dirtied=19
Planning time: 0.191 ms
Execution time: 297.334 ms
```
Now it takes just under 300 milliseconds to get our data, instead of 1.2
seconds. However, we still use 51,854 buffers, which is about 400 MB of memory.
300 milliseconds is also quite slow for such a simple query. To understand why
this query is still expensive, let's take a look at the following:
```sql
Index Only Scan using twitter_test on users (cost=0.43..60873.13 rows=51877 width=0) (actual time=279.184..293.532 rows=51833 loops=1)
Filter: ((twitter)::text <> ''::text)
Rows Removed by Filter: 2487830
```
We start with an index only scan on our index, but we somehow still apply a
`Filter` that filters out 2,487,830 rows. Why is that? Well, let's look at how
we created the index:
```sql
CREATE INDEX CONCURRENTLY twitter_test ON users (twitter);
```
We told PostgreSQL to index all possible values of the `twitter` column,
even empty strings. Our query in turn uses `WHERE twitter != ''`. This means
that the index does improve things, as we don't need to do a sequential scan,
but we may still encounter empty strings. This means PostgreSQL _has_ to apply a
Filter on the index results to get rid of those values.
Fortunately, we can improve this even further using "partial indexes". Partial
indexes are indexes with a `WHERE` condition that is applied when indexing data.
For example:
```sql
CREATE INDEX CONCURRENTLY some_index ON users (email) WHERE id < 100
```
This index would only index the `email` value of rows that match `WHERE id < 100`.
We can use partial indexes to change our Twitter index to the following:
```sql
CREATE INDEX CONCURRENTLY twitter_test ON users (twitter) WHERE twitter != '';
```
After being created, if we run our query again we are given the following plan:
```sql
Aggregate (cost=1608.26..1608.27 rows=1 width=8) (actual time=19.821..19.821 rows=1 loops=1)
Buffers: shared hit=44036
-> Index Only Scan using twitter_test on users (cost=0.41..1479.71 rows=51420 width=0) (actual time=0.023..15.514 rows=51833 loops=1)
Heap Fetches: 1208
Buffers: shared hit=44036
Planning time: 0.123 ms
Execution time: 19.848 ms
```
That's _a lot_ better! Now it only takes 20 milliseconds to get the data, and we
only use about 344 MB of buffers (instead of the original 1.58 GB). The reason
this works is that now PostgreSQL no longer needs to apply a `Filter`, as the
index only contains `twitter` values that are not empty.
Keep in mind that you shouldn't just add partial indexes every time you want to
optimize a query. Every index has to be updated for every write, and they may
require quite a bit of space, depending on the amount of indexed data. As a
result, first check if there are any existing indexes you may be able to reuse.
If there aren't any, check if you can perhaps slightly change an existing one to
fit both the existing and new queries. Only add a new index if none of the
existing indexes can be used in any way.
When comparing execution plans, don't take timing as the only important metric.
Good timing is the main goal of any optimization, but it can be too volatile to
be used for comparison (for example, it depends a lot on the state of cache).
When optimizing a query, we usually need to reduce the amount of data we're
dealing with. Indexes are the way to work with fewer pages (buffers) to get the
result, so, during optimization, look at the number of buffers used (read and hit),
and work on reducing these numbers. Reduced timing is the consequence of reduced
buffer numbers. [Database Lab Engine](#database-lab-engine) guarantees that the plan is structurally
identical to production (and overall number of buffers is the same as on production),
but difference in cache state and I/O speed may lead to different timings.
## Queries that can't be optimized
Now that we have seen how to optimize a query, let's look at another query that
we might not be able to optimize:
```sql
EXPLAIN (ANALYZE, BUFFERS)
SELECT COUNT(*)
FROM projects
WHERE visibility_level IN (0, 20);
```
The output of `EXPLAIN (ANALYZE, BUFFERS)` is as follows:
```sql
Aggregate (cost=922420.60..922420.61 rows=1 width=8) (actual time=3428.535..3428.535 rows=1 loops=1)
Buffers: shared hit=208846
-> Seq Scan on projects (cost=0.00..908053.18 rows=5746969 width=0) (actual time=0.041..2987.606 rows=5746940 loops=1)
Filter: (visibility_level = ANY ('{0,20}'::integer[]))
Rows Removed by Filter: 65677
Buffers: shared hit=208846
Planning time: 2.861 ms
Execution time: 3428.596 ms
```
Looking at the output we see the following Filter:
```sql
Filter: (visibility_level = ANY ('{0,20}'::integer[]))
Rows Removed by Filter: 65677
```
Looking at the number of rows removed by the filter, we may be tempted to add an
index on `projects.visibility_level` to somehow turn this Sequential scan +
filter into an index-only scan.
Unfortunately, doing so is unlikely to improve anything. Contrary to what some
might believe, an index being present _does not guarantee_ that PostgreSQL
actually uses it. For example, when doing a `SELECT * FROM projects` it is much
cheaper to just scan the entire table, instead of using an index and then
fetching data from the table. In such cases PostgreSQL may decide to not use an
index.
Second, let's think for a moment what our query does: it gets all projects with
visibility level 0 or 20. In the above plan we can see this produces quite a lot
of rows (5,745,940), but how much is that relative to the total? Let's find out
by running the following query:
```sql
SELECT visibility_level, count(*) AS amount
FROM projects
GROUP BY visibility_level
ORDER BY visibility_level ASC;
```
For GitLab.com this produces:
```sql
visibility_level | amount
------------------+---------
0 | 5071325
10 | 65678
20 | 674801
```
Here the total number of projects is 5,811,804, and 5,746,126 of those are of
level 0 or 20. That's 98% of the entire table!
So no matter what we do, this query retrieves 98% of the entire table. Since
most time is spent doing exactly that, there isn't really much we can do to
improve this query, other than _not_ running it at all.
What is important here is that while some may recommend to straight up add an
index the moment you see a sequential scan, it is _much more important_ to first
understand what your query does, how much data it retrieves, and so on. After
all, you cannot optimize something you do not understand.
### Cardinality and selectivity
Earlier we saw that our query had to retrieve 98% of the rows in the table.
There are two terms commonly used for databases: cardinality, and selectivity.
Cardinality refers to the number of unique values in a particular column in a
table.
Selectivity is the number of unique values produced by an operation (for example, an
index scan or filter), relative to the total number of rows. The higher the
selectivity, the more likely PostgreSQL is able to use an index.
In the above example, there are only 3 unique values: 0, 10, and 20. This means
the cardinality is 3. The selectivity in turn is also very low: 0.0000003% (2 /
5,811,804), because our `Filter` only filters using two values (`0` and `20`).
With such a low selectivity value it's not surprising that PostgreSQL decides
using an index is not worth it, because it would produce almost no unique rows.
## Rewriting queries
So the above query can't really be optimized as-is, or at least not much. But
what if we slightly change the purpose of it? What if instead of retrieving all
projects with `visibility_level` 0 or 20, we retrieve those that a user
interacted with somehow?
Prior to GitLab 16.7, GitLab used a table named `user_interacted_projects` to track user interactions with projects.
This table had the following schema:
```sql
Table "public.user_interacted_projects"
Column | Type | Modifiers
------------+---------+-----------
user_id | integer | not null
project_id | integer | not null
Indexes:
"index_user_interacted_projects_on_project_id_and_user_id" UNIQUE, btree (project_id, user_id)
"index_user_interacted_projects_on_user_id" btree (user_id)
Foreign-key constraints:
"fk_rails_0894651f08" FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
"fk_rails_722ceba4f7" FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE
```
Let's rewrite our query to `JOIN` this table onto our projects, and get the
projects for a specific user:
```sql
EXPLAIN ANALYZE
SELECT COUNT(*)
FROM projects
INNER JOIN user_interacted_projects ON user_interacted_projects.project_id = projects.id
WHERE projects.visibility_level IN (0, 20)
AND user_interacted_projects.user_id = 1;
```
What we do here is the following:
1. Get our projects.
1. `INNER JOIN` `user_interacted_projects`, meaning we're only left with rows in
`projects` that have a corresponding row in `user_interacted_projects`.
1. Limit this to the projects with `visibility_level` of 0 or 20, and to
projects that the user with ID 1 interacted with.
If we run this query we get the following plan:
```sql
Aggregate (cost=871.03..871.04 rows=1 width=8) (actual time=9.763..9.763 rows=1 loops=1)
-> Nested Loop (cost=0.86..870.52 rows=203 width=0) (actual time=1.072..9.748 rows=143 loops=1)
-> Index Scan using index_user_interacted_projects_on_user_id on user_interacted_projects (cost=0.43..160.71 rows=205 width=4) (actual time=0.939..2.508 rows=145 loops=1)
Index Cond: (user_id = 1)
-> Index Scan using projects_pkey on projects (cost=0.43..3.45 rows=1 width=4) (actual time=0.049..0.050 rows=1 loops=145)
Index Cond: (id = user_interacted_projects.project_id)
Filter: (visibility_level = ANY ('{0,20}'::integer[]))
Rows Removed by Filter: 0
Planning time: 2.614 ms
Execution time: 9.809 ms
```
Here it only took us just under 10 milliseconds to get the data. We can also see
we're retrieving far fewer projects:
```sql
Index Scan using projects_pkey on projects (cost=0.43..3.45 rows=1 width=4) (actual time=0.049..0.050 rows=1 loops=145)
Index Cond: (id = user_interacted_projects.project_id)
Filter: (visibility_level = ANY ('{0,20}'::integer[]))
Rows Removed by Filter: 0
```
Here we see we perform 145 loops (`loops=145`), with every loop producing 1 row
(`rows=1`). This is much less than before, and our query performs much better!
If we look at the plan we also see our costs are very low:
```sql
Index Scan using projects_pkey on projects (cost=0.43..3.45 rows=1 width=4) (actual time=0.049..0.050 rows=1 loops=145)
```
Here our cost is only 3.45, and it takes us 7.25 milliseconds to do so (0.05 * 145).
The next index scan is a bit more expensive:
```sql
Index Scan using index_user_interacted_projects_on_user_id on user_interacted_projects (cost=0.43..160.71 rows=205 width=4) (actual time=0.939..2.508 rows=145 loops=1)
```
Here the cost is 160.71 (`cost=0.43..160.71`), taking about 2.5 milliseconds
(based on the output of `actual time=....`).
The most expensive part here is the "Nested Loop" that acts upon the result of
these two index scans:
```sql
Nested Loop (cost=0.86..870.52 rows=203 width=0) (actual time=1.072..9.748 rows=143 loops=1)
```
Here we had to perform 870.52 disk page fetches for 203 rows, 9.748
milliseconds, producing 143 rows in a single loop.
The key takeaway here is that sometimes you have to rewrite (parts of) a query
to make it better. Sometimes that means having to slightly change your feature
to accommodate for better performance.
## What makes a bad plan
This is a bit of a difficult question to answer, because the definition of "bad"
is relative to the problem you are trying to solve. However, some patterns are
best avoided in most cases, such as:
- Sequential scans on large tables
- Filters that remove a lot of rows
- Performing a certain step that requires _a lot_ of
buffers (for example, an index scan for GitLab.com that requires more than 512 MB).
As a general guideline, aim for a query that:
1. Takes no more than 10 milliseconds. Our target time spent in SQL per request
is around 100 milliseconds, so every query should be as fast as possible.
1. Does not use an excessive number of buffers, relative to the workload. For
example, retrieving ten rows shouldn't require 1 GB of buffers.
1. Does not spend a long amount of time performing disk IO operations. The
setting `track_io_timing` must be enabled for this data to be included in the
output of `EXPLAIN ANALYZE`.
1. Applies a `LIMIT` when retrieving rows without aggregating them, such as
`SELECT * FROM users`.
1. Doesn't use a `Filter` to filter out too many rows, especially if the query
does not use a `LIMIT` to limit the number of returned rows. Filters can
usually be removed by adding a (partial) index.
These are _guidelines_ and not hard requirements, as different needs may require
different queries. The only _rule_ is that you _must always measure_ your query
(preferably using a production-like database) using `EXPLAIN (ANALYZE, BUFFERS)`
and related tools such as:
- [`explain.depesz.com`](https://explain.depesz.com/).
- [`explain.dalibo.com/`](https://explain.dalibo.com/).
## Producing query plans
There are a few ways to get the output of a query plan. Of course you
can directly run the `EXPLAIN` query in the `psql` console, or you can
follow one of the other options below.
### Database Lab Engine
GitLab team members can use [Database Lab Engine](https://gitlab.com/postgres-ai/database-lab), and the companion
SQL optimization tool - [Joe Bot](https://gitlab.com/postgres-ai/joe).
Database Lab Engine provides developers with their own clone of the production database, while Joe Bot helps with exploring execution plans.
Joe Bot is available through its [web interface](https://console.postgres.ai/gitlab/joe-instances).
With Joe Bot you can execute DDL statements (like creating indexes, tables, and columns) and get query plans for `SELECT`, `UPDATE`, and `DELETE` statements.
For example, to test new index on a column that is not existing on production yet, you can do the following:
Create the column:
```sql
exec ALTER TABLE projects ADD COLUMN last_at timestamp without time zone
```
Create the index:
```sql
exec CREATE INDEX index_projects_last_activity ON projects (last_activity_at) WHERE last_activity_at IS NOT NULL
```
Analyze the table to update its statistics:
```sql
exec ANALYZE projects
```
Get the query plan:
```sql
explain SELECT * FROM projects WHERE last_activity_at < CURRENT_DATE
```
Once done you can rollback your changes:
```sql
reset
```
For more information about the available options, run:
```sql
help
```
The web interface comes with the following execution plan visualizers included:
- [Depesz](https://explain.depesz.com/)
- [PEV2](https://github.com/dalibo/pev2)
- [FlameGraph](https://github.com/mgartner/pg_flame)
#### Tips & Tricks
The database connection is now maintained during your whole session, so you can use `exec set ...` for any session variables (such as `enable_seqscan` or `work_mem`). These settings are applied to all subsequent commands until you reset them. For example you can disable parallel queries with
```sql
exec SET max_parallel_workers_per_gather = 0
```
### Rails console
Using the Rails 7.1 [explain method](https://guides.rubyonrails.org/active_record_querying.html#explain-options)
you can directly generate the query plan from the Rails console:
```ruby
pry(main)> Project.where('build_timeout > ?', 3600).explain(:analyze, :buffers, :verbose)
Project Load (1.9ms) SELECT "projects".* FROM "projects" WHERE (build_timeout > 3600)
↳ (pry):12
=> EXPLAIN for: SELECT "projects".* FROM "projects" WHERE (build_timeout > 3600)
Seq Scan on public.projects (cost=0.00..2.17 rows=1 width=742) (actual time=0.040..0.041 rows=0 loops=1)
Output: id, name, path, description, created_at, updated_at, creator_id, namespace_id, ...
Filter: (projects.build_timeout > 3600)
Rows Removed by Filter: 16
Buffers: shared hit=1
Planning:
Buffers: shared hit=6
Planning Time: 0.230 ms
Execution Time: 0.033 ms
(9 rows)
```
## Further reading
A more extensive guide on understanding query plans can be found in
the [presentation](https://public.dalibo.com/exports/conferences/_archives/_2012/201211_explain/understanding_explain.pdf)
from [Dalibo.org](https://www.dalibo.com/en/).
The Depesz blog also has a good [section](https://www.depesz.com/tag/unexplainable/) dedicated to query plans.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.