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(notion): skip blocks Notion rejects with 400 instead of crashing the sync (#65229)

Tom Owers6c69c55e4639
diff --git a/posthog/temporal/data_imports/sources/notion/notion.py b/posthog/temporal/data_imports/sources/notion/notion.py
index e9a3763816c8..48d392e65814 100644
--- a/posthog/temporal/data_imports/sources/notion/notion.py
+++ b/posthog/temporal/data_imports/sources/notion/notion.py
@@ -54,6 +54,13 @@ class NotionNotFoundError(Exception):
is recoverable — skip it and keep syncing the rest rather than crashing the whole sync."""
+class NotionBadRequestError(Exception):
+ """Notion returned 400 for a per-page resource. Some blocks advertise has_children but cannot be
+ expanded via the API (e.g. blocks backed by synced/external content), so Notion rejects the
+ children request. Like a 404, this is recoverable in the fan-out streams (blocks/comments): skip
+ the offending block/page and keep syncing rather than crashing the whole sync."""
+
+
@dataclasses.dataclass
class NotionResumeConfig:
next_cursor: str
@@ -135,6 +142,14 @@ def _request(
if response.status_code == 404:
raise NotionNotFoundError(f"Notion resource not found: url={url}")
+ # A 400 on a per-page resource (block children) means Notion rejects expanding that specific
+ # block even though it advertised has_children. The fan-out streams skip it; on the collection
+ # endpoints (search/users) a 400 is a genuine bad request and propagates as a sync failure.
+ if response.status_code == 400:
+ # Carry Notion's error body so callers can log its `code`/`message` (e.g. `validation_error`),
+ # which distinguishes the known has_children quirk from an unexpected 400.
+ raise NotionBadRequestError(f"Notion rejected request: url={url}, body={response.text}")
+
if not response.ok:
logger.error(f"Notion API error: status={response.status_code}, body={response.text}, url={url}")
response.raise_for_status()
@@ -273,6 +288,14 @@ def _iter_block_children(
block_id=block_id,
)
return
+ except NotionBadRequestError as e:
+ logger.warning(
+ "Notion: skipping block whose children Notion rejected",
+ page_id=page_id,
+ block_id=block_id,
+ error=str(e),
+ )
+ return
for block in data.get("results", []):
block["_page_id"] = page_id
yield block
@@ -325,6 +348,13 @@ def _comments_stream(session: requests.Session, logger: FilteringBoundLogger) ->
page_id=page_id,
)
break
+ except NotionBadRequestError as e:
+ logger.warning(
+ "Notion: skipping comments Notion rejected for page",
+ page_id=page_id,
+ error=str(e),
+ )
+ break
for comment in data.get("results", []):
comment["_page_id"] = page_id
batcher.batch(comment)
diff --git a/posthog/temporal/data_imports/sources/notion/tests/test_notion.py b/posthog/temporal/data_imports/sources/notion/tests/test_notion.py
index e87f7e008f05..e21afa1f1c86 100644
--- a/posthog/temporal/data_imports/sources/notion/tests/test_notion.py
+++ b/posthog/temporal/data_imports/sources/notion/tests/test_notion.py
@@ -13,6 +13,7 @@ from posthog.temporal.data_imports.sources.notion.notion import (
MAX_CHILD_PAGES_PER_PARENT,
MAX_RETRY_AFTER_SECONDS,
NOTION_VERSION,
+ NotionBadRequestError,
NotionNotFoundError,
NotionResumeConfig,
NotionRetryableError,
@@ -233,6 +234,65 @@ class TestNotion:
assert attempts["count"] == 1
+ def test_request_400_raises_bad_request(self) -> None:
+ # Notion 400s a block it won't expand (e.g. has_children backed by synced/external content).
+ # It must surface as the typed NotionBadRequestError, carrying the body so callers can log
+ # Notion's `code`/`message`, so the fan-out streams can skip it.
+ response = FakeResponse({}, status_code=400)
+ response.text = '{"code":"validation_error","message":"boom"}'
+ session = FakeSession([response])
+ with pytest.raises(NotionBadRequestError) as exc_info:
+ cast(Any, _request).__wrapped__(
+ cast(requests.Session, session), "GET", "/v1/blocks/b1/children", mock.MagicMock(), params={}
+ )
+ assert "validation_error" in str(exc_info.value)
+
+ def test_request_400_is_not_retried(self) -> None:
+ # A 400 is not transient, so tenacity must propagate it immediately rather than burn attempts.
+ attempts = {"count": 0}
+
+ def request(*_args: Any, **_kwargs: Any) -> FakeResponse:
+ attempts["count"] += 1
+ return FakeResponse({}, status_code=400)
+
+ session = mock.MagicMock()
+ session.request.side_effect = request
+
+ with mock.patch(f"{MODULE}._wait_strategy", return_value=0):
+ with pytest.raises(NotionBadRequestError):
+ _request(cast(requests.Session, session), "GET", "/v1/blocks/b1/children", mock.MagicMock(), params={})
+
+ assert attempts["count"] == 1
+
+ def test_block_children_skips_rejected_block(self) -> None:
+ # A block Notion rejects with 400 (advertised has_children but can't be expanded) must
+ # terminate that branch gracefully, yielding nothing, rather than crashing the whole sync.
+ session = FakeSession([FakeResponse({}, status_code=400)])
+ logger = mock.MagicMock()
+ blocks = list(_iter_block_children(cast(requests.Session, session), "rejected", "page-1", logger, 0))
+
+ assert blocks == []
+ assert logger.warning.called
+
+ def test_comments_stream_skips_rejected_page(self) -> None:
+ # Notion 400s the comments fetch for one page; that page is skipped without crashing the
+ # sync, and comments for the surviving page still come through.
+ def responses(index: int) -> FakeResponse:
+ if index == 0:
+ return _list_response([{"id": "p1"}, {"id": "p2"}], has_more=False, next_cursor=None)
+ if index == 1:
+ return FakeResponse({}, status_code=400) # comments for p1 -> rejected
+ return _list_response([{"id": "cm"}], has_more=False, next_cursor=None) # comments for p2
+
+ session = FakeSession(responses)
+ logger = mock.MagicMock()
+ tables = list(_comments_stream(cast(requests.Session, session), logger))
+
+ total_rows = sum(t.num_rows for t in tables)
+ assert total_rows == 1
+ assert logger.warning.called
+ assert len(session.calls) == 3
+
def test_comments_stream_skips_missing_page(self) -> None:
# One page is deleted/unshared between search and the comments fetch (404). That page must be
# skipped without crashing the sync; comments for the surviving page still come through.