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): implement granola import source (#61149)

Tom Owers11cdaf3ee90b
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.md
index f31fd713f0f6..aab033369e34 100644
--- a/posthog/temporal/data_imports/sources/SOURCES.md
+++ b/posthog/temporal/data_imports/sources/SOURCES.md
@@ -67,6 +67,7 @@ the row lists both.
| github | HTTP | requests | ✅ |
| google_ads | gRPC | google-ads (googleads.client) | ✅ |
| google_sheets | HTTP (vendor SDK) | gspread | ✅ |
+| granola | HTTP | requests | ✅ |
| gorgias | HTTP | requests | ✅ |
| hubspot | HTTP | requests | ✅ |
| klaviyo | HTTP | requests | ✅ |
@@ -178,7 +179,6 @@ doesn't conflict with concurrent PRs.
- gong
- google_analytics
- google_drive
-- granola
- greenhouse
- helpscout
- instagram
diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.py
index e6ca899a043d..29cc1b9cf6e4 100644
--- a/posthog/temporal/data_imports/sources/generated_configs.py
+++ b/posthog/temporal/data_imports/sources/generated_configs.py
@@ -413,7 +413,7 @@ class GorgiasSourceConfig(config.Config):
@config.config
class GranolaSourceConfig(config.Config):
- pass
+ api_key: str
@config.config
diff --git a/posthog/temporal/data_imports/sources/granola/granola.py b/posthog/temporal/data_imports/sources/granola/granola.py
new file mode 100644
index 000000000000..f9f7da306d5a
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/granola/granola.py
@@ -0,0 +1,200 @@
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+from urllib.parse import urlencode
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+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.granola.settings import GRANOLA_ENDPOINTS, GranolaEndpointConfig
+
+GRANOLA_BASE_URL = "https://public-api.granola.ai"
+
+# Granola caps page_size at 30; use the max to keep request volume low against the
+# 5 req/s sustained / 25-per-5s burst rate limit.
+PAGE_SIZE = 30
+
+REQUEST_TIMEOUT_SECONDS = 60
+MAX_RETRY_ATTEMPTS = 5
+
+
+class GranolaRetryableError(Exception):
+ pass
+
+
+class GranolaResumeConfig:
+ # Full, self-contained next-page URL (base + filters + cursor) so a resume can GET it directly.
+ next_url: str
+
+
+def _get_headers(api_key: str) -> dict[str, str]:
+ return {
+ "Authorization": f"Bearer {api_key}",
+ "Accept": "application/json",
+ }
+
+
+def _format_timestamp(value: Any) -> str:
+ """Format an incremental cursor value as an ISO 8601 UTC timestamp with a Z suffix."""
+ if isinstance(value, datetime):
+ dt = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)
+ return dt.strftime("%Y-%m-%dT%H:%M:%SZ")
+ if isinstance(value, date):
+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
+ return str(value)
+
+
+def _build_initial_params(
+ config: GranolaEndpointConfig,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+ incremental_field: str | None,
+) -> dict[str, Any]:
+ params: dict[str, Any] = {"page_size": PAGE_SIZE}
+
+ if should_use_incremental_field and db_incremental_field_last_value is not None:
+ # Honour the user's chosen cursor field, falling back to the first advertised field.
+ field_name = incremental_field or (config.incremental_fields[0]["field"] if config.incremental_fields else None)
+ query_param = config.incremental_query_params.get(field_name) if field_name else None
+ if query_param:
+ params[query_param] = _format_timestamp(db_incremental_field_last_value)
+
+ return params
+
+
+def _build_url(path: str, params: dict[str, Any]) -> str:
+ return f"{GRANOLA_BASE_URL}{path}?{urlencode(params)}"
+
+
+def validate_credentials(api_key: str, schema_name: Optional[str] = None) -> tuple[bool, str | None]:
+ """Probe the endpoint matching the schema being validated to confirm the API key is genuine.
+
+ A 401 means the key is missing or invalid. A 403 means a valid key without the scope
+ for this endpoint - accepted at source-create (schema_name is None) since users may only
+ grant the scopes for the streams they want to sync. Probing the schema's own path means a
+ scope-limited key (e.g. folders-only) isn't rejected by an unrelated stream's probe.
+ """
+ endpoint = GRANOLA_ENDPOINTS.get(schema_name) if schema_name else None
+ path = endpoint.path if endpoint else GRANOLA_ENDPOINTS["notes"].path
+ url = _build_url(path, {"page_size": 1})
+ try:
+ response = make_tracked_session().get(url, headers=_get_headers(api_key), timeout=REQUEST_TIMEOUT_SECONDS)
+ except Exception:
+ return False, "Could not reach the Granola API. Please try again."
+
+ if response.status_code == 200:
+ return True, None
+ if response.status_code == 401:
+ return False, "Invalid Granola API key"
+ if response.status_code == 403 and schema_name is None:
+ return True, None
+ if response.status_code == 403:
+ return False, "Your Granola API key does not have access to this data"
+
+ return False, f"Granola API returned an unexpected status code: {response.status_code}"
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[GranolaResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+ incremental_field: str | None = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = GRANOLA_ENDPOINTS[endpoint]
+ headers = _get_headers(api_key)
+
+ params = _build_initial_params(
+ config, should_use_incremental_field, db_incremental_field_last_value, incremental_field
+ )
+
+ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume_config is not None:
+ url = resume_config.next_url
+ logger.debug(f"Granola: resuming {endpoint} from URL: {url}")
+ else:
+ url = _build_url(config.path, params)
+
+ @retry(
+ retry=retry_if_exception_type((GranolaRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+ )
+ def fetch_page(page_url: str) -> dict[str, Any]:
+ response = make_tracked_session().get(page_url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise GranolaRetryableError(f"Granola API error (retryable): status={response.status_code}, url={page_url}")
+
+ if not response.ok:
+ logger.error(f"Granola API error: status={response.status_code}, body={response.text}, url={page_url}")
+ response.raise_for_status()
+
+ return response.json()
+
+ while True:
+ data = fetch_page(url)
+
+ items = data.get(config.data_key, [])
+
+ # Compute the next-page URL before yielding so we can checkpoint after the batch.
+ next_url: str | None = None
+ if data.get("hasMore") and data.get("cursor"):
+ next_url = _build_url(config.path, {**params, "cursor": data["cursor"]})
+
+ if items:
+ yield items
+
+ if not next_url:
+ break
+
+ # Save state AFTER yielding so a crash re-yields the last batch (merge dedupes on id)
+ # rather than skipping it.
+ resumable_source_manager.save_state(GranolaResumeConfig(next_url=next_url))
+ url = next_url
+
+
+def granola_source(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[GranolaResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+ incremental_field: str | None = None,
+) -> SourceResponse:
+ config = GRANOLA_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ incremental_field=incremental_field,
+ ),
+ primary_keys=["id"],
+ # Granola's list endpoints have no sort parameter, so within-page ordering is
+ # undefined. "desc" here is the pipeline's "commit the incremental watermark only
+ # after every page has been processed" mode - with undefined ordering we must not
+ # advance the watermark per-batch (that could persist a high value early and skip
+ # older, not-yet-fetched rows on the next run's server-side `*_after` filter).
+ # Pagination is driven entirely by the opaque cursor, so we don't rely on ordering
+ # or on `db_incremental_field_earliest_value` to scroll; merge dedupes on `id`.
+ sort_mode="desc",
+ 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,
+ )
diff --git a/posthog/temporal/data_imports/sources/granola/settings.py b/posthog/temporal/data_imports/sources/granola/settings.py
new file mode 100644
index 000000000000..ef78e47d98c9
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/granola/settings.py
@@ -0,0 +1,54 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType
+
+
+@dataclass
+class GranolaEndpointConfig:
+ name: str
+ path: str
+ # Key that wraps the list of rows in the JSON response body (e.g. {"notes": [...]}).
+ data_key: str
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Stable datetime field to partition on. Never use updated_at - it changes and rewrites partitions.
+ partition_key: Optional[str] = None
+ # Maps an advertised incremental field name to the server-side query param that filters on it.
+ incremental_query_params: dict[str, str] = field(default_factory=dict)
+
+
+def _datetime_field(name: str) -> IncrementalField:
+ return {
+ "label": name,
+ "type": IncrementalFieldType.DateTime,
+ "field": name,
+ "field_type": IncrementalFieldType.DateTime,
+ }
+
+
+GRANOLA_ENDPOINTS: dict[str, GranolaEndpointConfig] = {
+ # https://docs.granola.ai/api-reference/list-notes
+ # Only returns notes that already have a generated AI summary + transcript.
+ # Both created_after and updated_after are genuine server-side filters per the OpenAPI spec.
+ "notes": GranolaEndpointConfig(
+ name="notes",
+ path="/v1/notes",
+ data_key="notes",
+ partition_key="created_at",
+ incremental_fields=[_datetime_field("updated_at"), _datetime_field("created_at")],
+ incremental_query_params={"updated_at": "updated_after", "created_at": "created_after"},
+ ),
+ # https://docs.granola.ai/api-reference/list-folders
+ # No timestamp fields and no server-side time filter - full refresh only.
+ "folders": GranolaEndpointConfig(
+ name="folders",
+ path="/v1/folders",
+ data_key="folders",
+ ),
+}
+
+ENDPOINTS = tuple(GRANOLA_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in GRANOLA_ENDPOINTS.items()
+}
diff --git a/posthog/temporal/data_imports/sources/granola/source.py b/posthog/temporal/data_imports/sources/granola/source.py
index 49d07b48bc5d..aeb41425d551 100644
--- a/posthog/temporal/data_imports/sources/granola/source.py
+++ b/posthog/temporal/data_imports/sources/granola/source.py
@@ -1,19 +1,31 @@
-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 GranolaSourceConfig
+from posthog.temporal.data_imports.sources.granola.granola import (
+ GranolaResumeConfig,
+ granola_source,
+ validate_credentials as validate_granola_credentials,
+)
+from posthog.temporal.data_imports.sources.granola.settings import ENDPOINTS, INCREMENTAL_FIELDS
from products.data_warehouse.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class GranolaSource(SimpleSource[GranolaSourceConfig]):
+class GranolaSource(ResumableSource[GranolaSourceConfig, GranolaResumeConfig]):
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.GRANOLA
@@ -23,7 +35,85 @@ class GranolaSource(SimpleSource[GranolaSourceConfig]):
return SourceConfig(
name=SchemaExternalDataSourceType.GRANOLA,
label="Granola",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your Granola API key to pull your meeting notes into the PostHog Data warehouse.
+
+API access requires a **Business** plan or higher. Create a key (prefixed `grn_`) in the Granola desktop app under **Settings → Connectors → API keys**.
+
+When creating the key, grant the access scopes for the data you want to sync:
+- **Personal notes**
+- **Public notes**
+
+Only notes with a generated AI summary and transcript are returned by the API.
+""",
iconPath="/static/services/granola.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://docs.granola.ai/introduction",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="grn_...",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_schemas(
+ self,
+ config: GranolaSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=INCREMENTAL_FIELDS.get(endpoint) is not None
+ and len(INCREMENTAL_FIELDS[endpoint]) > 0,
+ supports_append=INCREMENTAL_FIELDS.get(endpoint) is not None and len(INCREMENTAL_FIELDS[endpoint]) > 0,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ )
+ for endpoint in 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: GranolaSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ return validate_granola_credentials(config.api_key, schema_name)
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized": "Your Granola API key is invalid or expired. Please generate a new key and reconnect.",
+ "403 Client Error: Forbidden": "Your Granola API key does not have the required access scope. Please check the key's scopes and reconnect.",
+ }
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[GranolaResumeConfig]:
+ return ResumableSourceManager[GranolaResumeConfig](inputs, GranolaResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: GranolaSourceConfig,
+ resumable_source_manager: ResumableSourceManager[GranolaResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return granola_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
+ incremental_field=inputs.incremental_field,
)
diff --git a/posthog/temporal/data_imports/sources/granola/tests/test_granola.py b/posthog/temporal/data_imports/sources/granola/tests/test_granola.py
new file mode 100644
index 000000000000..cc6b3e7bf4df
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/granola/tests/test_granola.py
@@ -0,0 +1,262 @@
+import json
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+
+import pytest
+from unittest import mock
+
+import structlog
+
+from posthog.temporal.data_imports.sources.granola.granola import (
+ GRANOLA_BASE_URL,
+ PAGE_SIZE,
+ GranolaResumeConfig,
+ _build_initial_params,
+ _build_url,
+ _format_timestamp,
+ get_rows,
+ granola_source,
+ validate_credentials,
+)
+from posthog.temporal.data_imports.sources.granola.settings import GRANOLA_ENDPOINTS
+
+MODULE = "posthog.temporal.data_imports.sources.granola.granola"
+
+
+def _response(status: int = 200, body: Optional[dict[str, Any]] = None) -> mock.MagicMock:
+ resp = mock.MagicMock()
+ resp.status_code = status
+ resp.ok = 200 <= status < 300
+ resp.json.return_value = body or {}
+ resp.text = json.dumps(body or {})
+ return resp
+
+
+class _StubManager:
+ """Minimal stand-in for ResumableSourceManager that records saved state."""
+
+ def __init__(self, resume_state: Optional[GranolaResumeConfig] = None) -> None:
+ self._resume_state = resume_state
+ self.saved: list[GranolaResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._resume_state is not None
+
+ def load_state(self) -> Optional[GranolaResumeConfig]:
+ return self._resume_state
+
+ def save_state(self, data: GranolaResumeConfig) -> None:
+ self.saved.append(data)
+
+
+class TestFormatTimestamp:
+ @pytest.mark.parametrize(
+ "value, expected",
+ [
+ (datetime(2026, 1, 27, 15, 30, 0, tzinfo=UTC), "2026-01-27T15:30:00Z"),
+ (datetime(2026, 1, 27, 15, 30, 0), "2026-01-27T15:30:00Z"),
+ (date(2026, 1, 27), "2026-01-27T00:00:00Z"),
+ ("already-a-string", "already-a-string"),
+ ],
+ )
+ def test_format_timestamp(self, value: Any, expected: str) -> None:
+ assert _format_timestamp(value) == expected
+
+ def test_no_plus_zero_offset(self) -> None:
+ assert "+00:00" not in _format_timestamp(datetime(2026, 1, 27, 15, 30, tzinfo=UTC))
+
+
+class TestBuildInitialParams:
+ def test_non_incremental_only_sets_page_size(self) -> None:
+ params = _build_initial_params(GRANOLA_ENDPOINTS["notes"], False, None, None)
+
+ assert params == {"page_size": PAGE_SIZE}
+
+ @pytest.mark.parametrize(
+ "incremental_field, expected_param",
+ [
+ ("updated_at", "updated_after"),
+ ("created_at", "created_after"),
+ (None, "updated_after"), # falls back to the first advertised field
+ ],
+ )
+ def test_incremental_maps_field_to_server_filter(self, incremental_field, expected_param) -> None:
+ params = _build_initial_params(
+ GRANOLA_ENDPOINTS["notes"],
+ True,
+ datetime(2026, 1, 27, 15, 30, 0, tzinfo=UTC),
+ incremental_field,
+ )
+
+ assert params[expected_param] == "2026-01-27T15:30:00Z"
+ assert params["page_size"] == PAGE_SIZE
+
+ def test_incremental_without_last_value_skips_filter(self) -> None:
+ params = _build_initial_params(GRANOLA_ENDPOINTS["notes"], True, None, "updated_at")
+
+ assert params == {"page_size": PAGE_SIZE}
+
+ def test_folders_has_no_server_filter(self) -> None:
+ # folders advertises no incremental fields, so it never gets a timestamp filter.
+ params = _build_initial_params(
+ GRANOLA_ENDPOINTS["folders"], True, datetime(2026, 1, 27, tzinfo=UTC), "updated_at"
+ )
+
+ assert params == {"page_size": PAGE_SIZE}
+
+
+class TestBuildUrl:
+ def test_build_url(self) -> None:
+ url = _build_url("/v1/notes", {"page_size": 30, "cursor": "abc"})
+
+ assert url == f"{GRANOLA_BASE_URL}/v1/notes?page_size=30&cursor=abc"
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ "status, schema_name, expected_valid",
+ [
+ (200, None, True),
+ (200, "notes", True),
+ (401, None, False),
+ (401, "notes", False),
+ (403, None, True), # valid key, scope not granted - accepted at source-create
+ (403, "notes", False), # scope required for the specific schema
+ (500, None, False),
+ ],
+ )
+ def test_status_mapping(self, status, schema_name, expected_valid) -> None:
+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.return_value = _response(status)
+
+ is_valid, _ = validate_credentials("grn_test", schema_name)
+
+ assert is_valid is expected_valid
+
+ def test_network_error_is_invalid(self) -> None:
+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.side_effect = Exception("boom")
+
+ is_valid, message = validate_credentials("grn_test")
+
+ assert is_valid is False
+ assert message is not None
+
+ @pytest.mark.parametrize(
+ "schema_name, expected_path",
+ [
+ (None, "/v1/notes"),
+ ("notes", "/v1/notes"),
+ ("folders", "/v1/folders"),
+ ("unknown", "/v1/notes"),
+ ],
+ )
+ def test_probes_path_matching_schema(self, schema_name, expected_path) -> None:
+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.return_value = _response(200)
+
+ validate_credentials("grn_test", schema_name)
+
+ called_url = mock_session.return_value.get.call_args[0][0]
+
+ assert called_url.startswith(f"{GRANOLA_BASE_URL}{expected_path}?")
+
+
+class TestGetRows:
+ def _run(self, manager: _StubManager, pages: list[dict[str, Any]], **kwargs: Any) -> list[list[dict[str, Any]]]:
+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.side_effect = [_response(200, page) for page in pages]
+ return list(
+ get_rows(
+ api_key="grn_test",
+ endpoint="notes",
+ logger=structlog.get_logger(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ **kwargs,
+ )
+ )
+
+ def test_paginates_and_yields_each_page(self) -> None:
+ manager = _StubManager()
+ pages = [
+ {"notes": [{"id": "not_1"}, {"id": "not_2"}], "hasMore": True, "cursor": "c1"},
+ {"notes": [{"id": "not_3"}], "hasMore": False, "cursor": None},
+ ]
+
+ batches = self._run(manager, pages)
+
+ assert batches == [[{"id": "not_1"}, {"id": "not_2"}], [{"id": "not_3"}]]
+
+ def test_saves_state_after_yielding_each_page(self) -> None:
+ manager = _StubManager()
+ pages = [
+ {"notes": [{"id": "not_1"}], "hasMore": True, "cursor": "c1"},
+ {"notes": [{"id": "not_2"}], "hasMore": False, "cursor": None},
+ ]
+
+ self._run(manager, pages)
+
+ # Only one checkpoint - the final page has no next cursor.
+ assert len(manager.saved) == 1
+ assert "cursor=c1" in manager.saved[0].next_url
+
+ def test_stops_when_cursor_missing_even_if_has_more(self) -> None:
+ manager = _StubManager()
+ pages = [{"notes": [{"id": "not_1"}], "hasMore": True, "cursor": None}]
+
+ batches = self._run(manager, pages)
+
+ assert batches == [[{"id": "not_1"}]]
+ assert manager.saved == []
+
+ def test_resumes_from_saved_url(self) -> None:
+ resume_url = f"{GRANOLA_BASE_URL}/v1/notes?page_size=30&cursor=resume_token"
+ manager = _StubManager(resume_state=GranolaResumeConfig(next_url=resume_url))
+
+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.side_effect = [
+ _response(200, {"notes": [{"id": "not_9"}], "hasMore": False, "cursor": None})
+ ]
+ list(
+ get_rows(
+ api_key="grn_test",
+ endpoint="notes",
+ logger=structlog.get_logger(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ )
+ )
+
+ called_url = mock_session.return_value.get.call_args[0][0]
+
+ assert called_url == resume_url
+
+
+class TestGranolaSource:
+ def test_notes_response_has_datetime_partition(self) -> None:
+ response = granola_source(
+ api_key="grn_test",
+ endpoint="notes",
+ logger=structlog.get_logger(),
+ resumable_source_manager=mock.MagicMock(),
+ )
+
+ assert response.name == "notes"
+ assert response.primary_keys == ["id"]
+ # "desc" defers the incremental watermark commit until every page is processed.
+ assert response.sort_mode == "desc"
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == ["created_at"]
+ assert response.partition_format == "week"
+
+ def test_folders_response_has_no_partition(self) -> None:
+ response = granola_source(
+ api_key="grn_test",
+ endpoint="folders",
+ logger=structlog.get_logger(),
+ resumable_source_manager=mock.MagicMock(),
+ )
+
+ assert response.name == "folders"
+ assert response.primary_keys == ["id"]
+ assert response.partition_mode is None
+ assert response.partition_keys is None
diff --git a/posthog/temporal/data_imports/sources/granola/tests/test_granola_source.py b/posthog/temporal/data_imports/sources/granola/tests/test_granola_source.py
new file mode 100644
index 000000000000..a16d55fd7f1d
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/granola/tests/test_granola_source.py
@@ -0,0 +1,166 @@
+from datetime import UTC, datetime
+from typing import Optional
+
+import pytest
+from unittest import mock
+
+import structlog
+
+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 GranolaSourceConfig
+from posthog.temporal.data_imports.sources.granola.granola import GranolaResumeConfig
+from posthog.temporal.data_imports.sources.granola.settings import ENDPOINTS
+from posthog.temporal.data_imports.sources.granola.source import GranolaSource
+
+from products.data_warehouse.backend.types import ExternalDataSourceType
+
+
+def _make_inputs(
+ schema_name: str = "notes",
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: object = None,
+ incremental_field: Optional[str] = None,
+) -> SourceInputs:
+ return SourceInputs(
+ schema_name=schema_name,
+ schema_id="schema-id",
+ source_id="source-id",
+ team_id=123,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ db_incremental_field_earliest_value=None,
+ incremental_field=incremental_field,
+ incremental_field_type=None,
+ job_id="job-id",
+ logger=structlog.get_logger(),
+ reset_pipeline=False,
+ )
+
+
+class TestGranolaSource:
+ def setup_method(self):
+ self.source = GranolaSource()
+ self.team_id = 123
+ self.config = GranolaSourceConfig(api_key="grn_test")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.GRANOLA
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "Granola"
+ assert config.label == "Granola"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.iconPath == "/static/services/granola.png"
+ assert len(config.fields) == 1
+
+ api_key_field = config.fields[0]
+ assert isinstance(api_key_field, SourceFieldInputConfig)
+ assert api_key_field.name == "api_key"
+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD
+ assert api_key_field.required is True
+ assert api_key_field.secret is True
+
+ def test_get_schemas_lists_all_endpoints(self):
+ schemas = self.source.get_schemas(self.config, self.team_id)
+
+ assert {schema.name for schema in schemas} == set(ENDPOINTS)
+
+ @pytest.mark.parametrize(
+ "endpoint, expect_incremental",
+ [
+ ("notes", True),
+ ("folders", False),
+ ],
+ )
+ def test_get_schemas_incremental_support(self, endpoint, expect_incremental):
+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+
+ assert schemas[endpoint].supports_incremental is expect_incremental
+ assert schemas[endpoint].supports_append is expect_incremental
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["notes"])
+
+ assert len(schemas) == 1
+ assert schemas[0].name == "notes"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["nonexistent"])
+
+ assert schemas == []
+
+ @pytest.mark.parametrize(
+ "expected_key",
+ [
+ "401 Client Error: Unauthorized",
+ "403 Client Error: Forbidden",
+ ],
+ )
+ def test_non_retryable_errors_includes_auth_keys(self, expected_key):
+ assert expected_key in self.source.get_non_retryable_errors()
+
+ @pytest.mark.parametrize(
+ "mock_return, expected_valid, expected_message",
+ [
+ ((True, None), True, None),
+ ((False, "Invalid Granola API key"), False, "Invalid Granola API key"),
+ ],
+ )
+ @mock.patch("posthog.temporal.data_imports.sources.granola.source.validate_granola_credentials")
+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid, expected_message):
+ mock_validate.return_value = mock_return
+
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id, "notes")
+
+ assert is_valid is expected_valid
+ assert error_message == expected_message
+ mock_validate.assert_called_once_with(self.config.api_key, "notes")
+
+ def test_get_resumable_source_manager(self):
+ manager = self.source.get_resumable_source_manager(_make_inputs())
+
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is GranolaResumeConfig
+
+ @mock.patch("posthog.temporal.data_imports.sources.granola.source.granola_source")
+ def test_source_for_pipeline_plumbs_incremental_args(self, mock_granola_source):
+ manager = mock.MagicMock()
+ last_value = datetime(2026, 1, 1, tzinfo=UTC)
+ inputs = _make_inputs(
+ schema_name="notes",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=last_value,
+ incremental_field="updated_at",
+ )
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_granola_source.assert_called_once_with(
+ api_key="grn_test",
+ endpoint="notes",
+ logger=inputs.logger,
+ resumable_source_manager=manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=last_value,
+ incremental_field="updated_at",
+ )
+
+ @mock.patch("posthog.temporal.data_imports.sources.granola.source.granola_source")
+ def test_source_for_pipeline_drops_last_value_when_not_incremental(self, mock_granola_source):
+ manager = mock.MagicMock()
+ inputs = _make_inputs(
+ schema_name="folders",
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=datetime(2026, 1, 1, tzinfo=UTC),
+ )
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ _, kwargs = mock_granola_source.call_args
+ assert kwargs["should_use_incremental_field"] is False
+ assert kwargs["db_incremental_field_last_value"] is None