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.

fix(warehouse): check HubSpot leads scope before offering or syncing it (#74909)

posthog[bot]4be68948008c
diff --git a/products/warehouse_sources/backend/models/external_data_schema.py b/products/warehouse_sources/backend/models/external_data_schema.py
index 0d90652d6cc2..44cca4882eb2 100644
--- a/products/warehouse_sources/backend/models/external_data_schema.py
+++ b/products/warehouse_sources/backend/models/external_data_schema.py
@@ -1376,7 +1376,10 @@ def sync_old_schemas_with_new_schemas(
team_id=team_id, name=schema, source_id=source_id, deleted=False
)
for s in schemas_to_check:
- if s.table_id is None:
+ # Only rows nobody enabled disappear entirely. A user-enabled row survives as visibly
+ # disabled, because soft-deleting it would silently discard the user's selection (e.g.
+ # a scope-gated table the source stopped offering before its first successful sync).
+ if s.table_id is None and not s.should_sync:
s.soft_delete()
deleted_schemas.append(schema)
else:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/helpers.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/helpers.py
index 69a77946f176..550054d33a76 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/helpers.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/helpers.py
@@ -12,6 +12,7 @@ from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_ex
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
from .auth import HubspotRetryableError, hubspot_refresh_access_token
+from .scopes import HubspotForbiddenError, missing_scope_error, scope_gated_object_for_url
from .settings import OBJECT_TYPE_PLURAL, apply_crm_api_version
BASE_URL = "https://api.hubapi.com/"
@@ -39,6 +40,23 @@ def get_url(endpoint: str) -> str:
return urllib.parse.urljoin(BASE_URL, endpoint)
+def raise_for_hubspot_status(response: requests.Response, url: str) -> None:
+ """Raise for a non-2xx HubSpot response, mapping 403 to a non-reportable failure.
+
+ A 403 means the connected portal's grant can't read this object, which the customer fixes by
+ reconnecting (or by turning the table off) — retrying and reporting it as a crash helps nobody.
+ When the object sits behind an optional scope, name that scope so the failure says what to do.
+ """
+ if response.status_code == HTTPStatus.FORBIDDEN:
+ gated = scope_gated_object_for_url(url)
+ if gated is not None:
+ raise missing_scope_error(gated.endpoint, gated.scope)
+ # Keep requests' own wording: `get_non_retryable_errors` matches on it.
+ raise HubspotForbiddenError(f"403 Client Error: Forbidden for url: {url}")
+
+ response.raise_for_status()
+
+
def _get_headers(api_key: str) -> dict[str, str]:
"""
Return a dictionary of HTTP headers to use for API requests, including the specified API key.
@@ -166,7 +184,7 @@ def fetch_data(
if _is_retryable_status(r.status_code):
raise HubspotRetryableError(f"Hubspot API error (retryable): status={r.status_code}, url={page_url}")
- r.raise_for_status()
+ raise_for_hubspot_status(r, page_url)
# See hubspot.fetch_page: a truncated/partial body is transient, so retry rather than crash.
try:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/hubspot.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/hubspot.py
index 3ddc24dd5a5d..3b4558b669f9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/hubspot.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/hubspot.py
@@ -38,6 +38,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.hubspot.he
BASE_URL,
_get_headers,
_get_property_names,
+ raise_for_hubspot_status,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.hubspot.metadata import METADATA_FETCHERS
from products.warehouse_sources.backend.temporal.data_imports.sources.hubspot.settings import (
@@ -366,7 +367,7 @@ def get_rows(
if not response.ok:
logger.error(f"Hubspot API error: status={response.status_code}, body={response.text}, url={page_url}")
- response.raise_for_status()
+ raise_for_hubspot_status(response, page_url)
# Parse inside the retry so a truncated/partial body (JSONDecodeError, e.g. an
# "Unterminated string" mid-stream) is reissued like a 429/5xx instead of bubbling
@@ -480,7 +481,7 @@ def _batch_read_associations(
logger.error(
f"Hubspot v4 associations error: status={response.status_code}, body={response.text}, url={url}"
)
- response.raise_for_status()
+ raise_for_hubspot_status(response, url)
# See fetch_page: a truncated/partial body is transient, so retry rather than crash.
try:
@@ -648,7 +649,7 @@ def get_rows_via_search(
if not response.ok:
logger.error(f"Hubspot search error: status={response.status_code}, body={response.text}, url={search_url}")
- response.raise_for_status()
+ raise_for_hubspot_status(response, search_url)
# See fetch_page: a truncated/partial body is transient, so retry rather than crash.
try:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/scopes.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/scopes.py
new file mode 100644
index 000000000000..004fad07795d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/scopes.py
@@ -0,0 +1,103 @@
+"""Scope gating for HubSpot objects behind an optional OAuth scope.
+
+Some CRM objects need a scope that only exists on certain HubSpot plans, so we request it as an
+`optional_scope` (see `OauthIntegration.oauth_config_for_kind`). HubSpot grants optional scopes
+silently: the connection authorizes fine without them and the gap only shows up as a 403 once the
+table is synced. These helpers let the source check the scopes HubSpot reported at connect time
+before offering or syncing such a table, and turn a 403 that slips through into an actionable,
+non-crash failure.
+"""
+
+from collections.abc import Mapping
+from typing import Any
+from urllib.parse import urlsplit
+
+from posthog.dataclasses import frozen
+from posthog.temporal.common.errors import NonReportableError
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.hubspot.settings import HUBSPOT_ENDPOINTS
+
+# Objects whose read scope is optional, mapped to the scope they need.
+SCOPE_GATED_OBJECTS: dict[str, str] = {
+ name: endpoint.required_scope for name, endpoint in HUBSPOT_ENDPOINTS.items() if endpoint.required_scope
+}
+
+
+class HubspotForbiddenError(NonReportableError):
+ """HubSpot answered 403.
+
+ The grant can't read the requested object: a permission or plan problem on the connected
+ portal, never a PostHog defect. Subclasses NonReportableError so the job still fails with the
+ message (`get_non_retryable_errors` maps it to a friendly one) without minting an
+ error-tracking issue per sync.
+ """
+
+
+class HubspotMissingScopeError(HubspotForbiddenError):
+ """A selected object needs an optional scope this connection wasn't granted."""
+
+
+def missing_scope_message(endpoint: str, scope: str) -> str:
+ """Internal error message for `endpoint` being unreadable without `scope`.
+
+ `HubspotSource.get_non_retryable_errors` matches on this text, so both must be built from the
+ same helper.
+ """
+ return f"Hubspot {endpoint} sync needs the {scope} scope, which this connection was not granted"
+
+
+def missing_scope_error(endpoint: str, scope: str) -> HubspotMissingScopeError:
+ return HubspotMissingScopeError(missing_scope_message(endpoint, scope))
+
+
+def granted_scopes(integration_config: Mapping[str, Any] | None) -> frozenset[str] | None:
+ """Scopes HubSpot reported when the connection was authorized.
+
+ None when the connection carries no scope list (it predates us storing one), which is not
+ evidence of a missing grant: callers must treat it as unknown and let the sync find out.
+ """
+ raw = (integration_config or {}).get("scopes")
+ if isinstance(raw, str):
+ # HubSpot's token-info endpoint returns a list, but tolerate the delimited-string shape
+ # other providers persist so an odd row reads as scopes rather than as unknown.
+ parts = raw.replace(",", " ").split()
+ elif isinstance(raw, list):
+ parts = [str(scope).strip() for scope in raw]
+ else:
+ return None
+
+ scopes = frozenset(scope for scope in parts if scope)
+ return scopes or None
+
+
+def missing_scope_for_endpoint(endpoint: str, integration_config: Mapping[str, Any] | None) -> str | None:
+ """The scope `endpoint` needs and this connection provably lacks, else None."""
+ scope = SCOPE_GATED_OBJECTS.get(endpoint)
+ if scope is None:
+ return None
+
+ scopes = granted_scopes(integration_config)
+ if scopes is None:
+ return None
+
+ return None if scope in scopes else scope
+
+
+@frozen
+class ScopeGatedObject:
+ endpoint: str
+ scope: str
+
+
+def scope_gated_object_for_url(url: str) -> ScopeGatedObject | None:
+ """The scope-gated object `url` targets, else None.
+
+ Matches on a whole path segment so both the object endpoints (`/crm/objects/2026-03/leads`)
+ and the property-discovery endpoint (`/crm/properties/2026-03/leads`) resolve, across API
+ version layouts.
+ """
+ segments = urlsplit(url).path.strip("/").split("/")
+ for name, scope in SCOPE_GATED_OBJECTS.items():
+ if name in segments:
+ return ScopeGatedObject(endpoint=name, scope=scope)
+ return None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/settings.py
index 297366976330..594139e9bc6a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/settings.py
@@ -5,6 +5,8 @@ from dataclasses import dataclass, field
from datetime import datetime
from typing import Optional
+from posthog.dataclasses import frozen
+
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
STARTDATE = datetime(year=2000, month=1, day=1)
@@ -34,6 +36,10 @@ def apply_crm_api_version(path: str, api_version: str) -> str:
return _CRM_VERSION_SEGMENT.sub(rf"/crm/\1/{api_version}\2", path)
+# Reading leads requires Sales Hub Professional or above, so `OauthIntegration.oauth_config_for_kind`
+# asks HubSpot for this scope as an optional one and a connection can be authorized without it.
+LEADS_SCOPE = "crm.objects.leads.read"
+
CONTACT = "contact"
COMPANY = "company"
DEAL = "deal"
@@ -248,7 +254,7 @@ def _incremental_field(name: str) -> IncrementalField:
)
-@dataclass
+@frozen
class HubspotEndpointConfig:
name: str
path: str
@@ -261,6 +267,11 @@ class HubspotEndpointConfig:
# Whether this endpoint is selected for sync by default. False keeps a table off unless the
# user opts in — used for objects that need an OAuth scope existing connections lack (leads).
should_sync_default: bool = True
+ # OAuth scope this endpoint needs beyond the mandatory set, when we request that scope as an
+ # `optional_scope` because it only exists on some HubSpot plans. HubSpot grants optional scopes
+ # silently, so the source checks the connection's granted scopes before offering or syncing
+ # these endpoints instead of finding out via a 403 mid-sync.
+ required_scope: Optional[str] = None
# Request every property HubSpot defines for the object rather than only the non-hs_ ones.
# Objects whose useful properties are all hs_-prefixed (engagements, commerce) would otherwise
# sync near-empty rows, and listing those names by hand risks requesting properties a portal
@@ -336,6 +347,7 @@ HUBSPOT_ENDPOINTS: dict[str, HubspotEndpointConfig] = {
cursor_filter_property_field="hs_lastmodifieddate",
incremental_fields=[_incremental_field("hs_lastmodifieddate")],
should_sync_default=False,
+ required_scope=LEADS_SCOPE,
),
# Engagement objects. HubSpot authorizes all of them (and feedback submissions) under
# `crm.objects.contacts.read`, which every connection already holds, so they can default on.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/source.py
index 094f111a3efb..edb204f1f602 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/source.py
@@ -1,5 +1,7 @@
from typing import cast
+import structlog
+
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
@@ -31,6 +33,12 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.hubspot.hu
HubspotResumeConfig,
hubspot_source,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.hubspot.scopes import (
+ SCOPE_GATED_OBJECTS,
+ missing_scope_error,
+ missing_scope_for_endpoint,
+ missing_scope_message,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.hubspot.settings import (
DEFAULT_PROPS,
ENDPOINTS as HUBSPOT_ENDPOINTS,
@@ -41,6 +49,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.hubspot.se
)
from products.warehouse_sources.backend.types import ExternalDataSourceType
+logger = structlog.get_logger(__name__)
+
@config.config
class HubspotSourceOldConfig(config.Config):
@@ -107,7 +117,19 @@ class HubspotSource(ResumableSource[HubspotSourceConfig | HubspotSourceOldConfig
)
def get_non_retryable_errors(self) -> dict[str, str | None]:
+ # An object behind an optional scope the connection never got can't sync until the user
+ # reconnects, so name the fix instead of the generic "no permission" message below. Listed
+ # first so it wins over that message for a 403 we could attribute to a specific scope.
+ missing_scope_errors: dict[str, str | None] = {
+ missing_scope_message(endpoint, scope): (
+ f"Your HubSpot connection cannot read {endpoint}. Reconnect your HubSpot account to grant the "
+ f"{scope} permission, or turn off the {endpoint} table. Not every HubSpot plan includes it."
+ )
+ for endpoint, scope in SCOPE_GATED_OBJECTS.items()
+ }
+
return {
+ **missing_scope_errors,
"missing or invalid refresh token": "Your HubSpot connection is invalid or expired. Please reconnect it.",
"missing or unknown hub id": None,
# HubSpot's CRM API returns 401/403 when the OAuth grant can't read the requested object
@@ -166,8 +188,13 @@ class HubspotSource(ResumableSource[HubspotSourceConfig | HubspotSourceOldConfig
force_refresh: bool = False,
api_version: str | None = None,
) -> list[SourceSchema]:
+ unreadable = self._endpoints_missing_scopes(config, team_id)
+
schemas = []
for endpoint in HUBSPOT_ENDPOINTS:
+ if endpoint in unreadable:
+ continue
+
metadata_config = HUBSPOT_METADATA_ENDPOINT_CONFIGS.get(endpoint)
if metadata_config is not None:
# Lookup tables have no server-side timestamp filter, so they are full refresh only.
@@ -200,6 +227,36 @@ class HubspotSource(ResumableSource[HubspotSourceConfig | HubspotSourceOldConfig
return schemas
+ def _endpoints_missing_scopes(
+ self, config: HubspotSourceConfig | HubspotSourceOldConfig, team_id: int
+ ) -> frozenset[str]:
+ """Endpoints this connection provably cannot read, for want of an optional scope.
+
+ Keeping them out of discovery means nobody can select a table whose every sync would 403,
+ and an already-selected one gets turned off by the next discovery run.
+ """
+ if not SCOPE_GATED_OBJECTS or not isinstance(config, HubspotSourceConfig):
+ return frozenset()
+
+ try:
+ integration = self.get_oauth_integration(config.hubspot_integration_id, team_id)
+ except ValueError as e:
+ # A missing or deleted integration is permanent, but discovery stays best-effort
+ # because the sync path already surfaces it with an actionable message.
+ logger.warning(f"Hubspot scope gating skipped, integration lookup failed: {e}", team_id=team_id)
+ return frozenset()
+ except Exception:
+ # Dropping tables on a transient lookup failure would churn schema rows, so gating
+ # fails open. Log it so a gating no-op is distinguishable from unknown scopes.
+ logger.exception("Hubspot scope gating skipped, integration lookup failed", team_id=team_id)
+ return frozenset()
+
+ return frozenset(
+ endpoint
+ for endpoint in SCOPE_GATED_OBJECTS
+ if missing_scope_for_endpoint(endpoint, integration.config) is not None
+ )
+
def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[HubspotResumeConfig]:
return ResumableSourceManager[HubspotResumeConfig](inputs, HubspotResumeConfig)
@@ -215,6 +272,13 @@ class HubspotSource(ResumableSource[HubspotSourceConfig | HubspotSourceOldConfig
if not integration.access_token or not integration.refresh_token:
raise ValueError(f"Hubspot refresh or access token not found for job {inputs.job_id}")
+ # Fail before the first request when the connection was never granted this table's
+ # scope: HubSpot would 403 on property discovery anyway, and the message it produces
+ # doesn't tell the user that reconnecting is what fixes it.
+ missing_scope = missing_scope_for_endpoint(inputs.schema_name, integration.config)
+ if missing_scope is not None:
+ raise missing_scope_error(inputs.schema_name, missing_scope)
+
hubspot_access_code = integration.access_token
refresh_token = integration.refresh_token
else:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/test/test_hubspot_scopes.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/test/test_hubspot_scopes.py
new file mode 100644
index 000000000000..8cbd0883cc48
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/test/test_hubspot_scopes.py
@@ -0,0 +1,152 @@
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+from requests.exceptions import HTTPError
+
+from posthog.temporal.common.errors import NonReportableError
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.hubspot import (
+ HubspotSourceConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.hubspot.helpers import raise_for_hubspot_status
+from products.warehouse_sources.backend.temporal.data_imports.sources.hubspot.scopes import (
+ HubspotForbiddenError,
+ HubspotMissingScopeError,
+ ScopeGatedObject,
+ missing_scope_for_endpoint,
+ missing_scope_message,
+ scope_gated_object_for_url,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.hubspot.settings import LEADS_SCOPE
+from products.warehouse_sources.backend.temporal.data_imports.sources.hubspot.source import HubspotSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.hubspot.test.test_source_routing import (
+ _make_inputs,
+)
+
+
+def _response(status: int) -> MagicMock:
+ response = MagicMock()
+ response.status_code = status
+ response.raise_for_status.side_effect = (
+ None if 200 <= status < 300 else HTTPError(f"{status} Client Error", response=response)
+ )
+ return response
+
+
+def _integration(config: dict[str, Any]) -> MagicMock:
+ integration = MagicMock()
+ integration.config = config
+ integration.access_token = "access"
+ integration.refresh_token = "refresh"
+ return integration
+
+
+class TestMissingScopeForEndpoint:
+ @parameterized.expand(
+ [
+ ("granted", {"scopes": ["tickets", LEADS_SCOPE]}, None),
+ ("not_granted", {"scopes": ["tickets", "crm.objects.deals.read"]}, LEADS_SCOPE),
+ ("space_separated_string", {"scopes": f"tickets {LEADS_SCOPE}"}, None),
+ ("comma_separated_string", {"scopes": "tickets,crm.objects.deals.read"}, LEADS_SCOPE),
+ # Connections authorized before we stored scopes say nothing about the grant, so the
+ # table must stay available rather than being hidden from a portal that can read it.
+ ("field_absent", {"hub_id": 1}, None),
+ ("field_empty", {"scopes": []}, None),
+ ]
+ )
+ def test_leads_scope_verdict(self, _name: str, integration_config: dict[str, Any], expected: str | None) -> None:
+ assert missing_scope_for_endpoint("leads", integration_config) == expected
+
+ def test_endpoint_without_optional_scope_is_never_gated(self) -> None:
+ assert missing_scope_for_endpoint("deals", {"scopes": []}) is None
+
+
+_GATED_LEADS = ScopeGatedObject(endpoint="leads", scope=LEADS_SCOPE)
+
+
+class TestScopeGatedObjectForUrl:
+ @parameterized.expand(
+ [
+ ("properties_v3", "https://api.hubapi.com/crm/v3/properties/leads", _GATED_LEADS),
+ ("properties_dated", "https://api.hubapi.com/crm/properties/2026-03/leads", _GATED_LEADS),
+ ("objects_dated", "https://api.hubapi.com/crm/objects/2026-03/leads?limit=100", _GATED_LEADS),
+ ("search", "https://api.hubapi.com/crm/v3/objects/leads/search", _GATED_LEADS),
+ ("other_object", "https://api.hubapi.com/crm/v3/properties/deals", None),
+ # "leads" only counts as a whole path segment, not as part of another object's name.
+ ("substring_only", "https://api.hubapi.com/crm/v3/objects/leadsources", None),
+ ]
+ )
+ def test_url_attribution(self, _name: str, url: str, expected: ScopeGatedObject | None) -> None:
+ assert scope_gated_object_for_url(url) == expected
+
+
+class TestRaiseForHubspotStatus:
+ def test_forbidden_on_scope_gated_object_names_the_scope(self) -> None:
+ url = "https://api.hubapi.com/crm/properties/2026-03/leads"
+ with pytest.raises(HubspotMissingScopeError) as exc:
+ raise_for_hubspot_status(_response(403), url)
+
+ assert str(exc.value) == missing_scope_message("leads", LEADS_SCOPE)
+ assert str(exc.value) in HubspotSource().get_non_retryable_errors()
+
+ def test_forbidden_elsewhere_keeps_the_message_the_error_policy_matches(self) -> None:
+ url = "https://api.hubapi.com/crm/v3/objects/deals"
+ with pytest.raises(HubspotForbiddenError) as exc:
+ raise_for_hubspot_status(_response(403), url)
+
+ assert "403 Client Error: Forbidden for url: https://api.hubapi.com" in str(exc.value)
+
+ @parameterized.expand(
+ [("missing_scope", "/crm/properties/2026-03/leads"), ("other_object", "/crm/v3/objects/deals")]
+ )
+ def test_forbidden_stays_out_of_error_tracking(self, _name: str, path: str) -> None:
+ # A 403 is a permission problem on the customer's portal, so it must not read as a crash.
+ with pytest.raises(NonReportableError):
+ raise_for_hubspot_status(_response(403), f"https://api.hubapi.com{path}")
+
+ def test_other_client_errors_still_raise_http_error(self) -> None:
+ with pytest.raises(HTTPError):
+ raise_for_hubspot_status(_response(404), "https://api.hubapi.com/crm/v3/objects/deals")
+
+
+class TestScopeGatingInSource:
+ def _config(self) -> HubspotSourceConfig:
+ return HubspotSourceConfig.from_dict({"hubspot_integration_id": "1"})
+
+ @parameterized.expand(
+ [
+ ("granted", {"scopes": [LEADS_SCOPE]}, True),
+ ("not_granted", {"scopes": ["tickets"]}, False),
+ ("unknown", {}, True),
+ ]
+ )
+ def test_leads_offered_only_when_the_scope_is_not_provably_missing(
+ self, _name: str, integration_config: dict[str, Any], expected: bool
+ ) -> None:
+ source = HubspotSource()
+ with patch.object(source, "get_oauth_integration", return_value=_integration(integration_config)):
+ names = {schema.name for schema in source.get_schemas(self._config(), team_id=1)}
+
+ assert ("leads" in names) is expected
+ assert "deals" in names
+
+ def test_sync_fails_with_an_actionable_error_when_the_scope_is_missing(self) -> None:
+ source = HubspotSource()
+ inputs = _make_inputs(schema_name="leads")
+
+ with (
+ patch.object(source, "get_oauth_integration", return_value=_integration({"scopes": ["tickets"]})),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.hubspot.source.hubspot_source"
+ ) as hubspot_source_mock,
+ pytest.raises(HubspotMissingScopeError) as exc,
+ ):
+ source.source_for_pipeline(self._config(), MagicMock(), inputs)
+
+ hubspot_source_mock.assert_not_called()
+ friendly = HubspotSource().get_non_retryable_errors()[str(exc.value)]
+ assert friendly is not None
+ assert LEADS_SCOPE in friendly
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/test/test_hubspot_search.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/test/test_hubspot_search.py
index 5baaaff23bcb..b881e67a4ee8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/test/test_hubspot_search.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/test/test_hubspot_search.py
@@ -1,4 +1,5 @@
from collections.abc import Callable
+from dataclasses import replace
from datetime import UTC, datetime
from typing import Any
@@ -1211,21 +1212,17 @@ class TestGetRowsViaSearch:
class TestHubspotSourceRouting:
def test_search_path_requires_cursor_property(self) -> None:
# Temporarily strip the cursor property from `deals` config to exercise the guard.
- original = HUBSPOT_ENDPOINTS["deals"].cursor_filter_property_field
- HUBSPOT_ENDPOINTS["deals"].cursor_filter_property_field = None
- try:
- with pytest.raises(ValueError):
- hubspot_source(
- api_key="k",
- refresh_token="r",
- endpoint="deals",
- logger=MagicMock(),
- resumable_source_manager=MagicMock(),
- use_search_path=True,
- api_version=HUBSPOT_API_VERSION_V3,
- )
- finally:
- HUBSPOT_ENDPOINTS["deals"].cursor_filter_property_field = original
+ no_cursor = replace(HUBSPOT_ENDPOINTS["deals"], cursor_filter_property_field=None)
+ with patch.dict(HUBSPOT_ENDPOINTS, {"deals": no_cursor}), pytest.raises(ValueError):
+ hubspot_source(
+ api_key="k",
+ refresh_token="r",
+ endpoint="deals",
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ use_search_path=True,
+ api_version=HUBSPOT_API_VERSION_V3,
+ )
def test_search_path_happy_path(self) -> None:
resp = hubspot_source(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/test/test_source_routing.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/test/test_source_routing.py
index a03f4cc568e7..b7b749c2330c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/test/test_source_routing.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/test/test_source_routing.py
@@ -1,3 +1,4 @@
+from dataclasses import replace
from typing import Any
import pytest
@@ -123,12 +124,9 @@ class TestShouldUseSearchPath:
def test_false_when_endpoint_has_no_cursor(self) -> None:
src = HubspotSource()
inputs = _make_inputs(schema_name="deals")
- original = HUBSPOT_ENDPOINTS["deals"].cursor_filter_property_field
- HUBSPOT_ENDPOINTS["deals"].cursor_filter_property_field = None
- try:
+ no_cursor = replace(HUBSPOT_ENDPOINTS["deals"], cursor_filter_property_field=None)
+ with patch.dict(HUBSPOT_ENDPOINTS, {"deals": no_cursor}):
assert src._should_use_search_path(inputs) is False
- finally:
- HUBSPOT_ENDPOINTS["deals"].cursor_filter_property_field = original
def test_false_when_initial_sync_not_complete(self) -> None:
src = HubspotSource()
diff --git a/products/warehouse_sources/backend/tests/test_schema_discovery_reconcile.py b/products/warehouse_sources/backend/tests/test_schema_discovery_reconcile.py
index e0d078fe68a1..326f99c98b15 100644
--- a/products/warehouse_sources/backend/tests/test_schema_discovery_reconcile.py
+++ b/products/warehouse_sources/backend/tests/test_schema_discovery_reconcile.py
@@ -123,7 +123,7 @@ class TestSchemaDiscoveryReconcile(BaseTest):
def test_strict_match_retires_removed_repo_rows(self) -> None:
# Removing a repo drops its names from discovery: synced rows keep their table but stop
- # syncing; never-synced rows soft-delete. The legacy bare row must survive untouched.
+ # syncing; rows never enabled soft-delete. The legacy bare row must survive untouched.
source = self._make_source()
legacy = self._make_synced_schema(source, "issues")
synced_removed = self._make_synced_schema(source, "acme/other.issues")
@@ -146,6 +146,27 @@ class TestSchemaDiscoveryReconcile(BaseTest):
assert synced_removed.deleted is False
assert unsynced_removed.deleted is True
+ def test_dropped_user_enabled_schema_is_disabled_not_deleted_before_first_sync(self) -> None:
+ # A row the user enabled that never produced a table (every sync failed, then discovery
+ # stopped offering the endpoint, e.g. a scope-gated HubSpot table) must stay visible as
+ # disabled rather than vanish with the user's selection.
+ source = self._make_source()
+ enabled_unsynced = ExternalDataSchema.objects.create(
+ team_id=self.team.pk, source_id=source.pk, name="leads", should_sync=True
+ )
+
+ sync_result = sync_old_schemas_with_new_schemas(
+ {"contacts": None},
+ source_id=str(source.pk),
+ team_id=self.team.pk,
+ )
+
+ enabled_unsynced.refresh_from_db()
+ assert sync_result.deleted == []
+ assert enabled_unsynced.deleted is False
+ assert enabled_unsynced.should_sync is False
+ assert enabled_unsynced.status == ExternalDataSchema.Status.COMPLETED
+
class TestSchemaNameMatchesAutoSyncPatterns(SimpleTestCase):
@parameterized.expand(