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 granola transcripts table (#113252)

Tom Owers2bb7317b7140
diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
index fe64fcfd2e2f..545844f0c90d 100644
--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
@@ -629,8 +629,6 @@
1 products/warehouse_sources/backend/temporal/data_imports/sources/gorgias/gorgias.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/gorgias/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/grafana/settings.py
-1 products/warehouse_sources/backend/temporal/data_imports/sources/granola/granola.py
-1 products/warehouse_sources/backend/temporal/data_imports/sources/granola/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/greenhouse/greenhouse.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/gridly/gridly.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/gridly/settings.py
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index 729ccc049443..a38446ce32f1 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -3824,11 +3824,11 @@ Note: The published openapi3.json / api-merged.json cover 207 paths but only the
## Granola — adequate
-Today (2): `folders`, `notes`
+Today (3): `folders`, `notes`, `transcripts`
Diffed against: <https://docs.granola.ai/api-reference/openapi.json>
-No material gaps found.
+- [x] `transcripts (GET /v1/notes/{note_id}/transcript)` — cursor-paginated transcript items per note, added in API v1.4.0 for transcripts too large to return inline. Shipped as `transcripts`, fanned out over the notes listing (full refresh).
Note: The public OpenAPI declares only 5 paths: /v1/folders, /v1/notes, /v1/notes/{note_id}, and two webhook-endpoint management paths. PostHog's folders + notes tables cover every non-config resource in the API.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/granola/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/granola/canonical_descriptions.py
index 0f4c3b41c445..48f81d74d653 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/granola/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/granola/canonical_descriptions.py
@@ -31,4 +31,15 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"name": "Name of the folder.",
},
},
+ "transcripts": {
+ "description": "A single item of a meeting transcript in Granola, one row per spoken segment.",
+ "docs_url": "https://docs.granola.ai/api-reference/get-transcript",
+ "columns": {
+ "note_id": "ID of the note the transcript belongs to.",
+ "speaker": "Speaker of the segment: audio source, attribution (`me` or `them`), diarization label, and resolved name when known.",
+ "text": "Text of the transcript segment.",
+ "start_time": "Start time of the transcript segment.",
+ "end_time": "End time of the transcript segment.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/granola/granola.py b/products/warehouse_sources/backend/temporal/data_imports/sources/granola/granola.py
index 5fd4a4fa6df9..d6c0e17a9e22 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/granola/granola.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/granola/granola.py
@@ -1,7 +1,7 @@
import dataclasses
-from collections.abc import Callable
+from collections.abc import Callable, Iterable
from datetime import UTC, date, datetime
-from typing import Any, Optional
+from typing import Any, Optional, cast
from urllib.parse import urlencode
from requests import Response
@@ -11,28 +11,35 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
RESTAPIConfig,
rest_api_resource,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ build_dependent_resource,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
BaseNextUrlPaginator,
+ JSONResponseCursorPaginator,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import ClientConfig
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.granola.settings import (
GRANOLA_ENDPOINTS,
+ PAGE_SIZE,
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
-
[email protected](frozen=True)
class GranolaResumeConfig:
# Full, self-contained next-page URL (base + filters + cursor) so a resume can GET it directly.
- next_url: str
+ next_url: str | None = None
+ # Fan-out endpoints resume by parent: the parent paths already fully synced, the parent in
+ # progress, and that parent's paginator state.
+ completed: list[str] | None = None
+ current: str | None = None
+ child_state: dict[str, Any] | None = None
class GranolaCursorPaginator(BaseNextUrlPaginator):
@@ -61,6 +68,23 @@ class GranolaCursorPaginator(BaseNextUrlPaginator):
self._has_next_page = False
+class GranolaTranscriptPaginator(JSONResponseCursorPaginator):
+ """Body-cursor pagination for a single note's transcript, with the same ``hasMore`` gate."""
+
+ def __init__(self) -> None:
+ # A cursor that does not advance would re-request the same page until the activity times out.
+ super().__init__(cursor_path="cursor", cursor_param="cursor", raise_on_repeated_cursor=True)
+
+ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:
+ super().update_state(response, data)
+ try:
+ body = response.json()
+ except Exception:
+ body = {}
+ if not (isinstance(body, dict) and body.get("hasMore")):
+ self._has_next_page = False
+
+
def _get_headers(api_key: str) -> dict[str, str]:
return {
"Authorization": f"Bearer {api_key}",
@@ -109,6 +133,9 @@ def validate_credentials(api_key: str, schema_name: Optional[str] = None) -> tup
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
+ if endpoint is not None and endpoint.fanout is not None:
+ # A fan-out child's path needs a parent id, and its rows come from the parent's notes.
+ endpoint = GRANOLA_ENDPOINTS[endpoint.fanout.parent_name]
path = endpoint.path if endpoint else GRANOLA_ENDPOINTS["notes"].path
url = _build_url(path, {"page_size": 1})
@@ -132,6 +159,87 @@ def validate_credentials(api_key: str, schema_name: Optional[str] = None) -> tup
return False, f"Granola API returned an unexpected status code: {status}"
+def _source_response(config: GranolaEndpointConfig, items: Callable[[], Iterable[Any]]) -> SourceResponse:
+ return SourceResponse(
+ name=config.name,
+ items=items,
+ primary_keys=config.primary_keys,
+ # 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,
+ )
+
+
+def _fanout_source(
+ config: GranolaEndpointConfig,
+ api_key: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[GranolaResumeConfig],
+) -> SourceResponse:
+ assert config.fanout is not None
+ parent_config = GRANOLA_ENDPOINTS[config.fanout.parent_name]
+ parent_params: dict[str, Any] = {"page_size": parent_config.page_size}
+
+ client_config: ClientConfig = {
+ "base_url": GRANOLA_BASE_URL,
+ "headers": {"Accept": "application/json"},
+ "auth": {"type": "bearer", "token": api_key},
+ "paginator": GranolaCursorPaginator(
+ lambda cursor: _build_url(parent_config.path, {**parent_params, "cursor": cursor})
+ ),
+ }
+
+ initial_state: Optional[dict[str, Any]] = None
+ if resumable_source_manager.can_resume():
+ resume = resumable_source_manager.load_state()
+ if resume is not None and (resume.completed or resume.current):
+ initial_state = {
+ "completed": resume.completed or [],
+ "current": resume.current,
+ "child_state": resume.child_state,
+ }
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ if state is not None:
+ resumable_source_manager.save_state(
+ GranolaResumeConfig(
+ completed=state.get("completed"),
+ current=state.get("current"),
+ child_state=state.get("child_state"),
+ )
+ )
+
+ resource = cast(
+ Iterable[Any],
+ build_dependent_resource(
+ endpoint_configs=GRANOLA_ENDPOINTS,
+ child_endpoint=config.name,
+ fanout=config.fanout,
+ client_config=client_config,
+ path_format_values={},
+ team_id=team_id,
+ job_id=job_id,
+ db_incremental_field_last_value=None,
+ parent_endpoint_extra={"data_selector": parent_config.data_key},
+ child_endpoint_extra={"data_selector": config.data_key, "paginator": GranolaTranscriptPaginator()},
+ page_size_param="page_size",
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_state,
+ ),
+ )
+
+ return _source_response(config, lambda: resource)
+
+
def granola_source(
api_key: str,
endpoint: str,
@@ -144,6 +252,9 @@ def granola_source(
) -> SourceResponse:
config = GRANOLA_ENDPOINTS[endpoint]
+ if config.fanout is not None:
+ return _fanout_source(config, api_key, team_id, job_id, resumable_source_manager)
+
params = _build_initial_params(
config, should_use_incremental_field, db_incremental_field_last_value, incremental_field
)
@@ -178,7 +289,7 @@ def granola_source(
initial_paginator_state: Optional[dict[str, Any]] = None
if resumable_source_manager.can_resume():
resume = resumable_source_manager.load_state()
- if resume is not None:
+ if resume is not None and resume.next_url:
initial_paginator_state = {"next_url": resume.next_url}
def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
@@ -198,19 +309,4 @@ def granola_source(
initial_paginator_state=initial_paginator_state,
)
- return SourceResponse(
- name=endpoint,
- items=lambda: resource,
- 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,
- )
+ return _source_response(config, lambda: resource)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/granola/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/granola/settings.py
index e71772216f17..6015f8d34314 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/granola/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/granola/settings.py
@@ -1,10 +1,17 @@
from dataclasses import dataclass, field
from typing import Optional
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ DependentEndpointConfig,
+)
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+# Granola caps the notes 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
-@dataclass
+
+@dataclass(frozen=True)
class GranolaEndpointConfig:
name: str
path: str
@@ -15,6 +22,10 @@ class GranolaEndpointConfig:
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)
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ page_size: int = PAGE_SIZE
+ default_incremental_field: Optional[str] = None
+ fanout: Optional[DependentEndpointConfig] = None
def _datetime_field(name: str) -> IncrementalField:
@@ -45,6 +56,26 @@ GRANOLA_ENDPOINTS: dict[str, GranolaEndpointConfig] = {
path="/v1/folders",
data_key="folders",
),
+ # https://docs.granola.ai/api-reference/get-transcript
+ # One row per transcript item, fanned out over the notes listing. Items carry no id, and the
+ # endpoint has no server-side time filter, so this is full refresh only.
+ "transcripts": GranolaEndpointConfig(
+ name="transcripts",
+ path="/v1/notes/{note_id}/transcript",
+ data_key="transcript",
+ partition_key="start_time",
+ primary_keys=["note_id", "start_time", "end_time"],
+ page_size=100,
+ fanout=DependentEndpointConfig(
+ parent_name="notes",
+ resolve_param="note_id",
+ resolve_field="id",
+ include_from_parent=["id"],
+ parent_field_renames={"id": "note_id"},
+ # A note deleted between the listing and the transcript fetch 404s; skip it.
+ child_response_actions=[{"status_code": 404, "action": "ignore"}],
+ ),
+ ),
}
ENDPOINTS = tuple(GRANOLA_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/granola/tests/test_granola.py b/products/warehouse_sources/backend/temporal/data_imports/sources/granola/tests/test_granola.py
index 837e4ba012a5..a244aa206cb2 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/granola/tests/test_granola.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/granola/tests/test_granola.py
@@ -172,6 +172,7 @@ class TestValidateCredentials:
(None, "/v1/notes"),
("notes", "/v1/notes"),
("folders", "/v1/folders"),
+ ("transcripts", "/v1/notes"), # fan-out child probes its parent listing
("unknown", "/v1/notes"),
],
)
@@ -222,6 +223,7 @@ class TestPagination:
manager.save_state.assert_called_once()
saved = manager.save_state.call_args.args[0]
assert isinstance(saved, GranolaResumeConfig)
+ assert saved.next_url is not None
assert "cursor=c1" in saved.next_url
@mock.patch(CLIENT_SESSION_PATCH)
@@ -308,6 +310,84 @@ class TestPagination:
_rows(granola_source("grn_test", "notes", team_id=1, job_id="j", resumable_source_manager=_make_manager()))
+class TestTranscriptsFanout:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_paginates_each_note_transcript_and_skips_deleted_notes(self, MockSession) -> None:
+ session = MockSession.return_value
+ seen = _wire(
+ session,
+ [
+ _response({"notes": [{"id": "not_1"}, {"id": "not_2"}], "hasMore": False, "cursor": None}),
+ _response({"transcript": [{"text": "a"}], "hasMore": True, "cursor": "t1"}),
+ # A cursor alongside hasMore=false still ends the transcript.
+ _response({"transcript": [{"text": "b"}], "hasMore": False, "cursor": "t2"}),
+ _response({"message": "Not found"}, status=404),
+ ],
+ )
+
+ manager = _make_manager()
+ rows = _rows(granola_source("grn_test", "transcripts", team_id=1, job_id="j", resumable_source_manager=manager))
+
+ assert [(row["note_id"], row["text"]) for row in rows] == [("not_1", "a"), ("not_1", "b")]
+ assert all("_notes_id" not in row for row in rows)
+ child_requests = seen[1:]
+ assert [r["url"].removeprefix(GRANOLA_BASE_URL) for r in child_requests] == [
+ "/v1/notes/not_1/transcript",
+ "/v1/notes/not_1/transcript",
+ "/v1/notes/not_2/transcript",
+ ]
+ assert child_requests[0]["params"] == {"page_size": 100}
+ assert child_requests[1]["params"] == {"page_size": 100, "cursor": "t1"}
+ assert manager.save_state.call_args.args[0].completed == [
+ "/v1/notes/not_1/transcript",
+ "/v1/notes/not_2/transcript",
+ ]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_resume_skips_completed_notes_and_continues_current_cursor(self, MockSession) -> None:
+ session = MockSession.return_value
+ seen = _wire(
+ session,
+ [
+ _response({"notes": [{"id": "not_1"}, {"id": "not_2"}], "hasMore": False, "cursor": None}),
+ _response({"transcript": [{"text": "c"}], "hasMore": False, "cursor": None}),
+ ],
+ )
+
+ manager = _make_manager(
+ GranolaResumeConfig(
+ completed=["/v1/notes/not_1/transcript"],
+ current="/v1/notes/not_2/transcript",
+ child_state={"cursor": "t5"},
+ )
+ )
+ rows = _rows(granola_source("grn_test", "transcripts", team_id=1, job_id="j", resumable_source_manager=manager))
+
+ assert rows == [{"text": "c", "note_id": "not_2"}]
+ assert seen[1]["url"] == f"{GRANOLA_BASE_URL}/v1/notes/not_2/transcript"
+ assert seen[1]["params"]["cursor"] == "t5"
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_repeated_transcript_cursor_fails_instead_of_looping(self, MockSession) -> None:
+ session = MockSession.return_value
+ _wire(
+ session,
+ [
+ _response({"notes": [{"id": "not_1"}], "hasMore": False, "cursor": None}),
+ _response({"transcript": [{"text": "a"}], "hasMore": True, "cursor": "t1"}),
+ _response({"transcript": [{"text": "a"}], "hasMore": True, "cursor": "t1"}),
+ ],
+ )
+
+ with pytest.raises(ValueError, match="not advancing"):
+ _rows(
+ granola_source(
+ "grn_test", "transcripts", team_id=1, job_id="j", resumable_source_manager=_make_manager()
+ )
+ )
+ assert session.send.call_count == 3
+
+
class TestGranolaSource:
@mock.patch(CLIENT_SESSION_PATCH)
def test_notes_response_has_datetime_partition(self, MockSession) -> None: