Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): add 15 missing HubSpot tables (#77287)

Tom Owers770a22f7a052
diff --git a/posthog/models/integration.py b/posthog/models/integration.py
index 852c00fa4519..fe0826f16729 100644
--- a/posthog/models/integration.py
+++ b/posthog/models/integration.py
@@ -930,7 +930,15 @@ class OauthIntegration:
# NOTE: these scopes are only available on certain hubspot plans and as such are optional.
# crm.objects.leads.read is Sales Hub Pro+/Enterprise only — requesting it as a
# mandatory scope would fail the whole authorization for portals that lack it.
- "optional_scope": "analytics.behavioral_events.send behavioral_events.event_definitions.read_write crm.objects.leads.read"
+ # The owners/commerce/product scopes are the same story: the data warehouse
+ # source offers those tables, but the objects only exist on portals with the
+ # matching hub, so they stay optional and their tables start deselected.
+ "optional_scope": (
+ "analytics.behavioral_events.send behavioral_events.event_definitions.read_write "
+ "crm.objects.leads.read crm.objects.owners.read crm.objects.line_items.read "
+ "crm.objects.products.read crm.objects.invoices.read crm.objects.orders.read "
+ "crm.objects.subscriptions.read crm.objects.commercepayments.read"
+ )
},
id_path="hub_id",
name_path="hub_domain",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS.md
index 1b3d12bd0737..715398be5dba 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS.md
@@ -243,24 +243,29 @@ Have: `issues`, `issue_comments`, `issue_events`, `issue_types`, `labels`, `mile
- [ ] `code-quality/findings` and `pulls/stacks` (skipped: both back GitHub features that are still rolling out, and neither endpoint returns anything on an account without the feature enabled, so they would ship as tables that stay empty or error for nearly everyone. Worth revisiting once the features are generally available).
- [ ] `repos/{repo}/events` (skipped: GitHub caps this feed at 300 events over 90 days and it restates what `repository_activity`, `issues`, and `pull_requests` already carry).
-### HubSpot — our side code-verified, vendor side needs confirmation
-
-`ENDPOINTS` in `hubspot/settings.py` is exactly seven CRM objects.
-Two small additions would unblock most real analysis.
-
-- [ ] `pipelines` (and pipeline stages) — deals and tickets return `dealstage` and `pipeline` as opaque IDs today, so no one can group by stage name without hardcoding a mapping. Highest value item here.
-- [ ] `owners` — same problem for owner IDs. Also unblocks rep-level reporting.
-- [ ] `line_items` and `products` — deal composition and what was actually sold.
-- [ ] `calls`, `notes`, `tasks`, `communications` — the rest of the engagement objects. We have `emails` and `meetings` only.
-- [ ] `lists` and list memberships.
-- [ ] Marketing emails and marketing campaigns, with their statistics.
-- [ ] `forms` and form submissions.
-- [ ] Custom objects. Currently impossible to sync, and most mature HubSpot portals have them.
-- [ ] Property definitions — needed to interpret and label custom properties.
-- [ ] Associations as a first-class table. Today they ride along as a query param on contacts and companies only, so deal-to-contact links are not queryable.
-- [ ] Feedback submissions (NPS/CSAT surveys).
-- [ ] Workflows.
-- [ ] Web analytics events. `WEB_ANALYTICS_EVENTS_ENDPOINT` is already defined in `hubspot/settings.py:63` but is referenced nowhere else, so this is a half-finished thread rather than a new build.
+### HubSpot — spec-verified 2026-08-04
+
+Diffed against HubSpot's public spec catalog (<https://api.hubspot.com/public/api/spec/v1/specs>) and the
+individual 2026-03 OpenAPI specs behind it.
+
+Have: contacts, companies, deals, tickets, quotes, emails, meetings, leads, calls, notes, tasks,
+communications, feedback_submissions, line_items, products, invoices, orders, subscriptions,
+commerce_payments, pipelines, pipeline_stages, properties, owners.
+
+- [x] `pipelines` (and pipeline stages) — deals and tickets return `dealstage` and `pipeline` as opaque IDs today, so no one can group by stage name without hardcoding a mapping. Highest value item here.
+- [x] `owners` — same problem for owner IDs. Also unblocks rep-level reporting.
+- [x] `line_items` and `products` — deal composition and what was actually sold.
+- [x] `calls`, `notes`, `tasks`, `communications` — the rest of the engagement objects. We have `emails` and `meetings` only.
+- [ ] `lists` and list memberships. (skipped: the v3 Lists API is a POST `/crm/v3/lists/search` with its own paging, and memberships are an unbounded per-list fan-out — neither fits the CRM object machinery)
+- [ ] Marketing emails and marketing campaigns, with their statistics. (skipped: `/marketing/v3/*` is a separate API family needing its own scopes and paginator)
+- [ ] `forms` and form submissions. (skipped: the only published Forms spec is version `2026-09-beta`, not GA)
+- [ ] Custom objects. Currently impossible to sync, and most mature HubSpot portals have them. (skipped: needs schema discovery per portal rather than a fixed table)
+- [x] Property definitions — needed to interpret and label custom properties.
+- [ ] Associations as a first-class table. Today they ride along as a query param on contacts and companies only, so deal-to-contact links are not queryable. (skipped: needs a pair-by-pair batch read across every object type; `line_items` now carries its deal association inline)
+- [x] Feedback submissions (NPS/CSAT surveys).
+- [ ] Workflows. (skipped: Automation v4 is a separate API family)
+- [ ] Web analytics events. `WEB_ANALYTICS_EVENTS_ENDPOINT` is already defined in `hubspot/settings.py:63` but is referenced nowhere else, so this is a half-finished thread rather than a new build. (skipped: `/events/v3/events` requires an objectId per request, so it is a per-record fan-out over the whole portal rather than a listable table)
+- [x] Commerce: `invoices`, `orders`, `subscriptions`, `commerce_payments`. Not covered: `carts`, `discounts`, `fees`, `taxes`, `tax_rates`, `payment_links` — configuration-shaped objects with little query value.
### LinkedIn Ads — spec-verified
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/hubspot.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/hubspot.py
index 9c59228a7dd2..a206682e08f0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/hubspot.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/hubspot.py
@@ -15,6 +15,17 @@ class HubspotCustomPropertiesConfig(config.Config):
emails_properties: str | None = None
meetings_properties: str | None = None
leads_properties: str | None = None
+ calls_properties: str | None = None
+ notes_properties: str | None = None
+ tasks_properties: str | None = None
+ communications_properties: str | None = None
+ feedback_submissions_properties: str | None = None
+ line_items_properties: str | None = None
+ products_properties: str | None = None
+ invoices_properties: str | None = None
+ orders_properties: str | None = None
+ subscriptions_properties: str | None = None
+ commerce_payments_properties: str | None = None
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/canonical_descriptions.py
index 550502f78518..09b305e4743f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/canonical_descriptions.py
@@ -145,4 +145,182 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"hs_lastmodifieddate": "Date any property on the lead was last modified.",
},
},
+ "calls": {
+ "description": "A phone call logged against a contact, company, deal, or ticket.",
+ "docs_url": "https://developers.hubspot.com/docs/api-reference/crm-calls-v3",
+ "columns": {
+ "hs_object_id": "HubSpot's unique internal identifier for the call.",
+ "hs_timestamp": "Time the call took place.",
+ "hs_lastmodifieddate": "Date any property on the call was last modified.",
+ },
+ },
+ "notes": {
+ "description": "A free-text note logged against a CRM record.",
+ "docs_url": "https://developers.hubspot.com/docs/api-reference/crm-notes-v3",
+ "columns": {
+ "hs_object_id": "HubSpot's unique internal identifier for the note.",
+ "hs_timestamp": "Time the note was logged.",
+ "hs_lastmodifieddate": "Date any property on the note was last modified.",
+ },
+ },
+ "tasks": {
+ "description": "A to-do item assigned to a user and linked to a CRM record.",
+ "docs_url": "https://developers.hubspot.com/docs/api-reference/crm-tasks-v3",
+ "columns": {
+ "hs_object_id": "HubSpot's unique internal identifier for the task.",
+ "hs_timestamp": "Date the task is due.",
+ "hs_lastmodifieddate": "Date any property on the task was last modified.",
+ },
+ },
+ "communications": {
+ "description": "A message sent over an integrated channel such as SMS, WhatsApp, or LinkedIn.",
+ "docs_url": "https://developers.hubspot.com/docs/api-reference/crm-communications-v3",
+ "columns": {
+ "hs_object_id": "HubSpot's unique internal identifier for the communication.",
+ "hs_timestamp": "Time the message was sent.",
+ "hs_lastmodifieddate": "Date any property on the communication was last modified.",
+ },
+ },
+ "feedback_submissions": {
+ "description": "A customer response to a HubSpot feedback survey (NPS, CSAT, or CES).",
+ "docs_url": "https://developers.hubspot.com/docs/api-reference/crm-feedback-submissions-v3",
+ "columns": {
+ "hs_object_id": "HubSpot's unique internal identifier for the submission.",
+ "hs_lastmodifieddate": "Date any property on the submission was last modified.",
+ },
+ },
+ "line_items": {
+ "description": "An individual instance of a product sold on a deal or quote, with its own quantity and price.",
+ "docs_url": "https://developers.hubspot.com/docs/api-reference/crm-line-items-v3",
+ "columns": {
+ "hs_object_id": "HubSpot's unique internal identifier for the line item.",
+ "hs_lastmodifieddate": "Date any property on the line item was last modified.",
+ "deals": "Deals the line item belongs to, as {value, deals_id} pairs.",
+ },
+ },
+ "products": {
+ "description": "A good or service sold by the company, used as the template for line items.",
+ "docs_url": "https://developers.hubspot.com/docs/api-reference/crm-products-v3",
+ "columns": {
+ "hs_object_id": "HubSpot's unique internal identifier for the product.",
+ "hs_lastmodifieddate": "Date any property on the product was last modified.",
+ },
+ },
+ "invoices": {
+ "description": "A bill issued to a customer through HubSpot Commerce.",
+ "docs_url": "https://developers.hubspot.com/docs/api-reference/crm-invoices-v3",
+ "columns": {
+ "hs_object_id": "HubSpot's unique internal identifier for the invoice.",
+ "hs_lastmodifieddate": "Date any property on the invoice was last modified.",
+ },
+ },
+ "orders": {
+ "description": "A customer order, typically synced from a connected commerce store.",
+ "docs_url": "https://developers.hubspot.com/docs/api-reference/crm-orders-v3",
+ "columns": {
+ "hs_object_id": "HubSpot's unique internal identifier for the order.",
+ "hs_lastmodifieddate": "Date any property on the order was last modified.",
+ },
+ },
+ "subscriptions": {
+ "description": "A recurring commerce subscription billed through HubSpot.",
+ "docs_url": "https://developers.hubspot.com/docs/api-reference/crm-commerce-subscriptions-v3",
+ "columns": {
+ "hs_object_id": "HubSpot's unique internal identifier for the subscription.",
+ "hs_lastmodifieddate": "Date any property on the subscription was last modified.",
+ },
+ },
+ "commerce_payments": {
+ "description": "A payment collected through HubSpot Commerce against an invoice, quote, or payment link.",
+ "docs_url": "https://developers.hubspot.com/docs/api-reference/crm-commerce-payments-v3",
+ "columns": {
+ "hs_object_id": "HubSpot's unique internal identifier for the payment.",
+ "hs_lastmodifieddate": "Date any property on the payment was last modified.",
+ },
+ },
+ "pipelines": {
+ "description": "A pipeline that deals or tickets move through. Decodes the `pipeline` and `hs_pipeline` IDs carried on those records.",
+ "docs_url": "https://developers.hubspot.com/docs/api-reference/crm-pipelines-v3",
+ "columns": {
+ "object_type": "The object type the pipeline belongs to: deals or tickets.",
+ "id": "The pipeline's identifier, unique within its object type.",
+ "label": "The pipeline's display name.",
+ "displayOrder": "Position of the pipeline in the HubSpot UI, ascending.",
+ "archived": "Whether the pipeline has been archived.",
+ "archivedAt": "Time the pipeline was archived, if it was.",
+ "createdAt": "Time the pipeline was created.",
+ "updatedAt": "Time the pipeline was last updated.",
+ },
+ },
+ "pipeline_stages": {
+ "description": "A stage within a pipeline. Decodes the `dealstage` and `hs_pipeline_stage` IDs carried on deals and tickets.",
+ "docs_url": "https://developers.hubspot.com/docs/api-reference/crm-pipelines-v3",
+ "columns": {
+ "object_type": "The object type the stage's pipeline belongs to: deals or tickets.",
+ "pipeline_id": "Identifier of the pipeline the stage belongs to.",
+ "id": "The stage's identifier, unique within its pipeline.",
+ "label": "The stage's display name.",
+ "displayOrder": "Position of the stage in its pipeline, ascending.",
+ "archived": "Whether the stage has been archived.",
+ "archivedAt": "Time the stage was archived, if it was.",
+ "createdAt": "Time the stage was created.",
+ "updatedAt": "Time the stage was last updated.",
+ "metadata": "Stage configuration as a JSON string: win probability and closed state for deals, ticket state for tickets.",
+ "writePermissions": "Who may move records into this stage.",
+ },
+ },
+ "properties": {
+ "description": "The definition of a property on a CRM object, including custom properties. Use it to label and interpret the property columns on the object tables.",
+ "docs_url": "https://developers.hubspot.com/docs/api-reference/crm-properties-v3",
+ "columns": {
+ "object_type": "The object type the property is defined on.",
+ "name": "The property's internal name, matching its column on the object table.",
+ "label": "The property's human-readable label.",
+ "description": "The property's description.",
+ "groupName": "Name of the property group the property belongs to.",
+ "type": "The property's data type (e.g. string, number, date, enumeration, bool).",
+ "fieldType": "How the property is rendered in HubSpot (e.g. text, select, checkbox).",
+ "dataSensitivity": "The property's data sensitivity classification.",
+ "archived": "Whether the property has been archived.",
+ "archivedAt": "Time the property was archived, if it was.",
+ "calculated": "Whether the property's value is computed by a formula.",
+ "calculationFormula": "The formula used to compute the property, if it is calculated.",
+ "createdAt": "Time the property was created.",
+ "createdUserId": "ID of the user who created the property.",
+ "currencyPropertyName": "Name of the property holding the currency code for a currency-valued property.",
+ "dateDisplayHint": "How a date property is displayed.",
+ "displayOrder": "Position of the property in its group, ascending.",
+ "externalOptions": "Whether the property's options come from an external source.",
+ "formField": "Whether the property can be used in forms.",
+ "hasUniqueValue": "Whether HubSpot enforces unique values for the property.",
+ "hidden": "Whether the property is hidden in the HubSpot UI.",
+ "hubspotDefined": "Whether HubSpot defines the property, as opposed to it being custom.",
+ "modificationMetadata": "JSON string describing which parts of the definition are read-only.",
+ "numberDisplayHint": "How a number property is displayed.",
+ "options": "JSON string of the allowed values for an enumeration property.",
+ "referencedObjectType": "The object type an object-reference property points at.",
+ "sensitiveDataCategories": "JSON string listing the sensitive data categories applied to the property.",
+ "showCurrencySymbol": "Whether a currency symbol is shown alongside the value.",
+ "textDisplayHint": "How a text property is displayed.",
+ "updatedAt": "Time the property was last updated.",
+ "updatedUserId": "ID of the user who last updated the property.",
+ },
+ },
+ "owners": {
+ "description": "A HubSpot user who can own CRM records. Decodes the `hubspot_owner_id` carried on contacts, companies, deals, and tickets.",
+ "docs_url": "https://developers.hubspot.com/docs/api-reference/crm-owners-v3",
+ "columns": {
+ "id": "The owner's identifier, as referenced by `hubspot_owner_id` on CRM records.",
+ "email": "The owner's email address.",
+ "firstName": "The owner's first name.",
+ "lastName": "The owner's last name.",
+ "userId": "ID of the HubSpot user the owner maps to, null once the user is deactivated.",
+ "userIdIncludingInactive": "ID of the HubSpot user the owner maps to, kept after deactivation.",
+ "type": "Whether the owner is a person or a queue.",
+ "archived": "Whether the owner has been archived.",
+ "createdAt": "Time the owner was created.",
+ "updatedAt": "Time the owner was last updated.",
+ "teams": "JSON string listing the teams the owner belongs to.",
+ },
+ },
}
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 ec9b67e1edf9..69a77946f176 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
@@ -233,7 +233,10 @@ def _get_property_names(
Exception: If an error occurs during the API request.
"""
properties = []
- endpoint = apply_crm_api_version(f"/crm/v3/properties/{OBJECT_TYPE_PLURAL[object_type]}", api_version)
+ # Objects added after the original eight are keyed by their own plural name (calls, line_items,
+ # ...), so they aren't in the singular/plural map and pass straight through.
+ plural = OBJECT_TYPE_PLURAL.get(object_type, object_type)
+ endpoint = apply_crm_api_version(f"/crm/v3/properties/{plural}", api_version)
for page in fetch_data(endpoint, api_key, refresh_token, source_id=source_id):
properties.extend([prop["name"] for prop in page])
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 fe6a2aad411a..28f9a2860345 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,11 +38,13 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.hubspot.he
_get_headers,
_get_property_names,
)
+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 (
ASSOCIATIONS_BATCH_SIZE,
DEFAULT_PROPS,
HUBSPOT_API_VERSION_V3,
HUBSPOT_ENDPOINTS,
+ HUBSPOT_METADATA_ENDPOINTS,
OBJECT_TYPE_SINGULAR,
SEARCH_PAGE_SIZE,
SEARCH_RESULT_CAP,
@@ -73,6 +75,12 @@ class HubspotResumeConfig:
last_cursor_ms: Optional[int] = None
+def _object_type_for(endpoint: str) -> str:
+ """The object type used to look up an endpoint's property definitions. Only the original eight
+ endpoints have a distinct singular form; later ones are named by their own plural."""
+ return OBJECT_TYPE_SINGULAR.get(endpoint, endpoint)
+
+
def _get_properties_str(
props: Sequence[str],
api_key: str,
@@ -82,6 +90,7 @@ def _get_properties_str(
include_custom_props: bool = True,
source_id: str | None = None,
api_version: str = HUBSPOT_API_VERSION_V3,
+ discover_all_properties: bool = False,
) -> str:
"""Builds a comma-separated string of properties to request from the HubSpot API (GET path)."""
props = list(props)
@@ -89,7 +98,7 @@ def _get_properties_str(
all_props = _get_property_names(
api_key, refresh_token, object_type, source_id=source_id, api_version=api_version
)
- custom_props = [prop for prop in all_props if not prop.startswith("hs_")]
+ custom_props = [prop for prop in all_props if discover_all_properties or not prop.startswith("hs_")]
props = props + [c for c in custom_props if c not in props]
props_str = ""
@@ -120,6 +129,7 @@ def _resolve_search_properties(
logger: FilteringBoundLogger,
source_id: str | None,
api_version: str = HUBSPOT_API_VERSION_V3,
+ discover_all_properties: bool = False,
) -> tuple[list[str], list[str]]:
"""Resolve the properties list for the search body.
@@ -156,7 +166,7 @@ def _resolve_search_properties(
all_props = _get_property_names(
api_key, refresh_token, object_type, source_id=source_id, api_version=api_version
)
- custom = [p for p in all_props if not p.startswith("hs_") and p not in props]
+ custom = [p for p in all_props if (discover_all_properties or not p.startswith("hs_")) and p not in props]
props.extend(custom)
# Force-include required properties (cursor + id).
@@ -264,7 +274,7 @@ def get_rows(
) -> Iterator[Any]:
"""Full-refresh (and seed-incremental) fetch via the paginated GET endpoint."""
config = HUBSPOT_ENDPOINTS[endpoint]
- object_type = OBJECT_TYPE_SINGULAR[endpoint]
+ object_type = _object_type_for(endpoint)
# Build properties string (called once before sync loop)
# Keep track of the expected properties so we can backfill missing ones with None.
@@ -312,6 +322,7 @@ def get_rows(
logger=logger,
source_id=source_id,
api_version=api_version,
+ discover_all_properties=config.discover_all_properties,
)
expected_properties = props_str.split(",") if props_str else []
@@ -565,7 +576,7 @@ def get_rows_via_search(
- Checkpoint (sync_start_ms, sync_end_ms, last_cursor_ms) to Redis on each batch flush.
"""
config = HUBSPOT_ENDPOINTS[endpoint]
- object_type = OBJECT_TYPE_SINGULAR[endpoint]
+ object_type = _object_type_for(endpoint)
cursor_prop = config.cursor_filter_property_field
if not cursor_prop:
raise ValueError(f"Endpoint {endpoint} does not support search-based incremental sync")
@@ -581,6 +592,7 @@ def get_rows_via_search(
logger=logger,
source_id=source_id,
api_version=api_version,
+ discover_all_properties=config.discover_all_properties,
)
headers = _get_headers(api_key)
@@ -785,7 +797,27 @@ def hubspot_source(
upstream so the watermark is meaningful and associations backfill is the cheaper option).
- `use_search_path=False` → GET path (full refresh, seed incremental, or endpoints without
search support).
+
+ Lookup tables (pipelines, pipeline stages, property definitions, owners) take neither path:
+ they aren't CRM objects, so they go straight to their own fetcher and are always full refresh.
"""
+ metadata_config = HUBSPOT_METADATA_ENDPOINTS.get(endpoint)
+ if metadata_config is not None:
+ fetcher = METADATA_FETCHERS[endpoint]
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: fetcher(
+ api_key=api_key,
+ refresh_token=refresh_token,
+ logger=logger,
+ source_id=source_id,
+ api_version=api_version,
+ ),
+ primary_keys=metadata_config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ )
+
endpoint_config = HUBSPOT_ENDPOINTS[endpoint]
if use_search_path and not endpoint_config.cursor_filter_property_field:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/metadata.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/metadata.py
new file mode 100644
index 000000000000..418a08a34da4
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/metadata.py
@@ -0,0 +1,127 @@
+"""Fetchers for HubSpot's lookup tables: pipelines, pipeline stages, property definitions and owners.
+
+These are not CRM objects — they have no `properties` envelope, no `/search` endpoint and no
+server-side timestamp filter — so they are always a full refresh and reuse `helpers.fetch_data`
+for auth refresh, retries and `paging.next.link` following.
+
+Rows are flattened to a fixed column set (`HubspotMetadataEndpointConfig.columns`): missing fields
+are backfilled with None so an optional field a portal never sets can't shift the table's schema
+between syncs, and nested values are JSON-encoded so a heterogeneous `metadata` blob can't produce
+a different PyArrow struct per batch.
+"""
+
+import json
+from collections.abc import Iterator
+from typing import Any
+
+import requests
+from structlog.types import FilteringBoundLogger
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.hubspot.helpers import fetch_data
+from products.warehouse_sources.backend.temporal.data_imports.sources.hubspot.settings import (
+ HUBSPOT_ENDPOINTS,
+ HUBSPOT_METADATA_ENDPOINTS,
+ PIPELINE_OBJECT_TYPES,
+ apply_crm_api_version,
+)
+
+# A portal that hasn't enabled an object (or a grant that can't read it) answers with one of these
+# for that object type only. Skipping keeps one unavailable object type from failing the table.
+_SKIPPABLE_STATUSES = (403, 404)
+
+
+def _normalize_row(row: dict[str, Any], columns: list[str]) -> dict[str, Any]:
+ normalized = {k: json.dumps(v) if isinstance(v, dict | list) else v for k, v in row.items()}
+ for column in columns:
+ normalized.setdefault(column, None)
+ return normalized
+
+
+def _iter_pages(
+ path: str,
+ api_key: str,
+ refresh_token: str,
+ source_id: str | None,
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict[str, Any]]]:
+ try:
+ yield from fetch_data(path, api_key, refresh_token, source_id=source_id)
+ except requests.HTTPError as e:
+ status = e.response.status_code if e.response is not None else None
+ if status in _SKIPPABLE_STATUSES:
+ logger.warning(f"Hubspot: skipping {path} (status={status}); the portal cannot read it")
+ return
+ raise
+
+
+def get_pipelines_rows(
+ api_key: str,
+ refresh_token: str,
+ logger: FilteringBoundLogger,
+ source_id: str | None,
+ api_version: str,
+) -> Iterator[list[dict[str, Any]]]:
+ columns = HUBSPOT_METADATA_ENDPOINTS["pipelines"].columns
+ for object_type in PIPELINE_OBJECT_TYPES:
+ path = apply_crm_api_version(f"/crm/v3/pipelines/{object_type}", api_version)
+ for page in _iter_pages(path, api_key, refresh_token, source_id, logger):
+ # `stages` is dropped here — it is the pipeline_stages table.
+ yield [
+ _normalize_row({**{k: v for k, v in p.items() if k != "stages"}, "object_type": object_type}, columns)
+ for p in page
+ ]
+
+
+def get_pipeline_stages_rows(
+ api_key: str,
+ refresh_token: str,
+ logger: FilteringBoundLogger,
+ source_id: str | None,
+ api_version: str,
+) -> Iterator[list[dict[str, Any]]]:
+ columns = HUBSPOT_METADATA_ENDPOINTS["pipeline_stages"].columns
+ for object_type in PIPELINE_OBJECT_TYPES:
+ path = apply_crm_api_version(f"/crm/v3/pipelines/{object_type}", api_version)
+ for page in _iter_pages(path, api_key, refresh_token, source_id, logger):
+ rows = [
+ _normalize_row({**stage, "object_type": object_type, "pipeline_id": pipeline.get("id")}, columns)
+ for pipeline in page
+ for stage in pipeline.get("stages") or []
+ ]
+ if rows:
+ yield rows
+
+
+def get_properties_rows(
+ api_key: str,
+ refresh_token: str,
+ logger: FilteringBoundLogger,
+ source_id: str | None,
+ api_version: str,
+) -> Iterator[list[dict[str, Any]]]:
+ columns = HUBSPOT_METADATA_ENDPOINTS["properties"].columns
+ for object_type in HUBSPOT_ENDPOINTS:
+ path = apply_crm_api_version(f"/crm/v3/properties/{object_type}", api_version)
+ for page in _iter_pages(path, api_key, refresh_token, source_id, logger):
+ yield [_normalize_row({**p, "object_type": object_type}, columns) for p in page]
+
+
+def get_owners_rows(
+ api_key: str,
+ refresh_token: str,
+ logger: FilteringBoundLogger,
+ source_id: str | None,
+ api_version: str,
+) -> Iterator[list[dict[str, Any]]]:
+ columns = HUBSPOT_METADATA_ENDPOINTS["owners"].columns
+ path = apply_crm_api_version("/crm/v3/owners", api_version)
+ for page in _iter_pages(path, api_key, refresh_token, source_id, logger):
+ yield [_normalize_row(owner, columns) for owner in page]
+
+
+METADATA_FETCHERS = {
+ "pipelines": get_pipelines_rows,
+ "pipeline_stages": get_pipeline_stages_rows,
+ "properties": get_properties_rows,
+ "owners": get_owners_rows,
+}
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 b2b8481efd9a..297366976330 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
@@ -17,9 +17,10 @@ STARTDATE = datetime(year=2000, month=1, day=1)
HUBSPOT_API_VERSION_V3 = "v3"
HUBSPOT_API_VERSION_2026_03 = "2026-03"
-# Matches the leading "/crm/<v3|v4>/<resource>/" of a CRM path, capturing the resource name
-# (objects, properties, associations) so the version can be re-inserted after it.
-_CRM_VERSION_SEGMENT = re.compile(r"^/crm/v[34]/([^/]+)/")
+# Matches the leading "/crm/<v3|v4>/<resource>" of a CRM path, capturing the resource name
+# (objects, properties, associations, pipelines, owners) so the version can be re-inserted after
+# it. The trailing separator is optional so a resource-only path like "/crm/v3/owners" rewrites too.
+_CRM_VERSION_SEGMENT = re.compile(r"^/crm/v[34]/([^/]+)(/|$)")
def apply_crm_api_version(path: str, api_version: str) -> str:
@@ -30,7 +31,7 @@ def apply_crm_api_version(path: str, api_version: str) -> str:
/crm/associations/2026-03/a/b/batch/read."""
if api_version == HUBSPOT_API_VERSION_V3:
return path
- return _CRM_VERSION_SEGMENT.sub(rf"/crm/\1/{api_version}/", path)
+ return _CRM_VERSION_SEGMENT.sub(rf"/crm/\1/{api_version}\2", path)
CONTACT = "contact"
@@ -86,6 +87,22 @@ ENDPOINTS = (
OBJECT_TYPE_PLURAL[EMAILS],
OBJECT_TYPE_PLURAL[MEETINGS],
OBJECT_TYPE_PLURAL[LEAD],
+ "calls",
+ "notes",
+ "tasks",
+ "communications",
+ "feedback_submissions",
+ "line_items",
+ "products",
+ "invoices",
+ "orders",
+ "subscriptions",
+ "commerce_payments",
+ # Lookup tables (see HUBSPOT_METADATA_ENDPOINTS) — not CRM objects.
+ "pipelines",
+ "pipeline_stages",
+ "properties",
+ "owners",
)
# CRM search API constants — shared between windowing and pagination logic
@@ -191,6 +208,14 @@ DEFAULT_LEAD_PROPS = [
"hs_pipeline_stage",
]
+# Objects added after the original eight request their full property set from
+# /crm/v3/properties/{objectType} instead of carrying a hand-written default list (see
+# `discover_all_properties` below), so their entry here only seeds the properties HubSpot
+# guarantees on every non-contact CRM object: the primary key and the incremental cursor.
+# `hs_timestamp` is the activity time on engagement objects, matching emails and meetings above.
+BASE_OBJECT_PROPS = ["hs_object_id", "hs_lastmodifieddate"]
+BASE_ENGAGEMENT_PROPS = [*BASE_OBJECT_PROPS, "hs_timestamp"]
+
DEFAULT_PROPS = {
OBJECT_TYPE_PLURAL[CONTACT]: DEFAULT_CONTACT_PROPS,
OBJECT_TYPE_PLURAL[COMPANY]: DEFAULT_COMPANY_PROPS,
@@ -200,6 +225,17 @@ DEFAULT_PROPS = {
OBJECT_TYPE_PLURAL[EMAILS]: DEFAULT_EMAIL_PROPS,
OBJECT_TYPE_PLURAL[MEETINGS]: DEFAULT_MEETINGS_PROPS,
OBJECT_TYPE_PLURAL[LEAD]: DEFAULT_LEAD_PROPS,
+ "calls": BASE_ENGAGEMENT_PROPS,
+ "notes": BASE_ENGAGEMENT_PROPS,
+ "tasks": BASE_ENGAGEMENT_PROPS,
+ "communications": BASE_ENGAGEMENT_PROPS,
+ "feedback_submissions": BASE_OBJECT_PROPS,
+ "line_items": BASE_OBJECT_PROPS,
+ "products": BASE_OBJECT_PROPS,
+ "invoices": BASE_OBJECT_PROPS,
+ "orders": BASE_OBJECT_PROPS,
+ "subscriptions": BASE_OBJECT_PROPS,
+ "commerce_payments": BASE_OBJECT_PROPS,
}
@@ -225,6 +261,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
+ # 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
+ # doesn't have. The property list is still truncated by the URL-length / search caps.
+ discover_all_properties: bool = False
HUBSPOT_ENDPOINTS: dict[str, HubspotEndpointConfig] = {
@@ -296,4 +337,212 @@ HUBSPOT_ENDPOINTS: dict[str, HubspotEndpointConfig] = {
incremental_fields=[_incremental_field("hs_lastmodifieddate")],
should_sync_default=False,
),
+ # 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.
+ # `hs_timestamp` is the activity time, matching the emails and meetings entries above.
+ "calls": HubspotEndpointConfig(
+ name="calls",
+ path="/crm/v3/objects/calls",
+ associations=[],
+ partition_key="hs_timestamp",
+ cursor_filter_property_field="hs_lastmodifieddate",
+ incremental_fields=[_incremental_field("hs_lastmodifieddate")],
+ discover_all_properties=True,
+ ),
+ "notes": HubspotEndpointConfig(
+ name="notes",
+ path="/crm/v3/objects/notes",
+ associations=[],
+ partition_key="hs_timestamp",
+ cursor_filter_property_field="hs_lastmodifieddate",
+ incremental_fields=[_incremental_field("hs_lastmodifieddate")],
+ discover_all_properties=True,
+ ),
+ "tasks": HubspotEndpointConfig(
+ name="tasks",
+ path="/crm/v3/objects/tasks",
+ associations=[],
+ partition_key="hs_timestamp",
+ cursor_filter_property_field="hs_lastmodifieddate",
+ incremental_fields=[_incremental_field("hs_lastmodifieddate")],
+ discover_all_properties=True,
+ ),
+ "communications": HubspotEndpointConfig(
+ name="communications",
+ path="/crm/v3/objects/communications",
+ associations=[],
+ partition_key="hs_timestamp",
+ cursor_filter_property_field="hs_lastmodifieddate",
+ incremental_fields=[_incremental_field("hs_lastmodifieddate")],
+ discover_all_properties=True,
+ ),
+ "feedback_submissions": HubspotEndpointConfig(
+ name="feedback_submissions",
+ path="/crm/v3/objects/feedback_submissions",
+ associations=[],
+ cursor_filter_property_field="hs_lastmodifieddate",
+ incremental_fields=[_incremental_field("hs_lastmodifieddate")],
+ discover_all_properties=True,
+ ),
+ # Commerce and product objects. Each needs its own read scope that existing connections were
+ # never granted, so they start off and only sync once the account is reconnected. They are
+ # also unpartitioned: their creation-date property was not verified against a live portal, and
+ # partitioning on a property a portal doesn't have would put every row in one null partition.
+ "line_items": HubspotEndpointConfig(
+ name="line_items",
+ path="/crm/v3/objects/line_items",
+ associations=["deals"],
+ cursor_filter_property_field="hs_lastmodifieddate",
+ incremental_fields=[_incremental_field("hs_lastmodifieddate")],
+ should_sync_default=False,
+ discover_all_properties=True,
+ ),
+ "products": HubspotEndpointConfig(
+ name="products",
+ path="/crm/v3/objects/products",
+ associations=[],
+ cursor_filter_property_field="hs_lastmodifieddate",
+ incremental_fields=[_incremental_field("hs_lastmodifieddate")],
+ should_sync_default=False,
+ discover_all_properties=True,
+ ),
+ "invoices": HubspotEndpointConfig(
+ name="invoices",
+ path="/crm/v3/objects/invoices",
+ associations=[],
+ cursor_filter_property_field="hs_lastmodifieddate",
+ incremental_fields=[_incremental_field("hs_lastmodifieddate")],
+ should_sync_default=False,
+ discover_all_properties=True,
+ ),
+ "orders": HubspotEndpointConfig(
+ name="orders",
+ path="/crm/v3/objects/orders",
+ associations=[],
+ cursor_filter_property_field="hs_lastmodifieddate",
+ incremental_fields=[_incremental_field("hs_lastmodifieddate")],
+ should_sync_default=False,
+ discover_all_properties=True,
+ ),
+ "subscriptions": HubspotEndpointConfig(
+ name="subscriptions",
+ path="/crm/v3/objects/subscriptions",
+ associations=[],
+ cursor_filter_property_field="hs_lastmodifieddate",
+ incremental_fields=[_incremental_field("hs_lastmodifieddate")],
+ should_sync_default=False,
+ discover_all_properties=True,
+ ),
+ "commerce_payments": HubspotEndpointConfig(
+ name="commerce_payments",
+ path="/crm/v3/objects/commerce_payments",
+ associations=[],
+ cursor_filter_property_field="hs_lastmodifieddate",
+ incremental_fields=[_incremental_field("hs_lastmodifieddate")],
+ should_sync_default=False,
+ discover_all_properties=True,
+ ),
+}
+
+
+@dataclass
+class HubspotMetadataEndpointConfig:
+ """A HubSpot lookup table that is not a CRM object: no properties, no search endpoint, and no
+ server-side timestamp filter, so it is always a full refresh."""
+
+ name: str
+ primary_keys: list[str]
+ # Fixed column set, taken from the endpoint's OpenAPI response schema. Rows are backfilled to
+ # this set so a portal that omits an optional field doesn't shift the table's schema.
+ columns: list[str]
+ should_sync_default: bool = True
+
+
+# Object types whose pipelines HubSpot documents. Both read with scopes existing connections hold
+# (crm.objects.deals.read / tickets); anything a portal hasn't enabled is skipped on 403/404.
+PIPELINE_OBJECT_TYPES = ("deals", "tickets")
+
+_PIPELINE_COLUMNS = ["object_type", "id", "label", "displayOrder", "archived", "archivedAt", "createdAt", "updatedAt"]
+
+HUBSPOT_METADATA_ENDPOINTS: dict[str, HubspotMetadataEndpointConfig] = {
+ "pipelines": HubspotMetadataEndpointConfig(
+ name="pipelines",
+ # Pipeline ids are only unique within an object type ("default" names both the default
+ # deal pipeline and the default ticket pipeline), so the object type is part of the key.
+ primary_keys=["object_type", "id"],
+ columns=_PIPELINE_COLUMNS,
+ ),
+ "pipeline_stages": HubspotMetadataEndpointConfig(
+ name="pipeline_stages",
+ primary_keys=["object_type", "pipeline_id", "id"],
+ columns=[
+ "object_type",
+ "pipeline_id",
+ "id",
+ "label",
+ "displayOrder",
+ "archived",
+ "archivedAt",
+ "createdAt",
+ "updatedAt",
+ "metadata",
+ "writePermissions",
+ ],
+ ),
+ "properties": HubspotMetadataEndpointConfig(
+ name="properties",
+ primary_keys=["object_type", "name"],
+ columns=[
+ "object_type",
+ "name",
+ "label",
+ "description",
+ "groupName",
+ "type",
+ "fieldType",
+ "dataSensitivity",
+ "archived",
+ "archivedAt",
+ "calculated",
+ "calculationFormula",
+ "createdAt",
+ "createdUserId",
+ "currencyPropertyName",
+ "dateDisplayHint",
+ "displayOrder",
+ "externalOptions",
+ "formField",
+ "hasUniqueValue",
+ "hidden",
+ "hubspotDefined",
+ "modificationMetadata",
+ "numberDisplayHint",
+ "options",
+ "referencedObjectType",
+ "sensitiveDataCategories",
+ "showCurrencySymbol",
+ "textDisplayHint",
+ "updatedAt",
+ "updatedUserId",
+ ],
+ ),
+ # Owners needs `crm.objects.owners.read`, which existing connections were never granted.
+ "owners": HubspotMetadataEndpointConfig(
+ name="owners",
+ primary_keys=["id"],
+ columns=[
+ "id",
+ "email",
+ "firstName",
+ "lastName",
+ "userId",
+ "userIdIncludingInactive",
+ "type",
+ "archived",
+ "createdAt",
+ "updatedAt",
+ "teams",
+ ],
+ should_sync_default=False,
+ ),
}
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 0cc1f5e93d81..6b10273f7f2e 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
@@ -37,6 +37,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.hubspot.se
HUBSPOT_API_VERSION_2026_03,
HUBSPOT_API_VERSION_V3,
HUBSPOT_ENDPOINTS as HUBSPOT_ENDPOINT_CONFIGS,
+ HUBSPOT_METADATA_ENDPOINTS as HUBSPOT_METADATA_ENDPOINT_CONFIGS,
)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@@ -161,6 +162,20 @@ class HubspotSource(ResumableSource[HubspotSourceConfig | HubspotSourceOldConfig
) -> list[SourceSchema]:
schemas = []
for endpoint in HUBSPOT_ENDPOINTS:
+ 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.
+ schemas.append(
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=[],
+ should_sync_default=metadata_config.should_sync_default,
+ )
+ )
+ continue
+
endpoint_config = HUBSPOT_ENDPOINT_CONFIGS[endpoint]
supports_incremental = bool(endpoint_config.cursor_filter_property_field)
schemas.append(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/test/test_hubspot_metadata.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/test/test_hubspot_metadata.py
new file mode 100644
index 000000000000..e7599239710a
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/test/test_hubspot_metadata.py
@@ -0,0 +1,171 @@
+import json
+from collections.abc import Iterator
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from requests.exceptions import HTTPError
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.hubspot.metadata import (
+ METADATA_FETCHERS,
+ get_owners_rows,
+ get_pipeline_stages_rows,
+ get_pipelines_rows,
+ get_properties_rows,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.hubspot.settings import (
+ HUBSPOT_API_VERSION_2026_03,
+ HUBSPOT_METADATA_ENDPOINTS,
+ PIPELINE_OBJECT_TYPES,
+)
+
+_FETCH_DATA = "products.warehouse_sources.backend.temporal.data_imports.sources.hubspot.metadata.fetch_data"
+
+PIPELINE_PAYLOAD = [
+ {
+ "id": "default",
+ "label": "Sales pipeline",
+ "displayOrder": 0,
+ "archived": False,
+ "createdAt": "2020-01-01T00:00:00Z",
+ "updatedAt": "2020-01-02T00:00:00Z",
+ "stages": [
+ {
+ "id": "appointmentscheduled",
+ "label": "Appointment scheduled",
+ "displayOrder": 0,
+ "archived": False,
+ "metadata": {"isClosed": "false", "probability": "0.2"},
+ }
+ ],
+ }
+]
+
+
+def _fetch_data_returning(pages_by_path: dict[str, list[list[dict[str, Any]]]]) -> Any:
+ def _fake(path: str, *_args: Any, **_kwargs: Any) -> Iterator[list[dict[str, Any]]]:
+ yield from pages_by_path.get(path, [])
+
+ return _fake
+
+
+def _call(fetcher: Any) -> list[dict[str, Any]]:
+ rows: list[dict[str, Any]] = []
+ for page in fetcher(
+ api_key="key",
+ refresh_token="refresh",
+ logger=MagicMock(),
+ source_id="source-1",
+ api_version=HUBSPOT_API_VERSION_2026_03,
+ ):
+ rows.extend(page)
+ return rows
+
+
+class TestMetadataFetchers:
+ def test_pipelines_carry_object_type_and_drop_stages(self) -> None:
+ # Pipeline ids are only unique within an object type, so a row without object_type would
+ # let the deals and tickets "default" pipelines overwrite each other on merge. The nested
+ # stages blob belongs to the pipeline_stages table, not here.
+ with patch(
+ _FETCH_DATA,
+ new=_fetch_data_returning(
+ {f"/crm/pipelines/2026-03/{o}": [PIPELINE_PAYLOAD] for o in PIPELINE_OBJECT_TYPES}
+ ),
+ ):
+ rows = _call(get_pipelines_rows)
+
+ assert [r["object_type"] for r in rows] == list(PIPELINE_OBJECT_TYPES)
+ assert all(r["id"] == "default" for r in rows)
+ assert all("stages" not in r for r in rows)
+
+ def test_pipeline_stages_carry_parent_ids(self) -> None:
+ # Stage ids repeat across pipelines, so without object_type + pipeline_id the table's
+ # primary key is not unique and every merge multi-matches.
+ with patch(
+ _FETCH_DATA,
+ new=_fetch_data_returning(
+ {f"/crm/pipelines/2026-03/{o}": [PIPELINE_PAYLOAD] for o in PIPELINE_OBJECT_TYPES}
+ ),
+ ):
+ rows = _call(get_pipeline_stages_rows)
+
+ assert {(r["object_type"], r["pipeline_id"], r["id"]) for r in rows} == {
+ (o, "default", "appointmentscheduled") for o in PIPELINE_OBJECT_TYPES
+ }
+
+ def test_nested_values_are_json_encoded(self) -> None:
+ # Stage metadata keys differ between deals and tickets. Left as a dict, PyArrow infers a
+ # different struct per batch and the table's schema drifts between syncs.
+ with patch(
+ _FETCH_DATA,
+ new=_fetch_data_returning(
+ {f"/crm/pipelines/2026-03/{o}": [PIPELINE_PAYLOAD] for o in PIPELINE_OBJECT_TYPES}
+ ),
+ ):
+ rows = _call(get_pipeline_stages_rows)
+
+ assert json.loads(rows[0]["metadata"]) == {"isClosed": "false", "probability": "0.2"}
+
+ @pytest.mark.parametrize(
+ "fetcher,path,payload",
+ [
+ (get_owners_rows, "/crm/owners/2026-03", {"id": "1", "email": "[email protected]"}),
+ (get_properties_rows, "/crm/properties/2026-03/deals", {"name": "amount", "label": "Amount"}),
+ ],
+ )
+ def test_missing_optional_fields_are_backfilled(self, fetcher: Any, path: str, payload: dict[str, Any]) -> None:
+ # A portal that never sets an optional field would otherwise produce a narrower table than
+ # one that does, and the column would appear or vanish between syncs.
+ with patch(_FETCH_DATA, new=_fetch_data_returning({path: [[payload]]})):
+ rows = _call(fetcher)
+
+ table = "owners" if fetcher is get_owners_rows else "properties"
+ assert set(rows[0]) >= set(HUBSPOT_METADATA_ENDPOINTS[table].columns)
+
+ def test_owners_uses_the_pinned_date_version_path(self) -> None:
+ # "/crm/v3/owners" has no path segment after the resource, so a version rewrite that only
+ # matches "/crm/v3/<resource>/" would silently leave owners on the legacy path.
+ captured: list[str] = []
+
+ def _fake(path: str, *_args: Any, **_kwargs: Any) -> Iterator[list[dict[str, Any]]]:
+ captured.append(path)
+ yield []
+
+ with patch(_FETCH_DATA, new=_fake):
+ _call(get_owners_rows)
+
+ assert captured == ["/crm/owners/2026-03"]
+
+ def test_properties_skips_an_object_type_the_portal_cannot_read(self) -> None:
+ # Property definitions are fanned out over every object endpoint, several of which need a
+ # scope the connection may not hold. One 403 must not take the whole table down.
+ response = MagicMock()
+ response.status_code = 403
+
+ def _fake(path: str, *_args: Any, **_kwargs: Any) -> Iterator[list[dict[str, Any]]]:
+ if path == "/crm/properties/2026-03/deals":
+ yield [{"name": "amount"}]
+ return
+ raise HTTPError("403 Client Error", response=response)
+
+ with patch(_FETCH_DATA, new=_fake):
+ rows = _call(get_properties_rows)
+
+ assert [r["name"] for r in rows] == ["amount"]
+
+ def test_server_error_still_fails_the_table(self) -> None:
+ response = MagicMock()
+ response.status_code = 500
+
+ def _fake(*_args: Any, **_kwargs: Any) -> Iterator[list[dict[str, Any]]]:
+ if response.status_code:
+ raise HTTPError("500 Server Error", response=response)
+ yield []
+
+ with patch(_FETCH_DATA, new=_fake), pytest.raises(HTTPError):
+ _call(get_owners_rows)
+
+ def test_every_lookup_endpoint_has_a_fetcher(self) -> None:
+ assert set(METADATA_FETCHERS) == set(HUBSPOT_METADATA_ENDPOINTS)
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 6ea8c628bc71..90490d637586 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
@@ -25,6 +25,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.hubspot.se
HUBSPOT_API_VERSION_2026_03,
HUBSPOT_API_VERSION_V3,
HUBSPOT_ENDPOINTS,
+ HUBSPOT_METADATA_ENDPOINTS,
SEARCH_PAGE_SIZE,
SEARCH_RESULT_CAP,
)
@@ -213,6 +214,43 @@ class TestResolveSearchProperties:
assert "hs_internal_only" not in props # hs_ props are not auto-added
assert get_names_mock.call_args.kwargs["api_version"] == HUBSPOT_API_VERSION_2026_03
+ @pytest.mark.parametrize(
+ "endpoint,object_type,discover_all,expect_hs_prop",
+ [
+ # Engagement and commerce objects keep almost everything behind hs_-prefixed
+ # properties, so without discovery they sync only the two seeded columns.
+ ("calls", "calls", True, True),
+ ("line_items", "line_items", True, True),
+ # The original objects ship hand-written default lists; auto-adding every hs_ property
+ # would widen every existing customer's table.
+ ("deals", "deal", False, False),
+ ],
+ )
+ def test_discover_all_properties_controls_hs_prefixed_props(
+ self, endpoint: str, object_type: str, discover_all: bool, expect_hs_prop: bool
+ ) -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.hubspot.hubspot._get_property_names",
+ return_value=["hs_call_duration", "custom_field"],
+ ):
+ props, _ = _resolve_search_properties(
+ api_key="k",
+ refresh_token="r",
+ endpoint=endpoint,
+ object_type=object_type,
+ selected_properties=None,
+ include_custom_props=True,
+ required_props=["hs_lastmodifieddate", "hs_object_id"],
+ logger=MagicMock(),
+ source_id=None,
+ api_version=HUBSPOT_API_VERSION_2026_03,
+ discover_all_properties=discover_all,
+ )
+
+ assert ("hs_call_duration" in props) is expect_hs_prop
+ assert "custom_field" in props
+ assert HUBSPOT_ENDPOINTS[endpoint].discover_all_properties is discover_all
+
def test_invalid_selected_ignored(self) -> None:
logger = MagicMock()
with patch(
@@ -988,6 +1026,25 @@ class TestHubspotSourceRouting:
)
assert resp.name == "deals"
+ @pytest.mark.parametrize("endpoint", list(HUBSPOT_METADATA_ENDPOINTS))
+ def test_lookup_tables_bypass_the_crm_paths(self, endpoint: str) -> None:
+ # Lookup tables aren't in HUBSPOT_ENDPOINTS, so routing them through the CRM paths raises
+ # KeyError. Their keys are also composite: falling back to ["id"] would let the deals and
+ # tickets "default" pipelines overwrite each other on merge.
+ resp = hubspot_source(
+ api_key="k",
+ refresh_token="r",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ use_search_path=False,
+ api_version=HUBSPOT_API_VERSION_V3,
+ )
+
+ assert resp.name == endpoint
+ assert resp.primary_keys == HUBSPOT_METADATA_ENDPOINTS[endpoint].primary_keys
+ assert resp.partition_mode is None
+
class TestGetRowsFullRefresh:
"""Smoke test that the GET path still works alongside the search path."""
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 ddd0a1a4b4df..a0c6c7b10fb1 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
@@ -6,9 +6,11 @@ from unittest.mock import MagicMock, patch
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs
from products.warehouse_sources.backend.temporal.data_imports.sources.hubspot.settings import (
DEFAULT_PROPS,
+ ENDPOINTS,
HUBSPOT_API_VERSION_2026_03,
HUBSPOT_API_VERSION_V3,
HUBSPOT_ENDPOINTS,
+ HUBSPOT_METADATA_ENDPOINTS,
apply_crm_api_version,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.hubspot.source import (
@@ -46,14 +48,14 @@ def _make_inputs(
class TestGetSchemas:
- def test_declares_incremental_for_all_endpoints(self) -> None:
+ def test_declares_incremental_for_all_crm_endpoints(self) -> None:
src = HubspotSource()
schemas = src.get_schemas(MagicMock(), team_id=1)
by_name = {s.name: s for s in schemas}
- # Every endpoint currently has a cursor property, so all should support incremental.
- assert set(by_name.keys()) == set(HUBSPOT_ENDPOINTS.keys())
- for name, schema in by_name.items():
+ assert set(by_name.keys()) == set(ENDPOINTS)
+ for name in HUBSPOT_ENDPOINTS:
+ schema = by_name[name]
endpoint_config = HUBSPOT_ENDPOINTS[name]
assert schema.supports_incremental is bool(endpoint_config.cursor_filter_property_field)
assert schema.supports_append is schema.supports_incremental
@@ -63,14 +65,34 @@ class TestGetSchemas:
assert schema.incremental_fields
assert schema.incremental_fields[0]["field"] == expected_field
- def test_leads_is_default_disabled_others_default_enabled(self) -> None:
- # Leads needs the crm.objects.leads.read scope existing connections lack, so it must start
- # off; flipping it on by default would 403 every existing customer's sync.
+ def test_lookup_tables_are_full_refresh_only(self) -> None:
+ # Pipelines, stages, property definitions and owners have no server-side timestamp filter,
+ # so advertising them as incremental would checkpoint a watermark nothing can filter on.
src = HubspotSource()
by_name = {s.name: s for s in src.get_schemas(MagicMock(), team_id=1)}
- assert by_name["leads"].should_sync_default is False
- assert all(s.should_sync_default for name, s in by_name.items() if name != "leads")
+ for name in HUBSPOT_METADATA_ENDPOINTS:
+ assert by_name[name].supports_incremental is False
+ assert by_name[name].supports_append is False
+ assert by_name[name].incremental_fields == []
+
+ def test_tables_needing_an_ungranted_scope_are_default_disabled(self) -> None:
+ # Each of these reads under an OAuth scope existing connections were never granted, so they
+ # must start off; flipping one on by default would 403 an existing customer's sync.
+ src = HubspotSource()
+ by_name = {s.name: s for s in src.get_schemas(MagicMock(), team_id=1)}
+
+ expected_disabled = {
+ "leads",
+ "owners",
+ "line_items",
+ "products",
+ "invoices",
+ "orders",
+ "subscriptions",
+ "commerce_payments",
+ }
+ assert {name for name, s in by_name.items() if not s.should_sync_default} == expected_disabled
def test_filters_by_names(self) -> None:
src = HubspotSource()
@@ -223,6 +245,19 @@ class TestSourceForPipelineRouting:
class TestSettingsShape:
+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
+ def test_endpoint_resolves_to_exactly_one_config(self, endpoint: str) -> None:
+ # An endpoint in neither dict raises KeyError mid-sync; one in both would take whichever
+ # branch happens to be checked first.
+ assert (endpoint in HUBSPOT_ENDPOINTS) is not (endpoint in HUBSPOT_METADATA_ENDPOINTS)
+
+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
+ def test_endpoint_has_canonical_descriptions(self, endpoint: str) -> None:
+ # Curated descriptions are what the AI agent sees; a table missing from here falls back to
+ # paying an LLM to re-derive a fixed schema for every team that syncs it.
+ descriptions = HubspotSource().get_canonical_descriptions()
+ assert descriptions[endpoint]["description"]
+
@pytest.mark.parametrize("endpoint", list(HUBSPOT_ENDPOINTS.keys()))
def test_cursor_property_is_in_default_props(self, endpoint: str) -> None:
config = HUBSPOT_ENDPOINTS[endpoint]
@@ -318,6 +353,11 @@ class TestApiVersion:
HUBSPOT_API_VERSION_2026_03,
"/crm/associations/2026-03/contacts/deals/batch/read",
),
+ ("/crm/v3/pipelines/deals", HUBSPOT_API_VERSION_2026_03, "/crm/pipelines/2026-03/deals"),
+ # Resource-only path: nothing follows the resource name, so a rewrite that requires a
+ # trailing separator would leave owners calling the legacy endpoint under a date pin.
+ ("/crm/v3/owners", HUBSPOT_API_VERSION_2026_03, "/crm/owners/2026-03"),
+ ("/crm/v3/owners", HUBSPOT_API_VERSION_V3, "/crm/v3/owners"),
],
)
def test_apply_crm_api_version(self, path: str, api_version: str, expected: str) -> None: