Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): add 4 missing tables to the GitLab source (#117614)

Tom Owers24cf283a09d1
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index 60cc28e370db..0285344c9d65 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -5265,14 +5265,14 @@ Today (15): `branches`, `commits`, `deployments`, `issue_notes`, `issue_state_ev
Diffed against: <https://docs.gitlab.com/api/api_resources/>
-- [ ] `/projects/{id}/jobs` — CI job-level rows — pipelines alone cannot answer stage duration, runner cost, or failure attribution (high)
+- [x] `/projects/{id}/jobs` — CI job-level rows — pipelines alone cannot answer stage duration, runner cost, or failure attribution (high). Added as `jobs` (full refresh, keyset pagination).
- [x] `/projects/{id}/issues/{iid}/notes and /projects/{id}/merge_requests/{iid}/notes` — issue and merge-request comments, the main collaboration signal (high). Added as `issue_notes` and `merge_request_notes` (fan-out over `issues` / `merge_requests`).
- [x] `/projects/{id}/issues/{iid}/resource_state_events and /merge_requests/{iid}/resource_state_events` — open/close/reopen transition history — cycle time cannot be computed from current state alone (high). Added as `issue_state_events` and `merge_request_state_events` (fan-out over `issues` / `merge_requests`).
- [ ] `/projects/{id}/dora/metrics` — GitLab's headline DevOps metric (deployment frequency, lead time, change failure rate, MTTR) (high). Skipped: Ultimate-tier only, and it returns pre-aggregated daily values over a default 3-month window that GitLab recomputes, so it has no stable history to sync. Deployment frequency comes from `deployments`.
- [x] `/projects/{id}/deployments` — deployment records joining pipelines to environments, the basis of release analytics (high)
-- [ ] `/projects/{id}/issues/{iid}/resource_label_events` — label add/remove history, the standard way teams track workflow stage over time (medium)
-- [ ] `/projects/{id}/environments` — lookup resolving the environment IDs carried on deployments (medium)
-- [ ] `/projects/{id}/merge_requests/{iid}/approvals` — who approved each MR and when — core review-governance reporting (medium)
+- [x] `/projects/{id}/issues/{iid}/resource_label_events` — label add/remove history, the standard way teams track workflow stage over time (medium). Added as `issue_label_events` (fan-out over `issues`).
+- [x] `/projects/{id}/environments` — lookup resolving the environment IDs carried on deployments (medium). Added as `environments` (full refresh).
+- [x] `/projects/{id}/merge_requests/{iid}/approvals` — who approved each MR and when — core review-governance reporting (medium). Added as `merge_request_approvals`, one row per approver (fan-out over `merge_requests`).
- [ ] `/projects/{id}/events` — project activity stream covering pushes, comments, and membership changes in one table (medium)
- [ ] `/projects/{id}/issues/{iid}/resource_milestone_events` — milestone reassignment history for scope-change analysis (medium)
- [ ] `/projects/{id}/iterations` — iteration (sprint) definitions that resolve iteration IDs on issues (low)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gitlab/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gitlab/canonical_descriptions.py
index 2169009804a7..3c977212d857 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gitlab/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gitlab/canonical_descriptions.py
@@ -252,4 +252,71 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"created_at": "Time at which the state changed.",
},
},
+ "jobs": {
+ "description": "A CI/CD job run as part of a pipeline in the project.",
+ "docs_url": "https://docs.gitlab.com/api/jobs/",
+ "columns": {
+ "id": "Unique identifier for the job.",
+ "name": "Name of the job as defined in the CI/CD configuration.",
+ "stage": "Pipeline stage the job belongs to.",
+ "status": "Status of the job (for example created, running, success, failed, or canceled).",
+ "ref": "Branch or tag the job ran for.",
+ "tag": "Whether the job ran for a tag.",
+ "allow_failure": "Whether the pipeline can succeed when this job fails.",
+ "failure_reason": "Reason the job failed, if it failed.",
+ "pipeline": "The pipeline the job belongs to.",
+ "commit": "The commit the job ran for.",
+ "runner": "The runner that ran the job, if any.",
+ "user": "The user who started the job.",
+ "duration": "Time in seconds the job took to run.",
+ "queued_duration": "Time in seconds the job waited in the queue before it started.",
+ "coverage": "Code coverage percentage the job reported, if any.",
+ "artifacts": "Artifacts the job produced.",
+ "web_url": "URL of the job in the GitLab UI.",
+ "created_at": "Time at which the job was created.",
+ "started_at": "Time at which the job started, if it started.",
+ "finished_at": "Time at which the job finished, if it finished.",
+ "erased_at": "Time at which the job log and artifacts were erased, if they were erased.",
+ },
+ },
+ "environments": {
+ "description": "A deployment environment of the project, such as production or a review app.",
+ "docs_url": "https://docs.gitlab.com/api/environments/",
+ "columns": {
+ "id": "Unique identifier for the environment.",
+ "name": "Name of the environment.",
+ "slug": "URL-safe version of the environment name.",
+ "description": "Description of the environment.",
+ "external_url": "URL where the environment is reachable, if set.",
+ "state": "State of the environment (available, stopping, or stopped).",
+ "tier": "Deployment tier of the environment (for example production or staging).",
+ "auto_stop_at": "Time at which the environment stops automatically, if set.",
+ "created_at": "Time at which the environment was created.",
+ "updated_at": "Time at which the environment was last updated.",
+ },
+ },
+ "issue_label_events": {
+ "description": "A label added to or removed from an issue.",
+ "docs_url": "https://docs.gitlab.com/api/resource_label_events/",
+ "columns": {
+ "issue_iid": "Internal id of the issue whose labels changed, unique within its project.",
+ "id": "Unique identifier for the label event.",
+ "user": "The user who added or removed the label.",
+ "label": "The label that was added or removed. Empty when the label was deleted.",
+ "action": "Whether the label was added (add) or removed (remove).",
+ "resource_type": "Type of the object whose labels changed.",
+ "resource_id": "Identifier of the object whose labels changed.",
+ "created_at": "Time at which the label was added or removed.",
+ },
+ },
+ "merge_request_approvals": {
+ "description": "An approval given to a merge request by a user.",
+ "docs_url": "https://docs.gitlab.com/api/merge_request_approvals/",
+ "columns": {
+ "merge_request_iid": "Internal id of the approved merge request, unique within its project.",
+ "user_id": "Identifier of the user who approved the merge request.",
+ "user": "The user who approved the merge request.",
+ "approved_at": "Time at which the user approved the merge request.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gitlab/gitlab.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gitlab/gitlab.py
index 3e59d8754c7a..a8a8577a7672 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gitlab/gitlab.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gitlab/gitlab.py
@@ -157,7 +157,7 @@ def _build_initial_params(
db_incremental_field_last_value: Any,
incremental_field: str | None,
) -> dict[str, Any]:
- params: dict[str, Any] = {"per_page": config.page_size}
+ params: dict[str, Any] = {"per_page": config.page_size, **config.extra_params}
active_field = _active_incremental_field(
config, should_use_incremental_field, db_incremental_field_last_value, incremental_field
@@ -189,6 +189,18 @@ def _build_initial_url(
return f"{url}?{urlencode(params)}"
+def _shape_row(config: GitLabEndpointConfig, row: dict[str, Any]) -> dict[str, Any] | None:
+ """Lift a nested primary key onto the row; None when the row has no key and can't be merged."""
+ if config.primary_key_path is None:
+ return row
+ value: Any = row
+ for key in config.primary_key_path:
+ value = value.get(key) if isinstance(value, dict) else None
+ if value is None:
+ return None
+ return {**row, config.primary_key: value}
+
+
def _parse_next_url(link_header: str) -> str | None:
"""Return the URL with ``rel="next"`` from GitLab's ``Link`` header, if any."""
if not link_header:
@@ -409,7 +421,7 @@ def get_rows(
return response
def iter_pages(
- start_url: str, max_pages: int | None = None, allow_not_found: bool = False
+ start_url: str, max_pages: int | None = None, allow_not_found: bool = False, rows_key: str | None = None
) -> Iterator[tuple[str, list[Any]]]:
page_url = start_url
pages = 0
@@ -419,6 +431,8 @@ def get_rows(
logger.warning("GitLab: fan-out parent no longer exists, skipping it", endpoint=endpoint, url=page_url)
return
data = response.json()
+ if rows_key is not None:
+ data = data.get(rows_key) if isinstance(data, dict) else None
if not isinstance(data, list) or not data:
return
@@ -446,11 +460,14 @@ def get_rows(
page_url = next_url
if parent_config is None:
- for page_url, data in iter_pages(url):
+ for page_url, data in iter_pages(url, rows_key=config.rows_key):
# Page and chunk boundaries don't line up, so checkpoint the CURRENT page URL. On resume we
# re-fetch it and rely on primary-key merge semantics to dedupe already-yielded rows.
for item in data:
- batcher.batch(item)
+ row = _shape_row(config, item)
+ if row is None:
+ continue
+ batcher.batch(row)
if batcher.should_yield():
py_table = batcher.get_table()
@@ -467,9 +484,14 @@ def get_rows(
child_url = _build_initial_url(host, config, project, child_params, parent_iid=parent_iid)
# A parent deleted after the parent page was listed 404s; that must not fail the run
# with the non-retryable "project not found" error.
- for _, children in iter_pages(child_url, max_pages=MAX_PAGES_PER_PARENT, allow_not_found=True):
+ for _, children in iter_pages(
+ child_url, max_pages=MAX_PAGES_PER_PARENT, allow_not_found=True, rows_key=config.rows_key
+ ):
for child in children:
- batcher.batch({**child, config.fan_out_parent_column: parent_iid})
+ row = _shape_row(config, child)
+ if row is None:
+ continue
+ batcher.batch({**row, config.fan_out_parent_column: parent_iid})
if batcher.should_yield():
py_table = batcher.get_table()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gitlab/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gitlab/settings.py
index de07bb7e81bd..ce2f3545ad76 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gitlab/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gitlab/settings.py
@@ -40,6 +40,12 @@ class GitLabEndpointConfig:
# Column the parent's iid is injected into on every child row. Part of the primary key, since
# the child API has no project-wide uniqueness guarantee we can rely on.
fan_out_parent_column: Optional[str] = None
+ # Static query params sent on every request to this endpoint.
+ extra_params: dict[str, str] = field(default_factory=dict)
+ # When set, the endpoint returns one object and its rows sit in the list under this key.
+ rows_key: Optional[str] = None
+ # When set, primary_key is copied onto each row from this nested path (the API nests the id).
+ primary_key_path: Optional[tuple[str, ...]] = None
# Project-scoped endpoints. We cover the resources a user most commonly wants to analyze and that
@@ -126,6 +132,22 @@ GITLAB_ENDPOINTS: dict[str, GitLabEndpointConfig] = {
# Tag name is the unique key. created_at can be absent for some tags, so don't partition.
primary_key="name",
),
+ "jobs": GitLabEndpointConfig(
+ name="jobs",
+ path="/projects/{project}/jobs",
+ # No server-side timestamp filter -> full refresh only. GitLab recommends keyset pagination
+ # for this endpoint and only accepts it ordered by id descending.
+ extra_params={"pagination": "keyset"},
+ supports_order_by=True,
+ stable_order_by="id",
+ partition_key="created_at",
+ sort_mode="desc",
+ ),
+ "environments": GitLabEndpointConfig(
+ name="environments",
+ path="/projects/{project}/environments",
+ partition_key="created_at",
+ ),
"labels": GitLabEndpointConfig(
name="labels",
path="/projects/{project}/labels",
@@ -207,6 +229,35 @@ GITLAB_ENDPOINTS: dict[str, GitLabEndpointConfig] = {
fan_out_parent="merge_requests",
fan_out_parent_column="merge_request_iid",
),
+ "issue_label_events": GitLabEndpointConfig(
+ name="issue_label_events",
+ path="/projects/{project}/issues/{parent_iid}/resource_label_events",
+ incremental_fields=[
+ _datetime_incremental_field("created_at"),
+ ],
+ default_incremental_field="created_at",
+ partition_key="created_at",
+ sort_mode="desc",
+ fan_out_parent="issues",
+ fan_out_parent_column="issue_iid",
+ ),
+ # One row per approver. Approving adds a system note, which bumps the merge request's
+ # updated_at, so the incremental parent walk still finds new approvals. Revoked approvals
+ # only drop out on a full refresh.
+ "merge_request_approvals": GitLabEndpointConfig(
+ name="merge_request_approvals",
+ path="/projects/{project}/merge_requests/{parent_iid}/approvals",
+ incremental_fields=[
+ _datetime_incremental_field("approved_at"),
+ ],
+ default_incremental_field="approved_at",
+ primary_key="user_id",
+ primary_key_path=("user", "id"),
+ rows_key="approved_by",
+ sort_mode="desc",
+ fan_out_parent="merge_requests",
+ fan_out_parent_column="merge_request_iid",
+ ),
}
ENDPOINTS = tuple(GITLAB_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gitlab/tests/test_gitlab.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gitlab/tests/test_gitlab.py
index 2023cfe91816..847753796872 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gitlab/tests/test_gitlab.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gitlab/tests/test_gitlab.py
@@ -292,6 +292,9 @@ class TestGitLabSourceResponse:
("members", ["id"], None, "asc"),
("issue_notes", ["issue_iid", "id"], "created_at", "desc"),
("merge_request_state_events", ["merge_request_iid", "id"], "created_at", "desc"),
+ ("issue_label_events", ["issue_iid", "id"], "created_at", "desc"),
+ ("merge_request_approvals", ["merge_request_iid", "user_id"], None, "desc"),
+ ("jobs", ["id"], "created_at", "desc"),
],
)
def test_response_shape(self, endpoint, primary_keys, partition_key, sort_mode):
@@ -374,6 +377,73 @@ class TestGetRows:
assert saved.next_url == urls[0]
assert result.committed_states == [saved]
+ def test_jobs_walk_keyset_pages_newest_first(self):
+ next_url = (
+ "https://gitlab.com/api/v4/projects/group%2Fproject/jobs"
+ "?pagination=keyset&per_page=100&order_by=id&sort=desc&id_before=11"
+ )
+ page1 = ScriptedResponse(json=[{"id": 12}, {"id": 11}], headers={"Link": f'<{next_url}>; rel="next"'})
+ page2 = ScriptedResponse(json=[{"id": 10}])
+ result = _driver().run("jobs", [page1, page2])
+
+ assert result.raised is None
+ assert result.urls == [
+ "https://gitlab.com/api/v4/projects/group%2Fproject/jobs"
+ "?per_page=100&pagination=keyset&order_by=id&sort=desc",
+ next_url,
+ ]
+ assert [row["id"] for row in _rows(result)] == [12, 11, 10]
+
+ @pytest.mark.parametrize(
+ "body, expected",
+ [
+ pytest.param(
+ {
+ "id": 500,
+ "iid": 7,
+ "approved": True,
+ "approved_by": [
+ {"user": {"id": 3, "username": "ana"}, "approved_at": "2024-02-01T10:00:00.000Z"},
+ {"user": {"id": 4, "username": "ben"}, "approved_at": "2024-02-02T10:00:00.000Z"},
+ ],
+ },
+ [(7, 3, "2024-02-01T10:00:00.000Z"), (7, 4, "2024-02-02T10:00:00.000Z")],
+ id="enterprise_edition_response",
+ ),
+ pytest.param(
+ {"approved": True, "approved_by": [{"user": {"id": 5}, "approved_at": "2024-03-01T00:00:00.000Z"}]},
+ [(7, 5, "2024-03-01T00:00:00.000Z")],
+ id="community_edition_response",
+ ),
+ pytest.param({"approved": False, "approved_by": []}, [], id="no_approvals"),
+ pytest.param({"approved": False}, [], id="approved_by_missing"),
+ pytest.param(
+ {"approved_by": [{"user": None, "approved_at": "2024-03-01T00:00:00.000Z"}]},
+ [],
+ id="approver_without_user_is_skipped",
+ ),
+ ],
+ )
+ def test_merge_request_approvals_flatten_to_one_row_per_approver(self, body, expected):
+ parents = ScriptedResponse(json=[{"iid": 7}, {"iid": 8}])
+ result = _driver().run(
+ "merge_request_approvals",
+ [parents, ScriptedResponse(json=body), ScriptedResponse(status=404)],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2024, 1, 1, tzinfo=UTC),
+ incremental_field="approved_at",
+ )
+
+ assert result.raised is None
+ assert result.urls[0] == (
+ "https://gitlab.com/api/v4/projects/group%2Fproject/merge_requests"
+ "?per_page=100&updated_after=2024-01-01T00%3A00%3A00Z&order_by=updated_at&sort=asc"
+ )
+ assert result.paths[1] == "/api/v4/projects/group%2Fproject/merge_requests/7/approvals"
+ rows = _rows(result)
+ assert [(row["merge_request_iid"], row["user_id"], row["approved_at"]) for row in rows] == expected
+ assert all("approved" not in row for row in rows)
+
def test_fan_out_stops_child_pagination_at_page_cap(self):
parents = ScriptedResponse(json=[{"iid": 1}])
child_page = ScriptedResponse(