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 gerrit comments, files, branches and group members tables (#109112)

Tom Owers52f7b0f6c661
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 46f9dc3a0427..c7c82dc2268f 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
@@ -3522,14 +3522,14 @@ Note: Fetched the Swagger 2.0 spec behind the Apiary docs (api.aptrinsic.com). P
## Gerrit — gaps
-Today (4): `accounts`, `changes`, `groups`, `projects`
+Today (8): `accounts`, `change_comments`, `change_files`, `changes`, `group_members`, `groups`, `project_branches`, `projects`
Diffed against: <https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html>
-- [ ] `changes/{change-id}/comments` — inline review comments per change — the core code-review signal, not covered by the MESSAGES option (high)
-- [ ] `groups/{group-id}/members` — join table resolving accounts to the groups we already sync (high)
-- [ ] `changes/{change-id}/revisions/{revision-id}/files` — per-file insertions/deletions for code churn and review-size analysis (high)
-- [ ] `projects/{project-name}/branches` — lookup resolving the branch string carried on every change (medium)
+- [x] `changes/{change-id}/comments` — inline review comments per change — the core code-review signal, not covered by the MESSAGES option (high)
+- [x] `groups/{group-id}/members` — join table resolving accounts to the groups we already sync (high)
+- [x] `changes/{change-id}/revisions/{revision-id}/files` — per-file insertions/deletions for code churn and review-size analysis (high)
+- [x] `projects/{project-name}/branches` — lookup resolving the branch string carried on every change (medium)
- [ ] `changes/{change-id}/reviewers` — explicit reviewer and CC list per change, including reviewers who never voted (medium)
- [ ] `projects/{project-name}/labels` — label definitions that resolve the label names appearing in change votes (medium)
- [ ] `projects/{project-name}/tags` — release tags per project for cut-to-ship analysis (medium)
@@ -3537,7 +3537,7 @@ Diffed against: <https://gerrit-review.googlesource.com/Documentation/rest-api-c
- [ ] `groups/{group-id}/groups` — included subgroups, needed to expand nested group membership (low)
- [ ] `groups/{group-id}/log.audit` — membership change history over time (low)
-Note: Not dynamic — settings.py hardcodes 4 endpoints. The changes stream requests o=MESSAGES/DETAILED_LABELS/CURRENT_REVISION/DETAILED_ACCOUNTS, so review messages and label votes already ride inside the change row; inline comments and per-file stats do not. Also checked rest-api-projects.html, rest-api-accounts.html, rest-api-groups.html.
+Note: Not dynamic — settings.py hardcodes 8 endpoints. The changes stream requests o=MESSAGES/DETAILED_LABELS/CURRENT_REVISION/DETAILED_ACCOUNTS, so review messages and label votes already ride inside the change row; inline comments come from change_comments and current-revision per-file stats from change_files. Also checked rest-api-projects.html, rest-api-accounts.html, rest-api-groups.html.
## Giphy — gaps
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gerrit/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gerrit/canonical_descriptions.py
index ee2015280da3..68962843ba4b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gerrit/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gerrit/canonical_descriptions.py
@@ -78,4 +78,71 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"options": "Options of the group, e.g. whether the group is visible to all registered users.",
},
},
+ "group_members": {
+ "description": "The direct members of each internal account group, one row per group and account. External groups (such as LDAP or system groups) have no member list.",
+ "docs_url": "https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html#group-members",
+ "columns": {
+ "group_uuid": "The URL-encoded UUID of the group. Joins to groups.id.",
+ "_account_id": "The numeric ID of the member account. Joins to accounts._account_id.",
+ "name": "The full name of the member.",
+ "display_name": "The display name of the member.",
+ "email": "The preferred email address of the member.",
+ "username": "The username of the member.",
+ "avatars": "List of avatars of the member in various sizes.",
+ },
+ },
+ "project_branches": {
+ "description": "The branches of each project, including HEAD and refs/meta/config.",
+ "docs_url": "https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#branch-info",
+ "columns": {
+ "project": "The name of the project. Joins to projects.name.",
+ "ref": "The full ref of the branch (e.g. refs/heads/main).",
+ "revision": "The commit the branch points to. For HEAD, the name of the branch it points to.",
+ "can_delete": "Whether the calling user can delete the branch.",
+ "web_links": "Links to the branch in external sites (e.g. a Gitiles browser).",
+ },
+ },
+ "change_comments": {
+ "description": "Published inline and file-level review comments on each change, across all patch sets.",
+ "docs_url": "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#comment-info",
+ "columns": {
+ "_change_number": "The number of the change the row belongs to. Joins to changes._number.",
+ "project": "The name of the project the change belongs to.",
+ "change_updated": "The timestamp of when the change was last updated (UTC). Used as the incremental sync cursor.",
+ "change_created": "The timestamp of when the change was created (UTC).",
+ "id": "The URL-encoded UUID of the comment.",
+ "path": "The file path the comment is on. /COMMIT_MSG and /PATCHSET_LEVEL mark commit message and patch set level comments.",
+ "patch_set": "The patch set number the comment is on.",
+ "commit_id": "The commit ID of the patch set the comment is on.",
+ "side": "The side of the diff the comment is on (REVISION or PARENT). Not set means REVISION.",
+ "line": "The line number the comment is on. Not set for file-level comments.",
+ "range": "The range of the comment as a start and end line and character.",
+ "in_reply_to": "The ID of the comment this comment replies to.",
+ "message": "The text of the comment.",
+ "updated": "The timestamp of when the comment was written (UTC).",
+ "author": "The author of the comment as an account.",
+ "unresolved": "Whether the comment thread is unresolved.",
+ "change_message_id": "The ID of the change message the comment was published with.",
+ },
+ },
+ "change_files": {
+ "description": "The files modified by the current patch set of each change, with per-file line counts.",
+ "docs_url": "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#file-info",
+ "columns": {
+ "_change_number": "The number of the change the row belongs to. Joins to changes._number.",
+ "project": "The name of the project the change belongs to.",
+ "change_updated": "The timestamp of when the change was last updated (UTC). Used as the incremental sync cursor.",
+ "change_created": "The timestamp of when the change was created (UTC).",
+ "revision": "The commit ID of the patch set the files belong to. Rows for older patch sets stay after a new patch set is uploaded, so match it to changes.current_revision for the latest.",
+ "_revision_number": "The patch set number of the revision.",
+ "path": "The path of the file.",
+ "status": "The status of the file (A = added, D = deleted, R = renamed, C = copied, W = rewritten). Not set means modified.",
+ "binary": "Whether the file is binary.",
+ "old_path": "The old path of a renamed or copied file.",
+ "lines_inserted": "Number of inserted lines. Not set for binary files or when no lines were inserted.",
+ "lines_deleted": "Number of deleted lines. Not set for binary files or when no lines were deleted.",
+ "size_delta": "Number of bytes by which the file size increased or decreased.",
+ "size": "File size in bytes.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gerrit/gerrit.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gerrit/gerrit.py
index eb416c14622b..6117e73fd61d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gerrit/gerrit.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gerrit/gerrit.py
@@ -3,10 +3,10 @@ import json
import socket
import threading
import dataclasses
-from collections.abc import Iterator
+from collections.abc import Callable, Iterator
from datetime import UTC, date, datetime
from typing import Any, Optional
-from urllib.parse import urlencode, urlparse
+from urllib.parse import quote, urlencode, urlparse
import requests
from structlog.types import FilteringBoundLogger
@@ -20,6 +20,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.gerrit.set
CHANGES_BASE_QUERY,
GERRIT_ENDPOINTS,
GerritEndpointConfig,
+ GerritFanoutConfig,
)
REQUEST_TIMEOUT_SECONDS = 60
@@ -213,6 +214,50 @@ def _rows_from_response(config: GerritEndpointConfig, data: Any) -> tuple[list[d
return rows, has_more
+def _parent_columns(config: GerritEndpointConfig, parent: dict[str, Any]) -> dict[str, Any]:
+ return {column: parent.get(parent_field) for parent_field, column in config.include_from_parent.items()}
+
+
+def _fanout_path(fanout: GerritFanoutConfig, parent: dict[str, Any]) -> Optional[str]:
+ key = parent.get(fanout.key_field)
+ if key is None:
+ return None
+ return fanout.path.replace("{key}", quote(str(key), safe="") if fanout.quote_key else str(key))
+
+
+def _fanout_rows_from_response(
+ config: GerritEndpointConfig, fanout: GerritFanoutConfig, parent: dict[str, Any], data: Any
+) -> list[dict[str, Any]]:
+ if fanout.response_kind == "map_of_lists":
+ rows = []
+ for key, items in (data or {}).items():
+ for item in items if isinstance(items, list) else []:
+ if isinstance(item, dict):
+ rows.append({fanout.map_key_column: key, **item})
+ else:
+ rows = [dict(item) for item in (data or []) if isinstance(item, dict)]
+
+ parent_columns = _parent_columns(config, parent)
+ return [{**row, **parent_columns} for row in rows]
+
+
+def _current_revision_file_rows(config: GerritEndpointConfig, change: dict[str, Any]) -> list[dict[str, Any]]:
+ revision = change.get("current_revision")
+ revision_info = (change.get("revisions") or {}).get(revision) or {}
+ parent_columns = _parent_columns(config, change)
+ return [
+ {
+ **file_info,
+ "path": path,
+ "revision": revision,
+ "_revision_number": revision_info.get("_number"),
+ **parent_columns,
+ }
+ for path, file_info in (revision_info.get("files") or {}).items()
+ if isinstance(file_info, dict)
+ ]
+
+
def _connection_error_message(error: Exception) -> str:
"""Translate a low-level requests connection failure into a short, actionable message
without echoing the raw error, which embeds the customer's host/IP."""
@@ -283,7 +328,7 @@ def validate_credentials(
if schema_name is not None and schema_name in GERRIT_ENDPOINTS:
config = GERRIT_ENDPOINTS[schema_name]
params: dict[str, str | list[str]] = {**config.params, "n": "1"}
- if schema_name == "changes":
+ if config.path == "/changes/":
params["q"] = CHANGES_BASE_QUERY
probe_url = f"{api_base}{config.path}?{urlencode(params, doseq=True)}"
elif authenticated:
@@ -328,6 +373,34 @@ def validate_credentials(
return False, _connection_error_message(e)
+def _derive_batches(
+ config: GerritEndpointConfig,
+ rows: list[dict[str, Any]],
+ api_base: str,
+ fetch: Callable[[str, frozenset[int]], Optional[str]],
+) -> Iterator[list[dict[str, Any]]]:
+ """Turn a page of listing rows into the endpoint's rows: the rows themselves, the files of
+ each change's current revision, or the child rows fetched per parent."""
+ if config.expand_current_files:
+ yield [file_row for change in rows for file_row in _current_revision_file_rows(config, change)]
+ return
+
+ fanout = config.fanout
+ if fanout is None:
+ yield rows
+ return
+
+ # One batch per parent so a page of fan-out children is never held in memory at once.
+ for parent in rows:
+ path = _fanout_path(fanout, parent)
+ if path is None:
+ continue
+ body = fetch(f"{api_base}{path}", fanout.ignore_statuses)
+ if body is None:
+ continue
+ yield _fanout_rows_from_response(config, fanout, parent, parse_gerrit_response(body))
+
+
def get_rows(
host: str,
username: Optional[str],
@@ -353,7 +426,7 @@ def get_rows(
api_base = _api_base(base_url, authenticated)
params: dict[str, str | list[str]] = dict(config.params)
- if endpoint == "changes":
+ if config.path == "/changes/":
params["q"] = build_changes_query(db_incremental_field_last_value if should_use_incremental_field else None)
offset = 0
@@ -368,7 +441,7 @@ def get_rows(
wait=wait_exponential_jitter(initial=1, max=30),
reraise=True,
)
- def fetch(page_url: str) -> str:
+ def fetch(page_url: str, ignore_statuses: frozenset[int] = frozenset()) -> Optional[str]:
# Don't follow redirects: a customer-controlled host could 3xx to an internal address,
# bypassing the host check above (SSRF). stream=True so the body isn't buffered until we
# drain it under a cap (see _read_capped_text).
@@ -382,6 +455,8 @@ def get_rows(
raise GerritHostNotAllowedError(
f"Gerrit API returned an unexpected redirect (status={response.status_code}); refusing to follow it"
)
+ if response.status_code in ignore_statuses:
+ return None
if not response.ok:
logger.error(
f"Gerrit API error: status={response.status_code}, body={_read_capped_text(response)}, url={page_url}"
@@ -396,18 +471,23 @@ def get_rows(
page_params["S"] = str(offset)
url = f"{api_base}{config.path}?{urlencode(page_params, doseq=True)}"
- rows, has_more = _rows_from_response(config, parse_gerrit_response(fetch(url)))
+ body = fetch(url)
+ if body is None:
+ break
+ rows, has_more = _rows_from_response(config, parse_gerrit_response(body))
if not rows:
break
offset += len(rows)
- yield rows
+ for batch in _derive_batches(config, rows, api_base, fetch):
+ if batch:
+ yield batch
if not has_more:
break
- # Save AFTER yielding so a crash re-yields the last page rather than skipping it —
+ # Save AFTER yielding every batch of the page so a crash re-yields the last page rather than skipping it —
# merge dedupes on the primary key.
resumable_source_manager.save_state(GerritResumeConfig(offset=offset))
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gerrit/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gerrit/settings.py
index 18e58543c5bd..2827dc825657 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gerrit/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gerrit/settings.py
@@ -4,7 +4,22 @@ from typing import Literal, Optional
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
-@dataclass
+@dataclass(frozen=True)
+class GerritFanoutConfig:
+ # Child path; `{key}` is replaced with the parent row's `key_field` value.
+ path: str
+ key_field: str
+ # Change and group ids arrive URL-encoded from their list endpoints; project names don't.
+ quote_key: bool = False
+ # "list" returns a JSON array; "map_of_lists" returns an object keyed by `map_key_column`
+ # whose values are arrays (e.g. comments keyed by file path).
+ response_kind: Literal["list", "map_of_lists"] = "list"
+ map_key_column: str = "path"
+ # Parents that disappear or can't serve the child between the list and the child request.
+ ignore_statuses: frozenset[int] = frozenset({404})
+
+
+@dataclass(frozen=False)
class GerritEndpointConfig:
name: str
path: str
@@ -23,9 +38,16 @@ class GerritEndpointConfig:
# their list payload.
partition_key: Optional[str] = None
# Only /changes/ exposes a server-side timestamp filter (the `after:` query operator on
- # the change `updated` timestamp); every other endpoint is full refresh.
+ # the change `updated` timestamp); endpoints listing anything else are full refresh.
supports_incremental: bool = False
sort_mode: Literal["asc", "desc"] = "asc"
+ # When set, the endpoint's own listing is the parent and each row is fetched per parent.
+ fanout: Optional[GerritFanoutConfig] = None
+ # Emit one row per file of each change's current revision instead of the change itself.
+ expand_current_files: bool = False
+ # Parent fields copied onto each derived row (fan-out children and expanded files), as
+ # parent field -> row column.
+ include_from_parent: dict[str, str] = field(default_factory=dict)
# The query matching every change regardless of state: Gerrit defaults `/changes/` to
@@ -33,6 +55,14 @@ class GerritEndpointConfig:
# merged and abandoned.
CHANGES_BASE_QUERY = "status:open OR status:closed"
+# `_change_number` follows Gerrit's own naming for a change reference (e.g. RelatedChangeAndCommitInfo).
+CHANGE_PARENT_FIELDS = {
+ "_number": "_change_number",
+ "project": "project",
+ "updated": "change_updated",
+ "created": "change_created",
+}
+
GERRIT_ENDPOINTS: dict[str, GerritEndpointConfig] = {
"changes": GerritEndpointConfig(
name="changes",
@@ -73,6 +103,61 @@ GERRIT_ENDPOINTS: dict[str, GerritEndpointConfig] = {
primary_keys=["id"],
response_kind="map",
),
+ "group_members": GerritEndpointConfig(
+ name="group_members",
+ path="/groups/",
+ more_flag="_more_groups",
+ # `group_uuid` rather than `group_id`: GroupInfo already uses `group_id` for the numeric id.
+ primary_keys=["group_uuid", "_account_id"],
+ response_kind="map",
+ fanout=GerritFanoutConfig(
+ path="/groups/{key}/members/",
+ key_field="id",
+ # External groups (LDAP, system groups) have no member list and answer 405.
+ ignore_statuses=frozenset({404, 405}),
+ ),
+ include_from_parent={"id": "group_uuid"},
+ ),
+ "project_branches": GerritEndpointConfig(
+ name="project_branches",
+ path="/projects/",
+ more_flag="_more_projects",
+ primary_keys=["project", "ref"],
+ response_kind="map",
+ fanout=GerritFanoutConfig(path="/projects/{key}/branches/", key_field="name", quote_key=True),
+ include_from_parent={"name": "project"},
+ ),
+ "change_comments": GerritEndpointConfig(
+ name="change_comments",
+ path="/changes/",
+ more_flag="_more_changes",
+ # Comment ids are only documented as unique within a change.
+ primary_keys=["_change_number", "id"],
+ fanout=GerritFanoutConfig(
+ path="/changes/{key}/comments",
+ key_field="id",
+ response_kind="map_of_lists",
+ ),
+ include_from_parent=CHANGE_PARENT_FIELDS,
+ partition_key="change_created",
+ # A new comment bumps the change's `updated`, so the parent filter picks up every
+ # change with new comments.
+ supports_incremental=True,
+ sort_mode="desc",
+ ),
+ "change_files": GerritEndpointConfig(
+ name="change_files",
+ path="/changes/",
+ more_flag="_more_changes",
+ primary_keys=["_change_number", "revision", "path"],
+ # CURRENT_FILES inlines the per-file diffstat into the listing, so no per-change request.
+ params={"o": ["CURRENT_REVISION", "CURRENT_FILES"]},
+ expand_current_files=True,
+ include_from_parent=CHANGE_PARENT_FIELDS,
+ partition_key="change_created",
+ supports_incremental=True,
+ sort_mode="desc",
+ ),
}
ENDPOINTS = tuple(GERRIT_ENDPOINTS.keys())
@@ -86,4 +171,15 @@ INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
"field_type": IncrementalFieldType.DateTime,
},
],
+ **{
+ endpoint: [
+ {
+ "label": "change_updated",
+ "type": IncrementalFieldType.DateTime,
+ "field": "change_updated",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ]
+ for endpoint in ("change_comments", "change_files")
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gerrit/tests/test_gerrit.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gerrit/tests/test_gerrit.py
index 96a9c34445f5..1117336eee35 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gerrit/tests/test_gerrit.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gerrit/tests/test_gerrit.py
@@ -240,7 +240,8 @@ class TestGetRows:
assert "S=50" in session.get.call_args_list[0].args[0]
- def test_incremental_sync_sends_after_filter(self):
+ @pytest.mark.parametrize("endpoint", ["changes", "change_comments", "change_files"])
+ def test_incremental_sync_sends_after_filter(self, endpoint):
session, session_patcher = _patch_session([_response(text=")]}'\n[]")])
with (
@@ -252,7 +253,7 @@ class TestGetRows:
host="https://gerrit.example.com",
username="reviewbot",
http_password="secret",
- endpoint="changes",
+ endpoint=endpoint,
team_id=1,
logger=mock.MagicMock(),
resumable_source_manager=_FakeResumeManager(),
@@ -279,6 +280,159 @@ class TestGetRows:
]
]
+ @pytest.mark.parametrize(
+ "endpoint, parent_body, child_responses, expected_child_paths, expected_batches",
+ [
+ (
+ "group_members",
+ '{"Admins": {"id": "abc123"}, "ldap/eng": {"id": "ldap%3Acn%3Deng"}}',
+ # External groups have no member list and answer 405.
+ [_response(text=")]}'\n" + '[{"_account_id": 7, "name": "Ada"}]'), _response(status_code=405)],
+ ["/a/groups/abc123/members/", "/a/groups/ldap%3Acn%3Deng/members/"],
+ [[{"_account_id": 7, "name": "Ada", "group_uuid": "abc123"}]],
+ ),
+ (
+ "project_branches",
+ '{"plugins/replication": {"id": "plugins%2Freplication"}, "gerrit": {"id": "gerrit"}}',
+ [
+ _response(text=")]}'\n" + '[{"ref": "refs/heads/main", "revision": "abc"}]'),
+ _response(text=")]}'\n" + '[{"ref": "refs/heads/stable", "revision": "def"}]'),
+ ],
+ ["/a/projects/plugins%2Freplication/branches/", "/a/projects/gerrit/branches/"],
+ # One batch per parent, so a page of fan-out children is never buffered whole.
+ [
+ [{"ref": "refs/heads/main", "revision": "abc", "project": "plugins/replication"}],
+ [{"ref": "refs/heads/stable", "revision": "def", "project": "gerrit"}],
+ ],
+ ),
+ (
+ "change_comments",
+ '[{"id": "plugins%2Freplication~12", "_number": 12, "project": "plugins/replication",'
+ ' "updated": "u12", "created": "c12"}, {"id": "gerrit~13", "_number": 13, "project": "gerrit"}]',
+ # A change deleted between the listing and the comments request answers 404.
+ [
+ _response(
+ text=")]}'\n" + '{"src/a.py": [{"id": "c1", "line": 3}, {"id": "c2", "in_reply_to": "c1"}],'
+ ' "/COMMIT_MSG": [{"id": "c3"}]}'
+ ),
+ _response(status_code=404),
+ ],
+ ["/a/changes/plugins%2Freplication~12/comments", "/a/changes/gerrit~13/comments"],
+ [
+ [
+ {
+ "path": "src/a.py",
+ "id": "c1",
+ "line": 3,
+ "_change_number": 12,
+ "project": "plugins/replication",
+ "change_updated": "u12",
+ "change_created": "c12",
+ },
+ {
+ "path": "src/a.py",
+ "id": "c2",
+ "in_reply_to": "c1",
+ "_change_number": 12,
+ "project": "plugins/replication",
+ "change_updated": "u12",
+ "change_created": "c12",
+ },
+ {
+ "path": "/COMMIT_MSG",
+ "id": "c3",
+ "_change_number": 12,
+ "project": "plugins/replication",
+ "change_updated": "u12",
+ "change_created": "c12",
+ },
+ ],
+ ],
+ ),
+ ],
+ )
+ def test_fanout_fetches_children_per_parent(
+ self, endpoint, parent_body, child_responses, expected_child_paths, expected_batches
+ ):
+ session, session_patcher = _patch_session([_response(text=")]}'\n" + parent_body), *child_responses])
+
+ with (
+ session_patcher,
+ mock.patch.object(gerrit_module, "_is_host_safe", return_value=(True, None)),
+ ):
+ batches = list(
+ get_rows(
+ host="https://gerrit.example.com",
+ username="reviewbot",
+ http_password="secret",
+ endpoint=endpoint,
+ team_id=1,
+ logger=mock.MagicMock(),
+ resumable_source_manager=_FakeResumeManager(),
+ )
+ )
+
+ child_urls = [call.args[0] for call in session.get.call_args_list[1:]]
+ assert child_urls == [f"https://gerrit.example.com{path}" for path in expected_child_paths]
+ assert batches == expected_batches
+
+ def test_fanout_child_error_other_than_ignored_statuses_fails_the_sync(self):
+ parent_body = ")]}'\n" + '{"gerrit": {"id": "gerrit"}}'
+ forbidden = _response(status_code=403)
+ forbidden.raise_for_status.side_effect = requests.HTTPError("403 Client Error: Forbidden", response=forbidden)
+ with pytest.raises(requests.HTTPError):
+ _get_all_rows("project_branches", [_response(text=parent_body), forbidden])
+
+ def test_change_files_flattens_current_revision_files(self):
+ body = (
+ ")]}'\n"
+ '[{"id": "gerrit~12", "_number": 12, "project": "gerrit", "updated": "u", "created": "c",'
+ ' "current_revision": "sha2", "revisions": {"sha2": {"_number": 2, "files": {'
+ '"src/a.py": {"lines_inserted": 5, "lines_deleted": 1},'
+ ' "img.png": {"binary": true, "status": "A"}}}}},'
+ ' {"id": "gerrit~13", "_number": 13, "project": "gerrit", "current_revision": "sha9",'
+ ' "revisions": {"sha9": {"_number": 1}}, "_more_changes": true}]'
+ )
+ page_2 = ")]}'\n[]"
+ session, session_patcher = _patch_session([_response(text=body), _response(text=page_2)])
+ manager = _FakeResumeManager()
+
+ with (
+ session_patcher,
+ mock.patch.object(gerrit_module, "_is_host_safe", return_value=(True, None)),
+ ):
+ batches = list(
+ get_rows(
+ host="https://gerrit.example.com",
+ username="reviewbot",
+ http_password="secret",
+ endpoint="change_files",
+ team_id=1,
+ logger=mock.MagicMock(),
+ resumable_source_manager=manager,
+ )
+ )
+
+ parent = {"_change_number": 12, "project": "gerrit", "change_updated": "u", "change_created": "c"}
+ assert batches == [
+ [
+ {
+ "lines_inserted": 5,
+ "lines_deleted": 1,
+ "path": "src/a.py",
+ "revision": "sha2",
+ "_revision_number": 2,
+ **parent,
+ },
+ {"binary": True, "status": "A", "path": "img.png", "revision": "sha2", "_revision_number": 2, **parent},
+ ]
+ ]
+ first_url = session.get.call_args_list[0].args[0]
+ assert "o=CURRENT_REVISION&o=CURRENT_FILES" in first_url
+ # The resume offset counts changes, not file rows, because `S` skips changes.
+ assert "S=2" in session.get.call_args_list[1].args[0]
+ assert [s.offset for s in manager.saved] == [2]
+
def test_anonymous_requests_skip_the_auth_prefix(self):
session, session_patcher = _patch_session([_response(text=")]}'\n[]")])
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gerrit/tests/test_gerrit_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gerrit/tests/test_gerrit_source.py
index 3e12addc3106..71ada8231d13 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gerrit/tests/test_gerrit_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gerrit/tests/test_gerrit_source.py
@@ -17,12 +17,15 @@ class TestGerritSource:
schemas = self.source.get_schemas(self.config, self.team_id)
assert {s.name for s in schemas} == set(ENDPOINTS)
- def test_only_changes_supports_incremental(self):
+ def test_only_change_listings_support_incremental(self):
schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}
assert schemas["changes"].supports_incremental is True
assert [f["field"] for f in schemas["changes"].incremental_fields] == ["updated"]
- for name in ("accounts", "projects", "groups"):
+ for name in ("change_comments", "change_files"):
+ assert schemas[name].supports_incremental is True
+ assert [f["field"] for f in schemas[name].incremental_fields] == ["change_updated"]
+ for name in ("accounts", "projects", "groups", "group_members", "project_branches"):
assert schemas[name].supports_incremental is False
assert schemas[name].incremental_fields == []