:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(notion): skip pages that 404 during blocks/comments fan-out (#64193)
Tom Owersa205c60ebb30
diff --git a/posthog/temporal/data_imports/sources/notion/notion.py b/posthog/temporal/data_imports/sources/notion/notion.pyindex 4451e3c9ddbb..e9a3763816c8 100644--- a/posthog/temporal/data_imports/sources/notion/notion.py+++ b/posthog/temporal/data_imports/sources/notion/notion.py@@ -48,6 +48,12 @@ class NotionRetryableError(Exception):self.retry_after = retry_after+class NotionNotFoundError(Exception):+ """Notion returned 404 for a resource: the page/block was deleted or is no longer shared with+ the integration. In the per-page fan-out streams (blocks/comments) a single page going missing+ is recoverable — skip it and keep syncing the rest rather than crashing the whole sync."""++@dataclasses.dataclassclass NotionResumeConfig:next_cursor: str@@ -123,6 +129,12 @@ def _request(if response.status_code >= 500:raise NotionRetryableError(f"Notion API error (retryable): status={response.status_code}, url={url}")+ # A 404 on a per-page resource (a page's comments or block children) means that page was deleted+ # or unshared between enumeration and fetch. The fan-out streams catch this and skip the page;+ # on the collection endpoints (search/users) it is unexpected and propagates as a sync failure.+ if response.status_code == 404:+ raise NotionNotFoundError(f"Notion resource not found: url={url}")+if not response.ok:logger.error(f"Notion API error: status={response.status_code}, body={response.text}, url={url}")response.raise_for_status()@@ -252,7 +264,15 @@ def _iter_block_children(if cursor:params["start_cursor"] = cursor- data = _request(session, "GET", f"/v1/blocks/{block_id}/children", logger, params=params)+ try:+ data = _request(session, "GET", f"/v1/blocks/{block_id}/children", logger, params=params)+ except NotionNotFoundError:+ logger.warning(+ "Notion: skipping missing or unshared block while fetching children",+ page_id=page_id,+ block_id=block_id,+ )+ returnfor block in data.get("results", []):block["_page_id"] = page_idyield block@@ -297,7 +317,14 @@ def _comments_stream(session: requests.Session, logger: FilteringBoundLogger) ->if cursor:params["start_cursor"] = cursor- data = _request(session, "GET", "/v1/comments", logger, params=params)+ try:+ data = _request(session, "GET", "/v1/comments", logger, params=params)+ except NotionNotFoundError:+ logger.warning(+ "Notion: skipping comments for missing or unshared page",+ page_id=page_id,+ )+ breakfor comment in data.get("results", []):comment["_page_id"] = page_idbatcher.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.pyindex 6f559450ee7e..e87f7e008f05 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,+ NotionNotFoundError,NotionResumeConfig,NotionRetryableError,_comments_stream,@@ -206,6 +207,61 @@ class TestNotion:assert result == {"results": []}assert attempts["count"] == 2+ def test_request_404_raises_not_found(self) -> None:+ # Notion 404s a page/block that was deleted or unshared. It must surface as the typed+ # NotionNotFoundError so the fan-out streams can skip it instead of crashing.+ session = FakeSession([FakeResponse({}, status_code=404)])+ with pytest.raises(NotionNotFoundError):+ cast(Any, _request).__wrapped__(+ cast(requests.Session, session), "GET", "/v1/comments", mock.MagicMock(), params={}+ )++ def test_request_404_is_not_retried(self) -> None:+ # A 404 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=404)++ session = mock.MagicMock()+ session.request.side_effect = request++ with mock.patch(f"{MODULE}._wait_strategy", return_value=0):+ with pytest.raises(NotionNotFoundError):+ _request(cast(requests.Session, session), "GET", "/v1/comments", mock.MagicMock(), params={})++ assert attempts["count"] == 1++ 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.+ 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=404) # comments for p1 -> gone+ 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+ # search + comments(p1, 404) + comments(p2)+ assert len(session.calls) == 3++ def test_block_children_skips_missing_block(self) -> None:+ # A block that 404s (deleted/unshared) must terminate that branch gracefully, yielding nothing.+ session = FakeSession([FakeResponse({}, status_code=404)])+ logger = mock.MagicMock()+ blocks = list(_iter_block_children(cast(requests.Session, session), "gone", "page-1", logger, 0))++ assert blocks == []+ assert logger.warning.called+@parameterized.expand([("5", 5.0), (None, None), ("not-a-number", None)])def test_parse_retry_after(self, value: str | None, expected: float | None) -> None:assert _parse_retry_after(value) == expected