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(warehouse-sources): add pages, ask ai and team member tables to gitbook (#109110)

Tom Owers4b92b4a4fce6
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 ed970be21f9d..038a646facad 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
@@ -3556,14 +3556,14 @@ Note: Read-only content-search API with an inherently small analytical surface;
## GitBook — gaps
-Today (8): `change_requests`, `collections`, `comments`, `members`, `organizations`, `sites`, `spaces`, `teams`
+Today (12): `change_requests`, `collections`, `comments`, `members`, `organizations`, `pages`, `site_answers`, `site_questions`, `sites`, `spaces`, `team_members`, `teams`
Diffed against: <https://api.gitbook.com/openapi.json>
-- [ ] `/spaces/{spaceId}/content/pages` — the page inventory per space — the primary documentation object, currently absent entirely (high)
-- [ ] `/orgs/{organizationId}/sites/{siteId}/questions` — questions readers ask GitBook AI on published sites — the headline docs-effectiveness signal (high)
-- [ ] `/orgs/{organizationId}/sites/{siteId}/answers` — the answers served for those questions, including whether the docs could answer (high)
-- [ ] `/orgs/{organizationId}/teams/{teamId}/members` — join table resolving the members and teams we already sync (high)
+- [x] `/spaces/{spaceId}/content/pages` — the page inventory per space — the primary documentation object, currently absent entirely (high)
+- [x] `/orgs/{organizationId}/sites/{siteId}/questions` — questions readers ask GitBook AI on published sites — the headline docs-effectiveness signal (high)
+- [x] `/orgs/{organizationId}/sites/{siteId}/answers` — the answers served for those questions, including whether the docs could answer (high)
+- [x] `/orgs/{organizationId}/teams/{teamId}/members` — join table resolving the members and teams we already sync (high)
- [ ] `/orgs/{organizationId}/sites/{siteId}/question-stats` — aggregated question volume and resolution rate per site (medium)
- [ ] `/orgs/{organizationId}/sites/{siteId}/findings` — detected content gaps per site, the actionable output of site scans (medium)
- [ ] `/orgs/{organizationId}/sites/{siteId}/insights/visitor-segments` — published-site visitor breakdown dimensions (medium)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gitbook/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gitbook/canonical_descriptions.py
index 7e3780d475a5..52e5c6298ae1 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gitbook/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gitbook/canonical_descriptions.py
@@ -143,4 +143,82 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"urls": "URLs associated with the comment.",
},
},
+ "pages": {
+ "description": "Pages in the current revision of every space the token can access, flattened from the space's page tree to one row per page.",
+ "docs_url": "https://gitbook.com/docs/developers/gitbook-api/api-reference/spaces/space-content",
+ "columns": {
+ "id": "Unique identifier for the page in the revision.",
+ "space_id": "ID of the space the page belongs to (added by PostHog during sync).",
+ "parent_page_id": "ID of the page or group this page is nested under, null for top-level pages (added by PostHog during sync).",
+ "type": "Type of page: document, group, link, or computed.",
+ "title": "Title of the page.",
+ "linkTitle": "Optional custom title for the page in the table of contents and mentions.",
+ "emoji": "Emoji of the page, if one has been set.",
+ "icon": "Icon of the page, if one has been set.",
+ "slug": "Page's slug in its direct parent.",
+ "path": "Complete path to access the page in the revision.",
+ "description": "Description of the page.",
+ "hidden": "Whether the page is hidden from the navigation while still being accessible.",
+ "noIndex": "Whether the page is excluded from the search and ask features.",
+ "noRobotsIndex": "Whether the page is excluded from indexing by search engine robots.",
+ "createdAt": "When the page was first created. Only present if the page has been edited at least once.",
+ "updatedAt": "When the page was last edited. Only present if the page has been edited at least once.",
+ "target": "For link pages, the content the link points to.",
+ "href": "For link pages, the resolved URL of the link target.",
+ "urls": "URLs associated with the page.",
+ },
+ },
+ "site_questions": {
+ "description": "Unique questions visitors asked the Ask AI assistant on each docs site, with usage stats.",
+ "docs_url": "https://gitbook.com/docs/developers/gitbook-api/api-reference/docs-sites/site-questions",
+ "columns": {
+ "id": "The ID of the site question.",
+ "object": 'Type of object, always equal to "site-question".',
+ "organization_id": "ID of the organization owning the site (added by PostHog during sync).",
+ "site_id": "ID of the site the question was asked on (added by PostHog during sync).",
+ "question": "Canonical text for the unique site question.",
+ "type": "Type classification of the question: exploring, how-to, troubleshooting, reference, or unknown.",
+ "createdAt": "Timestamp of when the canonical question was created.",
+ "askedAt": "Timestamp of when the question was last asked.",
+ "stats": "Aggregated stats for the question and its linked answers, such as answer count, answered rate, feedback, and weekly volume.",
+ "urls": "URLs associated with the site question.",
+ },
+ },
+ "site_answers": {
+ "description": "Individual answers the Ask AI assistant generated on each docs site, with the raw question, channel, and feedback.",
+ "docs_url": "https://gitbook.com/docs/developers/gitbook-api/api-reference/docs-sites/site-questions",
+ "columns": {
+ "id": "The ID of the site question answer.",
+ "object": 'Type of object, always equal to "site-question-answer".',
+ "organization_id": "ID of the organization owning the site (added by PostHog during sync).",
+ "site_id": "ID of the site the answer was generated on (added by PostHog during sync).",
+ "question": "The parent site question, with its ID and type.",
+ "topics": "The IDs of the associated site topics.",
+ "input": "The question as asked: normalized text and raw text.",
+ "thread": "The thread this answer belongs to and the previous answer in it.",
+ "session": "The visitor session the answer was generated in.",
+ "feedback": "Optional visitor feedback object whose rating is 1 or -1.",
+ "responseId": "The response identifier for this answer.",
+ "language": "ISO language code of the question.",
+ "answered": "Whether the response answered the question: yes, partially, or no.",
+ "helpfulness": "How helpful the answer was judged to be.",
+ "relevance": "How relevant the question was judged to be to the site.",
+ "channel": "The channel the answer was served through.",
+ "createdAt": "Timestamp of when the answer was created.",
+ "updatedAt": "Timestamp of when the answer was last updated.",
+ "urls": "URLs associated with the site question answer.",
+ },
+ },
+ "team_members": {
+ "description": "Membership of every team in every organization the token can access, with each member's role in the team.",
+ "docs_url": "https://gitbook.com/docs/developers/gitbook-api/api-reference/teams",
+ "columns": {
+ "organization_id": "ID of the organization the team belongs to (added by PostHog during sync).",
+ "team_id": "ID of the team (added by PostHog during sync).",
+ "user_id": "ID of the user who is a member of the team (added by PostHog during sync from organization.user.id).",
+ "organization": "The user's organization membership, including their user profile and organization role.",
+ "team": "The user's membership in the team, including their team role.",
+ "permissions": "The set of permissions the token has on the team member.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gitbook/gitbook.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gitbook/gitbook.py
index ec4398abaacd..a077d866e5d0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gitbook/gitbook.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gitbook/gitbook.py
@@ -1,6 +1,10 @@
import dataclasses
+from collections.abc import Callable
from typing import Any, Optional
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.datetime_utils import (
+ coerce_datetime_to_utc,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (
RESTAPIConfig,
@@ -15,12 +19,17 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
ClientConfig,
+ Endpoint,
EndpointResource,
+ IncrementalConfig,
)
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.gitbook.settings import GITBOOK_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.gitbook.settings import (
+ GITBOOK_ENDPOINTS,
+ GitBookEndpointConfig,
+)
GITBOOK_BASE_URL = "https://api.gitbook.com/v1"
# List endpoints accept a `limit` of up to 1000 per the OpenAPI spec; a moderate page keeps
@@ -31,9 +40,14 @@ PAGE_SIZE = 250
DEFAULT_PROBE_PATH = "/user"
# Every list response is `{"items": [...], "next": {"page": "..."}}`; `next` is omitted on the last
-# page. The parent list of a space-scoped endpoint is enumerated per organization (orgs -> spaces).
+# page. The parent list of a space-, site- or team-scoped endpoint is enumerated per organization
+# (orgs -> spaces/sites/teams).
_ORGS_PATH = "/orgs"
-_SPACES_PATH = "/orgs/{parent_id}/spaces"
+_INTERMEDIATE_PARENTS: dict[str, tuple[str, str]] = {
+ "space": ("spaces", "/orgs/{parent_id}/spaces"),
+ "site": ("sites", "/orgs/{parent_id}/sites"),
+ "team": ("teams", "/orgs/{parent_id}/teams"),
+}
@dataclasses.dataclass
@@ -86,33 +100,110 @@ def _list_resource(name: str, path: str) -> EndpointResource:
}
-def _child_resource(name: str, child_path: str, parent_name: str, inject_as: Optional[str]) -> EndpointResource:
- resource: EndpointResource = {
- "name": name,
- "endpoint": {
- "path": child_path,
- "params": {
- "limit": PAGE_SIZE,
- "parent_id": {"type": "resolve", "resource": parent_name, "field": "id"},
- },
- "data_selector": "items",
- "data_selector_required": True,
- },
+def _format_gitbook_datetime(value: Any) -> str:
+ normalized = coerce_datetime_to_utc(value)
+ if normalized is None:
+ return str(value)
+ return normalized.strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+def _flatten_pages(row: dict[str, Any]) -> list[dict[str, Any]]:
+ # One row per page of the revision tree. Nested pages drop their `pages` children and record
+ # their parent instead, and inherit the space id injected on the top-level row.
+ space_id = row.get("space_id")
+ rows: list[dict[str, Any]] = []
+ stack: list[tuple[dict[str, Any], Optional[str]]] = [(row, None)]
+ while stack:
+ page, parent_page_id = stack.pop()
+ children = page.get("pages") or []
+ rows.append(
+ {
+ **{k: v for k, v in page.items() if k != "pages"},
+ "space_id": space_id,
+ "parent_page_id": parent_page_id,
+ }
+ )
+ stack.extend((child, page.get("id")) for child in reversed(children))
+ return rows
+
+
+def _lift_team_member_user_id(row: dict[str, Any]) -> dict[str, Any]:
+ row["user_id"] = ((row.get("organization") or {}).get("user") or {}).get("id")
+ return row
+
+
+_ROW_MAPS: dict[str, Callable[[dict[str, Any]], dict[str, Any] | list[dict[str, Any]]]] = {
+ "pages": _flatten_pages,
+ "team_members": _lift_team_member_user_id,
+}
+
+
+def _child_resource(
+ name: str,
+ child_path: str,
+ parent_name: str,
+ inject: dict[str, str],
+ bind: Optional[dict[str, str]] = None,
+ paginated: bool = True,
+ data_selector: str = "items",
+ row_map: Optional[Callable[[dict[str, Any]], dict[str, Any] | list[dict[str, Any]]]] = None,
+ incremental: Optional[IncrementalConfig] = None,
+) -> EndpointResource:
+ # `bind` maps each path placeholder to the parent row field it is resolved from; `inject` maps
+ # parent row fields to the columns they are copied into on every child row.
+ params: dict[str, Any] = {"limit": PAGE_SIZE} if paginated else {}
+ for placeholder, parent_field in (bind or {"parent_id": "id"}).items():
+ params[placeholder] = {"type": "resolve", "resource": parent_name, "field": parent_field}
+ endpoint: Endpoint = {
+ "path": child_path,
+ "params": params,
+ "data_selector": data_selector,
+ "data_selector_required": True,
}
- if inject_as is not None:
- # Inject the parent's id into every row so rows from different parents stay distinguishable
- # (and usable in composite primary keys), matching the old `parent_id_key` behavior.
- resource["include_from_parent"] = ["id"]
- resource["data_map"] = rename_parent_fields(parent_name, {"id": inject_as})
+ if not paginated:
+ endpoint["paginator"] = "single_page"
+ if incremental is not None:
+ endpoint["incremental"] = incremental
+ resource: EndpointResource = {"name": name, "endpoint": endpoint}
+
+ maps: list[Callable[[dict[str, Any]], Any]] = []
+ if inject:
+ # Inject the parent's fields into every row so rows from different parents stay
+ # distinguishable (and usable in composite primary keys).
+ resource["include_from_parent"] = list(inject)
+ maps.append(rename_parent_fields(parent_name, inject))
+ if row_map is not None:
+ maps.append(row_map)
+ if len(maps) == 1:
+ resource["data_map"] = maps[0]
+ elif maps:
+ rename, reshape = maps
+ resource["data_map"] = lambda row: reshape(rename(row))
return resource
+def _incremental_config(
+ config: GitBookEndpointConfig, should_use_incremental_field: bool, incremental_field: Optional[str]
+) -> Optional[IncrementalConfig]:
+ if not should_use_incremental_field or not config.incremental_fields or config.incremental_param is None:
+ return None
+ return {
+ "cursor_path": incremental_field or config.incremental_fields[0]["field"],
+ "start_param": config.incremental_param,
+ "initial_value": "1970-01-01T00:00:00Z",
+ "convert": _format_gitbook_datetime,
+ }
+
+
def gitbook_source(
api_token: str,
endpoint: str,
team_id: int,
job_id: str,
resumable_source_manager: ResumableSourceManager[GitBookResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+ incremental_field: Optional[str] = None,
) -> SourceResponse:
config = GITBOOK_ENDPOINTS[endpoint]
client = _client_config(api_token)
@@ -141,7 +232,7 @@ def gitbook_source(
resume_hook=save_cursor,
initial_paginator_state=initial_state,
)
- return _source_response(endpoint, config.primary_keys, resource)
+ return _source_response(config, resource)
if config.parent == "organization":
# Single-hop fan-out (orgs -> child). One dependent resource, so the framework checkpoints
@@ -151,7 +242,12 @@ def gitbook_source(
"client": client,
"resources": [
_list_resource("orgs", _ORGS_PATH),
- _child_resource(endpoint, config.path, parent_name="orgs", inject_as=config.parent_id_key),
+ _child_resource(
+ endpoint,
+ config.path,
+ parent_name="orgs",
+ inject={"id": config.parent_id_key} if config.parent_id_key else {},
+ ),
],
}
@@ -174,32 +270,64 @@ def gitbook_source(
initial_paginator_state=fanout_initial,
)
resource = next(r for r in built if r.name == endpoint)
- return _source_response(endpoint, config.primary_keys, resource)
+ return _source_response(config, resource)
- # Space-scoped fan-out (comments): a two-level chain orgs -> spaces -> comments. With more than
- # one dependent resource the framework disables resume; a retry re-fetches and the merge dedupes
- # on the primary key.
+ # Space-, site- and team-scoped fan-out: a two-level chain orgs -> spaces/sites/teams -> child.
+ # With more than one dependent resource the framework disables resume; a retry re-fetches and
+ # the merge dedupes on the primary key.
+ parent_name, parent_path = _INTERMEDIATE_PARENTS[config.parent]
+ if config.parent == "space":
+ intermediate = _child_resource(parent_name, parent_path, parent_name="orgs", inject={})
+ bind = None
+ inject = {"id": config.parent_id_key} if config.parent_id_key else {}
+ else:
+ # Site and team paths are nested under the organization, so the intermediate rows carry
+ # the organization id for the child path to bind.
+ intermediate = _child_resource(parent_name, parent_path, parent_name="orgs", inject={"id": "organization_id"})
+ bind = {"organization_id": "organization_id", "parent_id": "id"}
+ inject = {"organization_id": "organization_id"}
+ if config.parent_id_key:
+ inject["id"] = config.parent_id_key
rest_config = {
"client": client,
"resources": [
_list_resource("orgs", _ORGS_PATH),
- _child_resource("spaces", _SPACES_PATH, parent_name="orgs", inject_as=None),
- _child_resource(endpoint, config.path, parent_name="spaces", inject_as=config.parent_id_key),
+ intermediate,
+ _child_resource(
+ endpoint,
+ config.path,
+ parent_name=parent_name,
+ inject=inject,
+ bind=bind,
+ paginated=config.paginated,
+ data_selector=config.data_selector,
+ row_map=_ROW_MAPS.get(endpoint),
+ incremental=_incremental_config(config, should_use_incremental_field, incremental_field),
+ ),
],
}
- built = rest_api_resources(rest_config, team_id, job_id, None)
+ built = rest_api_resources(
+ rest_config,
+ team_id,
+ job_id,
+ db_incremental_field_last_value if should_use_incremental_field else None,
+ )
resource = next(r for r in built if r.name == endpoint)
- return _source_response(endpoint, config.primary_keys, resource)
+ return _source_response(config, resource)
-def _source_response(endpoint: str, primary_keys: list[str], resource: Any) -> SourceResponse:
+def _source_response(config: GitBookEndpointConfig, resource: Any) -> SourceResponse:
+ # Most objects have no stable creation timestamp, so only endpoints with one partition by it.
return SourceResponse(
- name=endpoint,
+ name=config.name,
items=lambda: resource,
- primary_keys=primary_keys,
- # No stable creation timestamp exists on every object, so we don't partition by datetime.
+ primary_keys=config.primary_keys,
+ sort_mode=config.sort_mode,
partition_count=1,
partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="month" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gitbook/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gitbook/settings.py
index 8f1dec196212..bb62ea2c2063 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gitbook/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gitbook/settings.py
@@ -1,28 +1,41 @@
-from dataclasses import dataclass, field
+from dataclasses import field
from typing import Literal, Optional
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
from products.warehouse_sources.backend.types import IncrementalField
-@dataclass
+@frozen
class GitBookEndpointConfig:
name: str
# Path relative to the API base URL. Fan-out endpoints carry a single `{parent_id}`
# placeholder resolved per parent organization or space.
path: str
- # Fan-out parent resource. Organizations come straight from `/orgs`; spaces are
- # enumerated per organization via `/orgs/{id}/spaces`.
- parent: Optional[Literal["organization", "space"]] = None
+ # Fan-out parent resource. Organizations come straight from `/orgs`; spaces, sites and teams
+ # are enumerated per organization via `/orgs/{id}/<parent>`. Site- and team-scoped paths also
+ # carry an `{organization_id}` placeholder, bound from the parent row.
+ parent: Optional[Literal["organization", "space", "site", "team"]] = None
# When set, the parent's id is injected into every row under this column so rows from
- # different parents stay distinguishable (and usable in composite primary keys).
+ # different parents stay distinguishable (and usable in composite primary keys). Site- and
+ # team-scoped rows also get `organization_id`.
parent_id_key: Optional[str] = None
primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ # False for endpoints that return their whole collection in one response and take no `limit`.
+ paginated: bool = True
+ data_selector: str = "items"
+ partition_key: Optional[str] = None
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Query param that filters rows server-side to at or after the incremental watermark.
+ incremental_param: Optional[str] = None
+ sort_mode: Literal["asc", "desc"] = "asc"
# GitBook REST API v1 list endpoints (https://gitbook.com/docs/developers). All are full refresh
-# only: per the published OpenAPI spec, no list endpoint accepts an updated-after/since timestamp
-# filter, so there is no server-side cursor to advance an incremental sync (see the
-# implementing-warehouse-sources skill).
+# except `site_answers`: per the published OpenAPI spec, it is the only list endpoint whose
+# timestamp filter (`from`) restricts the rows returned. `site_questions` also takes `from`, but
+# there it only narrows the embedded stats, not which questions are listed.
#
# Primary keys: space and collection ids are globally addressable (`/spaces/{id}`,
# `/collections/{id}`), so `id` alone is safe there. Member ids are user ids (the same user can
@@ -70,8 +83,53 @@ GITBOOK_ENDPOINTS: dict[str, GitBookEndpointConfig] = {
parent_id_key="space_id",
primary_keys=["space_id", "id"],
),
+ # The page tree of each space's current revision, flattened to one row per page. The endpoint
+ # returns the whole tree in one `{"pages": [...]}` response with no pagination. Page ids are
+ # only documented as unique within a revision, so they pair with the space id.
+ "pages": GitBookEndpointConfig(
+ name="pages",
+ path="/spaces/{parent_id}/content/pages",
+ parent="space",
+ parent_id_key="space_id",
+ primary_keys=["space_id", "id"],
+ paginated=False,
+ data_selector="pages",
+ ),
+ "site_questions": GitBookEndpointConfig(
+ name="site_questions",
+ path="/orgs/{organization_id}/sites/{parent_id}/questions",
+ parent="site",
+ parent_id_key="site_id",
+ primary_keys=["organization_id", "site_id", "id"],
+ partition_key="createdAt",
+ ),
+ # The API does not document the order of answers, and rows arrive grouped per site, so
+ # `sort_mode="desc"` makes the pipeline persist the watermark only when a sync completes.
+ # `from` is inclusive, so the boundary row is re-pulled and the merge dedupes it.
+ "site_answers": GitBookEndpointConfig(
+ name="site_answers",
+ path="/orgs/{organization_id}/sites/{parent_id}/answers",
+ parent="site",
+ parent_id_key="site_id",
+ primary_keys=["organization_id", "site_id", "id"],
+ partition_key="createdAt",
+ incremental_fields=[incremental_field("createdAt")],
+ incremental_param="from",
+ sort_mode="desc",
+ ),
+ # Team membership rows nest the user under `organization.user`; its id is lifted to a top-level
+ # `user_id` column so it can key the table.
+ "team_members": GitBookEndpointConfig(
+ name="team_members",
+ path="/orgs/{organization_id}/teams/{parent_id}/members",
+ parent="team",
+ parent_id_key="team_id",
+ primary_keys=["organization_id", "team_id", "user_id"],
+ ),
}
ENDPOINTS = tuple(GITBOOK_ENDPOINTS.keys())
-INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in GITBOOK_ENDPOINTS.items() if config.incremental_fields
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gitbook/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gitbook/source.py
index 8069edafd225..d668ffec42f4 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gitbook/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gitbook/source.py
@@ -52,7 +52,7 @@ class GitBookSource(ResumableSource[GitBookSourceConfig, GitBookResumeConfig]):
releaseStatus=ReleaseStatus.ALPHA,
caption="""Enter your GitBook API token to pull your documentation workspace into the PostHog Data warehouse.
-You can create a personal access token under **Account settings → Developer** in [GitBook](https://app.gitbook.com/account/developer). The token inherits your account permissions and grants read access to your organizations, spaces, collections, sites, members, teams, change requests, and comments.
+You can create a personal access token under **Account settings → Developer** in [GitBook](https://app.gitbook.com/account/developer). The token inherits your account permissions and grants read access to your organizations, spaces, pages, collections, sites, site questions and answers, members, teams, team members, change requests, and comments.
""",
iconPath="/static/services/gitbook.png",
docsUrl="https://posthog.com/docs/cdp/sources/gitbook",
@@ -94,10 +94,8 @@ You can create a personal access token under **Account settings → Developer**
force_refresh: bool = False,
api_version: str | None = None,
) -> list[SourceSchema]:
- # Every endpoint is full refresh only — GitBook's list endpoints expose no server-side
- # updated-after/since filter, so there is no timestamp cursor to advance an incremental sync.
- # INCREMENTAL_FIELDS is empty, so build_endpoint_schemas yields supports_incremental=False,
- # supports_append=False, incremental_fields=[] for every endpoint.
+ # Only `site_answers` has a server-side timestamp filter, so it is the only endpoint in
+ # INCREMENTAL_FIELDS; every other endpoint is full refresh only.
return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)
def validate_credentials(
@@ -129,4 +127,7 @@ You can create a personal access token under **Account settings → Developer**
team_id=inputs.team_id,
job_id=inputs.job_id,
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,
+ incremental_field=inputs.incremental_field,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gitbook/tests/test_gitbook.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gitbook/tests/test_gitbook.py
index b3a336a0eb7e..97614c6efd75 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gitbook/tests/test_gitbook.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gitbook/tests/test_gitbook.py
@@ -1,5 +1,6 @@
import json
from collections.abc import Iterable
+from datetime import UTC, datetime
from types import SimpleNamespace
from typing import Any, Optional, cast
@@ -93,7 +94,7 @@ def _wire(session: MagicMock, pages: dict[PageKey, Response]) -> list[tuple[str,
def _drive(
- endpoint: str, pages: dict[PageKey, Response], manager: _FakeManager
+ endpoint: str, pages: dict[PageKey, Response], manager: _FakeManager, **kwargs: Any
) -> tuple[list[dict], list[tuple[str, dict[str, Any]]]]:
with mock.patch(CLIENT_SESSION_PATCH) as MockSession:
session = MockSession.return_value
@@ -104,6 +105,7 @@ def _drive(
team_id=1,
job_id="job-1",
resumable_source_manager=manager, # type: ignore[arg-type]
+ **kwargs,
)
rows = [row for page in cast("Iterable[Any]", response.items()) for row in page]
return rows, snapshots
@@ -197,6 +199,111 @@ class TestFanOut:
rows, _ = _drive("comments", pages, _FakeManager())
assert rows == [{"id": "c1", "space_id": "sp1"}, {"id": "c2", "space_id": "sp2"}]
+ def test_pages_tree_is_flattened_with_parent_links(self) -> None:
+ tree = {
+ "pages": [
+ {
+ "id": "p1",
+ "type": "document",
+ "pages": [{"id": "p1a", "type": "document", "pages": [{"id": "p1a1", "type": "link"}]}],
+ },
+ {"id": "g1", "type": "group", "pages": [{"id": "p2", "type": "document", "pages": []}]},
+ ]
+ }
+ pages: dict[PageKey, Response] = {
+ (self.ORGS, None): _response([{"id": "org1"}]),
+ (_u("/orgs/org1/spaces"), None): _response([{"id": "sp1"}]),
+ (_u("/spaces/sp1/content/pages"), None): _response(None, raw_body=tree),
+ }
+ rows, snapshots = _drive("pages", pages, _FakeManager())
+ assert rows == [
+ {"id": "p1", "type": "document", "space_id": "sp1", "parent_page_id": None},
+ {"id": "p1a", "type": "document", "space_id": "sp1", "parent_page_id": "p1"},
+ {"id": "p1a1", "type": "link", "space_id": "sp1", "parent_page_id": "p1a"},
+ {"id": "g1", "type": "group", "space_id": "sp1", "parent_page_id": None},
+ {"id": "p2", "type": "document", "space_id": "sp1", "parent_page_id": "g1"},
+ ]
+ # The pages endpoint is not paginated, so it gets no `limit`.
+ assert snapshots[-1] == (_u("/spaces/sp1/content/pages"), {})
+
+ @parameterized.expand(
+ [
+ (
+ "site_questions",
+ "sites",
+ "/orgs/{org}/sites/{parent}/questions",
+ "site_id",
+ {"id": "q1"},
+ {"id": "q1"},
+ ),
+ (
+ "team_members",
+ "teams",
+ "/orgs/{org}/teams/{parent}/members",
+ "team_id",
+ {"organization": {"id": "membership1", "user": {"id": "user1"}}, "team": {"role": "member"}},
+ {
+ "organization": {"id": "membership1", "user": {"id": "user1"}},
+ "team": {"role": "member"},
+ "user_id": "user1",
+ },
+ ),
+ ]
+ )
+ def test_org_nested_fanout_binds_and_injects_both_parent_ids(
+ self,
+ endpoint: str,
+ parent_segment: str,
+ child_path: str,
+ parent_key: str,
+ api_row: dict[str, Any],
+ expected_row: dict[str, Any],
+ ) -> None:
+ pages: dict[PageKey, Response] = {
+ (self.ORGS, None): _response([{"id": "org1"}, {"id": "org2"}]),
+ (_u(f"/orgs/org1/{parent_segment}"), None): _response([{"id": "x1"}]),
+ (_u(f"/orgs/org2/{parent_segment}"), None): _response([{"id": "x1"}]),
+ (_u(child_path.format(org="org1", parent="x1")), None): _response([dict(api_row)]),
+ (_u(child_path.format(org="org2", parent="x1")), None): _response([dict(api_row)]),
+ }
+ rows, _ = _drive(endpoint, pages, _FakeManager())
+ # The same child id under two organizations stays distinguishable via organization_id.
+ assert rows == [
+ {**expected_row, "organization_id": "org1", parent_key: "x1"},
+ {**expected_row, "organization_id": "org2", parent_key: "x1"},
+ ]
+
+ @parameterized.expand(
+ [
+ ("incremental", True, datetime(2026, 5, 1, 12, 30, 15, 250000, tzinfo=UTC), "2026-05-01T12:30:15Z"),
+ ("incremental_first_sync", True, None, "1970-01-01T00:00:00Z"),
+ ("full_refresh", False, datetime(2026, 5, 1, tzinfo=UTC), None),
+ ]
+ )
+ def test_site_answers_filter_on_watermark_only_when_incremental(
+ self, _name: str, incremental: bool, last_value: Optional[datetime], expected_from: Optional[str]
+ ) -> None:
+ answers = _u("/orgs/org1/sites/s1/answers")
+ pages: dict[PageKey, Response] = {
+ (self.ORGS, None): _response([{"id": "org1"}]),
+ (_u("/orgs/org1/sites"), None): _response([{"id": "s1"}]),
+ (answers, None): _response([{"id": "a1"}], next_page="tok2"),
+ (answers, "tok2"): _response([{"id": "a2"}]),
+ }
+ rows, snapshots = _drive(
+ "site_answers",
+ pages,
+ _FakeManager(),
+ should_use_incremental_field=incremental,
+ db_incremental_field_last_value=last_value,
+ incremental_field="createdAt" if incremental else None,
+ )
+ assert [row["id"] for row in rows] == ["a1", "a2"]
+ answer_params = [params for url, params in snapshots if url == answers]
+ assert len(answer_params) == 2
+ # The watermark filter stays on every page, not just the first.
+ assert all(params.get("from") == expected_from for params in answer_params)
+
def test_saves_completed_parents_and_mid_parent_page_token(self) -> None:
manager = _FakeManager()
pages = {
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gitbook/tests/test_gitbook_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gitbook/tests/test_gitbook_source.py
index d3da9b3801d7..e46aaafcdace 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gitbook/tests/test_gitbook_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gitbook/tests/test_gitbook_source.py
@@ -52,7 +52,10 @@ class TestGitBookSource:
@mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.gitbook.source.gitbook_source")
def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:
inputs = mock.MagicMock()
- inputs.schema_name = "spaces"
+ inputs.schema_name = "site_answers"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2026-05-01T00:00:00Z"
+ inputs.incremental_field = "createdAt"
manager = mock.MagicMock()
self.source.source_for_pipeline(self.config, manager, inputs)
@@ -60,8 +63,11 @@ class TestGitBookSource:
mock_source.assert_called_once()
kwargs = mock_source.call_args.kwargs
assert kwargs["api_token"] == "gb-token"
- assert kwargs["endpoint"] == "spaces"
+ assert kwargs["endpoint"] == "site_answers"
assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == "2026-05-01T00:00:00Z"
+ assert kwargs["incremental_field"] == "createdAt"
def test_source_for_pipeline_rejects_unknown_schema(self) -> None:
inputs = mock.MagicMock()