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.

32.2 KB
Raw Blame
import time
import dataclasses
from collections.abc import Callable, Iterator
from typing import Any, Literal, Optional
from urllib.parse import urlencode

import requests
from structlog.types import FilteringBoundLogger
from tenacity import RetryCallState, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
from urllib3.util.retry import Retry

from products.warehouse_sources.sources.notion.settings import NOTION_ENDPOINTS, NOTION_PAGE_SIZE, NotionEndpointConfig
from products.warehouse_sources.sources.sdk import (
    ResumableSourceManager,
    SourceResponse,
    capture_exception,
    make_tracked_session,
    retry_with_deadline,
)
from products.warehouse_sources.sources.sdk.internals import Batcher

NOTION_BASE_URL = "https://api.notion.com"
# Supported API versions, as opaque Notion-Version header labels (never parsed or ordered). The pin
# is resolved by the source class and threaded down to the request headers.
# - 2025-09-03 introduced the data sources model: a "database" is a container, and the
#   schema-bearing tables are "data sources", so the databases stream filters search on
#   "data_source" instead of "database".
# - 2026-03-11 is a stable follow-up. For the read-only endpoints we consume it only renames
#   response fields (archived -> in_trash, the transcription block type -> meeting_notes) and
#   reshapes the append-block-children request, which we never call; the search object filter is
#   still "data_source". So for our sync the two versions differ only in this header value, and the
#   auto-inferred schema absorbs the renamed response fields.
NOTION_VERSION_2025_09_03 = "2025-09-03"
NOTION_VERSION_2026_03_11 = "2026-03-11"

# The Admin API takes a different token (an organization bot token) and has its own version line, so
# the source's version pin does not apply to it. Its header enum accepts only this one value.
NOTION_ADMIN_BASE_PATH = "/admin"
NOTION_ADMIN_API_VERSION = "2026-06-01"

CHUNK_SIZE = 2000
CHUNK_SIZE_BYTES = 100 * 1024 * 1024

# Bounds for the fan-out streams (blocks/comments). Notion block trees are finite and acyclic, so
# this cap is not needed for termination — it is a backstop against pathological/cyclic data. It is
# set high enough that all real content (deeply nested toggles, lists, sub-pages) syncs: a low cap
# silently dropped everything below it. When the cap is actually reached we log a warning so the
# truncation is observable rather than silent. Deep recursion is affordable now that the blocks
# stream resumes across retries and paces itself under Notion's rate limit.
MAX_BLOCK_DEPTH = 30
MAX_CHILD_PAGES_PER_PARENT = 50
# In the blocks and comments fan-out, a partly filled chunk is yielded at a page boundary once this
# long has passed since the last yield, so sparse pages still reach the pipeline regularly.
PARTIAL_FLUSH_INTERVAL_SECONDS = 60.0
# A page with no buffered rows stages the shrinking page queue at most this often, because staging
# serializes the whole queue.
EMPTY_PAGE_STAGE_INTERVAL_SECONDS = 10.0

# Notion enforces an average of ~3 requests/second per integration. Pacing requests to this minimum
# interval keeps us under the cap proactively, avoiding the retry churn that reacting to 429s alone
# produces (each 429 burns an attempt and can extend Notion's penalty window).
NOTION_MAX_REQUESTS_PER_SECOND = 3.0
NOTION_MIN_REQUEST_INTERVAL_SECONDS = 1.0 / NOTION_MAX_REQUESTS_PER_SECOND

MAX_RETRY_WAIT_SECONDS = 30.0
# Notion can ask us to back off for several minutes via Retry-After under sustained load (values
# of 5+ minutes are common). Honor that instruction up to this bound instead of retrying early and
# getting throttled again — retrying inside the penalty window just burns attempts and can extend
# the penalty. Blocking this long is safe: the import activity has a week-long timeout and
# heartbeats on an independent timer, so a waiting request won't trip the heartbeat. The bound is a
# backstop against a pathologically large Retry-After.
MAX_RETRY_AFTER_SECONDS = 600.0


class NotionRetryableError(Exception):
    def __init__(self, message: str, retry_after: float | None = None) -> None:
        super().__init__(message)
        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."""


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."""


class NotionAdminTokenMissingError(Exception):
    pass


@dataclasses.dataclass(frozen=False)
class NotionResumeConfig:
    # Cursor-paginated streams (search, users) persist the next page cursor.
    next_cursor: str | None = None
    # The blocks fan-out persists its queue of pages still to process, head first. The head is the
    # page currently in progress: a retry re-processes it in full (blocks already written are deduped
    # on the primary key at merge) and continues with the rest, instead of restarting from page one.
    remaining_page_ids: list[str] | None = None


class _RateLimiter:
    """Proactive throttle keeping requests under Notion's average rate limit.

    Requests within a stream are issued serially by a single generator, so tracking one last-request
    timestamp and sleeping to maintain a minimum interval is enough to pace the whole run.
    """

    def __init__(self, min_interval_seconds: float) -> None:
        self._min_interval = min_interval_seconds
        self._last_request_at: float | None = None

    def wait(self) -> None:
        if self._last_request_at is not None:
            sleep_for = self._min_interval - (time.monotonic() - self._last_request_at)
            if sleep_for > 0:
                time.sleep(sleep_for)
        self._last_request_at = time.monotonic()


def _get_headers(token: str, api_version: str) -> dict[str, str]:
    return {
        "Authorization": f"Bearer {token}",
        "Notion-Version": api_version,
        "Content-Type": "application/json",
    }


def _build_session(token: str, api_version: 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, api_version), 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


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)


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_AFTER_SECONDS)
    return _wait_exponential(retry_state)


@retry_with_deadline(
    # ChunkedEncodingError is a sibling of ConnectionError (both RequestException, not subclasses of
    # each other): Notion can break the connection mid-response, surfacing as a malformed chunk
    # ("Connection broken: InvalidChunkLength"). It is a transient connection failure like the others,
    # so retry it rather than letting it crash the sync.
    retry=retry_if_exception_type(
        (
            NotionRetryableError,
            requests.ReadTimeout,
            requests.ConnectionError,
            requests.exceptions.ChunkedEncodingError,
        )
    ),
    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,
    throttle: Optional["_RateLimiter"] = None,
) -> dict[str, Any]:
    if throttle is not None:
        throttle.wait()

    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}")

    # 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}")

    # 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()

    try:
        return response.json()
    except requests.exceptions.JSONDecodeError as e:
        # A 2xx with an empty or non-JSON body is a truncated/garbled response (a proxy hiccup, or the
        # connection dropped after the status line) rather than real Notion output — every success
        # path returns JSON. Treat it like the other transient response failures and retry.
        raise NotionRetryableError(
            f"Notion returned a non-JSON response: status={response.status_code}, url={url}"
        ) from e


# Setup-time messages for a token Notion refuses. Worded to match the sync-time messages the
# source class maps the same two failures to, so the same problem reads the same way in the
# wizard and in the sync error panel.
INVALID_TOKEN_ERROR = (
    "Your Notion integration token is invalid or expired. Create a new internal integration token in Notion, "
    "then enter it here."
)
MISSING_CAPABILITIES_ERROR = (
    "Your Notion integration cannot read your content. Give it read capabilities in Notion and share the pages "
    "and databases you want to sync with it."
)
# The raw exception, and Notion's own error body, carry request URLs and response detail that mean
# nothing to the person filling in the form. Capture them instead and show fixed guidance.
TOKEN_CHECK_FAILED_ERROR = "PostHog could not check your Notion token. Wait a few minutes, then try again."


def validate_credentials(token: str, api_version: str) -> tuple[bool, str | None]:
    try:
        session = make_tracked_session(headers=_get_headers(token, api_version), redact_values=(token,))
        response = session.get(f"{NOTION_BASE_URL}/v1/users/me", timeout=10)
    except Exception as e:
        capture_exception(e)
        return False, TOKEN_CHECK_FAILED_ERROR

    if response.status_code == 200:
        return True, None
    if response.status_code == 401:
        return False, INVALID_TOKEN_ERROR
    if response.status_code == 403:
        return False, MISSING_CAPABILITIES_ERROR
    return False, TOKEN_CHECK_FAILED_ERROR


ADMIN_TOKEN_MISSING_ERROR = (
    "Add an organization bot token with the permission-group:read scope to sync permission groups. "
    "Organization owners create these tokens in the Notion organization console."
)
ADMIN_TOKEN_INVALID_ERROR = (
    "Your Notion organization bot token is invalid or revoked. Create a new one in the Notion organization console, "
    "then update this source."
)
ADMIN_TOKEN_FORBIDDEN_ERROR = (
    "Your Notion organization bot token cannot read permission groups. Give it the permission-group:read scope. "
    "This scope is only available to eligible Notion Enterprise organizations."
)


def check_permission_groups_access(token: str, admin_token: str | None, api_version: str) -> str | None:
    if not admin_token:
        return ADMIN_TOKEN_MISSING_ERROR
    try:
        public_session = make_tracked_session(headers=_get_headers(token, api_version), redact_values=(token,))
        me_response = public_session.get(f"{NOTION_BASE_URL}/v1/users/me", timeout=10)
        # A bad integration token is reported by validate_credentials, not as a per-table problem.
        if not me_response.ok:
            return None
        workspace_id = (me_response.json().get("bot") or {}).get("workspace_id")
        if not workspace_id:
            return None
        admin_session = make_tracked_session(
            headers=_get_headers(admin_token, NOTION_ADMIN_API_VERSION), redact_values=(admin_token,)
        )
        query = urlencode({"page_size": 1})
        response = admin_session.get(
            f"{NOTION_BASE_URL}{NOTION_ADMIN_BASE_PATH}/v1/spaces/{workspace_id}/groups?{query}", timeout=10
        )
    except Exception as e:
        capture_exception(e)
        return None

    if response.status_code == 401:
        return ADMIN_TOKEN_INVALID_ERROR
    if response.status_code == 403:
        return ADMIN_TOKEN_FORBIDDEN_ERROR
    return None


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],
    throttle: Optional["_RateLimiter"] = None,
) -> 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:
        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")

        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
        if not batcher.should_yield(include_incomplete_chunk=True):
            # Nothing is buffered, so every row before `next_cursor` is already yielded.
            resumable_source_manager.save_state(NotionResumeConfig(next_cursor=next_cursor))
            resumable_source_manager.safe_point()
        cursor = next_cursor

    if batcher.should_yield(include_incomplete_chunk=True):
        yield batcher.get_table()


def _cursor_list_stream(
    session: requests.Session,
    path: str,
    stream_name: str,
    logger: FilteringBoundLogger,
    resumable_source_manager: ResumableSourceManager[NotionResumeConfig],
    throttle: Optional["_RateLimiter"] = None,
) -> 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

        try:
            data = _request(session, "GET", path, 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(
                f"Notion: resumed {stream_name} cursor rejected as invalid; restarting stream from the start"
            )
            cursor = None
            continue
        results = data.get("results", [])
        if results:
            batcher.batch(results)

        next_cursor = data.get("next_cursor")
        if not data.get("has_more") or not next_cursor:
            break
        # Yield only at a page boundary, so the staged cursor covers every row in the yielded table.
        if batcher.should_yield():
            resumable_source_manager.save_state(NotionResumeConfig(next_cursor=next_cursor))
            yield batcher.get_table()
        elif not batcher.should_yield(include_incomplete_chunk=True):
            resumable_source_manager.save_state(NotionResumeConfig(next_cursor=next_cursor))
            resumable_source_manager.safe_point()
        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],
    throttle: Optional["_RateLimiter"] = None,
) -> Iterator[Any]:
    yield from _cursor_list_stream(session, "/v1/users", "users", logger, resumable_source_manager, throttle)


def _get_workspace_id(
    session: requests.Session, logger: FilteringBoundLogger, throttle: Optional["_RateLimiter"] = None
) -> str:
    # Admin API paths take the workspace id, which the integration token's bot user reports.
    data = _request(session, "GET", "/v1/users/me", logger, throttle=throttle)
    workspace_id = (data.get("bot") or {}).get("workspace_id")
    if not workspace_id:
        raise ValueError("Notion did not return a workspace_id for the integration token's bot user")
    return workspace_id


def _permission_groups_stream(
    session: requests.Session,
    admin_session: requests.Session,
    logger: FilteringBoundLogger,
    resumable_source_manager: ResumableSourceManager[NotionResumeConfig],
    throttle: Optional["_RateLimiter"] = None,
) -> Iterator[Any]:
    workspace_id = _get_workspace_id(session, logger, throttle)
    yield from _cursor_list_stream(
        admin_session,
        f"{NOTION_ADMIN_BASE_PATH}/v1/spaces/{workspace_id}/groups",
        "permission_groups",
        logger,
        resumable_source_manager,
        throttle,
    )


def _iter_page_ids(
    session: requests.Session,
    logger: FilteringBoundLogger,
    throttle: Optional["_RateLimiter"] = None,
    resumable_source_manager: ResumableSourceManager[NotionResumeConfig] | None = None,
) -> Iterator[str]:
    cursor: str | None = None
    while True:
        try:
            data = _request(
                session, "POST", "/v1/search", logger, json_body=_search_body("page", cursor), throttle=throttle
            )
        except NotionBadRequestError as e:
            if cursor is None or not _is_invalid_start_cursor(e):
                raise
            # A cursor can expire mid-enumeration on a large workspace; restart from the beginning
            # rather than failing the blocks/comments fan-out. Page ids already yielded get re-yielded,
            # which the callers tolerate (blocks/comments dedup on primary key at merge).
            logger.warning("Notion: page-id search cursor rejected as invalid; restarting enumeration from the start")
            cursor = None
            continue
        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"]
        if resumable_source_manager is not None:
            # The enumeration buffers page ids, not rows, and stages no state, so a resume restarts it.
            resumable_source_manager.safe_point()


def _iter_block_children(
    session: requests.Session,
    block_id: str,
    page_id: str,
    logger: FilteringBoundLogger,
    depth: int,
    throttle: Optional["_RateLimiter"] = None,
) -> 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

        try:
            data = _request(session, "GET", f"/v1/blocks/{block_id}/children", logger, params=params, throttle=throttle)
        except NotionNotFoundError:
            logger.warning(
                "Notion: skipping missing or unshared block while fetching children",
                page_id=page_id,
                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
            if block.get("has_children"):
                if depth < MAX_BLOCK_DEPTH:
                    yield from _iter_block_children(session, block["id"], page_id, logger, depth + 1, throttle)
                else:
                    # Truncation at the depth backstop must be observable, not silent: without this the
                    # sync reports success while quietly leaving every block below this one behind.
                    logger.warning(
                        "Notion: block nesting exceeds max depth; deeper blocks were not synced",
                        page_id=page_id,
                        block_id=block["id"],
                        max_depth=MAX_BLOCK_DEPTH,
                    )

        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 _page_fan_out(
    session: requests.Session,
    logger: FilteringBoundLogger,
    resumable_source_manager: ResumableSourceManager[NotionResumeConfig],
    rows_for_page: Callable[[str], Iterator[dict[str, Any]]],
    throttle: Optional["_RateLimiter"] = None,
) -> Iterator[Any]:
    """Fetch rows for every page, with the fan-out position saved as a shrinking queue of page ids."""
    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
    if resume is not None and resume.remaining_page_ids is not None:
        # Resume the fan-out from the persisted queue rather than re-enumerating every page.
        page_ids = list(resume.remaining_page_ids)
        logger.debug(f"Notion: resuming page fan-out with {len(page_ids)} page(s) remaining")
    else:
        # Materialize the full set of page IDs up front so the fan-out position can be persisted as a
        # shrinking queue (a crash during this initial enumeration restarts it, like other sources).
        page_ids = list(_iter_page_ids(session, logger, throttle, resumable_source_manager))

    last_flush_at = time.monotonic()
    last_empty_stage_at = last_flush_at
    while page_ids:
        page_id = page_ids[0]
        remaining = page_ids[1:]
        for row in rows_for_page(page_id):
            batcher.batch(row)
            if batcher.should_yield():
                yield batcher.get_table()
                last_flush_at = time.monotonic()
                # Keep the in-progress page at the head: yielding flushes every buffered row from
                # already-finished pages, so only this page and the untouched rest can still be lost
                # on a crash. A retry re-fetches this page's rows (deduped on merge), losing nothing.
                resumable_source_manager.save_state(NotionResumeConfig(remaining_page_ids=[page_id, *remaining]))
        page_ids = remaining

        # Most pages have few or no rows (comments especially), so a chunk can take many pages to
        # fill. Without the two branches below, a long run of sparse pages records no progress and
        # gives the pipeline no point at which to hand the run off during a worker shutdown.
        now = time.monotonic()
        if batcher.should_yield(include_incomplete_chunk=True):
            if now - last_flush_at >= PARTIAL_FLUSH_INTERVAL_SECONDS:
                # Staged before the yield, so the commit that follows this table's write covers it.
                resumable_source_manager.save_state(NotionResumeConfig(remaining_page_ids=remaining))
                yield batcher.get_table()
                last_flush_at = time.monotonic()
        else:
            # Every row of the finished pages is yielded, so the queue can move past them. Staging
            # dumps the whole queue, so it runs at most every EMPTY_PAGE_STAGE_INTERVAL_SECONDS.
            if now - last_empty_stage_at >= EMPTY_PAGE_STAGE_INTERVAL_SECONDS:
                resumable_source_manager.save_state(NotionResumeConfig(remaining_page_ids=remaining))
                last_empty_stage_at = now
            resumable_source_manager.safe_point()

    if batcher.should_yield(include_incomplete_chunk=True):
        yield batcher.get_table()


def _blocks_stream(
    session: requests.Session,
    logger: FilteringBoundLogger,
    resumable_source_manager: ResumableSourceManager[NotionResumeConfig],
    throttle: Optional["_RateLimiter"] = None,
) -> Iterator[Any]:
    def blocks_for_page(page_id: str) -> Iterator[dict[str, Any]]:
        return _iter_block_children(session, page_id, page_id, logger, 0, throttle)

    yield from _page_fan_out(session, logger, resumable_source_manager, blocks_for_page, throttle)


def _iter_page_comments(
    session: requests.Session,
    page_id: str,
    logger: FilteringBoundLogger,
    throttle: Optional["_RateLimiter"] = None,
) -> Iterator[dict[str, Any]]:
    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

        try:
            data = _request(session, "GET", "/v1/comments", logger, params=params, throttle=throttle)
        except NotionNotFoundError:
            logger.warning(
                "Notion: skipping comments for missing or unshared page",
                page_id=page_id,
            )
            return
        except NotionBadRequestError as e:
            logger.warning(
                "Notion: skipping comments Notion rejected for page",
                page_id=page_id,
                error=str(e),
            )
            return
        for comment in data.get("results", []):
            comment["_page_id"] = page_id
            yield comment

        pages_fetched += 1
        if not data.get("has_more") or not data.get("next_cursor"):
            return
        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,
            )
            return
        cursor = data["next_cursor"]


def _comments_stream(
    session: requests.Session,
    logger: FilteringBoundLogger,
    resumable_source_manager: ResumableSourceManager[NotionResumeConfig],
    throttle: Optional["_RateLimiter"] = None,
) -> Iterator[Any]:
    def comments_for_page(page_id: str) -> Iterator[dict[str, Any]]:
        return _iter_page_comments(session, page_id, logger, throttle)

    yield from _page_fan_out(session, logger, resumable_source_manager, comments_for_page, throttle)


def get_rows(
    token: str,
    endpoint: str,
    logger: FilteringBoundLogger,
    resumable_source_manager: ResumableSourceManager[NotionResumeConfig],
    api_version: str,
    admin_token: str | None = None,
) -> Iterator[Any]:
    config = NOTION_ENDPOINTS[endpoint]
    session = _build_session(token, api_version)
    throttle = _RateLimiter(NOTION_MIN_REQUEST_INTERVAL_SECONDS)

    if config.stream_type == "permission_groups":
        if not admin_token:
            raise NotionAdminTokenMissingError(
                "Notion permission_groups table requires an organization bot token, but none is configured"
            )
        admin_session = _build_session(admin_token, NOTION_ADMIN_API_VERSION)
        yield from _permission_groups_stream(session, admin_session, logger, resumable_source_manager, throttle)
    elif config.stream_type == "search":
        yield from _search_stream(session, config, logger, resumable_source_manager, throttle)
    elif config.stream_type == "users":
        yield from _users_stream(session, logger, resumable_source_manager, throttle)
    elif config.stream_type == "blocks":
        yield from _blocks_stream(session, logger, resumable_source_manager, throttle)
    elif config.stream_type == "comments":
        yield from _comments_stream(session, logger, resumable_source_manager, throttle)
    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],
    api_version: str,
    admin_token: str | None = None,
) -> 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,
            api_version=api_version,
            admin_token=admin_token,
        ),
        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",
    )