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 Notion data warehouse source (#61125)

Tom Owers2660c1ef4ac2
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.md
index e97597d6bd3f..6b6c681e839a 100644
--- a/posthog/temporal/data_imports/sources/SOURCES.md
+++ b/posthog/temporal/data_imports/sources/SOURCES.md
@@ -74,6 +74,7 @@ the row lists both.
| mongodb | DB protocol | pymongo | ➖ |
| mssql | DB protocol | pyodbc / pymssql | ➖ |
| mysql | DB protocol | pymysql | ➖ |
+| notion | HTTP | requests | ✅ |
| paddle | HTTP | requests | ✅ |
| pagerduty | HTTP | requests | ✅ |
| pinterest_ads | HTTP | requests | ✅ |
@@ -186,7 +187,6 @@ doesn't conflict with concurrent PRs.
- mixpanel
- monday
- netsuite
-- notion
- okta
- omnisend
- onedrive
diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.py
index b248b2b7ab02..f6ec61a40e1b 100644
--- a/posthog/temporal/data_imports/sources/generated_configs.py
+++ b/posthog/temporal/data_imports/sources/generated_configs.py
@@ -553,7 +553,7 @@ class NetSuiteSourceConfig(config.Config):
@config.config
class NotionSourceConfig(config.Config):
- pass
+ api_key: str
@config.config
diff --git a/posthog/temporal/data_imports/sources/notion/notion.py b/posthog/temporal/data_imports/sources/notion/notion.py
new file mode 100644
index 000000000000..22d717e04850
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/notion/notion.py
@@ -0,0 +1,349 @@
+import dataclasses
+from collections.abc import Iterator
+from typing import Any, Literal, Optional
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import RetryCallState, retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+from urllib3.util.retry import Retry
+
+from posthog.temporal.data_imports.pipelines.pipeline.batcher import Batcher
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from posthog.temporal.data_imports.sources.common.http import make_tracked_session
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.notion.settings import (
+ NOTION_ENDPOINTS,
+ NOTION_PAGE_SIZE,
+ NotionEndpointConfig,
+)
+
+NOTION_BASE_URL = "https://api.notion.com"
+# Pinned API version. 2025-09-03 is the current official SDK default and introduces the
+# data sources model: a "database" is a container, and the schema-bearing tables are
+# "data sources". For the endpoints we use this only changes the search object filter
+# ("database" -> "data_source"); users/blocks/comments are unaffected.
+NOTION_VERSION = "2025-09-03"
+
+CHUNK_SIZE = 2000
+CHUNK_SIZE_BYTES = 100 * 1024 * 1024
+
+# Bounds for the fan-out streams (blocks/comments). Notion is rate limited to ~3 req/s, so deep
+# recursion and unbounded child pagination would make syncs prohibitively slow.
+MAX_BLOCK_DEPTH = 2
+MAX_CHILD_PAGES_PER_PARENT = 50
+
+MAX_RETRY_WAIT_SECONDS = 30.0
+
+
+class NotionRetryableError(Exception):
+ def __init__(self, message: str, retry_after: float | None = None) -> None:
+ super().__init__(message)
+ self.retry_after = retry_after
+
+
+class NotionResumeConfig:
+ next_cursor: str
+
+
+def _get_headers(token: str) -> dict[str, str]:
+ return {
+ "Authorization": f"Bearer {token}",
+ "Notion-Version": NOTION_VERSION,
+ "Content-Type": "application/json",
+ }
+
+
+def _build_session(token: str) -> requests.Session:
+ # Disable the tracked session's built-in urllib3 retries so tenacity is the single retry layer;
+ # one session is reused across every request of a stream to keep connection pooling/keep-alive.
+ return make_tracked_session(headers=_get_headers(token), redact_values=(token,), retry=Retry(total=0))
+
+
+def _parse_retry_after(value: str | None) -> float | None:
+ if value is None:
+ return None
+ try:
+ return float(value)
+ except ValueError:
+ return None
+
+
+_wait_exponential = wait_exponential_jitter(initial=1, max=MAX_RETRY_WAIT_SECONDS)
+
+
+def _wait_strategy(retry_state: RetryCallState) -> float:
+ # Honor Notion's Retry-After on 429s; fall back to exponential backoff otherwise.
+ exc = retry_state.outcome.exception() if retry_state.outcome is not None else None
+ if isinstance(exc, NotionRetryableError) and exc.retry_after is not None:
+ return min(exc.retry_after, MAX_RETRY_WAIT_SECONDS)
+ return _wait_exponential(retry_state)
+
+
+@retry(
+ retry=retry_if_exception_type((NotionRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(5),
+ wait=_wait_strategy,
+ reraise=True,
+)
+def _request(
+ session: requests.Session,
+ method: Literal["GET", "POST"],
+ path: str,
+ logger: FilteringBoundLogger,
+ *,
+ json_body: Optional[dict[str, Any]] = None,
+ params: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ url = f"{NOTION_BASE_URL}{path}"
+ response = session.request(method, url, json=json_body, params=params, timeout=60)
+
+ if response.status_code == 429:
+ retry_after = _parse_retry_after(response.headers.get("Retry-After"))
+ raise NotionRetryableError(f"Notion rate limited: url={url}, retry_after={retry_after}", retry_after)
+
+ if response.status_code >= 500:
+ raise NotionRetryableError(f"Notion API error (retryable): status={response.status_code}, 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()
+
+ return response.json()
+
+
+def validate_credentials(token: str) -> tuple[bool, str | None]:
+ try:
+ session = make_tracked_session(headers=_get_headers(token), redact_values=(token,))
+ response = session.get(f"{NOTION_BASE_URL}/v1/users/me", timeout=10)
+ except Exception as e:
+ return False, str(e)
+
+ if response.status_code == 200:
+ return True, None
+ if response.status_code == 401:
+ return False, "Invalid Notion integration token"
+ if response.status_code == 403:
+ return False, "Notion integration token is missing the required capabilities"
+ return False, f"Notion API error: HTTP {response.status_code}"
+
+
+def _search_body(object_filter: str, cursor: str | None) -> dict[str, Any]:
+ body: dict[str, Any] = {
+ "filter": {"property": "object", "value": object_filter},
+ "sort": {"timestamp": "last_edited_time", "direction": "ascending"},
+ "page_size": NOTION_PAGE_SIZE,
+ }
+ if cursor:
+ body["start_cursor"] = cursor
+ return body
+
+
+def _search_stream(
+ session: requests.Session,
+ config: NotionEndpointConfig,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[NotionResumeConfig],
+) -> Iterator[Any]:
+ assert config.object_filter is not None
+ batcher = Batcher(logger=logger, chunk_size=CHUNK_SIZE, chunk_size_bytes=CHUNK_SIZE_BYTES)
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ 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))
+ results = data.get("results", [])
+ has_more = data.get("has_more", False)
+ next_cursor = data.get("next_cursor")
+
+ for item in results:
+ batcher.batch(item)
+ if batcher.should_yield():
+ yield batcher.get_table()
+ if has_more and next_cursor:
+ resumable_source_manager.save_state(NotionResumeConfig(next_cursor=next_cursor))
+
+ if not has_more or not next_cursor:
+ break
+ cursor = next_cursor
+
+ if batcher.should_yield(include_incomplete_chunk=True):
+ yield batcher.get_table()
+
+
+def _users_stream(
+ session: requests.Session,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[NotionResumeConfig],
+) -> Iterator[Any]:
+ batcher = Batcher(logger=logger, chunk_size=CHUNK_SIZE, chunk_size_bytes=CHUNK_SIZE_BYTES)
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ cursor = resume.next_cursor if resume is not None else None
+
+ while True:
+ params: dict[str, Any] = {"page_size": NOTION_PAGE_SIZE}
+ if cursor:
+ params["start_cursor"] = cursor
+
+ data = _request(session, "GET", "/v1/users", logger, params=params)
+ results = data.get("results", [])
+ has_more = data.get("has_more", False)
+ next_cursor = data.get("next_cursor")
+
+ for item in results:
+ batcher.batch(item)
+ if batcher.should_yield():
+ yield batcher.get_table()
+ if has_more and next_cursor:
+ resumable_source_manager.save_state(NotionResumeConfig(next_cursor=next_cursor))
+
+ if not has_more or not next_cursor:
+ break
+ cursor = next_cursor
+
+ if batcher.should_yield(include_incomplete_chunk=True):
+ yield batcher.get_table()
+
+
+def _iter_page_ids(session: requests.Session, logger: FilteringBoundLogger) -> Iterator[str]:
+ cursor: str | None = None
+ while True:
+ data = _request(session, "POST", "/v1/search", logger, json_body=_search_body("page", cursor))
+ for item in data.get("results", []):
+ # "id" is the primary key driving the blocks/comments fan-out; access it directly so a
+ # malformed response missing it surfaces loudly instead of silently dropping the page.
+ yield item["id"]
+ if not data.get("has_more") or not data.get("next_cursor"):
+ break
+ cursor = data["next_cursor"]
+
+
+def _iter_block_children(
+ session: requests.Session,
+ block_id: str,
+ page_id: str,
+ logger: FilteringBoundLogger,
+ depth: int,
+) -> Iterator[dict[str, Any]]:
+ cursor: str | None = None
+ pages_fetched = 0
+ while True:
+ params: dict[str, Any] = {"page_size": NOTION_PAGE_SIZE}
+ if cursor:
+ params["start_cursor"] = cursor
+
+ data = _request(session, "GET", f"/v1/blocks/{block_id}/children", logger, params=params)
+ for block in data.get("results", []):
+ block["_page_id"] = page_id
+ yield block
+ if block.get("has_children") and depth < MAX_BLOCK_DEPTH:
+ yield from _iter_block_children(session, block["id"], page_id, logger, depth + 1)
+
+ pages_fetched += 1
+ if not data.get("has_more") or not data.get("next_cursor"):
+ break
+ if pages_fetched >= MAX_CHILD_PAGES_PER_PARENT:
+ logger.warning(
+ "Notion: reached block children page cap for parent",
+ page_id=page_id,
+ block_id=block_id,
+ cap=MAX_CHILD_PAGES_PER_PARENT,
+ )
+ break
+ cursor = data["next_cursor"]
+
+
+def _blocks_stream(session: requests.Session, logger: FilteringBoundLogger) -> Iterator[Any]:
+ batcher = Batcher(logger=logger, chunk_size=CHUNK_SIZE, chunk_size_bytes=CHUNK_SIZE_BYTES)
+
+ for page_id in _iter_page_ids(session, logger):
+ for block in _iter_block_children(session, page_id, page_id, logger, 0):
+ batcher.batch(block)
+ if batcher.should_yield():
+ yield batcher.get_table()
+
+ if batcher.should_yield(include_incomplete_chunk=True):
+ yield batcher.get_table()
+
+
+def _comments_stream(session: requests.Session, logger: FilteringBoundLogger) -> Iterator[Any]:
+ batcher = Batcher(logger=logger, chunk_size=CHUNK_SIZE, chunk_size_bytes=CHUNK_SIZE_BYTES)
+
+ for page_id in _iter_page_ids(session, logger):
+ cursor: str | None = None
+ pages_fetched = 0
+ while True:
+ params: dict[str, Any] = {"block_id": page_id, "page_size": NOTION_PAGE_SIZE}
+ if cursor:
+ params["start_cursor"] = cursor
+
+ data = _request(session, "GET", "/v1/comments", logger, params=params)
+ for comment in data.get("results", []):
+ comment["_page_id"] = page_id
+ batcher.batch(comment)
+ if batcher.should_yield():
+ yield batcher.get_table()
+
+ pages_fetched += 1
+ if not data.get("has_more") or not data.get("next_cursor"):
+ break
+ if pages_fetched >= MAX_CHILD_PAGES_PER_PARENT:
+ logger.warning(
+ "Notion: reached comments page cap for parent",
+ page_id=page_id,
+ cap=MAX_CHILD_PAGES_PER_PARENT,
+ )
+ break
+ cursor = data["next_cursor"]
+
+ if batcher.should_yield(include_incomplete_chunk=True):
+ yield batcher.get_table()
+
+
+def get_rows(
+ token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[NotionResumeConfig],
+) -> Iterator[Any]:
+ config = NOTION_ENDPOINTS[endpoint]
+ session = _build_session(token)
+
+ if config.stream_type == "search":
+ yield from _search_stream(session, config, logger, resumable_source_manager)
+ elif config.stream_type == "users":
+ yield from _users_stream(session, logger, resumable_source_manager)
+ elif config.stream_type == "blocks":
+ yield from _blocks_stream(session, logger)
+ elif config.stream_type == "comments":
+ yield from _comments_stream(session, logger)
+ else:
+ raise ValueError(f"Unknown Notion stream type: {config.stream_type}")
+
+
+def notion_source(
+ token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[NotionResumeConfig],
+) -> SourceResponse:
+ config = NOTION_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ token=token,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ ),
+ primary_keys=["id"],
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="week" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ sort_mode="asc",
+ )
diff --git a/posthog/temporal/data_imports/sources/notion/settings.py b/posthog/temporal/data_imports/sources/notion/settings.py
new file mode 100644
index 000000000000..c49ed62c80cf
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/notion/settings.py
@@ -0,0 +1,58 @@
+from dataclasses import dataclass
+from typing import Literal, Optional
+
+from products.data_warehouse.backend.types import IncrementalField
+
+# Notion search and query endpoints cap page_size at 100.
+NOTION_PAGE_SIZE = 100
+
+StreamType = Literal["search", "users", "blocks", "comments"]
+
+
+@dataclass
+class NotionEndpointConfig:
+ name: str
+ stream_type: StreamType
+ # Field to partition by. Must be stable (immutable) - Notion's created_time fits;
+ # last_edited_time changes on every edit so it is unsuitable.
+ partition_key: Optional[str] = None
+ # For "search" streams: the Notion object type to filter to ("page" or "data_source").
+ # Under API version 2025-09-03 the schema-bearing "database" tables are returned as
+ # "data_source" objects, so the databases stream filters on "data_source".
+ object_filter: Optional[str] = None
+
+
+NOTION_ENDPOINTS: dict[str, NotionEndpointConfig] = {
+ "pages": NotionEndpointConfig(
+ name="pages",
+ stream_type="search",
+ object_filter="page",
+ partition_key="created_time",
+ ),
+ "databases": NotionEndpointConfig(
+ name="databases",
+ stream_type="search",
+ object_filter="data_source",
+ partition_key="created_time",
+ ),
+ "users": NotionEndpointConfig(
+ name="users",
+ stream_type="users",
+ ),
+ "blocks": NotionEndpointConfig(
+ name="blocks",
+ stream_type="blocks",
+ partition_key="created_time",
+ ),
+ "comments": NotionEndpointConfig(
+ name="comments",
+ stream_type="comments",
+ partition_key="created_time",
+ ),
+}
+
+ENDPOINTS = tuple(NOTION_ENDPOINTS.keys())
+
+# Notion's search endpoint only sorts (not filters) by last_edited_time, so there is no
+# server-side timestamp filter we can use for true incremental sync - all streams are full refresh.
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {name: [] for name in NOTION_ENDPOINTS}
diff --git a/posthog/temporal/data_imports/sources/notion/source.py b/posthog/temporal/data_imports/sources/notion/source.py
index be7f8854a8c8..dc16fe21013b 100644
--- a/posthog/temporal/data_imports/sources/notion/source.py
+++ b/posthog/temporal/data_imports/sources/notion/source.py
@@ -1,29 +1,109 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse
+from posthog.temporal.data_imports.sources.common.base import FieldType, ResumableSource
from posthog.temporal.data_imports.sources.common.registry import SourceRegistry
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.common.schema import SourceSchema
from posthog.temporal.data_imports.sources.generated_configs import NotionSourceConfig
+from posthog.temporal.data_imports.sources.notion.notion import (
+ NotionResumeConfig,
+ notion_source,
+ validate_credentials as validate_notion_credentials,
+)
+from posthog.temporal.data_imports.sources.notion.settings import ENDPOINTS, INCREMENTAL_FIELDS
from products.data_warehouse.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class NotionSource(SimpleSource[NotionSourceConfig]):
+class NotionSource(ResumableSource[NotionSourceConfig, NotionResumeConfig]):
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.NOTION
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://api.notion.com": "Your Notion integration token is invalid or expired. Please generate a new token and reconnect.",
+ "403 Client Error: Forbidden for url: https://api.notion.com": "Your Notion integration is missing the required capabilities, or the pages/databases you want to sync have not been shared with it.",
+ }
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.NOTION,
label="Notion",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your Notion internal integration token to pull your Notion data into the PostHog Data warehouse.
+
+Create an internal integration at [notion.so/my-integrations](https://www.notion.so/my-integrations) and copy its token (starts with `ntn_` or `secret_`).
+
+Then **share** each page or database you want to sync with the integration (via the page's `•••` menu → Connections), otherwise it will not be visible to the sync.
+""",
iconPath="/static/services/notion.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/notion",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="ntn_...",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_schemas(
+ self,
+ config: NotionSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ )
+ for endpoint in list(ENDPOINTS)
+ ]
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+ return schemas
+
+ def validate_credentials(
+ self, config: NotionSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ return validate_notion_credentials(config.api_key)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[NotionResumeConfig]:
+ return ResumableSourceManager[NotionResumeConfig](inputs, NotionResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: NotionSourceConfig,
+ resumable_source_manager: ResumableSourceManager[NotionResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return notion_source(
+ token=config.api_key,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
)
diff --git a/posthog/temporal/data_imports/sources/notion/tests/test_notion.py b/posthog/temporal/data_imports/sources/notion/tests/test_notion.py
new file mode 100644
index 000000000000..713bf5a8ba56
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/notion/tests/test_notion.py
@@ -0,0 +1,242 @@
+from collections.abc import Callable
+from typing import Any, Optional, cast
+
+import pytest
+from unittest import mock
+
+import requests
+from parameterized import parameterized
+from tenacity import RetryCallState
+
+from posthog.temporal.data_imports.sources.notion.notion import (
+ MAX_BLOCK_DEPTH,
+ MAX_CHILD_PAGES_PER_PARENT,
+ MAX_RETRY_WAIT_SECONDS,
+ NOTION_VERSION,
+ NotionResumeConfig,
+ NotionRetryableError,
+ _comments_stream,
+ _get_headers,
+ _iter_block_children,
+ _parse_retry_after,
+ _request,
+ _search_body,
+ _search_stream,
+ _wait_strategy,
+ validate_credentials,
+)
+from posthog.temporal.data_imports.sources.notion.settings import NOTION_ENDPOINTS
+
+MODULE = "posthog.temporal.data_imports.sources.notion.notion"
+
+
+class FakeResponse:
+ def __init__(self, json_data: Any, status_code: int = 200, headers: Optional[dict[str, str]] = None) -> None:
+ self._json = json_data
+ self.status_code = status_code
+ self.headers = headers or {}
+ self.ok = 200 <= status_code < 400
+ self.text = ""
+
+ def json(self) -> Any:
+ return self._json
+
+ def raise_for_status(self) -> None:
+ if not self.ok:
+ raise requests.HTTPError(f"{self.status_code} Client Error", response=cast(requests.Response, self))
+
+
+class FakeSession:
+ def __init__(self, responses: list[FakeResponse] | Callable[[int], FakeResponse]) -> None:
+ self._responses = responses
+ self.calls: list[dict[str, Any]] = []
+
+ def _next(self) -> FakeResponse:
+ index = len(self.calls) - 1
+ if callable(self._responses):
+ return self._responses(index)
+ return self._responses.pop(0)
+
+ def request(
+ self,
+ method: str,
+ url: str,
+ json: Any = None,
+ params: Any = None,
+ timeout: Any = None,
+ ) -> FakeResponse:
+ self.calls.append({"method": method, "url": url, "json": json, "params": params})
+ return self._next()
+
+ def get(self, url: str, timeout: Any = None) -> FakeResponse:
+ self.calls.append({"method": "GET", "url": url})
+ return self._next()
+
+
+def _list_response(results: list[dict[str, Any]], has_more: bool, next_cursor: str | None) -> FakeResponse:
+ return FakeResponse({"results": results, "has_more": has_more, "next_cursor": next_cursor})
+
+
+class _FakeRetryState:
+ """Minimal RetryCallState stand-in carrying just the failing outcome."""
+
+ def __init__(self, exception: BaseException) -> None:
+ self.outcome = mock.MagicMock()
+ self.outcome.exception.return_value = exception
+
+
+class TestNotion:
+ def test_headers_include_bearer_token_and_version(self) -> None:
+ headers = _get_headers("ntn_secret")
+ assert headers["Authorization"] == "Bearer ntn_secret"
+ assert headers["Notion-Version"] == NOTION_VERSION
+ assert headers["Content-Type"] == "application/json"
+
+ @parameterized.expand([("page",), ("data_source",)])
+ def test_search_body_shape(self, object_filter: str) -> None:
+ body = _search_body(object_filter, None)
+ assert body["filter"] == {"property": "object", "value": object_filter}
+ assert body["sort"] == {"timestamp": "last_edited_time", "direction": "ascending"}
+ assert body["page_size"] == 100
+ assert "start_cursor" not in body
+
+ def test_search_body_includes_cursor_when_set(self) -> None:
+ body = _search_body("page", "cursor-123")
+ assert body["start_cursor"] == "cursor-123"
+
+ def test_search_stream_paginates_and_terminates(self) -> None:
+ session = FakeSession(
+ [
+ _list_response([{"id": "p1"}], has_more=True, next_cursor="c1"),
+ _list_response([{"id": "p2"}], has_more=False, next_cursor=None),
+ ]
+ )
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = False
+
+ tables = list(
+ _search_stream(cast(requests.Session, session), NOTION_ENDPOINTS["pages"], mock.MagicMock(), manager)
+ )
+
+ total_rows = sum(t.num_rows for t in tables)
+ assert total_rows == 2
+ # Two pages fetched, then the loop terminates on has_more=False.
+ assert len(session.calls) == 2
+
+ def test_search_stream_resumes_from_saved_cursor(self) -> None:
+ session = FakeSession([_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="resume-cursor")
+
+ list(_search_stream(cast(requests.Session, session), NOTION_ENDPOINTS["pages"], mock.MagicMock(), manager))
+
+ # The first request must start from the persisted cursor.
+ assert session.calls[0]["json"]["start_cursor"] == "resume-cursor"
+
+ 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(
+ _iter_block_children(cast(requests.Session, session), "block-root", "page-42", mock.MagicMock(), 0)
+ )
+
+ assert len(blocks) == 1
+ assert blocks[0]["_page_id"] == "page-42"
+
+ def test_block_children_respect_depth_limit(self) -> None:
+ # Every fetched block has children, so recursion would be unbounded without the depth cap.
+ def always_has_children(_index: int) -> FakeResponse:
+ return _list_response([{"id": "child", "has_children": True}], has_more=False, next_cursor=None)
+
+ session = FakeSession(always_has_children)
+ blocks = list(
+ _iter_block_children(cast(requests.Session, session), "block-root", "page-1", mock.MagicMock(), 0)
+ )
+
+ # depth 0 yields one block, then recurses up to MAX_BLOCK_DEPTH levels.
+ assert len(blocks) == MAX_BLOCK_DEPTH + 1
+
+ def test_block_children_respect_page_cap(self) -> None:
+ # Endpoint always reports another page; the per-parent cap must stop the scan.
+ def always_more(_index: int) -> FakeResponse:
+ return _list_response([{"id": "b", "has_children": False}], has_more=True, next_cursor="next")
+
+ session = FakeSession(always_more)
+ logger = mock.MagicMock()
+ blocks = list(_iter_block_children(cast(requests.Session, session), "block-root", "page-1", logger, 0))
+
+ assert len(blocks) == MAX_CHILD_PAGES_PER_PARENT
+ assert logger.warning.called
+
+ def test_request_429_raises_retryable_with_retry_after(self) -> None:
+ session = FakeSession([FakeResponse({}, status_code=429, headers={"Retry-After": "7"})])
+ # Bypass the tenacity retry wrapper so we observe a single attempt's behaviour.
+ with pytest.raises(NotionRetryableError) as exc_info:
+ cast(Any, _request).__wrapped__(
+ cast(requests.Session, session), "GET", "/v1/users", mock.MagicMock(), params={}
+ )
+ assert exc_info.value.retry_after == 7.0
+
+ def test_request_5xx_raises_retryable_without_retry_after(self) -> None:
+ session = FakeSession([FakeResponse({}, status_code=503)])
+ with pytest.raises(NotionRetryableError) as exc_info:
+ cast(Any, _request).__wrapped__(
+ cast(requests.Session, session), "GET", "/v1/users", mock.MagicMock(), params={}
+ )
+ assert exc_info.value.retry_after is None
+
+ @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
+
+ def test_wait_strategy_honors_retry_after(self) -> None:
+ state = _FakeRetryState(NotionRetryableError("rate limited", retry_after=3.0))
+ assert _wait_strategy(cast(RetryCallState, state)) == 3.0
+
+ def test_wait_strategy_caps_retry_after(self) -> None:
+ state = _FakeRetryState(NotionRetryableError("rate limited", retry_after=10_000.0))
+ assert _wait_strategy(cast(RetryCallState, state)) == MAX_RETRY_WAIT_SECONDS
+
+ def test_comments_stream_respects_page_cap(self) -> None:
+ # First call is the page search (one page, then done); every subsequent /v1/comments
+ # call reports another page, so the per-parent cap must stop the scan.
+ def responses(index: int) -> FakeResponse:
+ if index == 0:
+ return _list_response([{"id": "p1"}], has_more=False, next_cursor=None)
+ return _list_response([{"id": "cm"}], has_more=True, next_cursor="next")
+
+ session = FakeSession(responses)
+ logger = mock.MagicMock()
+ list(_comments_stream(cast(requests.Session, session), logger))
+
+ # One search call plus the capped number of comment-page fetches.
+ assert len(session.calls) == 1 + MAX_CHILD_PAGES_PER_PARENT
+ assert logger.warning.called
+
+ @parameterized.expand([(200, True), (401, False), (403, False), (500, False)])
+ def test_validate_credentials_status_mapping(self, status_code: int, expected_valid: bool) -> None:
+ session = FakeSession([FakeResponse({}, status_code=status_code)])
+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):
+ valid, message = validate_credentials("tok")
+
+ assert valid is expected_valid
+ if expected_valid:
+ assert message is None
+ else:
+ assert message is not None
+
+ def test_validate_credentials_handles_exception(self) -> None:
+ with mock.patch(f"{MODULE}.make_tracked_session", side_effect=requests.ConnectionError("boom")):
+ valid, message = validate_credentials("tok")
+
+ assert valid is False
+ assert message == "boom"
+
+
[email protected]("endpoint", list(NOTION_ENDPOINTS.keys()))
+def test_every_endpoint_has_config(endpoint: str) -> None:
+ config = NOTION_ENDPOINTS[endpoint]
+ assert config.name == endpoint
+ assert config.stream_type in ("search", "users", "blocks", "comments")
+ if config.stream_type == "search":
+ assert config.object_filter in ("page", "data_source")
diff --git a/posthog/temporal/data_imports/sources/notion/tests/test_notion_source.py b/posthog/temporal/data_imports/sources/notion/tests/test_notion_source.py
new file mode 100644
index 000000000000..a4445f351769
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/notion/tests/test_notion_source.py
@@ -0,0 +1,135 @@
+import pytest
+from unittest import mock
+
+import requests
+import structlog
+from parameterized import parameterized
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.generated_configs import NotionSourceConfig
+from posthog.temporal.data_imports.sources.notion.notion import NotionResumeConfig
+from posthog.temporal.data_imports.sources.notion.settings import ENDPOINTS
+from posthog.temporal.data_imports.sources.notion.source import NotionSource
+
+from products.data_warehouse.backend.types import ExternalDataSourceType
+
+NOTION_MODULE = "posthog.temporal.data_imports.sources.notion.notion"
+
+
+def _make_inputs(schema_name: str = "pages") -> SourceInputs:
+ return SourceInputs(
+ schema_name=schema_name,
+ schema_id="schema-id",
+ source_id="source-id",
+ team_id=1,
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ db_incremental_field_earliest_value=None,
+ incremental_field=None,
+ incremental_field_type=None,
+ job_id="job-id",
+ logger=structlog.get_logger(),
+ reset_pipeline=False,
+ )
+
+
+class FakeResponse:
+ def __init__(self, status_code: int) -> None:
+ self.status_code = status_code
+ self.ok = 200 <= status_code < 400
+
+
+class TestNotionSource:
+ def setup_method(self) -> None:
+ self.source = NotionSource()
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.NOTION
+
+ def test_source_config_is_released_with_api_key_field(self) -> None:
+ config = self.source.get_source_config
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert not getattr(config, "unreleasedSource", None)
+
+ fields = config.fields
+ assert len(fields) == 1
+ field = fields[0]
+ assert isinstance(field, SourceFieldInputConfig)
+ assert field.name == "api_key"
+ assert field.type == SourceFieldInputConfigType.PASSWORD
+ assert field.required is True
+ assert field.secret is True
+
+ def test_get_schemas_returns_all_endpoints_full_refresh(self) -> None:
+ schemas = self.source.get_schemas(NotionSourceConfig(api_key="tok"), team_id=1)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+ assert all(s.supports_incremental is False for s in schemas)
+ assert all(s.supports_append is False for s in schemas)
+
+ def test_get_schemas_honors_names_filter(self) -> None:
+ schemas = self.source.get_schemas(NotionSourceConfig(api_key="tok"), team_id=1, names=["users"])
+ assert [s.name for s in schemas] == ["users"]
+
+ @parameterized.expand([(200, True), (401, False)])
+ def test_validate_credentials(self, status_code: int, expected_valid: bool) -> None:
+ session = mock.MagicMock()
+ session.get.return_value = FakeResponse(status_code)
+ with mock.patch(f"{NOTION_MODULE}.make_tracked_session", return_value=session):
+ valid, _message = self.source.validate_credentials(NotionSourceConfig(api_key="tok"), team_id=1)
+ assert valid is expected_valid
+
+ def test_get_resumable_source_manager_is_bound_to_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(_make_inputs())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is NotionResumeConfig
+
+ def test_source_for_pipeline_partitions_search_streams(self) -> None:
+ inputs = _make_inputs("pages")
+ manager = self.source.get_resumable_source_manager(inputs)
+ response = self.source.source_for_pipeline(NotionSourceConfig(api_key="tok"), manager, inputs)
+
+ assert response.name == "pages"
+ assert response.primary_keys == ["id"]
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == ["created_time"]
+
+ def test_source_for_pipeline_users_has_no_partition(self) -> None:
+ inputs = _make_inputs("users")
+ manager = self.source.get_resumable_source_manager(inputs)
+ response = self.source.source_for_pipeline(NotionSourceConfig(api_key="tok"), manager, inputs)
+
+ assert response.name == "users"
+ assert response.partition_mode is None
+ assert response.partition_keys is None
+
+ @parameterized.expand(
+ [
+ ("401 Client Error: Unauthorized for url: https://api.notion.com/v1/search",),
+ ("403 Client Error: Forbidden for url: https://api.notion.com/v1/users",),
+ ]
+ )
+ def test_non_retryable_errors_match(self, error_message: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert any(pattern in error_message for pattern in non_retryable)
+
+ def test_other_errors_are_retryable(self) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert not any(
+ pattern in "429 Client Error: Too Many Requests for url: https://api.notion.com/v1/search"
+ for pattern in non_retryable
+ )
+
+
[email protected]("status_code", [500, 503])
+def test_http_error_message_format_matches_non_retryable(status_code: int) -> None:
+ # Sanity check that raised HTTPError messages won't accidentally match the 401/403 patterns.
+ mock_response = requests.Response()
+ mock_response.status_code = status_code
+ mock_response.url = "https://api.notion.com/v1/search"
+ with pytest.raises(requests.HTTPError) as exc_info:
+ mock_response.raise_for_status()
+ non_retryable = NotionSource().get_non_retryable_errors()
+ assert not any(pattern in str(exc_info.value) for pattern in non_retryable)