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(pardot): sync the tables the v5 API refuses with a 400 (#102066)

Tom Owers205bbe5ec8db
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pardot/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pardot/canonical_descriptions.py
index 88ffa0775251..5ff8b96c6a53 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/pardot/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pardot/canonical_descriptions.py
@@ -205,7 +205,6 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"isRequired": "Whether the field is required on forms.",
"isRecordMultipleResponses": "Whether every response is kept rather than overwriting the last one.",
"isUseValues": "Whether the field is limited to a predefined set of values.",
- "valuesPrefill": "Whether the field's values prefill for known prospects.",
"isAnalyticsSynced": "Whether the field syncs with connected analytics.",
},
},
@@ -240,7 +239,6 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"isOperational": "Whether the email is operational and ignores opt-outs.",
"isPaused": "Whether sending is paused.",
"isSent": "Whether the email has been sent.",
- "scheduledTime": "Timestamp the email is scheduled to send at.",
"sentAt": "Timestamp the email was sent at.",
},
},
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pardot/pardot.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pardot/pardot.py
index 5726f3d0ef75..8428631b6f79 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/pardot/pardot.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pardot/pardot.py
@@ -1,3 +1,4 @@
+import re
import dataclasses
from collections.abc import Iterator
from datetime import UTC, date, datetime
@@ -41,6 +42,18 @@ class PardotPageTokenExpiredError(Exception):
"""A saved `nextPageToken` was rejected — page tokens expire after 4 hours."""
+class PardotQueryRejectedError(Exception):
+ """v5 refused the query itself, so an identical retry cannot succeed."""
+
+
+# The source keys its non-retryable error map on this, so the two must not drift apart.
+QUERY_REJECTED_MESSAGE = "Account Engagement rejected the request"
+
+# v5 names the offending field in the 400 body, e.g. "Invalid parameter: fields. It
+# contains an invalid or unknown field: salesforceCmsId."
+_UNKNOWN_FIELD_PATTERN = re.compile(r"invalid or unknown field:\s*([A-Za-z0-9_]+)", re.IGNORECASE)
+
+
def _api_host(environment: str) -> str:
api_host = PARDOT_HOSTS.get(environment)
if api_host is None:
@@ -75,16 +88,24 @@ def _refresh_token(refresh_token: str | None, instance_url: str | None) -> str:
def _format_datetime(value: Any) -> str:
- """Format an incremental cursor as the ISO 8601 UTC timestamp v5 filters expect."""
+ """Format an incremental cursor as the ISO 8601 UTC timestamp v5 filters expect.
+
+ v5 wants a numeric offset and refuses the `Z` designator with "Invalid date time
+ value", which fails the whole query rather than just the filter. Strings go through
+ the same conversion so a stored cursor cannot smuggle a `Z` back in.
+ """
if isinstance(value, datetime):
dt = value
elif isinstance(value, date):
dt = datetime.combine(value, datetime.min.time())
else:
- return str(value)
+ try:
+ dt = datetime.fromisoformat(str(value))
+ except ValueError:
+ return str(value)
utc_dt = dt.replace(tzinfo=UTC) if dt.tzinfo is None else dt.astimezone(UTC)
- return utc_dt.strftime("%Y-%m-%dT%H:%M:%SZ")
+ return utc_dt.strftime("%Y-%m-%dT%H:%M:%S+00:00")
def _cursor_field(config: PardotEndpointConfig, incremental_field: str | None) -> str | None:
@@ -130,6 +151,29 @@ def _is_expired_page_token(response: requests.Response) -> bool:
return "pagetoken" in response.text.lower().replace(" ", "").replace("_", "")
+def _rejected_field(response: requests.Response) -> str | None:
+ """The field a 400 refuses, when an unrequestable field is why it was refused.
+
+ Which fields a business unit can return depends on its edition and connectors, so a
+ field the v5 docs list can still be refused here — and one refused name fails the
+ whole query, leaving the table empty.
+ """
+ if response.status_code != 400:
+ return None
+ match = _UNKNOWN_FIELD_PATTERN.search(response.text)
+ return match.group(1) if match else None
+
+
+def _error_reason(response: requests.Response) -> str:
+ """The reason v5 gives for refusing a request, for the error the customer reads."""
+ try:
+ body = response.json()
+ except ValueError:
+ body = None
+ message = body.get("message") if isinstance(body, dict) else None
+ return str(message).strip() if message else response.text.strip()[:500]
+
+
def validate_credentials(
environment: str,
business_unit_id: str,
@@ -208,6 +252,15 @@ def get_rows(
# Only `fields` may ride along with a page token — sending limit/orderBy/filters
# alongside one is a 400.
page_params = {"fields": query_params["fields"]}
+ fields = list(config.fields)
+
+ def drop_field(name: str) -> bool:
+ """Stop asking for a field v5 refuses, so the rest of the table still syncs."""
+ if name == config.primary_key or name not in fields:
+ return False
+ fields.remove(name)
+ query_params["fields"] = page_params["fields"] = ",".join(fields)
+ return True
def request(params: dict[str, Any]) -> dict[str, Any]:
nonlocal token
@@ -226,11 +279,23 @@ def get_rows(
token = _refresh_token(refresh_token, instance_url)
response = _do()
+ # v5 names one refused field per response, so drop them one at a time. Each pass
+ # removes a name from `fields`, which bounds the loop.
+ while (rejected := _rejected_field(response)) is not None and drop_field(rejected):
+ logger.warning(
+ f"Account Engagement cannot return '{rejected}' for this business unit, "
+ f"so {config.name} syncs without that column"
+ )
+ params = {**params, "fields": query_params["fields"]}
+ response = _do()
+
if _is_expired_page_token(response):
raise PardotPageTokenExpiredError(response.text)
if not response.ok:
logger.error(f"Account Engagement API error: status={response.status_code}, body={response.text}")
+ if response.status_code == 400:
+ raise PardotQueryRejectedError(f"{QUERY_REJECTED_MESSAGE}: {_error_reason(response)}")
response.raise_for_status()
return response.json()
@@ -244,7 +309,7 @@ def get_rows(
resumed = True
while True:
- params = {**page_params, "nextPageToken": next_page_token} if next_page_token else query_params
+ params = {**page_params, "nextPageToken": next_page_token} if next_page_token else {**query_params}
try:
data = request(params)
except PardotPageTokenExpiredError:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pardot/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pardot/settings.py
index ce4efa50b1b8..6ee8aa988b85 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/pardot/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pardot/settings.py
@@ -332,7 +332,8 @@ PARDOT_ENDPOINTS: dict[str, PardotEndpointConfig] = {
"isUseValues",
"isRequired",
"isAnalyticsSynced",
- "valuesPrefill",
+ # valuesPrefill is write-only on create — the v5 API 400s if it's requested
+ # in a query's `fields` list.
"salesforceId",
*_TIMESTAMPS,
),
@@ -384,7 +385,8 @@ PARDOT_ENDPOINTS: dict[str, PardotEndpointConfig] = {
"isPaused",
"isSent",
"isDeleted",
- "scheduledTime",
+ # scheduledTime is write-only on create — the v5 API 400s if it's requested
+ # in a query's `fields` list.
"sentAt",
*_TIMESTAMPS,
),
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pardot/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pardot/source.py
index f38d87941072..e1b0e193a572 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/pardot/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pardot/source.py
@@ -24,6 +24,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.sch
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.pardot import PardotSourceConfig
from products.warehouse_sources.backend.temporal.data_imports.sources.pardot.pardot import (
+ QUERY_REJECTED_MESSAGE,
PardotResumeConfig,
pardot_source,
validate_credentials as validate_pardot_credentials,
@@ -63,6 +64,9 @@ class PardotSource(ResumableSource[PardotSourceConfig, PardotResumeConfig], OAut
"Integration not found": "The linked Account Engagement integration no longer exists. Please reconnect the source.",
"401 Client Error: Unauthorized for url": "Account Engagement rejected the access token. Please reconnect the source.",
"403 Client Error: Forbidden for url": "Account Engagement denied access. Check that the connected user has API access and that the business unit ID is correct.",
+ # A refused query is deterministic, so retrying burns the activity's whole budget
+ # on the same 400. None keeps the raised message, which carries the reason v5 gave.
+ QUERY_REJECTED_MESSAGE: None,
}
@property
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pardot/tests/test_pardot.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pardot/tests/test_pardot.py
index 8f825d525a68..18fb987489fc 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/pardot/tests/test_pardot.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pardot/tests/test_pardot.py
@@ -13,6 +13,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
from products.warehouse_sources.backend.temporal.data_imports.sources.pardot.pardot import (
PAGE_SIZE,
PardotPageTokenExpiredError,
+ PardotQueryRejectedError,
PardotResumeConfig,
_build_query_params,
_format_datetime,
@@ -98,10 +99,14 @@ class TestFormatDatetime:
@pytest.mark.parametrize(
"value, expected",
[
- (datetime(2024, 1, 2, 3, 4, 5, tzinfo=UTC), "2024-01-02T03:04:05Z"),
- (datetime(2024, 1, 2, 3, 4, 5), "2024-01-02T03:04:05Z"),
- (date(2024, 1, 2), "2024-01-02T00:00:00Z"),
- ("2024-01-02T03:04:05Z", "2024-01-02T03:04:05Z"),
+ # v5 refuses the `Z` designator with "Invalid date time value" and fails the
+ # whole query, so every branch has to emit a numeric offset.
+ (datetime(2024, 1, 2, 3, 4, 5, tzinfo=UTC), "2024-01-02T03:04:05+00:00"),
+ (datetime(2024, 1, 2, 3, 4, 5), "2024-01-02T03:04:05+00:00"),
+ (date(2024, 1, 2), "2024-01-02T00:00:00+00:00"),
+ ("2024-01-02T03:04:05Z", "2024-01-02T03:04:05+00:00"),
+ ("2024-01-02T05:04:05+02:00", "2024-01-02T03:04:05+00:00"),
+ ("not a timestamp", "not a timestamp"),
],
)
def test_formats_cursor_values(self, value: Any, expected: str) -> None:
@@ -110,7 +115,7 @@ class TestFormatDatetime:
def test_converts_non_utc_offsets(self) -> None:
naive = datetime.fromisoformat("2024-01-02T05:04:05+02:00")
- assert _format_datetime(naive) == "2024-01-02T03:04:05Z"
+ assert _format_datetime(naive) == "2024-01-02T03:04:05+00:00"
class TestBuildQueryParams:
@@ -136,7 +141,7 @@ class TestBuildQueryParams:
)
assert params["orderBy"] == "updatedAt"
- assert params["updatedAtAfterOrEqualTo"] == "2024-05-01T00:00:00Z"
+ assert params["updatedAtAfterOrEqualTo"] == "2024-05-01T00:00:00+00:00"
def test_first_incremental_run_sorts_on_the_cursor_without_filtering(self) -> None:
params = _build_query_params(
@@ -180,6 +185,46 @@ class TestBuildQueryParams:
assert "orderBy" not in params
+def _refused_field_body(field: str) -> dict[str, Any]:
+ return {"code": 51, "message": f"Invalid parameter: fields. It contains an invalid or unknown field: {field}."}
+
+
+class TestFieldLists:
+ @pytest.mark.parametrize(
+ "endpoint, write_only_field",
+ [
+ # v5 400s a query whose `fields` list names a write-only-on-create field.
+ ("custom_fields", "valuesPrefill"),
+ ("list_emails", "scheduledTime"),
+ ],
+ )
+ def test_does_not_request_write_only_fields(self, endpoint: str, write_only_field: str) -> None:
+ assert write_only_field not in PARDOT_ENDPOINTS[endpoint].fields
+
+ def test_a_refused_field_is_dropped_and_the_query_retried(self) -> None:
+ session = _session(
+ [
+ _response(_refused_field_body("salesforceCmsId"), status_code=400),
+ _response({"values": [{"id": 1}], "nextPageToken": "t1"}),
+ _response({"values": [{"id": 2}]}),
+ ]
+ )
+
+ rows = _collect(session, FakeResumeManager(), endpoint="forms")
+ first, retried, paged = _get_params(session)
+
+ assert [row["id"] for row in rows] == [1, 2]
+ assert "salesforceCmsId" in first["fields"].split(",")
+ assert "salesforceCmsId" not in retried["fields"].split(",")
+ assert paged["fields"] == retried["fields"]
+
+ def test_a_refused_primary_key_stops_the_endpoint(self) -> None:
+ session = _session([_response(_refused_field_body("id"), status_code=400)])
+
+ with pytest.raises(PardotQueryRejectedError):
+ _collect(session, FakeResumeManager(), endpoint="forms")
+
+
class TestPagination:
def test_walks_pages_until_the_token_runs_out(self) -> None:
session = _session(
@@ -270,13 +315,24 @@ class TestResume:
with pytest.raises(PardotPageTokenExpiredError):
_collect(session, FakeResumeManager())
- def test_other_bad_requests_are_raised_rather_than_restarted(self) -> None:
- session = _session([_response({"message": "Invalid field name"}, status_code=400)])
+ def test_other_bad_requests_surface_the_reason_rather_than_restarting(self) -> None:
+ # raise_for_status would store the 900-character request URL as the customer's error,
+ # which says nothing about why v5 refused it.
+ session = _session(
+ [
+ _response(
+ {"code": 51, "message": "Invalid parameter: Parameter updatedAtAfterOrEqualTo is invalid."},
+ status_code=400,
+ )
+ ]
+ )
manager = FakeResumeManager(PardotResumeConfig(next_page_token="saved-token"))
- with pytest.raises(requests.HTTPError):
+ with pytest.raises(PardotQueryRejectedError) as exc_info:
_collect(session, manager)
+ assert "Parameter updatedAtAfterOrEqualTo is invalid" in str(exc_info.value)
+
class TestAuth:
def test_the_integration_token_is_used_as_is(self) -> None: