: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 G2 import source (#84364)
Tom Owers82c453206039
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/g2/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/g2/canonical_descriptions.pynew file mode 100644index 000000000000..eb5f9c667c4d--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/g2/canonical_descriptions.py@@ -0,0 +1,77 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "products": {+ "description": "G2's public catalog of software products, including vendor, category, rating, and pricing metadata.",+ "docs_url": "https://documentation.g2.com/docs/g2-api",+ "columns": {+ "id": "Unique identifier for the product.",+ "type": "Type of product, for example Software or Hardware.",+ "detail_description": "Detailed description of the product.",+ "domain": "Primary domain of the product website.",+ "g2_url": "Full URL to the product page on G2.",+ "name": "Name of the product.",+ "public_detail_url": "Vendor website URL for the product.",+ "review_count": "Total number of reviews for the product.",+ "slug": "URL-friendly identifier for the product.",+ "write_review_url": "URL to write a review for this product on G2.",+ "image_url": "URL to the product logo or favicon.",+ "pricing_tiers": "List of pricing tiers with prices.",+ "star_rating": "Average star rating, on a 1-5 scale.",+ },+ },+ "categories": {+ "description": "G2's product category taxonomy.",+ "docs_url": "https://documentation.g2.com/docs/g2-api",+ "columns": {+ "id": "Unique identifier for the category.",+ "uuid": "Category UUID (duplicates id).",+ "name": "Category name.",+ "slug": "URL-friendly identifier for the category.",+ "description": "Category description.",+ "updated_at": "When the category was last updated.",+ },+ },+ "vendors": {+ "description": "Vendors (software companies) listed on G2.",+ "docs_url": "https://documentation.g2.com/docs/g2-api",+ "columns": {+ "id": "Unique identifier for the vendor.",+ "name": "Vendor name.",+ "description": "Vendor description.",+ "company_website": "Vendor company website URL.",+ "slug": "URL-friendly identifier for the vendor.",+ "public_products_count": "Number of public products the vendor has on G2.",+ "updated_at": "When the vendor record was last updated.",+ },+ },+ "reviews": {+ "description": "Published reviews for your G2 product.",+ "docs_url": "https://documentation.g2.com/docs/g2-api",+ "columns": {+ "id": "Unique identifier for the review.",+ "answers": "Formatted question answers, such as pros and cons.",+ "attribution": "Attribution information for syndication.",+ "comments_present": "Whether comments are present on the review.",+ "country_name": "Country of the reviewer.",+ "default_sort": "Default sort score for the review.",+ "is_public": "Whether the review is public.",+ "official_response_present": "Whether the vendor has responded.",+ "percent_complete": "Completion percentage of the review.",+ "product_name": "Name of the reviewed product.",+ "published_at": "When the review was published.",+ "regions": "Geographic regions associated with the reviewer.",+ "review_incentive": "Whether the review was incentivized.",+ "slug": "URL-friendly identifier for the review.",+ "source": "Source of the review, for example organic or incentivized.",+ "star_rating": "Star rating, on a 1-5 scale.",+ "submitted_at": "When the review was submitted.",+ "title": "Review title.",+ "url": "Full URL to the review on G2.",+ "user_updated_at": "When the reviewer's profile was last updated.",+ "verified_current_user": "Whether the reviewer is a verified current user.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/g2/g2.py b/products/warehouse_sources/backend/temporal/data_imports/sources/g2/g2.pynew file mode 100644index 000000000000..82f7e0a12040--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/g2/g2.py@@ -0,0 +1,176 @@+from collections.abc import Iterator+from typing import Any+from urllib.parse import urlencode++import requests+from structlog.types import FilteringBoundLogger++from posthog.dataclasses import frozen++from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.batcher import Batcher+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.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.g2.settings import (+ G2_BASE_URL,+ G2_ENDPOINTS,+ PAGE_SIZE,+)+++class MissingProductIdError(Exception):+ pass+++@frozen+class G2ResumeConfig:+ next_url: str | None = None+++def _headers(access_token: str) -> dict[str, str]:+ return {"Authorization": f"Bearer {access_token}", "Accept": "application/vnd.api+json"}+++def _flatten_item(item: dict[str, Any]) -> dict[str, Any]:+ """Merge a JSON:API resource's `attributes` object into its row root, alongside its `id`.++ `rest_source`'s declarative `data_selector` can pull the `data` array out of the envelope, but+ can't reshape each item, so G2's `{id, type, attributes: {...}}` resources are flattened here.+ """+ row = dict(item.get("attributes") or {})+ row["id"] = item.get("id")+ return row+++def _extract_error_detail(response: requests.Response) -> str | None:+ """Pull the human-readable reason out of a G2 JSON:API error body, if there is one."""+ try:+ errors = response.json().get("errors", [])+ titles = [str(error["title"]) for error in errors if isinstance(error, dict) and error.get("title")]+ return "; ".join(titles)[:500] if titles else None+ except Exception:+ return None+++def _raise_for_status_with_detail(response: requests.Response) -> None:+ try:+ response.raise_for_status()+ except requests.HTTPError as exc:+ detail = _extract_error_detail(response)+ if detail:+ raise requests.HTTPError(f"{exc} ({detail})", response=response) from exc+ raise+++def _build_url(base_url: str, params: dict[str, Any]) -> str:+ if not params:+ return base_url+ return f"{base_url}?{urlencode(params)}"+++def _ensure_g2_url(url: str) -> str:+ """Pin a pagination/resume URL to the G2 API origin before it carries the bearer token.++ `links.next` is response-controlled and resume URLs are replayed from persisted state, so+ refuse anything outside the G2 API origin — the token must never be sent to a host we didn't+ choose.+ """+ if not url.startswith(f"{G2_BASE_URL}/"):+ raise ValueError(f"Refusing to follow non-G2 URL: {url}")+ return url+++def _fetch_page(session: requests.Session, url: str, headers: dict[str, str]) -> dict[str, Any]:+ response = session.get(url, headers=headers, timeout=30)+ if not response.ok:+ _raise_for_status_with_detail(response)+ return response.json()+++def validate_credentials(access_token: str, api_version: str) -> tuple[bool, int | None]:+ # `/categories` requires no scope, so a 200 here confirms the token itself is genuine without+ # depending on any per-endpoint permission the account may not have granted yet.+ url = _build_url(f"{G2_BASE_URL}/api/{api_version}/categories", {"page[size]": 1})+ return validate_via_probe(+ lambda: make_tracked_session(redact_values=(access_token,)),+ url,+ headers=_headers(access_token),+ )+++def get_rows(+ access_token: str,+ endpoint: str,+ product_id: str,+ api_version: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[G2ResumeConfig],+) -> Iterator[Any]:+ config = G2_ENDPOINTS[endpoint]+ if config.requires_product_id and not product_id:+ raise MissingProductIdError(f"G2 product ID is required to sync {endpoint}")++ path = config.path.format(product_id=product_id) if config.requires_product_id else config.path+ headers = _headers(access_token)+ # `allow_redirects=False`: defense-in-depth so a redirect can't carry the bearer token off+ # the validated host, on top of the origin check in `_ensure_g2_url`.+ session = make_tracked_session(redact_values=(access_token,), allow_redirects=False)+ batcher = Batcher(logger=logger, chunk_size=2000, chunk_size_bytes=100 * 1024 * 1024)++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume is not None and resume.next_url:+ url = _ensure_g2_url(resume.next_url)+ logger.debug(f"G2: resuming {endpoint} from URL: {url}")+ else:+ url = _build_url(f"{G2_BASE_URL}/api/{api_version}{path}", {"page[size]": PAGE_SIZE})++ while True:+ data = _fetch_page(session, url, headers)+ items = data.get("data", [])+ next_url = data.get("links", {}).get("next")+ next_url = _ensure_g2_url(next_url) if next_url else None++ for item in items:+ batcher.batch(_flatten_item(item))++ if batcher.should_yield():+ yield batcher.get_table()+ # Save AFTER yielding, and only when another page remains, so a crash re-yields the+ # last batch (merge dedupes on primary key) instead of skipping it.+ if next_url:+ resumable_source_manager.save_state(G2ResumeConfig(next_url=next_url))++ if not next_url:+ break+ url = next_url++ if batcher.should_yield(include_incomplete_chunk=True):+ yield batcher.get_table()+++def g2_source(+ access_token: str,+ endpoint: str,+ product_id: str,+ api_version: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[G2ResumeConfig],+) -> SourceResponse:+ config = G2_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ access_token=access_token,+ endpoint=endpoint,+ product_id=product_id,+ api_version=api_version,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ ),+ primary_keys=config.primary_keys,+ # G2's OpenAPI spec documents no `sort` parameter or default order for any list endpoint,+ # so no sync here can claim a verified direction (see settings.py).+ sort_mode=None,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/g2/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/g2/settings.pynew file mode 100644index 000000000000..f9b618de6428--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/g2/settings.py@@ -0,0 +1,49 @@+from posthog.dataclasses import frozen++from products.warehouse_sources.backend.types import IncrementalField++G2_API_VERSION = "v2"+G2_BASE_URL = "https://data.g2.com"+# G2 caps page[size] at 250 and defaults to 25.+PAGE_SIZE = 250+++@frozen+class G2EndpointConfig:+ # Relative to /api/{version}. `{product_id}` is filled in from the source's product_id field.+ path: str+ primary_keys: list[str]+ requires_product_id: bool = False+ description: str | None = None+++G2_ENDPOINTS: dict[str, G2EndpointConfig] = {+ "products": G2EndpointConfig(+ path="/products",+ primary_keys=["id"],+ description="G2's public catalog of software products.",+ ),+ "categories": G2EndpointConfig(+ path="/categories",+ primary_keys=["id"],+ description="G2's product category taxonomy.",+ ),+ "vendors": G2EndpointConfig(+ path="/vendors",+ primary_keys=["id"],+ description="Vendors (software companies) listed on G2.",+ ),+ "reviews": G2EndpointConfig(+ path="/products/{product_id}/reviews",+ primary_keys=["id"],+ requires_product_id=True,+ description="Published reviews for your G2 product.",+ ),+}++ENDPOINTS = tuple(G2_ENDPOINTS.keys())++# G2's OpenAPI spec documents no `sort` parameter and no guaranteed default order for any list+# endpoint, so a cursor watermark built from `filter[updated_at_gt]` couldn't be verified safe —+# every endpoint ships full refresh only, even though categories/vendors/reviews accept that filter.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/g2/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/g2/source.pyindex 9082d3d67f6d..39160af6c94d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/g2/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/g2/source.py@@ -1,19 +1,46 @@-from typing import cast+from typing import Optional, castfrom 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.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,+ build_endpoint_schemas,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.g2.g2 import (+ G2ResumeConfig,+ g2_source,+ validate_credentials as validate_g2_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.g2.settings import (+ ENDPOINTS,+ G2_BASE_URL,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.g2 import G2SourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class G2Source(SimpleSource[G2SourceConfig]):+class G2Source(ResumableSource[G2SourceConfig, G2ResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+ supported_versions = ("v2",)+ default_version = "v2"+ api_docs_url = "https://documentation.g2.com/docs/g2-api"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.G2@@ -24,7 +51,101 @@ class G2Source(SimpleSource[G2SourceConfig]):name=SchemaExternalDataSourceType.G2,category=DataWarehouseSourceCategory.MARKETING___EMAIL,label="G2 (G2.com, Inc.)",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your G2 access token to pull your product's reviews and G2's product catalog into the PostHog Data warehouse.++Create an account and generate an access token in the [G2 Developer Portal](https://my.g2.com/developers). Grant read access to the tables you want to sync:+- Products and vendors need no scope+- Reviews need the `products.reviews.read` scope++Access tokens expire one year after creation and must be regenerated.+""",iconPath="/static/services/g2.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/g2",+ keywords=["buyer intent", "reviews"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="access_token",+ label="Access token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="product_id",+ label="G2 product ID or slug",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="salesforce-sales-cloud",+ secret=False,+ caption="Used to sync reviews for your product. Find it in your G2 vendor dashboard, or in your product's G2 URL.",+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.g2.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ f"401 Client Error: Unauthorized for url: {G2_BASE_URL}": "Your G2 access token is invalid or has expired. Generate a new one in the G2 Developer Portal, then reconnect.",+ f"403 Client Error: Forbidden for url: {G2_BASE_URL}": "Your G2 access token does not have read access to this table. Grant it in the G2 Developer Portal, then reconnect.",+ "G2 product ID is required": "Add your G2 product ID to this source's settings, then reconnect.",+ }++ def get_schemas(+ self,+ config: G2SourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ # G2's global product catalog runs into the hundreds of thousands of rows and is full+ # refresh only, so it's opt-in rather than selected for every new connection.+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names, should_sync_default={"products": False})++ def validate_credentials(+ self,+ config: G2SourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ is_valid, status_code = validate_g2_credentials(config.access_token, self.resolve_api_version(api_version))+ if is_valid:+ return True, None++ if status_code == 403 and schema_name is None:+ # A genuine token that can't read categories still connects: per-endpoint scopes are+ # granted individually, so the account may only be entitled to tables the user picks.+ return True, None++ return False, "Invalid G2 access token"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[G2ResumeConfig]:+ return ResumableSourceManager[G2ResumeConfig](inputs, G2ResumeConfig)++ def source_for_pipeline(+ self,+ config: G2SourceConfig,+ resumable_source_manager: ResumableSourceManager[G2ResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return g2_source(+ access_token=config.access_token,+ endpoint=inputs.schema_name,+ product_id=config.product_id,+ api_version=self.resolve_api_version(inputs.api_version),+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/g2/tests/test_g2.py b/products/warehouse_sources/backend/temporal/data_imports/sources/g2/tests/test_g2.pynew file mode 100644index 000000000000..92ad7121ed87--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/g2/tests/test_g2.py@@ -0,0 +1,286 @@+from typing import Any, cast++import pytest+from unittest import mock++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.g2 import g2+from products.warehouse_sources.backend.temporal.data_imports.sources.g2.g2 import (+ G2ResumeConfig,+ MissingProductIdError,+ _build_url,+ _ensure_g2_url,+ _extract_error_detail,+ _flatten_item,+ g2_source,+ get_rows,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.g2.settings import G2_ENDPOINTS+++class _FakeResumeManager(ResumableSourceManager[G2ResumeConfig]):+ def __init__(self, state: G2ResumeConfig | None = None) -> None:+ self.state = state+ self.saved: list[G2ResumeConfig] = []++ def can_resume(self) -> bool:+ return self.state is not None++ def load_state(self) -> G2ResumeConfig | None:+ return self.state++ def save_state(self, data: G2ResumeConfig) -> None:+ self.saved.append(data)+++def _page(items: list[dict[str, Any]], next_url: str | None = None) -> dict[str, Any]:+ return {"data": items, "links": {"self": "irrelevant", "next": next_url, "prev": None}}+++def _resource(item_id: str, attributes: dict[str, Any] | None = None) -> dict[str, Any]:+ return {"id": item_id, "type": "products", "attributes": attributes or {}}+++def _collect_rows(+ monkeypatch: pytest.MonkeyPatch,+ pages: dict[str, dict[str, Any]],+ endpoint: str = "products",+ product_id: str = "",+ manager: ResumableSourceManager[G2ResumeConfig] | None = None,+) -> list[dict[str, Any]]:+ def fake_fetch(session: Any, url: str, headers: dict[str, str]) -> dict[str, Any]:+ return pages[url]++ monkeypatch.setattr(g2, "_fetch_page", fake_fetch)++ rows: list[dict[str, Any]] = []+ for table in cast(+ "list[Any]",+ list(+ get_rows(+ access_token="token-1",+ endpoint=endpoint,+ product_id=product_id,+ api_version="v2",+ logger=mock.MagicMock(),+ resumable_source_manager=manager or _FakeResumeManager(),+ )+ ),+ ):+ rows.extend(table.to_pylist())+ return rows+++class TestFlattenItem:+ def test_merges_attributes_into_root_alongside_id(self) -> None:+ item = _resource("p1", {"name": "Product One", "star_rating": 4.5})+ assert _flatten_item(item) == {"id": "p1", "name": "Product One", "star_rating": 4.5}++ def test_missing_attributes_yields_just_the_id(self) -> None:+ assert _flatten_item({"id": "p1", "type": "products"}) == {"id": "p1"}+++class TestBuildUrl:+ def test_no_params_returns_bare_url(self) -> None:+ assert _build_url("https://data.g2.com/api/v2/products", {}) == "https://data.g2.com/api/v2/products"++ def test_encodes_bracketed_params(self) -> None:+ url = _build_url("https://data.g2.com/api/v2/products", {"page[size]": 250})+ assert url == "https://data.g2.com/api/v2/products?page%5Bsize%5D=250"+++class TestEnsureG2Url:+ def test_g2_origin_is_returned_unchanged(self) -> None:+ url = "https://data.g2.com/api/v2/products?page%5Bafter%5D=cursor-1"+ assert _ensure_g2_url(url) == url++ @parameterized.expand(+ [+ # A pagination link or poisoned resume state pointing anywhere but the G2 API+ # origin would receive the bearer token — refuse it.+ ("foreign_host", "https://evil.example.com/api/v2/products"),+ ("http_downgrade", "http://data.g2.com/api/v2/products"),+ ("userinfo_trick", "https://[email protected]/api/v2/products"),+ ("host_suffix", "https://data.g2.com.evil.example.com/api/v2/products"),+ ("path_prefix_escape", "https://data.g2.comevil/api/v2/products"),+ ]+ )+ def test_non_g2_urls_are_refused(self, _name: str, url: str) -> None:+ with pytest.raises(ValueError):+ _ensure_g2_url(url)+++class TestExtractErrorDetail:+ def test_extracts_joined_titles(self) -> None:+ response = mock.MagicMock()+ response.json.return_value = {"errors": [{"status": "403", "title": "Forbidden"}]}+ assert _extract_error_detail(response) == "Forbidden"++ def test_returns_none_for_unparseable_body(self) -> None:+ response = mock.MagicMock()+ response.json.side_effect = ValueError("not json")+ assert _extract_error_detail(response) is None+++class TestGetRowsPagination:+ def test_follows_links_next_and_flattens_rows(self, monkeypatch: pytest.MonkeyPatch) -> None:+ first_url = "https://data.g2.com/api/v2/products?page%5Bsize%5D=250"+ next_url = "https://data.g2.com/api/v2/products?page%5Bafter%5D=cursor-1&page%5Bsize%5D=250"+ pages = {+ first_url: _page([_resource("p1", {"name": "One"})], next_url=next_url),+ next_url: _page([_resource("p2", {"name": "Two"})]),+ }++ rows = _collect_rows(monkeypatch, pages)++ assert rows == [{"id": "p1", "name": "One"}, {"id": "p2", "name": "Two"}]++ def test_stops_when_next_is_absent(self, monkeypatch: pytest.MonkeyPatch) -> None:+ first_url = "https://data.g2.com/api/v2/categories?page%5Bsize%5D=250"+ pages = {first_url: _page([_resource("c1")])}++ rows = _collect_rows(monkeypatch, pages, endpoint="categories")++ assert len(rows) == 1++ def test_resumes_from_saved_next_url(self, monkeypatch: pytest.MonkeyPatch) -> None:+ resume_url = "https://data.g2.com/api/v2/products?page%5Bafter%5D=cursor-9"+ pages = {resume_url: _page([_resource("p9")])}++ rows = _collect_rows(monkeypatch, pages, manager=_FakeResumeManager(G2ResumeConfig(next_url=resume_url)))++ # No request for the first-page URL is wired, so resuming past it would raise KeyError.+ assert rows == [{"id": "p9"}]++ def test_refuses_a_links_next_pointing_off_the_g2_origin(self, monkeypatch: pytest.MonkeyPatch) -> None:+ first_url = "https://data.g2.com/api/v2/products?page%5Bsize%5D=250"+ pages = {first_url: _page([_resource("p1")], next_url="https://evil.example.com/steal-token")}++ with pytest.raises(ValueError):+ _collect_rows(monkeypatch, pages)++ def test_refuses_a_saved_resume_url_pointing_off_the_g2_origin(self, monkeypatch: pytest.MonkeyPatch) -> None:+ poisoned_url = "https://evil.example.com/steal-token"++ with pytest.raises(ValueError):+ _collect_rows(monkeypatch, {}, manager=_FakeResumeManager(G2ResumeConfig(next_url=poisoned_url)))++ def test_reviews_path_is_formatted_with_product_id(self, monkeypatch: pytest.MonkeyPatch) -> None:+ url = "https://data.g2.com/api/v2/products/prod-123/reviews?page%5Bsize%5D=250"+ pages = {url: _page([_resource("r1", {"title": "Great"})])}++ rows = _collect_rows(monkeypatch, pages, endpoint="reviews", product_id="prod-123")++ assert rows == [{"id": "r1", "title": "Great"}]++ def test_missing_product_id_raises_for_reviews(self, monkeypatch: pytest.MonkeyPatch) -> None:+ with pytest.raises(MissingProductIdError):+ _collect_rows(monkeypatch, {}, endpoint="reviews", product_id="")++ def test_missing_product_id_is_fine_for_endpoints_that_do_not_need_it(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ url = "https://data.g2.com/api/v2/vendors?page%5Bsize%5D=250"+ pages = {url: _page([_resource("v1")])}++ rows = _collect_rows(monkeypatch, pages, endpoint="vendors", product_id="")++ assert rows == [{"id": "v1"}]+++class TestResumeStateSaving:+ def _drive_with_small_chunks(+ self, monkeypatch: pytest.MonkeyPatch, pages: dict[str, dict[str, Any]]+ ) -> _FakeResumeManager:+ real_batcher_cls = g2.Batcher++ def small_batcher(*args: Any, **kwargs: Any) -> Any:+ kwargs["chunk_size"] = 1+ return real_batcher_cls(*args, **kwargs)++ monkeypatch.setattr(g2, "Batcher", small_batcher)++ def fake_fetch(session: Any, url: str, headers: dict[str, str]) -> dict[str, Any]:+ return pages[url]++ monkeypatch.setattr(g2, "_fetch_page", fake_fetch)++ manager = _FakeResumeManager()+ for _table in get_rows(+ access_token="token-1",+ endpoint="products",+ product_id="",+ api_version="v2",+ logger=mock.MagicMock(),+ resumable_source_manager=manager,+ ):+ pass+ return manager++ def test_saves_state_only_while_a_later_page_remains(self, monkeypatch: pytest.MonkeyPatch) -> None:+ first_url = "https://data.g2.com/api/v2/products?page%5Bsize%5D=250"+ second_url = "https://data.g2.com/api/v2/products?page%5Bafter%5D=c1"+ pages = {+ first_url: _page([_resource("p1")], next_url=second_url),+ second_url: _page([_resource("p2")]),+ }++ manager = self._drive_with_small_chunks(monkeypatch, pages)++ # The first (non-terminal) page saves a checkpoint; the terminal page does not, so a+ # resumed run stops re-fetching once the sync actually finished.+ assert manager.saved == [G2ResumeConfig(next_url=second_url)]+++class TestValidateCredentials:+ @parameterized.expand(+ [+ ("ok", 200, True),+ ("unauthorized", 401, False),+ ("forbidden", 403, False),+ ]+ )+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.g2.g2.make_tracked_session")+ def test_reports_the_probe_status(+ self, _name: str, status_code: int, expected: bool, mock_session_factory: mock.MagicMock+ ) -> None:+ mock_session_factory.return_value.get.return_value = mock.MagicMock(status_code=status_code)++ assert validate_credentials("token-1", "v2") == (expected, status_code)++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.g2.g2.make_tracked_session")+ def test_transport_failure_does_not_raise(self, mock_session_factory: mock.MagicMock) -> None:+ mock_session_factory.return_value.get.side_effect = requests.ConnectionError("boom")++ assert validate_credentials("token-1", "v2") == (False, None)+++class TestG2Source:+ @parameterized.expand([(name, config.primary_keys) for name, config in G2_ENDPOINTS.items()])+ def test_primary_keys_match_settings(self, endpoint: str, primary_keys: list[str]) -> None:+ response = g2_source(+ access_token="token-1",+ endpoint=endpoint,+ product_id="prod-1",+ api_version="v2",+ logger=mock.MagicMock(),+ resumable_source_manager=_FakeResumeManager(),+ )+ assert response.primary_keys == primary_keys++ def test_sort_mode_is_unset(self) -> None:+ # No G2 list endpoint documents a `sort` param or default order, so no endpoint may claim+ # a verified direction (see settings.py).+ response = g2_source(+ access_token="token-1",+ endpoint="products",+ product_id="",+ api_version="v2",+ logger=mock.MagicMock(),+ resumable_source_manager=_FakeResumeManager(),+ )+ assert response.sort_mode is Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/g2/tests/test_g2_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/g2/tests/test_g2_source.pynew file mode 100644index 000000000000..8244497a2af8--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/g2/tests/test_g2_source.py@@ -0,0 +1,146 @@+from unittest import mock++from parameterized import parameterized++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.g2.g2 import G2ResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.g2.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.g2.source import G2Source+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.g2 import G2SourceConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType++VALIDATE_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.g2.source.validate_g2_credentials"+++class TestG2Source:+ def setup_method(self) -> None:+ self.source = G2Source()+ self.team_id = 123+ self.config = G2SourceConfig(access_token="token-1", product_id="prod-1")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.G2++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config++ assert config.name.value == "G2"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.iconPath == "/static/services/g2.png"+ # A finished source ships visible: unreleasedSource would hide it from every user.+ assert config.unreleasedSource is None++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["access_token", "product_id"]++ def test_access_token_field_is_a_secret_password(self) -> None:+ config = self.source.get_source_config+ token_field = next(+ f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "access_token"+ )++ assert token_field.type == SourceFieldInputConfigType.PASSWORD+ assert token_field.secret is True+ assert token_field.required is True++ def test_product_id_field_is_required_plain_text(self) -> None:+ config = self.source.get_source_config+ product_field = next(+ f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "product_id"+ )++ assert product_field.type == SourceFieldInputConfigType.TEXT+ assert product_field.secret is False+ assert product_field.required is True++ @parameterized.expand(+ [+ ("unauthorized", "401 Client Error: Unauthorized for url: https://data.g2.com/api/v2/categories"),+ ("forbidden", "403 Client Error: Forbidden for url: https://data.g2.com/api/v2/products/x/reviews"),+ ("missing_product_id", "G2 product ID is required to sync reviews"),+ ]+ )+ def test_non_retryable_errors_match_auth_failures(self, _name: str, observed_error: str) -> None:+ assert any(key in observed_error for key in self.source.get_non_retryable_errors())++ @parameterized.expand(+ [+ ("other_vendor", "401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers"),+ ("server_error", "500 Server Error for url: https://data.g2.com/api/v2/products"),+ ]+ )+ def test_non_retryable_errors_do_not_match_unrelated(self, _name: str, other_error: str) -> None:+ assert not any(key in other_error for key in self.source.get_non_retryable_errors())++ def test_get_schemas_are_full_refresh_only(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)++ assert {schema.name for schema in schemas} == set(ENDPOINTS)+ # No G2 list endpoint documents a `sort` param, so claiming incremental would ship a+ # cursor watermark on an order the API never promised.+ for schema in schemas:+ assert schema.supports_incremental is False+ assert schema.supports_append is False+ assert schema.incremental_fields == []++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["reviews"])+ assert [schema.name for schema in schemas] == ["reviews"]++ def test_products_catalog_is_opt_in(self) -> None:+ # G2's global product catalog runs into the hundreds of thousands of rows, so it must not+ # be silently enabled for every new connection.+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}+ assert schemas["products"].should_sync_default is False+ assert schemas["reviews"].should_sync_default is True++ @parameterized.expand(+ [+ ("valid", (True, 200), None, True, None),+ ("bad_token", (False, 401), None, False, "Invalid G2 access token"),+ ("unreachable", (False, None), None, False, "Invalid G2 access token"),+ # 403 at connect time is a real token without every scope granted — per-endpoint+ # scoping means the account may only want a subset of tables.+ ("forbidden_at_connect", (False, 403), None, True, None),+ ("forbidden_for_schema", (False, 403), "reviews", False, "Invalid G2 access token"),+ ]+ )+ def test_validate_credentials(+ self, _name: str, probe_result: tuple[bool, int | None], schema_name, expected_valid, expected_message+ ) -> None:+ with mock.patch(VALIDATE_PATCH, return_value=probe_result) as mock_validate:+ is_valid, error_message = self.source.validate_credentials(+ self.config, self.team_id, schema_name=schema_name+ )++ assert is_valid is expected_valid+ assert error_message == expected_message+ mock_validate.assert_called_once_with("token-1", "v2")++ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(mock.MagicMock())++ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is G2ResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.g2.source.g2_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_g2_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "reviews"+ inputs.api_version = None+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ kwargs = mock_g2_source.call_args.kwargs+ assert kwargs["access_token"] == "token-1"+ assert kwargs["product_id"] == "prod-1"+ assert kwargs["endpoint"] == "reviews"+ assert kwargs["resumable_source_manager"] is manager+ # An unpinned source must still send a version, or every request 404s off /api/.+ assert kwargs["api_version"] == "v2"++ def test_canonical_descriptions_cover_declared_endpoints(self) -> None:+ assert set(self.source.get_canonical_descriptions().keys()) == set(ENDPOINTS)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/g2.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/g2.pyindex 33025c08fac7..f56b7548fe36 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/g2.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/g2.py@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass G2SourceConfig(config.Config):- pass+ access_token: str+ product_id: str