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): restart search stream when a resumed cursor is invalid (#70749)

Tom Owersb8072756a9cf
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/notion/notion.py b/products/warehouse_sources/backend/temporal/data_imports/sources/notion/notion.py
index e1ce9fc1587c..40b57d9a6186 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/notion/notion.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/notion/notion.py
@@ -124,6 +124,11 @@ def _parse_retry_after(value: str | None) -> float | None:
return None
+def _is_invalid_start_cursor(error: NotionBadRequestError) -> bool:
+ # Notion rejects an expired or otherwise stale pagination cursor with this validation_error text.
+ return "start_cursor provided is invalid" in str(error)
+
+
_wait_exponential = wait_exponential_jitter(initial=1, max=MAX_RETRY_WAIT_SECONDS)
@@ -237,14 +242,24 @@ def _search_stream(
cursor = resume.next_cursor if resume is not None else None
while True:
- data = _request(
- session,
- "POST",
- "/v1/search",
- logger,
- json_body=_search_body(config.object_filter, cursor),
- throttle=throttle,
- )
+ try:
+ data = _request(
+ session,
+ "POST",
+ "/v1/search",
+ logger,
+ json_body=_search_body(config.object_filter, cursor),
+ throttle=throttle,
+ )
+ except NotionBadRequestError as e:
+ if cursor is None or not _is_invalid_start_cursor(e):
+ raise
+ # A resumed cursor can expire before the retry runs; Notion then rejects it as invalid.
+ # Restart from the beginning rather than failing the sync — search is sorted ascending
+ # and rows dedup on the primary key at merge, so replaying loses nothing.
+ logger.warning("Notion: resumed search cursor rejected as invalid; restarting stream from the start")
+ cursor = None
+ continue
results = data.get("results", [])
has_more = data.get("has_more", False)
next_cursor = data.get("next_cursor")
@@ -280,7 +295,17 @@ def _users_stream(
if cursor:
params["start_cursor"] = cursor
- data = _request(session, "GET", "/v1/users", logger, params=params, throttle=throttle)
+ try:
+ data = _request(session, "GET", "/v1/users", logger, params=params, throttle=throttle)
+ except NotionBadRequestError as e:
+ if cursor is None or not _is_invalid_start_cursor(e):
+ raise
+ # A resumed cursor can expire before the retry runs; Notion then rejects it as invalid.
+ # Restart from the beginning rather than failing the sync — rows dedup on the primary key
+ # at merge, so replaying loses nothing.
+ logger.warning("Notion: resumed users cursor rejected as invalid; restarting stream from the start")
+ cursor = None
+ continue
results = data.get("results", [])
has_more = data.get("has_more", False)
next_cursor = data.get("next_cursor")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/notion/tests/test_notion.py b/products/warehouse_sources/backend/temporal/data_imports/sources/notion/tests/test_notion.py
index 98d25570442e..e08f2190b3e0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/notion/tests/test_notion.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/notion/tests/test_notion.py
@@ -25,6 +25,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.notion.not
_request,
_search_body,
_search_stream,
+ _users_stream,
_wait_strategy,
validate_credentials,
)
@@ -137,6 +138,70 @@ class TestNotion:
# The first request must start from the persisted cursor.
assert session.calls[0]["json"]["start_cursor"] == "resume-cursor"
+ @staticmethod
+ def _invalid_cursor_response() -> FakeResponse:
+ response = FakeResponse({}, status_code=400)
+ response.text = (
+ '{"object":"error","status":400,"code":"validation_error",'
+ '"message":"The start_cursor provided is invalid: dead-cursor"}'
+ )
+ return response
+
+ def test_search_stream_restarts_when_resumed_cursor_invalid(self) -> None:
+ # A resumed search cursor can expire before the retry runs; Notion then rejects it with a 400
+ # validation_error. The stream must drop the stale cursor and restart from the beginning
+ # rather than crashing the whole sync.
+ session = FakeSession(
+ [
+ self._invalid_cursor_response(),
+ _list_response([{"id": "p1"}], has_more=False, next_cursor=None),
+ ]
+ )
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = NotionResumeConfig(next_cursor="stale-cursor")
+
+ tables = list(
+ _search_stream(cast(requests.Session, session), NOTION_ENDPOINTS["pages"], mock.MagicMock(), manager)
+ )
+
+ assert sum(t.num_rows for t in tables) == 1
+ # First request replays the stale cursor (rejected); the restart carries no cursor.
+ assert session.calls[0]["json"]["start_cursor"] == "stale-cursor"
+ assert "start_cursor" not in session.calls[1]["json"]
+
+ def test_search_stream_propagates_non_cursor_bad_request(self) -> None:
+ # A 400 that is not the invalid-cursor case is a genuine bad request and must still fail the
+ # sync rather than being silently restarted.
+ other_400 = FakeResponse({}, status_code=400)
+ other_400.text = '{"code":"validation_error","message":"something else"}'
+ session = FakeSession([other_400])
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = NotionResumeConfig(next_cursor="stale-cursor")
+
+ with pytest.raises(NotionBadRequestError):
+ list(_search_stream(cast(requests.Session, session), NOTION_ENDPOINTS["pages"], mock.MagicMock(), manager))
+
+ def test_users_stream_restarts_when_resumed_cursor_invalid(self) -> None:
+ # The users stream persists the same kind of resume cursor as search, so a stale cursor must
+ # trigger the same restart-from-the-beginning recovery rather than crashing the sync.
+ session = FakeSession(
+ [
+ self._invalid_cursor_response(),
+ _list_response([{"id": "u1"}], has_more=False, next_cursor=None),
+ ]
+ )
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = NotionResumeConfig(next_cursor="stale-cursor")
+
+ tables = list(_users_stream(cast(requests.Session, session), mock.MagicMock(), manager))
+
+ assert sum(t.num_rows for t in tables) == 1
+ assert session.calls[0]["params"]["start_cursor"] == "stale-cursor"
+ assert "start_cursor" not in session.calls[1]["params"]
+
def test_block_children_inject_page_id(self) -> None:
session = FakeSession([_list_response([{"id": "b1", "has_children": False}], has_more=False, next_cursor=None)])
blocks = list(