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): implement gerrit import source (#71177)

Tom Owers7651491df62e
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index ba0fb9014614..6c0dd9885c2c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -200,6 +200,7 @@ the row lists both.
| fulcrum | HTTP | requests | ✅ |
| fullstory | HTTP | requests | ✅ |
| gainsight_px | HTTP | requests | ✅ |
+| gerrit | HTTP | requests | ✅ |
| gitbook | HTTP | requests | ✅ |
| github | HTTP + Webhook | requests + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) |
| giphy | HTTP | requests | ✅ |
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index 9cb74718fee8..cf72df835642 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
@@ -1641,7 +1641,9 @@ class GainsightPxSourceConfig(config.Config):
@config.config
class GerritSourceConfig(config.Config):
- pass
+ host: str
+ username: str | None = None
+ http_password: str | None = None
@config.config
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
new file mode 100644
index 000000000000..ee2015280da3
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gerrit/canonical_descriptions.py
@@ -0,0 +1,81 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "changes": {
+ "description": "A change under review: one unit of work (a commit and its patch sets) proposed for a project branch, with its labels, review messages, and current revision.",
+ "docs_url": "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#change-info",
+ "columns": {
+ "id": "Change ID in the format '<project>~<_number>' (older servers use '<project>~<branch>~<Change-Id>'), URL-decoded.",
+ "project": "The name of the project this change belongs to.",
+ "branch": "The name of the target branch (without the refs/heads/ prefix).",
+ "topic": "The topic to which this change belongs.",
+ "change_id": "The Change-Id footer of the change.",
+ "subject": "The subject of the change (header line of the commit message).",
+ "status": "The status of the change (NEW, MERGED, ABANDONED).",
+ "created": "The timestamp of when the change was created (UTC).",
+ "updated": "The timestamp of when the change was last updated (UTC).",
+ "submitted": "The timestamp of when the change was submitted (merged). Only set for merged changes.",
+ "submitter": "The user who submitted the change.",
+ "insertions": "Number of inserted lines.",
+ "deletions": "Number of deleted lines.",
+ "total_comment_count": "Total number of inline comments across all patch sets.",
+ "unresolved_comment_count": "Number of unresolved inline comment threads across all patch sets.",
+ "_number": "The change number (server-unique numeric ID).",
+ "owner": "The owner of the change as an account.",
+ "labels": "The review labels of the change (e.g. Code-Review) with applied votes and permitted values.",
+ "reviewers": "The reviewers of the change, grouped by reviewer state (REVIEWER, CC, REMOVED).",
+ "messages": "Messages associated with the change: the chronological review timeline.",
+ "current_revision": "The commit ID of the current patch set of the change.",
+ "revisions": "Information about the current patch set of the change, keyed by commit ID.",
+ "hashtags": "List of hashtags set on the change.",
+ "submit_type": "The submit type of the change (e.g. MERGE_IF_NECESSARY). Not set for merged changes.",
+ "work_in_progress": "Whether the change is marked as work in progress.",
+ "has_review_started": "Whether the change has been marked ready for review at least once.",
+ "meta_rev_id": "The SHA-1 of the NoteDb meta ref of the change.",
+ "attention_set": "The accounts in the attention set of the change, with the reason they were added.",
+ },
+ },
+ "accounts": {
+ "description": "A user account on the Gerrit instance. Only active accounts are synced.",
+ "docs_url": "https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#account-info",
+ "columns": {
+ "_account_id": "The numeric ID of the account.",
+ "name": "The full name of the user.",
+ "display_name": "The display name of the user.",
+ "email": "The email address the user prefers to be contacted through.",
+ "username": "The username of the user.",
+ "status": "Status message of the account (free text, e.g. 'OOO until Aug 1st').",
+ "tags": "List of additional tags, e.g. SERVICE_USER for bot accounts.",
+ "avatars": "List of avatars of the user in various sizes.",
+ },
+ },
+ "projects": {
+ "description": "A project (Git repository) hosted on the Gerrit instance.",
+ "docs_url": "https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#project-info",
+ "columns": {
+ "id": "The URL-encoded project name.",
+ "name": "The name of the project.",
+ "parent": "The name of the parent project the project inherits access rights and config from.",
+ "description": "The description of the project.",
+ "state": "The state of the project (ACTIVE, READ_ONLY, HIDDEN).",
+ "web_links": "Links to the project in external sites (e.g. a Gitiles browser).",
+ },
+ },
+ "groups": {
+ "description": "An account group on the Gerrit instance. Listing groups requires an authenticated account.",
+ "docs_url": "https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html#group-info",
+ "columns": {
+ "id": "The URL-encoded UUID of the group.",
+ "name": "The name of the group.",
+ "url": "URL to information about the group, typically the group's page on the instance.",
+ "description": "The description of the group.",
+ "group_id": "The numeric ID of the group.",
+ "owner": "The name of the group that owns this group.",
+ "owner_id": "The URL-encoded UUID of the owner group.",
+ "created_on": "The timestamp of when the group was created (UTC).",
+ "options": "Options of the group, e.g. whether the group is visible to all registered users.",
+ },
+ },
+}
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
new file mode 100644
index 000000000000..b209124b526f
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gerrit/gerrit.py
@@ -0,0 +1,448 @@
+import re
+import json
+import socket
+import threading
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+from urllib.parse import urlencode, urlparse
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import _is_host_safe
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.gerrit.settings import (
+ CHANGES_BASE_QUERY,
+ GERRIT_ENDPOINTS,
+ GerritEndpointConfig,
+)
+
+REQUEST_TIMEOUT_SECONDS = 60
+MAX_RETRIES = 5
+
+# Hard ceilings on how much of a response body we'll pull into memory and how long we'll spend
+# pulling it. The host is customer-supplied, so a hostile server could otherwise stream an
+# unbounded or slow-drip body and OOM / tie up a shared worker — the socket read timeout only
+# bounds idle gaps, not total bytes or total wall-clock. A single page of the largest endpoint
+# (100 fully-expanded changes) sits comfortably under the byte cap.
+MAX_RESPONSE_BYTES = 64 * 1024 * 1024
+MAX_DOWNLOAD_SECONDS = 120
+DOWNLOAD_CHUNK_BYTES = 64 * 1024
+
+# Anti-XSSI magic prefix Gerrit prepends to every JSON response body.
+XSSI_PREFIX = ")]}'"
+
+HOST_NOT_ALLOWED_ERROR = "Gerrit host is not allowed"
+
+# Loopback hosts where plaintext HTTP carries no network-exposure risk (local dev / self-hosted on
+# the same box). Every other host is forced to HTTPS so credentials never traverse a network in
+# cleartext.
+LOOPBACK_HOSTS = {"localhost", "127.0.0.1", "::1"}
+
+
+class GerritRetryableError(Exception):
+ pass
+
+
+class GerritHostNotAllowedError(Exception):
+ pass
+
+
+class GerritResponseTooLargeError(Exception):
+ pass
+
+
+class GerritResumeConfig:
+ # Number of rows already fetched for the endpoint — Gerrit paginates with an `S` skip offset.
+ offset: int = 0
+
+
+def normalize_host(host: str) -> str:
+ """Turn whatever the user typed into a Gerrit base URL (scheme + host + optional context path).
+
+ Unlike most SaaS sources, a self-hosted Gerrit can live under a context path (e.g.
+ ``https://example.com/r``), so any path the user supplied is preserved — only trailing slashes
+ and a trailing ``/a`` (the authenticated-API prefix we add ourselves) are stripped. Defaults to
+ https when no scheme is given, and forces a plaintext ``http://`` host to ``https://`` so
+ credentials are never sent over the network in cleartext — except for loopback hosts.
+ """
+ host = host.strip()
+ if not re.match(r"^https?://", host, flags=re.IGNORECASE):
+ host = f"https://{host}"
+ parsed = urlparse(host)
+ scheme = parsed.scheme.lower()
+ if scheme == "http" and (parsed.hostname or "").lower() not in LOOPBACK_HOSTS:
+ scheme = "https"
+ path = parsed.path.rstrip("/")
+ if path.endswith("/a"):
+ path = path[: -len("/a")]
+ return f"{scheme}://{parsed.netloc}{path}"
+
+
+def _hostname(host: str) -> str:
+ return (urlparse(normalize_host(host)).hostname or "").lower()
+
+
+def parse_gerrit_response(text: str) -> Any:
+ """Parse a Gerrit JSON response body, stripping the ``)]}'`` anti-XSSI prefix."""
+ stripped = text.lstrip()
+ if stripped.startswith(XSSI_PREFIX):
+ stripped = stripped[len(XSSI_PREFIX) :]
+ return json.loads(stripped)
+
+
+def _underlying_socket(response: requests.Response) -> Optional[socket.socket]:
+ """Best-effort reach for the raw socket behind a streamed response.
+
+ Used only to release a drain thread stuck in a body read once the download deadline fires.
+ The attribute chain into urllib3/``http.client`` is private, so this stays defensive and
+ returns ``None`` if the layout differs — the caller still returns at the deadline either way.
+ """
+ for path in (("_fp", "fp", "raw", "_sock"), ("_connection", "sock")):
+ obj: Any = getattr(response, "raw", None)
+ for attr in path:
+ obj = getattr(obj, attr, None)
+ if obj is None:
+ break
+ if isinstance(obj, socket.socket):
+ return obj
+ return None
+
+
+def _read_capped_text(response: requests.Response) -> str:
+ """Drain a streamed response body under a byte cap and a hard wall-clock deadline, then decode.
+
+ The request is issued with ``stream=True`` so nothing is buffered until this read. Two limits
+ protect a shared worker from a hostile customer-supplied host:
+
+ * ``MAX_RESPONSE_BYTES`` caps how much we buffer into memory, checked as chunks arrive.
+ * ``MAX_DOWNLOAD_SECONDS`` caps total wall-clock. This is *not* enforceable via the socket read
+ timeout alone: that timeout resets on every ``recv``, so a host dripping one byte just under
+ it keeps a single ``iter_content`` read (which blocks until a full chunk is read) parked
+ indefinitely. Nor can ``Response.close()`` from a timer reliably cancel that parked read. So
+ the body is drained on a worker thread and this caller waits on it for at most the deadline;
+ once it elapses the caller returns immediately — a sync worker is never held past the
+ deadline regardless of platform — and shuts the socket down to release the drain thread
+ (``shutdown`` unblocks a parked ``recv`` on POSIX where ``close`` does not).
+ """
+ result: dict[str, Any] = {}
+ done = threading.Event()
+
+ def _drain() -> None:
+ try:
+ chunks: list[bytes] = []
+ total = 0
+ for chunk in response.iter_content(chunk_size=DOWNLOAD_CHUNK_BYTES):
+ if not chunk:
+ continue
+ total += len(chunk)
+ if total > MAX_RESPONSE_BYTES:
+ raise GerritResponseTooLargeError("Gerrit returned an oversized response body")
+ chunks.append(chunk)
+ result["text"] = b"".join(chunks).decode(response.encoding or "utf-8", errors="replace")
+ except Exception as exc:
+ result["error"] = exc
+ finally:
+ done.set()
+
+ thread = threading.Thread(target=_drain, name="gerrit-body-drain", daemon=True)
+ thread.start()
+
+ if not done.wait(MAX_DOWNLOAD_SECONDS):
+ drain_socket = _underlying_socket(response)
+ if drain_socket is not None:
+ try:
+ drain_socket.shutdown(socket.SHUT_RDWR)
+ except OSError:
+ pass
+ response.close()
+ raise GerritResponseTooLargeError("Gerrit response body took too long to download")
+
+ if "error" in result:
+ raise result["error"]
+ return result["text"]
+
+
+def _api_base(base_url: str, authenticated: bool) -> str:
+ # Authenticated requests go through the `/a/` path prefix; anonymous ones hit the same
+ # endpoints without it (public instances allow anonymous reads).
+ return f"{base_url}/a" if authenticated else base_url
+
+
+def format_after_value(value: Any) -> str:
+ """Format an incremental cursor for Gerrit's ``after:"YYYY-MM-DD HH:MM:SS"`` query operator.
+
+ Gerrit timestamps are UTC; the stored watermark comes back as a (usually naive, UTC) datetime
+ parsed from the change's ``updated`` field.
+ """
+ if isinstance(value, datetime):
+ utc_value = value.astimezone(UTC) if value.tzinfo is not None else value
+ return utc_value.strftime("%Y-%m-%d %H:%M:%S")
+ if isinstance(value, date):
+ return value.strftime("%Y-%m-%d 00:00:00")
+ return str(value)
+
+
+def build_changes_query(db_incremental_field_last_value: Optional[Any]) -> str:
+ if db_incremental_field_last_value is None:
+ return CHANGES_BASE_QUERY
+ return f'({CHANGES_BASE_QUERY}) after:"{format_after_value(db_incremental_field_last_value)}"'
+
+
+def _rows_from_response(config: GerritEndpointConfig, data: Any) -> tuple[list[dict[str, Any]], bool]:
+ """Normalize a page into row dicts and read Gerrit's more-results flag off the last entry."""
+ if config.response_kind == "map":
+ rows = []
+ for key, value in (data or {}).items():
+ if not isinstance(value, dict):
+ continue
+ row = dict(value)
+ # Map responses key entries by resource name and may omit it from the entry itself.
+ row.setdefault("name", key)
+ rows.append(row)
+ else:
+ rows = [dict(item) for item in (data or []) if isinstance(item, dict)]
+
+ has_more = any(row.pop(config.more_flag, False) for row in rows)
+ return rows, has_more
+
+
+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."""
+ text = str(error).lower()
+ if isinstance(error, requests.exceptions.SSLError):
+ return (
+ "Couldn't establish a secure (HTTPS) connection to your Gerrit instance. "
+ "Check that the instance URL is correct and its TLS certificate is valid."
+ )
+ if isinstance(error, requests.exceptions.Timeout):
+ return (
+ "Connecting to your Gerrit instance timed out. "
+ "Check that the instance URL is correct and reachable from the public internet."
+ )
+ if isinstance(error, requests.exceptions.ConnectionError) and (
+ "name or service not known" in text or "nodename nor servname" in text or "failed to resolve" in text
+ ):
+ return (
+ "Couldn't resolve the Gerrit host. "
+ "Check that the instance URL is spelled correctly and reachable from the public internet."
+ )
+ return (
+ "Couldn't connect to your Gerrit instance. "
+ "Check that the instance URL is correct and reachable from the public internet."
+ )
+
+
+def _make_session(username: Optional[str], http_password: Optional[str]) -> requests.Session:
+ redact_values = tuple(v for v in (http_password,) if v)
+ session = make_tracked_session(allow_redirects=False, redact_values=redact_values)
+ if username and http_password:
+ session.auth = (username, http_password)
+ return session
+
+
+def validate_credentials(
+ host: str,
+ username: Optional[str],
+ http_password: Optional[str],
+ team_id: Optional[int] = None,
+ schema_name: Optional[str] = None,
+) -> tuple[bool, str | None]:
+ """Probe the instance: with credentials, ``/a/accounts/self`` confirms the HTTP password is
+ genuine; without, ``/config/server/version`` confirms the instance allows anonymous reads.
+ With ``schema_name`` set, probe that endpoint instead — group listing in particular needs an
+ authenticated account."""
+ try:
+ base_url = normalize_host(host)
+ except Exception:
+ return False, "Invalid Gerrit instance URL"
+
+ hostname = _hostname(host)
+ if not hostname or not re.match(r"^[A-Za-z0-9.\-]+$", hostname):
+ return False, "Invalid Gerrit instance URL"
+
+ if team_id is not None:
+ host_ok, host_err = _is_host_safe(hostname, team_id)
+ if not host_ok:
+ return False, host_err or HOST_NOT_ALLOWED_ERROR
+
+ authenticated = bool(username and http_password)
+ if (username and not http_password) or (http_password and not username):
+ return False, "Enter both a username and an HTTP password, or leave both blank for anonymous access"
+
+ session = _make_session(username, http_password)
+ api_base = _api_base(base_url, authenticated)
+
+ 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":
+ params["q"] = CHANGES_BASE_QUERY
+ probe_url = f"{api_base}{config.path}?{urlencode(params, doseq=True)}"
+ elif authenticated:
+ probe_url = f"{api_base}/accounts/self"
+ else:
+ probe_url = f"{api_base}/config/server/version"
+
+ # stream=True so the body isn't buffered until we drain it under a cap (see _read_capped_text).
+ try:
+ with session.get(probe_url, timeout=10, allow_redirects=False, stream=True) as response:
+ if response.is_redirect or response.is_permanent_redirect:
+ return False, HOST_NOT_ALLOWED_ERROR
+ if response.status_code == 200:
+ try:
+ parse_gerrit_response(_read_capped_text(response))
+ except GerritResponseTooLargeError:
+ return False, (
+ "Gerrit returned an unexpectedly large response. "
+ "Check that the instance URL points to your Gerrit instance."
+ )
+ except (json.JSONDecodeError, ValueError):
+ return False, (
+ "Gerrit didn't return a valid API response. "
+ "Check that the instance URL points to your Gerrit instance."
+ )
+ return True, None
+ if response.status_code == 401:
+ return False, "Invalid Gerrit username or HTTP password"
+ if response.status_code == 403:
+ # Valid token but missing permission for this probe — let source creation through;
+ # per-schema probes still report it so users can deselect the table.
+ if schema_name is None:
+ return True, None
+ return False, "Your Gerrit account lacks permission to read this resource"
+
+ return (
+ False,
+ f"Gerrit returned an unexpected response (HTTP {response.status_code}). "
+ "Check that the instance URL points to your Gerrit instance.",
+ )
+ except requests.exceptions.RequestException as e:
+ return False, _connection_error_message(e)
+
+
+def get_rows(
+ host: str,
+ username: Optional[str],
+ http_password: Optional[str],
+ endpoint: str,
+ team_id: int,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[GerritResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = GERRIT_ENDPOINTS[endpoint]
+ base_url = normalize_host(host)
+
+ # Re-check at run time (not just source-create) in case the host was edited or now resolves
+ # to an internal address (SSRF / DNS rebinding). Only enforced on cloud.
+ host_ok, host_err = _is_host_safe(_hostname(host), team_id)
+ if not host_ok:
+ raise GerritHostNotAllowedError(host_err or HOST_NOT_ALLOWED_ERROR)
+
+ authenticated = bool(username and http_password)
+ session = _make_session(username, http_password)
+ api_base = _api_base(base_url, authenticated)
+
+ params: dict[str, str | list[str]] = dict(config.params)
+ if endpoint == "changes":
+ params["q"] = build_changes_query(db_incremental_field_last_value if should_use_incremental_field else None)
+
+ offset = 0
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume is not None and resume.offset:
+ offset = resume.offset
+ logger.debug(f"Gerrit: resuming {endpoint} from offset {offset}")
+
+ @retry(
+ retry=retry_if_exception_type((GerritRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRIES),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+ )
+ def fetch(page_url: str) -> 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).
+ with session.get(page_url, timeout=REQUEST_TIMEOUT_SECONDS, allow_redirects=False, stream=True) as response:
+ # Gerrit rate limits surface as 429 with an instance-configured window; back off and retry.
+ if response.status_code == 429 or response.status_code >= 500:
+ raise GerritRetryableError(
+ f"Gerrit API error (retryable): status={response.status_code}, url={page_url}"
+ )
+ if response.is_redirect or response.is_permanent_redirect:
+ raise GerritHostNotAllowedError(
+ f"Gerrit API returned an unexpected redirect (status={response.status_code}); refusing to follow it"
+ )
+ if not response.ok:
+ logger.error(
+ f"Gerrit API error: status={response.status_code}, body={_read_capped_text(response)}, url={page_url}"
+ )
+ response.raise_for_status()
+
+ return _read_capped_text(response)
+
+ while True:
+ page_params: dict[str, str | list[str]] = {**params, "n": str(config.page_size)}
+ if offset:
+ 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)))
+
+ if not rows:
+ break
+
+ offset += len(rows)
+ yield rows
+
+ if not has_more:
+ break
+
+ # Save AFTER yielding 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))
+
+
+def gerrit_source(
+ host: str,
+ username: Optional[str],
+ http_password: Optional[str],
+ endpoint: str,
+ team_id: int,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[GerritResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = GERRIT_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ host=host,
+ username=username,
+ http_password=http_password,
+ endpoint=endpoint,
+ team_id=team_id,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ ),
+ primary_keys=config.primary_keys,
+ # /changes/ returns newest-first on `updated` with no ascending option, so the pipeline
+ # must persist the incremental watermark only at successful job end.
+ sort_mode=config.sort_mode,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="month" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ )
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
new file mode 100644
index 000000000000..18e58543c5bd
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gerrit/settings.py
@@ -0,0 +1,89 @@
+from dataclasses import dataclass, field
+from typing import Literal, Optional
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+
+@dataclass
+class GerritEndpointConfig:
+ name: str
+ path: str
+ # Gerrit signals "there are more results" with a boolean flag on the last entry of a
+ # truncated page (e.g. `_more_changes`) instead of a next-page token.
+ more_flag: str
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ # "list" endpoints return a JSON array; "map" endpoints (/projects/, /groups/) return an
+ # object keyed by resource name, with the name omitted from some entries.
+ response_kind: Literal["list", "map"] = "list"
+ # Static query params sent on every request. Values that are lists are repeated
+ # (e.g. the `o` option params on /changes/).
+ params: dict[str, str | list[str]] = field(default_factory=dict)
+ page_size: int = 100
+ # Stable creation-time field used for datetime partitioning. Only changes carry one in
+ # 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.
+ supports_incremental: bool = False
+ sort_mode: Literal["asc", "desc"] = "asc"
+
+
+# The query matching every change regardless of state: Gerrit defaults `/changes/` to
+# `status:open`, silently hiding merged/abandoned changes, and `status:closed` covers both
+# merged and abandoned.
+CHANGES_BASE_QUERY = "status:open OR status:closed"
+
+GERRIT_ENDPOINTS: dict[str, GerritEndpointConfig] = {
+ "changes": GerritEndpointConfig(
+ name="changes",
+ path="/changes/",
+ more_flag="_more_changes",
+ primary_keys=["id"],
+ params={
+ # CURRENT_REVISION (not ALL_REVISIONS) keeps row size bounded on long-lived
+ # changes with hundreds of patch sets; MESSAGES carries the full review timeline.
+ "o": ["DETAILED_LABELS", "CURRENT_REVISION", "MESSAGES", "DETAILED_ACCOUNTS"],
+ },
+ partition_key="created",
+ supports_incremental=True,
+ # Gerrit returns changes newest-first on `updated` and offers no ascending sort.
+ sort_mode="desc",
+ ),
+ "accounts": GerritEndpointConfig(
+ name="accounts",
+ path="/accounts/",
+ more_flag="_more_accounts",
+ primary_keys=["_account_id"],
+ # /accounts/ requires a query; `is:active` lists every active account.
+ params={"q": "is:active", "o": ["DETAILS"]},
+ ),
+ "projects": GerritEndpointConfig(
+ name="projects",
+ path="/projects/",
+ more_flag="_more_projects",
+ primary_keys=["id"],
+ response_kind="map",
+ # `d` includes project descriptions in the listing.
+ params={"d": ""},
+ ),
+ "groups": GerritEndpointConfig(
+ name="groups",
+ path="/groups/",
+ more_flag="_more_groups",
+ primary_keys=["id"],
+ response_kind="map",
+ ),
+}
+
+ENDPOINTS = tuple(GERRIT_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ "changes": [
+ {
+ "label": "updated",
+ "type": IncrementalFieldType.DateTime,
+ "field": "updated",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gerrit/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gerrit/source.py
index 2ad8a3066135..df1b8681c81e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gerrit/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gerrit/source.py
@@ -1,19 +1,43 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import GerritSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.gerrit.gerrit import (
+ HOST_NOT_ALLOWED_ERROR,
+ GerritResumeConfig,
+ gerrit_source,
+ validate_credentials as validate_gerrit_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.gerrit.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class GerritSource(SimpleSource[GerritSourceConfig]):
+class GerritSource(ResumableSource[GerritSourceConfig, GerritResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.GERRIT
@@ -23,8 +47,113 @@ class GerritSource(SimpleSource[GerritSourceConfig]):
return SourceConfig(
name=SchemaExternalDataSourceType.GERRIT,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
- label="Gerrit Code Review (Google / open source)",
+ label="Gerrit",
+ releaseStatus=ReleaseStatus.ALPHA,
+ keywords=["code review"],
+ caption="""Enter your Gerrit instance URL and credentials to pull your code review data into the PostHog Data warehouse.
+
+Generate an HTTP password in your Gerrit account under **Settings > HTTP Credentials** (or **HTTP Password** on older versions) and enter it together with your Gerrit username. On public instances you can leave both blank to sync with anonymous read access — you'll only see the changes, accounts, and projects that are publicly visible, and group listing requires an authenticated account.""",
iconPath="/static/services/gerrit.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/gerrit",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="host",
+ label="Instance URL",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="https://gerrit.example.com",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="username",
+ label="Username",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="http_password",
+ label="HTTP password",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=False,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error": "Your Gerrit username or HTTP password is invalid or expired. Generate a new HTTP password and reconnect.",
+ "403 Client Error": "Your Gerrit account lacks the permissions needed to sync this data. Grant read access (or connect with credentials) and reconnect.",
+ HOST_NOT_ALLOWED_ERROR: "The Gerrit host is not allowed. Please use your instance's public URL.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.gerrit.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: GerritSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=INCREMENTAL_FIELDS.get(endpoint) is not None,
+ supports_append=INCREMENTAL_FIELDS.get(endpoint) is not None,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ )
+ for endpoint in ENDPOINTS
+ ]
+
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+
+ return schemas
+
+ def validate_credentials(
+ self, config: GerritSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ return validate_gerrit_credentials(
+ host=config.host,
+ username=config.username,
+ http_password=config.http_password,
+ team_id=team_id,
+ schema_name=schema_name,
+ )
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[GerritResumeConfig]:
+ return ResumableSourceManager[GerritResumeConfig](inputs, GerritResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: GerritSourceConfig,
+ resumable_source_manager: ResumableSourceManager[GerritResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return gerrit_source(
+ host=config.host,
+ username=config.username,
+ http_password=config.http_password,
+ endpoint=inputs.schema_name,
+ team_id=inputs.team_id,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
)
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
new file mode 100644
index 000000000000..96a9c34445f5
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gerrit/tests/test_gerrit.py
@@ -0,0 +1,470 @@
+import time
+import socket
+import threading
+from datetime import UTC, datetime, timedelta, timezone
+from typing import Any, Optional
+
+import pytest
+from unittest import mock
+
+import requests
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.gerrit import gerrit as gerrit_module
+from products.warehouse_sources.backend.temporal.data_imports.sources.gerrit.gerrit import (
+ HOST_NOT_ALLOWED_ERROR,
+ GerritResumeConfig,
+ build_changes_query,
+ format_after_value,
+ gerrit_source,
+ get_rows,
+ normalize_host,
+ parse_gerrit_response,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.gerrit.settings import GERRIT_ENDPOINTS
+
+
+def _response(*, status_code: int = 200, text: str = "", is_redirect: bool = False) -> mock.MagicMock:
+ response = mock.MagicMock()
+ response.status_code = status_code
+ response.ok = 200 <= status_code < 400
+ response.is_redirect = is_redirect
+ response.is_permanent_redirect = False
+ response.text = text
+ response.encoding = "utf-8"
+ response.headers = {}
+ # The source reads bodies with stream=True via response.iter_content; hand back the body in one
+ # chunk (empty bodies yield nothing). A fresh iterator per call mirrors requests' behaviour.
+ body = text.encode("utf-8")
+ response.iter_content.side_effect = lambda chunk_size=None: iter([body] if body else [])
+ # Responses are used as context managers (with session.get(...) as response).
+ response.__enter__.return_value = response
+ response.__exit__.return_value = False
+ return response
+
+
+class _FakeResumeManager(ResumableSourceManager[GerritResumeConfig]):
+ # In-memory stand-in — deliberately doesn't call super().__init__, so no Redis is touched.
+ def __init__(self, state: Optional[GerritResumeConfig] = None):
+ self._state = state
+ self.saved: list[GerritResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> Optional[GerritResumeConfig]:
+ return self._state
+
+ def save_state(self, state: GerritResumeConfig) -> None:
+ self.saved.append(state)
+
+
+def _start_drip_server(byte_interval: float) -> int:
+ """Serve a body one byte at a time, forever, on a loopback port. Returns the port.
+
+ Models a host that trickles data just under the socket read timeout to keep a body read alive
+ indefinitely. Threads are daemons and the socket is released once the client hangs up.
+ """
+ server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+ server.bind(("127.0.0.1", 0))
+ server.listen(1)
+ port = server.getsockname()[1]
+
+ def _serve() -> None:
+ try:
+ conn, _ = server.accept()
+ conn.recv(65536) # consume the request line/headers
+ conn.sendall(b"HTTP/1.1 200 OK\r\nContent-Length: 1000000\r\n\r\n")
+ while True:
+ conn.sendall(b"x")
+ time.sleep(byte_interval)
+ except OSError:
+ pass
+ finally:
+ server.close()
+
+ threading.Thread(target=_serve, name="drip-server", daemon=True).start()
+ return port
+
+
+def _patch_session(responses: list[mock.MagicMock]) -> tuple[mock.MagicMock, Any]:
+ session = mock.MagicMock()
+ session.get.side_effect = responses
+ patcher = mock.patch.object(gerrit_module, "make_tracked_session", return_value=session)
+ return session, patcher
+
+
+def _get_all_rows(endpoint: str, session_responses: list[mock.MagicMock], **kwargs: Any) -> list[list[dict[str, Any]]]:
+ session, session_patcher = _patch_session(session_responses)
+ manager = kwargs.pop("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=kwargs.pop("username", "reviewbot"),
+ http_password=kwargs.pop("http_password", "secret"),
+ endpoint=endpoint,
+ team_id=1,
+ logger=mock.MagicMock(),
+ resumable_source_manager=manager,
+ **kwargs,
+ )
+ )
+ return batches
+
+
+class TestParseGerritResponse:
+ @pytest.mark.parametrize(
+ "text, expected",
+ [
+ (')]}\'\n[{"id": 1}]', [{"id": 1}]),
+ (")]}'[]", []),
+ ('[{"id": 1}]', [{"id": 1}]), # some proxies strip the prefix already
+ (' )]}\'\n{"a": 1}', {"a": 1}),
+ ],
+ )
+ def test_strips_xssi_prefix(self, text, expected):
+ assert parse_gerrit_response(text) == expected
+
+
+class TestNormalizeHost:
+ @pytest.mark.parametrize(
+ "raw, expected",
+ [
+ ("https://gerrit.example.com", "https://gerrit.example.com"),
+ ("gerrit.example.com", "https://gerrit.example.com"),
+ ("https://gerrit.example.com/", "https://gerrit.example.com"),
+ # A trailing /a (the authenticated prefix we add ourselves) is stripped, but a
+ # genuine context path (self-hosted Gerrit mounted under /r) is preserved.
+ ("https://gerrit.example.com/a", "https://gerrit.example.com"),
+ ("https://example.com/r/", "https://example.com/r"),
+ ("https://example.com/r/a", "https://example.com/r"),
+ (" gerrit.example.com ", "https://gerrit.example.com"),
+ # Plaintext HTTP to a remote host is upgraded to HTTPS so credentials aren't sent in the clear.
+ ("http://gerrit.example.com", "https://gerrit.example.com"),
+ ("http://localhost:8080", "http://localhost:8080"),
+ ("http://127.0.0.1:8080", "http://127.0.0.1:8080"),
+ ],
+ )
+ def test_normalize_host(self, raw, expected):
+ assert normalize_host(raw) == expected
+
+
+class TestChangesQuery:
+ def test_no_watermark_matches_all_statuses(self):
+ assert build_changes_query(None) == "status:open OR status:closed"
+
+ def test_watermark_appends_after_operator(self):
+ query = build_changes_query(datetime(2026, 7, 15, 16, 15, 24))
+ assert query == '(status:open OR status:closed) after:"2026-07-15 16:15:24"'
+
+ @pytest.mark.parametrize(
+ "value, expected",
+ [
+ (datetime(2026, 7, 15, 16, 15, 24), "2026-07-15 16:15:24"),
+ # Aware datetimes are converted to UTC — Gerrit timestamps are UTC.
+ (datetime(2026, 7, 15, 18, 15, 24, tzinfo=timezone(timedelta(hours=2))), "2026-07-15 16:15:24"),
+ (datetime(2026, 7, 15, 16, 15, 24, tzinfo=UTC), "2026-07-15 16:15:24"),
+ (datetime(2026, 7, 15).date(), "2026-07-15 00:00:00"),
+ ("2026-07-15 16:15:24.000000000", "2026-07-15 16:15:24.000000000"),
+ ],
+ )
+ def test_format_after_value(self, value, expected):
+ assert format_after_value(value) == expected
+
+
+class TestGetRows:
+ def test_paginates_with_offset_until_more_flag_absent(self):
+ page_1 = ")]}'\n" + '[{"id": "p~1", "updated": "t1"}, {"id": "p~2", "updated": "t2", "_more_changes": true}]'
+ page_2 = ")]}'\n" + '[{"id": "p~3", "updated": "t3"}]'
+ session, session_patcher = _patch_session([_response(text=page_1), _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="changes",
+ team_id=1,
+ logger=mock.MagicMock(),
+ resumable_source_manager=manager,
+ )
+ )
+
+ # The _more_changes marker is pagination metadata, not a row column.
+ assert batches == [
+ [{"id": "p~1", "updated": "t1"}, {"id": "p~2", "updated": "t2"}],
+ [{"id": "p~3", "updated": "t3"}],
+ ]
+
+ first_url = session.get.call_args_list[0].args[0]
+ second_url = session.get.call_args_list[1].args[0]
+ # Authenticated requests go through the /a/ prefix; page 2 skips the rows already fetched.
+ assert "/a/changes/" in first_url
+ assert "S=" not in first_url
+ assert "S=2" in second_url
+
+ # Resume state is saved after yielding a page, and only while more pages remain.
+ assert [s.offset for s in manager.saved] == [2]
+
+ def test_resumes_from_saved_offset(self):
+ page = ")]}'\n" + '[{"id": "p~51"}]'
+ session, session_patcher = _patch_session([_response(text=page)])
+ manager = _FakeResumeManager(state=GerritResumeConfig(offset=50))
+
+ with (
+ session_patcher,
+ mock.patch.object(gerrit_module, "_is_host_safe", return_value=(True, None)),
+ ):
+ list(
+ get_rows(
+ host="https://gerrit.example.com",
+ username="reviewbot",
+ http_password="secret",
+ endpoint="changes",
+ team_id=1,
+ logger=mock.MagicMock(),
+ resumable_source_manager=manager,
+ )
+ )
+
+ assert "S=50" in session.get.call_args_list[0].args[0]
+
+ def test_incremental_sync_sends_after_filter(self):
+ session, session_patcher = _patch_session([_response(text=")]}'\n[]")])
+
+ with (
+ session_patcher,
+ mock.patch.object(gerrit_module, "_is_host_safe", return_value=(True, None)),
+ ):
+ list(
+ get_rows(
+ host="https://gerrit.example.com",
+ username="reviewbot",
+ http_password="secret",
+ endpoint="changes",
+ team_id=1,
+ logger=mock.MagicMock(),
+ resumable_source_manager=_FakeResumeManager(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 7, 15, 16, 15, 24),
+ )
+ )
+
+ url = session.get.call_args_list[0].args[0]
+ assert "after%3A%222026-07-15+16%3A15%3A24%22" in url
+
+ def test_map_endpoint_rows_carry_name_from_key(self):
+ body = (
+ ")]}'\n"
+ '{"Core-Plugins": {"id": "Core-Plugins", "state": "ACTIVE"},'
+ ' "gerrit": {"id": "gerrit", "name": "gerrit", "state": "ACTIVE"}}'
+ )
+ batches = _get_all_rows("projects", [_response(text=body)])
+
+ assert batches == [
+ [
+ {"id": "Core-Plugins", "state": "ACTIVE", "name": "Core-Plugins"},
+ {"id": "gerrit", "name": "gerrit", "state": "ACTIVE"},
+ ]
+ ]
+
+ def test_anonymous_requests_skip_the_auth_prefix(self):
+ session, session_patcher = _patch_session([_response(text=")]}'\n[]")])
+
+ with (
+ session_patcher,
+ mock.patch.object(gerrit_module, "_is_host_safe", return_value=(True, None)),
+ ):
+ list(
+ get_rows(
+ host="https://gerrit.example.com",
+ username=None,
+ http_password=None,
+ endpoint="changes",
+ team_id=1,
+ logger=mock.MagicMock(),
+ resumable_source_manager=_FakeResumeManager(),
+ )
+ )
+
+ url = session.get.call_args_list[0].args[0]
+ assert "/a/" not in url
+ assert "https://gerrit.example.com/changes/" in url
+
+ def test_oversized_response_body_is_rejected(self):
+ body = ")]}'\n" + "[" + ",".join(f'{{"id": "p~{i}"}}' for i in range(50)) + "]"
+ with (
+ mock.patch.object(gerrit_module, "MAX_RESPONSE_BYTES", 8),
+ pytest.raises(gerrit_module.GerritResponseTooLargeError),
+ ):
+ _get_all_rows("changes", [_response(text=body)])
+
+ def test_slow_drip_body_returns_at_the_download_deadline(self):
+ # A hostile host can drip one byte just under the socket read timeout, which keeps a single
+ # urllib3 body read parked in recv indefinitely — the per-recv timeout resets on every byte,
+ # so it never bounds total download time, and close() from a timer does not cancel a parked
+ # read. The drain must be abandoned at MAX_DOWNLOAD_SECONDS so a shared sync worker is never
+ # held open by such a host. Exercised against a real loopback server because the regression
+ # lives in the socket/urllib3 read path, which a mocked iter_content can't reproduce.
+ port = _start_drip_server(byte_interval=0.05) # never finishes within the deadline
+ session = requests.Session()
+ response = session.get(f"http://127.0.0.1:{port}", stream=True, timeout=5)
+
+ start = time.monotonic()
+ with (
+ mock.patch.object(gerrit_module, "MAX_DOWNLOAD_SECONDS", 0.5),
+ pytest.raises(gerrit_module.GerritResponseTooLargeError),
+ ):
+ gerrit_module._read_capped_text(response)
+ # Returned at the deadline rather than blocking on the drip (which would run for minutes).
+ assert time.monotonic() - start < 3.0
+
+ def test_unsafe_host_is_rejected_before_any_request(self):
+ session, session_patcher = _patch_session([])
+
+ with (
+ session_patcher,
+ mock.patch.object(gerrit_module, "_is_host_safe", return_value=(False, "internal IP")),
+ pytest.raises(gerrit_module.GerritHostNotAllowedError),
+ ):
+ list(
+ get_rows(
+ host="https://internal.example.com",
+ username=None,
+ http_password=None,
+ endpoint="changes",
+ team_id=1,
+ logger=mock.MagicMock(),
+ resumable_source_manager=_FakeResumeManager(),
+ )
+ )
+
+ session.get.assert_not_called()
+
+
+class TestGerritSourceResponse:
+ def test_changes_response_shape(self):
+ response = gerrit_source(
+ host="https://gerrit.example.com",
+ username="reviewbot",
+ http_password="secret",
+ endpoint="changes",
+ team_id=1,
+ logger=mock.MagicMock(),
+ resumable_source_manager=_FakeResumeManager(),
+ )
+
+ assert response.name == "changes"
+ assert response.primary_keys == ["id"]
+ # Gerrit returns changes newest-first, so the watermark must only persist at job end.
+ assert response.sort_mode == "desc"
+ assert response.partition_keys == ["created"]
+ assert response.partition_mode == "datetime"
+
+ @pytest.mark.parametrize("endpoint", ["accounts", "projects", "groups"])
+ def test_dimension_endpoints_are_unpartitioned(self, endpoint):
+ response = gerrit_source(
+ host="https://gerrit.example.com",
+ username=None,
+ http_password=None,
+ endpoint=endpoint,
+ team_id=1,
+ logger=mock.MagicMock(),
+ resumable_source_manager=_FakeResumeManager(),
+ )
+
+ assert response.name == endpoint
+ assert response.primary_keys == GERRIT_ENDPOINTS[endpoint].primary_keys
+ assert response.sort_mode == "asc"
+ assert response.partition_mode is None
+
+
+class TestValidateCredentials:
+ def _validate(self, responses: list[mock.MagicMock], **kwargs: Any) -> tuple[bool, str | None]:
+ session, session_patcher = _patch_session(responses)
+ with (
+ session_patcher,
+ mock.patch.object(gerrit_module, "_is_host_safe", return_value=(True, None)),
+ ):
+ result = validate_credentials(
+ host=kwargs.pop("host", "https://gerrit.example.com"),
+ username=kwargs.pop("username", "reviewbot"),
+ http_password=kwargs.pop("http_password", "secret"),
+ team_id=kwargs.pop("team_id", 1),
+ **kwargs,
+ )
+ self.session = session
+ return result
+
+ def test_valid_credentials_probe_accounts_self(self):
+ valid, error = self._validate([_response(text=')]}\'\n{"_account_id": 1}')])
+ assert (valid, error) == (True, None)
+ assert "/a/accounts/self" in self.session.get.call_args.args[0]
+
+ def test_anonymous_probe_uses_server_version(self):
+ valid, error = self._validate(
+ [_response(text=')]}\'\n"3.10.0"')],
+ username=None,
+ http_password=None,
+ )
+ assert (valid, error) == (True, None)
+ assert self.session.get.call_args.args[0] == "https://gerrit.example.com/config/server/version"
+
+ def test_401_is_invalid(self):
+ valid, error = self._validate([_response(status_code=401, text="Unauthorized")])
+ assert valid is False
+ assert error is not None and "HTTP password" in error
+
+ def test_403_passes_at_source_create_but_fails_per_schema(self):
+ assert self._validate([_response(status_code=403)])[0] is True
+ valid, error = self._validate([_response(status_code=403)], schema_name="groups")
+ assert valid is False
+ assert error is not None and "permission" in error
+
+ def test_schema_probe_hits_the_endpoint(self):
+ self._validate([_response(text=")]}'\n{}")], schema_name="groups")
+ assert "/a/groups/?" in self.session.get.call_args.args[0]
+
+ def test_redirect_is_rejected(self):
+ valid, error = self._validate([_response(status_code=302, is_redirect=True)])
+ assert (valid, error) == (False, HOST_NOT_ALLOWED_ERROR)
+
+ def test_non_json_200_is_rejected(self):
+ valid, error = self._validate([_response(text="<html>a login page</html>")])
+ assert valid is False
+ assert error is not None and "valid API response" in error
+
+ def test_oversized_response_body_is_rejected(self):
+ with mock.patch.object(gerrit_module, "MAX_RESPONSE_BYTES", 8):
+ valid, error = self._validate([_response(text=')]}\'\n{"_account_id": 1, "padding": "xxxxxxxxxx"}')])
+ assert valid is False
+ assert error is not None and "large" in error
+
+ def test_username_without_password_is_rejected_without_a_request(self):
+ valid, error = self._validate([], http_password=None)
+ assert valid is False
+ assert error is not None and "both" in error
+ self.session.get.assert_not_called()
+
+ def test_unsafe_host_is_rejected(self):
+ session, session_patcher = _patch_session([])
+ with (
+ session_patcher,
+ mock.patch.object(gerrit_module, "_is_host_safe", return_value=(False, "internal IP")),
+ ):
+ valid, error = validate_credentials(
+ host="https://internal.example.com", username=None, http_password=None, team_id=1
+ )
+ assert (valid, error) == (False, "internal IP")
+ session.get.assert_not_called()
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
new file mode 100644
index 000000000000..d86119c8fdae
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gerrit/tests/test_gerrit_source.py
@@ -0,0 +1,132 @@
+from datetime import datetime
+
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import GerritSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.gerrit.gerrit import GerritResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.gerrit.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.gerrit.source import GerritSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestGerritSource:
+ def setup_method(self):
+ self.source = GerritSource()
+ self.team_id = 123
+ self.config = GerritSourceConfig(host="https://gerrit.example.com", username="bot", http_password="secret")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.GERRIT
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "Gerrit"
+ assert config.label == "Gerrit"
+ assert config.unreleasedSource is None
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.iconPath == "/static/services/gerrit.png"
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/gerrit"
+
+ host_field, username_field, password_field = config.fields
+ assert isinstance(host_field, SourceFieldInputConfig)
+ assert (host_field.name, host_field.required, host_field.secret) == ("host", True, False)
+ assert isinstance(username_field, SourceFieldInputConfig)
+ assert (username_field.name, username_field.required, username_field.secret) == ("username", False, False)
+ assert isinstance(password_field, SourceFieldInputConfig)
+ assert (password_field.name, password_field.required, password_field.secret) == ("http_password", False, True)
+
+ def test_lists_tables_without_credentials(self):
+ # get_schemas is a static catalog, so the public docs render the table list.
+ assert self.source.lists_tables_without_credentials is True
+
+ @pytest.mark.parametrize("expected_key", ["401 Client Error", "403 Client Error"])
+ def test_non_retryable_errors(self, expected_key):
+ assert expected_key in self.source.get_non_retryable_errors()
+
+ def test_get_schemas_returns_all_endpoints(self):
+ 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):
+ 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"):
+ assert schemas[name].supports_incremental is False
+ assert schemas[name].incremental_fields == []
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["changes"])
+ assert [s.name for s in schemas] == ["changes"]
+
+ def test_get_schemas_unknown_name_returns_empty(self):
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ @pytest.mark.parametrize("mock_return", [(True, None), (False, "Invalid Gerrit username or HTTP password")])
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.gerrit.source.validate_gerrit_credentials"
+ )
+ def test_validate_credentials(self, mock_validate, mock_return):
+ mock_validate.return_value = mock_return
+
+ result = self.source.validate_credentials(self.config, self.team_id, schema_name="groups")
+
+ assert result == mock_return
+ kwargs = mock_validate.call_args.kwargs
+ assert kwargs["host"] == "https://gerrit.example.com"
+ assert kwargs["username"] == "bot"
+ assert kwargs["http_password"] == "secret"
+ assert kwargs["team_id"] == self.team_id
+ assert kwargs["schema_name"] == "groups"
+
+ def test_get_resumable_source_manager_binds_resume_config(self):
+ inputs = mock.MagicMock()
+ manager = self.source.get_resumable_source_manager(inputs)
+ assert manager._data_class is GerritResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.gerrit.source.gerrit_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_gerrit_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "changes"
+ inputs.team_id = 42
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = datetime(2026, 7, 15, 16, 15, 24)
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ kwargs = mock_gerrit_source.call_args.kwargs
+ assert kwargs["host"] == "https://gerrit.example.com"
+ assert kwargs["username"] == "bot"
+ assert kwargs["http_password"] == "secret"
+ assert kwargs["endpoint"] == "changes"
+ assert kwargs["team_id"] == 42
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == datetime(2026, 7, 15, 16, 15, 24)
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.gerrit.source.gerrit_source")
+ def test_source_for_pipeline_drops_watermark_for_full_refresh(self, mock_gerrit_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "changes"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = datetime(2026, 7, 15, 16, 15, 24)
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_gerrit_source.call_args.kwargs["db_incremental_field_last_value"] is None
+
+ def test_canonical_descriptions_cover_endpoints(self):
+ descriptions = self.source.get_canonical_descriptions()
+ assert set(descriptions.keys()) == set(ENDPOINTS)
+
+ def test_documented_tables_render_without_credentials(self):
+ tables = {t["name"]: t for t in self.source.get_documented_tables()}
+ assert set(tables.keys()) == set(ENDPOINTS)
+ assert "Incremental" in tables["changes"]["sync_methods"]
+ assert tables["changes"]["description"]