: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): add gitlab deployments, notes, and state event tables (#109936)
Tom Owersa64442538bd4
diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txtindex 3ae8ab013373..7a38f56bc273 100644--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt@@ -614,8 +614,6 @@1 products/warehouse_sources/backend/temporal/data_imports/sources/gitguardian/settings.py1 products/warehouse_sources/backend/temporal/data_imports/sources/github/github.py1 products/warehouse_sources/backend/temporal/data_imports/sources/github/settings.py-1 products/warehouse_sources/backend/temporal/data_imports/sources/gitlab/gitlab.py-1 products/warehouse_sources/backend/temporal/data_imports/sources/gitlab/settings.py1 products/warehouse_sources/backend/temporal/data_imports/sources/gladly/gladly.py1 products/warehouse_sources/backend/temporal/data_imports/sources/gladly/settings.py1 products/warehouse_sources/backend/temporal/data_imports/sources/glassfrog/settings.pydiff --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.mdindex ec85598c389c..9a8dc2b063f5 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@@ -3619,15 +3619,15 @@ Note: Fetched the live 5 MB OpenAPI document from the vendor's own /v1/openapi.j## GitLab — **thin**-Today (10): `branches`, `commits`, `issues`, `labels`, `members`, `merge_requests`, `milestones`, `pipelines`, `releases`, `tags`+Today (15): `branches`, `commits`, `deployments`, `issue_notes`, `issue_state_events`, `issues`, `labels`, `members`, `merge_request_notes`, `merge_request_state_events`, `merge_requests`, `milestones`, `pipelines`, `releases`, `tags`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)-- [ ] `/projects/{id}/issues/{iid}/notes and /projects/{id}/merge_requests/{iid}/notes` — issue and merge-request comments, the main collaboration signal (high)-- [ ] `/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)-- [ ] `/projects/{id}/dora/metrics` — GitLab's headline DevOps metric (deployment frequency, lead time, change failure rate, MTTR) (high)-- [ ] `/projects/{id}/deployments` — deployment records joining pipelines to environments, the basis of release analytics (high)+- [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)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.pyindex afd9eaf3f307..2169009804a7 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@@ -166,4 +166,90 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"expires_at": "Date the member's access expires, if set.",},},+ "deployments": {+ "description": "A deployment of a commit to an environment in the project.",+ "docs_url": "https://docs.gitlab.com/api/deployments/",+ "columns": {+ "id": "Globally unique identifier for the deployment.",+ "iid": "Internal id of the deployment, unique within its project.",+ "ref": "The branch or tag that was deployed.",+ "sha": "SHA of the commit that was deployed.",+ "status": "Status of the deployment (created, running, success, failed, canceled, or blocked).",+ "environment": "The environment the deployment targets.",+ "deployable": "The CI/CD job that ran the deployment, including its pipeline and commit.",+ "user": "The user who triggered the deployment.",+ "created_at": "Time at which the deployment was created.",+ "updated_at": "Time at which the deployment was last updated.",+ },+ },+ "issue_notes": {+ "description": "A comment or system note on an issue in the project.",+ "docs_url": "https://docs.gitlab.com/api/notes/",+ "columns": {+ "issue_iid": "Internal id of the issue the note belongs to, unique within its project.",+ "id": "Globally unique identifier for the note.",+ "body": "The note's content in markdown.",+ "author": "The user who wrote the note.",+ "system": "Whether GitLab generated the note to record an activity (for example, a label change) rather than a person writing it.",+ "internal": "Whether the note is internal and visible only to project members with at least the Reporter role.",+ "confidential": "Whether the note is confidential. Superseded by internal.",+ "resolvable": "Whether the note starts a thread that can be resolved.",+ "noteable_id": "Globally unique identifier of the object the note is attached to.",+ "noteable_iid": "Internal id of the object the note is attached to, unique within its project.",+ "noteable_type": "Type of the object the note is attached to.",+ "project_id": "Identifier of the project the note belongs to.",+ "created_at": "Time at which the note was created.",+ "updated_at": "Time at which the note was last updated.",+ },+ },+ "merge_request_notes": {+ "description": "A comment or system note on a merge request in the project.",+ "docs_url": "https://docs.gitlab.com/api/notes/",+ "columns": {+ "merge_request_iid": "Internal id of the merge request the note belongs to, unique within its project.",+ "id": "Globally unique identifier for the note.",+ "body": "The note's content in markdown.",+ "author": "The user who wrote the note.",+ "system": "Whether GitLab generated the note to record an activity (for example, a label change) rather than a person writing it.",+ "internal": "Whether the note is internal and visible only to project members with at least the Reporter role.",+ "confidential": "Whether the note is confidential. Superseded by internal.",+ "resolvable": "Whether the note starts a thread that can be resolved.",+ "noteable_id": "Globally unique identifier of the object the note is attached to.",+ "noteable_iid": "Internal id of the object the note is attached to, unique within its project.",+ "noteable_type": "Type of the object the note is attached to.",+ "project_id": "Identifier of the project the note belongs to.",+ "created_at": "Time at which the note was created.",+ "updated_at": "Time at which the note was last updated.",+ },+ },+ "issue_state_events": {+ "description": "A change to an issue's state, such as closing or reopening it.",+ "docs_url": "https://docs.gitlab.com/api/resource_state_events/",+ "columns": {+ "issue_iid": "Internal id of the issue whose state changed, unique within its project.",+ "id": "Unique identifier for the state event.",+ "user": "The user who changed the state.",+ "state": "The state the issue moved to (for example opened, closed, or reopened).",+ "resource_type": "Type of the object whose state changed.",+ "resource_id": "Identifier of the object whose state changed.",+ "source_commit": "Commit that closed the issue, if a commit closed it.",+ "source_merge_request_id": "Merge request that closed the issue, if a merge request closed it.",+ "created_at": "Time at which the state changed.",+ },+ },+ "merge_request_state_events": {+ "description": "A change to a merge request's state, such as closing, reopening, or merging it.",+ "docs_url": "https://docs.gitlab.com/api/resource_state_events/",+ "columns": {+ "merge_request_iid": "Internal id of the merge request whose state changed, unique within its project.",+ "id": "Unique identifier for the state event.",+ "user": "The user who changed the state.",+ "state": "The state the merge request moved to (for example opened, closed, or reopened).",+ "resource_type": "Type of the object whose state changed.",+ "resource_id": "Identifier of the object whose state changed.",+ "source_commit": "Commit that closed the merge request, if a commit closed it.",+ "source_merge_request_id": "Merge request that closed the merge request, if a merge request closed it.",+ "created_at": "Time at which the state changed.",+ },+ },}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.pyindex 6027efd9d0ea..3e59d8754c7a 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@@ -1,4 +1,5 @@import re+import timeimport dataclassesfrom collections.abc import Iteratorfrom datetime import UTC, date, datetime@@ -22,6 +23,12 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.gitlab.setREQUEST_TIMEOUT_SECONDS = 60MAX_RETRIES = 5MAX_RETRY_AFTER_SECONDS = 60+# Bounds a runaway child pagination (a bot-spammed issue) in a fan-out. 100 pages = 10k rows per parent.+# Children page newest-first, so the cap drops the oldest tail and new rows still arrive every sync.+MAX_PAGES_PER_PARENT = 100+# In a fan-out, a partly filled chunk is yielded at a parent boundary once this long has passed since+# the last yield, so the batcher empties and sparse runs still reach safe points.+PARTIAL_FLUSH_INTERVAL_SECONDS = 60.0DEFAULT_HOST = "https://gitlab.com"HOST_NOT_ALLOWED_ERROR = "GitLab host is not allowed"@@ -48,7 +55,7 @@ class GitLabHostNotAllowedError(Exception):pass[email protected](frozen=True)class GitLabResumeConfig:next_url: str@@ -168,8 +175,14 @@ def _build_initial_params(return params-def _build_initial_url(host: str | None, config: GitLabEndpointConfig, project: str, params: dict[str, Any]) -> str:- path = config.path.format(project=_encode_project(project))+def _build_initial_url(+ host: str | None,+ config: GitLabEndpointConfig,+ project: str,+ params: dict[str, Any],+ parent_iid: Any = None,+) -> str:+ path = config.path.format(project=_encode_project(project), parent_iid=quote(str(parent_iid), safe=""))url = f"{_base_url(host)}{path}"if not params:return url@@ -335,10 +348,22 @@ def get_rows(# fails fast instead of retrying an SSRF/host failure (_is_host_safe returns its own message).raise GitLabHostNotAllowedError(f"{HOST_NOT_ALLOWED_ERROR}: {host_err}" if host_err else HOST_NOT_ALLOWED_ERROR)- params = _build_initial_params(- config, should_use_incremental_field, db_incremental_field_last_value, incremental_field- )- initial_url = _build_initial_url(host, config, project, params)+ # A fan-out child walks its parent list, bounded by the parent's own cursor (updated_after)+ # compared against the child watermark; see the fan-out comment in settings.py.+ parent_config = GITLAB_ENDPOINTS[config.fan_out_parent] if config.fan_out_parent else None+ if parent_config is not None:+ params = _build_initial_params(+ parent_config,+ should_use_incremental_field,+ db_incremental_field_last_value,+ parent_config.default_incremental_field,+ )+ initial_url = _build_initial_url(host, parent_config, project, params)+ else:+ params = _build_initial_params(+ config, should_use_incremental_field, db_incremental_field_last_value, incremental_field+ )+ initial_url = _build_initial_url(host, config, project, params)resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else Noneif resume_config is not None and _is_same_host(resume_config.next_url, host):@@ -355,7 +380,7 @@ def get_rows(wait=_retry_wait,reraise=True,)- def fetch_page(page_url: str) -> requests.Response:+ def fetch_page(page_url: str, allow_not_found: bool = False) -> requests.Response | None:# Don't follow redirects: an attacker-controlled host could 3xx to an internal address (SSRF).response = make_tracked_session().get(page_url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS, allow_redirects=False@@ -374,42 +399,93 @@ def get_rows(f"(status={response.status_code}); refusing to follow it")+ if allow_not_found and response.status_code == 404:+ return None+if not response.ok:logger.error(f"GitLab API error: status={response.status_code}, body={response.text}, url={page_url}")response.raise_for_status()return response- while True:- response = fetch_page(url)-- data = response.json()- if not isinstance(data, list) or not data:- break-- next_url = _parse_next_url(response.headers.get("Link", ""))-- # 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.- checkpoint_url = url-- for item in data:- batcher.batch(item)-- if batcher.should_yield():- py_table = batcher.get_table()- yield py_table- resumable_source_manager.save_state(GitLabResumeConfig(next_url=checkpoint_url))-- if not next_url:- break-- # The next-page URL is server-controlled; only follow it if it stays on the configured host.- if not _is_same_host(next_url, host):- logger.warning("GitLab: stopping pagination, next URL host does not match the configured host")- break-- url = next_url+ def iter_pages(+ start_url: str, max_pages: int | None = None, allow_not_found: bool = False+ ) -> Iterator[tuple[str, list[Any]]]:+ page_url = start_url+ pages = 0+ while True:+ response = fetch_page(page_url, allow_not_found=allow_not_found)+ if response is None:+ logger.warning("GitLab: fan-out parent no longer exists, skipping it", endpoint=endpoint, url=page_url)+ return+ data = response.json()+ if not isinstance(data, list) or not data:+ return++ yield page_url, data+ pages += 1++ next_url = _parse_next_url(response.headers.get("Link", ""))+ if not next_url:+ return++ # The next-page URL is server-controlled; only follow it if it stays on the configured host.+ if not _is_same_host(next_url, host):+ logger.warning("GitLab: stopping pagination, next URL host does not match the configured host")+ return++ if max_pages is not None and pages >= max_pages:+ logger.warning(+ "GitLab: page cap reached for fan-out parent, remaining child pages skipped",+ endpoint=endpoint,+ url=page_url,+ max_pages=max_pages,+ )+ return++ page_url = next_url++ if parent_config is None:+ for page_url, data in iter_pages(url):+ # 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)++ if batcher.should_yield():+ py_table = batcher.get_table()+ yield py_table+ resumable_source_manager.save_state(GitLabResumeConfig(next_url=page_url))+ else:+ assert config.fan_out_parent_column is not None+ child_params = _build_initial_params(config, False, None, None)+ last_flush_at = time.monotonic()+ # Checkpoint the parent page: resuming re-fans its parents, and merge dedupes their children.+ for parent_page_url, parents in iter_pages(url):+ for parent in parents:+ parent_iid = parent["iid"]+ 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 child in children:+ batcher.batch({**child, config.fan_out_parent_column: parent_iid})++ if batcher.should_yield():+ py_table = batcher.get_table()+ yield py_table+ last_flush_at = time.monotonic()+ resumable_source_manager.save_state(GitLabResumeConfig(next_url=parent_page_url))++ # Most parents have no state events, so a run can make many requests that yield nothing.+ if batcher.should_yield(include_incomplete_chunk=True):+ if time.monotonic() - last_flush_at >= PARTIAL_FLUSH_INTERVAL_SECONDS:+ # Staged before the yield, so the commit that follows this table's write covers it.+ resumable_source_manager.save_state(GitLabResumeConfig(next_url=parent_page_url))+ yield batcher.get_table()+ last_flush_at = time.monotonic()+ else:+ resumable_source_manager.safe_point()if batcher.should_yield(include_incomplete_chunk=True):py_table = batcher.get_table()@@ -444,7 +520,9 @@ def gitlab_source(db_incremental_field_last_value=db_incremental_field_last_value,incremental_field=incremental_field,),- primary_keys=[endpoint_config.primary_key],+ primary_keys=[endpoint_config.fan_out_parent_column, endpoint_config.primary_key]+ if endpoint_config.fan_out_parent_column+ else [endpoint_config.primary_key],sort_mode=endpoint_config.sort_mode,partition_count=1,partition_size=1,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.pyindex e0b379309323..de07bb7e81bd 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@@ -13,7 +13,7 @@ def _datetime_incremental_field(name: str) -> IncrementalField:}-@dataclass+@dataclass(frozen=True)class GitLabEndpointConfig:name: strpath: str # Path template with a {project} placeholder (project id or URL-encoded path)@@ -34,6 +34,12 @@ class GitLabEndpointConfig:# The order rows are emitted in. Endpoints we sort ascending stay "asc"; commits cannot be# sorted server-side and always come newest-first, so they are "desc".sort_mode: Literal["asc", "desc"] = "asc"+ # Fan-out: name of the parent endpoint (issues / merge_requests) whose rows seed this child's+ # path. The child path carries a {parent_iid} placeholder filled from the parent's `iid`.+ fan_out_parent: Optional[str] = None+ # 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# Project-scoped endpoints. We cover the resources a user most commonly wants to analyze and that@@ -128,6 +134,79 @@ GITLAB_ENDPOINTS: dict[str, GitLabEndpointConfig] = {name="members",path="/projects/{project}/members/all",),+ "deployments": GitLabEndpointConfig(+ name="deployments",+ path="/projects/{project}/deployments",+ incremental_fields=[+ _datetime_incremental_field("updated_at"),+ ],+ default_incremental_field="updated_at",+ # GitLab rejects an updated_after filter unless the list is also ordered by updated_at,+ # which _build_initial_params does for the active incremental field.+ incremental_filter_params={"updated_at": "updated_after"},+ supports_order_by=True,+ stable_order_by="created_at",+ partition_key="created_at",+ ),+ # The fan-out children have no server-side time filter of their own. An incremental sync+ # instead bounds the parent walk with updated_after on the child watermark: creating a note or+ # a state event bumps the parent's updated_at, so only parents bumped since then are re-fanned.+ # Rows arrive grouped by parent rather than by created_at, hence "desc" (the watermark only+ # advances once the run completes). GitLab skips the parent touch for cross-reference system+ # notes ("mentioned in !12"), so an incremental sync picks those up only once the parent is next+ # updated; a full refresh collects them all.+ "issue_notes": GitLabEndpointConfig(+ name="issue_notes",+ path="/projects/{project}/issues/{parent_iid}/notes",+ incremental_fields=[+ _datetime_incremental_field("created_at"),+ ],+ default_incremental_field="created_at",+ supports_order_by=True,+ stable_order_by="created_at",+ partition_key="created_at",+ sort_mode="desc",+ fan_out_parent="issues",+ fan_out_parent_column="issue_iid",+ ),+ "merge_request_notes": GitLabEndpointConfig(+ name="merge_request_notes",+ path="/projects/{project}/merge_requests/{parent_iid}/notes",+ incremental_fields=[+ _datetime_incremental_field("created_at"),+ ],+ default_incremental_field="created_at",+ supports_order_by=True,+ stable_order_by="created_at",+ partition_key="created_at",+ sort_mode="desc",+ fan_out_parent="merge_requests",+ fan_out_parent_column="merge_request_iid",+ ),+ "issue_state_events": GitLabEndpointConfig(+ name="issue_state_events",+ path="/projects/{project}/issues/{parent_iid}/resource_state_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",+ ),+ "merge_request_state_events": GitLabEndpointConfig(+ name="merge_request_state_events",+ path="/projects/{project}/merge_requests/{parent_iid}/resource_state_events",+ incremental_fields=[+ _datetime_incremental_field("created_at"),+ ],+ default_incremental_field="created_at",+ partition_key="created_at",+ 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/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gitlab/source.pyindex 9a904e64ebcc..48037d86d3e8 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gitlab/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gitlab/source.py@@ -25,6 +25,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.gitlab.git)from products.warehouse_sources.backend.temporal.data_imports.sources.gitlab.settings import (ENDPOINTS,+ GITLAB_ENDPOINTS,INCREMENTAL_FIELDS,)from products.warehouse_sources.backend.types import ExternalDataSourceType@@ -127,7 +128,10 @@ For self-managed GitLab, set the instance URL (for example `https://gitlab.exampSourceSchema(name=endpoint,supports_incremental=bool(INCREMENTAL_FIELDS.get(endpoint)),- supports_append=bool(INCREMENTAL_FIELDS.get(endpoint)),+ # An incremental fan-out re-emits every child of a re-fanned parent, which append+ # would duplicate; merge dedupes them on the primary key.+ supports_append=bool(INCREMENTAL_FIELDS.get(endpoint))+ and GITLAB_ENDPOINTS[endpoint].fan_out_parent is None,incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),)for endpoint in ENDPOINTSdiff --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.pyindex 292e50dfdb59..b51904ea0291 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@@ -174,9 +174,10 @@ class TestBuildInitialParams:assert "order_by" not in paramsassert "sort" not in params- def test_pipelines_incremental_uses_updated_after(self):+ @pytest.mark.parametrize("endpoint", ["pipelines", "deployments"])+ def test_updated_after_is_paired_with_updated_at_order(self, endpoint):params = _build_initial_params(- GITLAB_ENDPOINTS["pipelines"],+ GITLAB_ENDPOINTS[endpoint],should_use_incremental_field=True,db_incremental_field_last_value=datetime(2024, 1, 1, tzinfo=UTC),incremental_field="updated_at",@@ -368,21 +369,23 @@ class TestValidateCredentials:class TestGitLabSourceResponse:@pytest.mark.parametrize(- "endpoint, primary_key, partition_key, sort_mode",+ "endpoint, primary_keys, partition_key, sort_mode",[- ("issues", "id", "created_at", "asc"),- ("merge_requests", "id", "created_at", "asc"),- ("commits", "id", "created_at", "desc"),- ("pipelines", "id", "created_at", "asc"),- ("releases", "tag_name", "created_at", "asc"),- ("milestones", "id", "created_at", "asc"),- ("branches", "name", None, "asc"),- ("tags", "name", None, "asc"),- ("labels", "id", None, "asc"),- ("members", "id", None, "asc"),+ ("issues", ["id"], "created_at", "asc"),+ ("merge_requests", ["id"], "created_at", "asc"),+ ("commits", ["id"], "created_at", "desc"),+ ("pipelines", ["id"], "created_at", "asc"),+ ("releases", ["tag_name"], "created_at", "asc"),+ ("milestones", ["id"], "created_at", "asc"),+ ("branches", ["name"], None, "asc"),+ ("tags", ["name"], None, "asc"),+ ("labels", ["id"], None, "asc"),+ ("members", ["id"], None, "asc"),+ ("issue_notes", ["issue_iid", "id"], "created_at", "desc"),+ ("merge_request_state_events", ["merge_request_iid", "id"], "created_at", "desc"),],)- def test_response_shape(self, endpoint, primary_key, partition_key, sort_mode):+ def test_response_shape(self, endpoint, primary_keys, partition_key, sort_mode):response = gitlab_source(host="https://gitlab.com",personal_access_token="tok",@@ -393,7 +396,7 @@ class TestGitLabSourceResponse:team_id=1,)assert response.name == endpoint- assert response.primary_keys == [primary_key]+ assert response.primary_keys == primary_keysassert response.sort_mode == sort_modeif partition_key:assert response.partition_keys == [partition_key]@@ -404,7 +407,7 @@ class TestGitLabSourceResponse:class TestGetRows:- def _run(self, manager, responses, endpoint="issues"):+ def _run(self, manager, responses, endpoint="issues", **kwargs):session = mock.MagicMock()session.get.side_effect = responseswith (@@ -420,6 +423,7 @@ class TestGetRows:logger=mock.MagicMock(),resumable_source_manager=manager,team_id=1,+ **kwargs,):rows.extend(table)return rows, session@@ -459,6 +463,75 @@ class TestGetRows:assert first_url == "https://gitlab.com/api/v4/projects/1/issues?page=5"assert [r["id"] for r in rows] == [9]+ def test_fan_out_bounds_parent_walk_and_tags_children_with_parent_iid(self):+ manager = mock.MagicMock()+ manager.can_resume.return_value = False+ parents = _response(json_data=[{"iid": 7}, {"iid": 8}, {"iid": 9}])+ notes_7 = _response(json_data=[{"id": 70}])+ deleted_parent = _response(status_code=404)+ notes_9 = _response(json_data=[{"id": 90}, {"id": 91}])+ rows, session = self._run(+ manager,+ [parents, notes_7, deleted_parent, notes_9],+ endpoint="issue_notes",+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2024, 1, 1, tzinfo=UTC),+ incremental_field="created_at",+ )++ urls = [call.args[0] for call in session.get.call_args_list]+ assert urls[0] == (+ "https://gitlab.com/api/v4/projects/group%2Fproject/issues"+ "?per_page=100&updated_after=2024-01-01T00%3A00%3A00Z&order_by=updated_at&sort=asc"+ )+ assert urls[1].startswith("https://gitlab.com/api/v4/projects/group%2Fproject/issues/7/notes?")+ assert urls[3].startswith("https://gitlab.com/api/v4/projects/group%2Fproject/issues/9/notes?")+ assert [(r["issue_iid"], r["id"]) for r in rows] == [(7, 70), (9, 90), (9, 91)]+ saved = manager.save_state.call_args.args[0]+ assert saved.next_url == urls[0]++ def test_fan_out_stops_child_pagination_at_page_cap(self):+ manager = mock.MagicMock()+ manager.can_resume.return_value = False+ parents = _response(json_data=[{"iid": 1}])+ child_page = _response(+ json_data=[{"id": 1}],+ link='<https://gitlab.com/api/v4/projects/1/issues/1/notes?page=2>; rel="next"',+ )+ with mock.patch.object(gitlab_module, "MAX_PAGES_PER_PARENT", 2):+ _rows, session = self._run(manager, [parents, child_page, child_page], endpoint="issue_notes")++ assert session.get.call_count == 3++ def test_fan_out_flushes_sparse_rows_so_later_empty_parents_reach_a_safe_point(self):+ manager = mock.MagicMock()+ manager.can_resume.return_value = False+ parents = _response(json_data=[{"iid": 1}, {"iid": 2}, {"iid": 3}])+ responses = [parents, _response(json_data=[{"id": 10}]), _response(json_data=[]), _response(json_data=[])]+ session = mock.MagicMock()+ session.get.side_effect = responses+ batcher = gitlab_module.Batcher(logger=mock.MagicMock(), chunk_size=2000)+ with (+ mock.patch.object(gitlab_module, "make_tracked_session", return_value=session),+ mock.patch.object(gitlab_module, "Batcher", return_value=batcher),+ mock.patch.object(gitlab_module, "PARTIAL_FLUSH_INTERVAL_SECONDS", 0.0),+ ):+ tables = list(+ get_rows(+ host="https://gitlab.com",+ personal_access_token="tok",+ project="group/project",+ endpoint="issue_state_events",+ logger=mock.MagicMock(),+ resumable_source_manager=manager,+ team_id=1,+ )+ )++ assert [table.num_rows for table in tables] == [1]+ assert manager.save_state.call_args.args[0].next_url == session.get.call_args_list[0].args[0]+ assert manager.safe_point.call_count == 2+def test_empty_page_terminates(self):manager = mock.MagicMock()manager.can_resume.return_value = Falsediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gitlab/tests/test_gitlab_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gitlab/tests/test_gitlab_source.pyindex ad9425a894af..7319d10d5003 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gitlab/tests/test_gitlab_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gitlab/tests/test_gitlab_source.py@@ -32,24 +32,27 @@ class TestGitLabSource:assert {s.name for s in schemas} == set(ENDPOINTS)@pytest.mark.parametrize(- "endpoint, incremental",+ "endpoint, incremental, append",[- ("issues", True),- ("merge_requests", True),- ("commits", True),- ("pipelines", True),- ("releases", False),- ("milestones", False),- ("branches", False),- ("tags", False),- ("labels", False),- ("members", False),+ ("issues", True, True),+ ("merge_requests", True, True),+ ("commits", True, True),+ ("pipelines", True, True),+ ("deployments", True, True),+ ("releases", False, False),+ ("milestones", False, False),+ ("branches", False, False),+ ("tags", False, False),+ ("labels", False, False),+ ("members", False, False),+ ("issue_notes", True, False),+ ("merge_request_state_events", True, False),],)- def test_schema_incremental_support(self, endpoint, incremental):+ def test_schema_incremental_support(self, endpoint, incremental, append):schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}assert schemas[endpoint].supports_incremental is incremental- assert schemas[endpoint].supports_append is incremental+ assert schemas[endpoint].supports_append is appenddef test_get_schemas_filtered_by_names(self):schemas = self.source.get_schemas(self.config, self.team_id, names=["issues"])