: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(bettermode): sync space members, post types, collections and roles (#99807)
Tom Owers02218773b653
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.mdindex 36f0e6cedb73..6fca3d9aa01a 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@@ -757,14 +757,14 @@ Diffed against: <https://developers.beehiiv.com/api-reference>## Bettermode — **thin**-Today (6): `members`, `moderation_items`, `posts`, `replies`, `spaces`, `tags`+Today (11): `collections`, `members`, `moderation_items`, `post_types`, `posts`, `replies`, `roles`, `space_members`, `space_post_types`, `spaces`, `tags`Diffed against: <https://api.bettermode.com/ (live GraphQL introspection of queryType fields; 159 root queries)>-- [ ] `spaceMembers` — join table linking members to spaces; without it space membership is unqueryable (high)-- [ ] `postTypes / spacePostTypes` — lookup resolving the postTypeId carried on every post we already sync (high)-- [ ] `collections` — lookup that groups the spaces we already sync (high)-- [ ] `roles` — lookup resolving roleId on members and space members (high)+- [x] `spaceMembers` — join table linking members to spaces; without it space membership is unqueryable (high), added here+- [x] `postTypes / spacePostTypes` — lookup resolving the postTypeId carried on every post we already sync (high), both added here+- [x] `collections` — lookup that groups the spaces we already sync (high), added here+- [x] `roles` — lookup resolving roleId on members and space members (high), added here- [ ] `events` — community events are a first-class content object alongside posts (high)- [ ] `eventRegistrations / memberEventRegistrations` — attendance and RSVP records, the core event engagement metric (high)- [ ] `activityLogs` — network-wide activity event stream for behavioral analysis (high)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bettermode/bettermode.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bettermode/bettermode.pyindex ae771f11d0be..f7a6871a36cc 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bettermode/bettermode.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bettermode/bettermode.py@@ -1,6 +1,6 @@import jsonimport dataclasses-from collections.abc import Iterator+from collections.abc import Callable, Iteratorfrom datetime import UTC, date, datetimefrom typing import Any, Optional@@ -23,8 +23,8 @@ BETTERMODE_HOSTS = {}REQUEST_TIMEOUT_SECONDS = 60MAX_RETRY_ATTEMPTS = 5-# Page size when enumerating parent post ids for the replies fan-out — id-only nodes are-# cheap in Bettermode's query-cost model, so the maximum-ish page keeps request count low.+# Page size when enumerating parent ids for a fan-out — id-only nodes are cheap in+# Bettermode's query-cost model, so the maximum-ish page keeps request count low.PARENT_PAGE_SIZE = 100_TOKEN_QUERY = """@@ -50,6 +50,20 @@ query ParentPosts($limit: Int!, $after: String) {}"""+_PARENT_SPACES_QUERY = """+query ParentSpaces($limit: Int!, $after: String) {+ spaces(limit: $limit, after: $after) {+ pageInfo {+ endCursor+ hasNextPage+ }+ nodes {+ id+ }+ }+}+"""+class BettermodeRetryableError(Exception):pass@@ -61,7 +75,7 @@ class BettermodeGraphQLError(Exception):prefix that `get_non_retryable_errors` matches on."""[email protected](frozen=True)class BettermodeResumeConfig:# Relay cursor of the last fully-yielded page within the current connection.after: str | None = None@@ -69,6 +83,8 @@ class BettermodeResumeConfig:# bookmark (not a positional index) so posts created/deleted between a crash and the# retry can't resume us into the wrong parent. None for top-level endpoints.post_id: str | None = None+ # Same bookmark for space-scoped fan-outs (`space_members`, `space_post_types`).+ space_id: str | None = Nonedef _base_url(region: str) -> str:@@ -176,6 +192,56 @@ query ({declarations}) {{"""+def _build_list_query(config: BettermodeEndpointConfig) -> str:+ """Query document for a root field that returns a plain list (`collections`, `roles`).++ These fields take no `limit`/`after`, so the whole list arrives in one response.+ """+ return f"""+query {{+ {config.query_field} {{+{config.node_fields}+ }}+}}+"""+++def _space_member_row(node: dict[str, Any], space_id: str) -> dict[str, Any] | None:+ """Flatten a SpaceMember into join columns.++ SpaceMember exposes no scalars of its own, so a usable primary key has to come from the+ nested member plus the space the fan-out is currently walking. A membership whose member+ is no longer readable is dropped: half its primary key would be null, and every such row+ in a space would merge onto the same one.+ """+ member = node.get("member") or {}+ member_id = member.get("id")+ if not member_id:+ return None++ role = node.get("role") or {}+ return {+ "spaceId": space_id,+ "memberId": member_id,+ "roleId": role.get("id"),+ "roleName": role.get("name"),+ "roleType": role.get("type"),+ }+++_RowMapper = Callable[[dict[str, Any], str], dict[str, Any] | None]++_ROW_MAPPERS: dict[str, _RowMapper] = {+ "spaceMembers": _space_member_row,+}+++def _map_rows(nodes: list[dict[str, Any]], parent_id: str, row_mapper: _RowMapper | None) -> list[dict[str, Any]]:+ if row_mapper is None:+ return nodes+ return [row for row in (row_mapper(node, parent_id) for node in nodes) if row is not None]++def _build_post_variables(should_use_incremental_field: bool,db_incremental_field_last_value: Any,@@ -244,48 +310,90 @@ def _iter_connection(after = next_cursor-def _get_reply_rows(+def _fan_out_rows(execute: Any,config: BettermodeEndpointConfig,+ parent_ids: list[str],+ parent_arg: str,+ resume_field: str,resumable_source_manager: ResumableSourceManager[BettermodeResumeConfig],logger: FilteringBoundLogger,) -> Iterator[list[dict[str, Any]]]:- """Fan out one `replies(postId: ...)` connection per post that has replies.+ """Walk one connection per parent id, checkpointing against a parent-ID bookmark.- Bettermode has no flat network-wide replies listing, so parents are enumerated with a- cheap id-only posts walk first. Only direct replies of listed posts are fetched.+ The bookmark is a stable parent ID (not a positional index) so parents created or deleted+ between a crash and the retry can't resume us into the wrong parent. If the bookmarked+ parent no longer exists, start over — merge dedupes re-pulled rows on the primary key.+ `resume_after` is consumed by the bookmarked parent only."""- parent_ids: list[str] = []- for nodes, _ in _iter_connection(execute, _PARENT_POSTS_QUERY, "posts", {}, PARENT_PAGE_SIZE, None):- parent_ids.extend(node["id"] for node in nodes if (node.get("totalRepliesCount") or 0) > 0)-- # Resolve the saved post-ID bookmark to the slice of parents still to process. If the- # bookmarked post no longer exists, start over — merge dedupes re-pulled rows on the- # primary key. `resume_after` is consumed by the bookmarked parent only.resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ bookmark = getattr(resume, resume_field) if resume is not None else Noneremaining = parent_idsresume_after: str | None = None- if resume is not None and resume.post_id is not None and resume.post_id in parent_ids:- remaining = parent_ids[parent_ids.index(resume.post_id) :]+ if resume is not None and bookmark is not None and bookmark in parent_ids:+ remaining = parent_ids[parent_ids.index(bookmark) :]resume_after = resume.after- logger.debug(f"Bettermode: resuming replies from post_id={resume.post_id}")+ logger.debug(f"Bettermode: resuming {config.query_field} from {resume_field}={bookmark}")+ row_mapper = _ROW_MAPPERS.get(config.query_field)query = _build_query(config)- for index, post_id in enumerate(remaining):- variables = {"postId": post_id, "orderBy": "createdAt", "reverse": False}+ for index, parent_id in enumerate(remaining):+ variables = {parent_arg: parent_id, **config.base_variables}for nodes, next_cursor in _iter_connection(- execute, query, "replies", variables, config.page_size, resume_after+ execute, query, config.query_field, variables, config.page_size, resume_after):- yield nodes+ rows = _map_rows(nodes, parent_id, row_mapper)+ if rows:+ yield rows# Save AFTER yielding (and only when more pages remain) so a crash re-yields the# last page rather than skipping it — merge dedupes on the primary key.if next_cursor:- resumable_source_manager.save_state(BettermodeResumeConfig(after=next_cursor, post_id=post_id))+ resumable_source_manager.save_state(+ BettermodeResumeConfig(after=next_cursor, **{resume_field: parent_id})+ )resume_after = None- # Advance the bookmark so a crash between parents resumes at the next post.+ # Advance the bookmark so a crash between parents resumes at the next one.if index + 1 < len(remaining):- resumable_source_manager.save_state(BettermodeResumeConfig(after=None, post_id=remaining[index + 1]))+ resumable_source_manager.save_state(+ BettermodeResumeConfig(after=None, **{resume_field: remaining[index + 1]})+ )+++def _get_reply_rows(+ execute: Any,+ config: BettermodeEndpointConfig,+ resumable_source_manager: ResumableSourceManager[BettermodeResumeConfig],+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ """Fan out one `replies(postId: ...)` connection per post that has replies.++ Bettermode has no flat network-wide replies listing, so parents are enumerated with a+ cheap id-only posts walk first. Only direct replies of listed posts are fetched.+ """+ parent_ids: list[str] = []+ for nodes, _ in _iter_connection(execute, _PARENT_POSTS_QUERY, "posts", {}, PARENT_PAGE_SIZE, None):+ parent_ids.extend(node["id"] for node in nodes if (node.get("totalRepliesCount") or 0) > 0)++ yield from _fan_out_rows(execute, config, parent_ids, "postId", "post_id", resumable_source_manager, logger)+++def _get_space_scoped_rows(+ execute: Any,+ config: BettermodeEndpointConfig,+ resumable_source_manager: ResumableSourceManager[BettermodeResumeConfig],+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ """Fan out one connection per space.++ `spaceMembers` and `spacePostTypes` are only reachable per space, so spaces are+ enumerated with a cheap id-only walk first.+ """+ parent_ids: list[str] = []+ for nodes, _ in _iter_connection(execute, _PARENT_SPACES_QUERY, "spaces", {}, PARENT_PAGE_SIZE, None):+ parent_ids.extend(node["id"] for node in nodes)++ yield from _fan_out_rows(execute, config, parent_ids, "spaceId", "space_id", resumable_source_manager, logger)def get_rows(@@ -304,11 +412,22 @@ def get_rows(session = _get_authed_session(region, client_id, client_secret, network_id)execute = _make_execute(session, _base_url(region), logger)+ if config.is_list:+ data = execute(_build_list_query(config), {})+ rows = data.get(config.query_field) or []+ if rows:+ yield rows+ return+if config.fan_out_replies:yield from _get_reply_rows(execute, config, resumable_source_manager, logger)return- base_variables: dict[str, Any] = {}+ if config.fan_out_spaces:+ yield from _get_space_scoped_rows(execute, config, resumable_source_manager, logger)+ return++ base_variables: dict[str, Any] = dict(config.base_variables)if config.query_field == "posts":base_variables = _build_post_variables(should_use_incremental_field, db_incremental_field_last_value, incremental_fielddiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bettermode/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bettermode/canonical_descriptions.pyindex 2cf64e094b36..79ddd3995888 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bettermode/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bettermode/canonical_descriptions.py@@ -109,6 +109,80 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"description": "Description of the tag.",},},+ "space_members": {+ "description": "Join table linking members to the spaces they belong to, with their role in that space.",+ "docs_url": "https://developers.bettermode.com/docs/graphql/objects/space-member/",+ "columns": {+ "spaceId": "ID of the space the membership belongs to.",+ "memberId": "ID of the member who belongs to the space.",+ "roleId": "ID of the member's role within the space.",+ "roleName": "Name of the member's role within the space.",+ "roleType": "Space role type: admin or member.",+ },+ },+ "space_post_types": {+ "description": "Join table of the post types enabled in each space, with the roles allowed to use them.",+ "docs_url": "https://developers.bettermode.com/docs/graphql/objects/space-post-type/",+ "columns": {+ "spaceId": "ID of the space the post type is enabled in.",+ "postTypeId": "ID of the enabled post type.",+ "whoCanPost": "IDs of the space roles allowed to create posts of this type.",+ "whoCanReact": "IDs of the space roles allowed to react to posts of this type.",+ "whoCanReply": "IDs of the space roles allowed to reply to posts of this type.",+ },+ },+ "post_types": {+ "description": "Post types available in the community, resolving the postTypeId carried on every post.",+ "docs_url": "https://developers.bettermode.com/docs/graphql/objects/post-type/",+ "columns": {+ "id": "Unique identifier of the post type.",+ "name": "Singular name of the post type (e.g. Discussion, Question, Article).",+ "pluralName": "Plural name of the post type.",+ "slug": "URL slug of the post type.",+ "description": "Description of the post type.",+ "context": "Where the type applies: post or reply.",+ "layout": "Layout used to render posts of this type.",+ "archived": "Whether the post type is archived and no longer offered.",+ "iconId": "ID of the icon shown for the post type.",+ "titleTemplate": "Template used to render the post title.",+ "shortContentTemplate": "Template used to render the truncated post content.",+ "languageTemplate": "Template used to localize the post type.",+ "allowedReactions": "Reactions members can leave on posts of this type.",+ "forbiddenReactions": "Reactions blocked on posts of this type.",+ "singleChoiceReactions": "Reactions of which a member may leave only one.",+ "excludedNativeShortcuts": "Native shortcuts hidden for this post type.",+ "createdAt": "Timestamp when the post type was created.",+ "updatedAt": "Timestamp when the post type was last updated.",+ },+ },+ "collections": {+ "description": "Collections (groups) that organize spaces in the community's navigation.",+ "docs_url": "https://developers.bettermode.com/docs/graphql/objects/collection/",+ "columns": {+ "id": "Unique identifier of the collection.",+ "name": "Name of the collection.",+ "slug": "URL slug of the collection.",+ "description": "Description of the collection.",+ "customOrderingIndex": "Position of the collection in the custom navigation order.",+ "externalId": "External identifier assigned by an integration, if any.",+ "createdAt": "Timestamp when the collection was created.",+ "updatedAt": "Timestamp when the collection was last updated.",+ "relativeUrl": "Path of the collection relative to the community domain.",+ "url": "Full URL of the collection.",+ },+ },+ "roles": {+ "description": "Network roles, resolving the roleId carried on members.",+ "docs_url": "https://developers.bettermode.com/docs/graphql/objects/role/",+ "columns": {+ "id": "Unique identifier of the role.",+ "name": "Name of the role.",+ "description": "Description of the role.",+ "type": "Role type: admin, moderator, member, or guest.",+ "scopes": "Permission scopes granted by the role.",+ "visible": "Whether the role is shown in the community.",+ },+ },"moderation_items": {"description": "Items (posts or members) flagged for moderation review, with their resolution status.","docs_url": "https://developers.bettermode.com/docs/graphql/objects/moderation-item/",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bettermode/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bettermode/settings.pyindex 3df37881f38b..4e07ab81b868 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bettermode/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bettermode/settings.py@@ -119,6 +119,68 @@ slugdescription"""+_SPACE_MEMBER_NODE_FIELDS = """+member {+id+}+role {+id+name+type+}+"""++_SPACE_POST_TYPE_NODE_FIELDS = """+spaceId+postTypeId+whoCanPost+whoCanReact+whoCanReply+"""++_POST_TYPE_NODE_FIELDS = """+id+name+pluralName+slug+description+context+layout+archived+iconId+titleTemplate+shortContentTemplate+languageTemplate+allowedReactions+forbiddenReactions+singleChoiceReactions+excludedNativeShortcuts+createdAt+updatedAt+"""++_COLLECTION_NODE_FIELDS = """+id+name+slug+description+customOrderingIndex+externalId+createdAt+updatedAt+relativeUrl+url+"""++_ROLE_NODE_FIELDS = """+id+name+description+type+scopes+visible+"""+_MODERATION_NODE_FIELDS = """idstatus@@ -140,7 +202,7 @@ updatedAt"""-@dataclass+@dataclass(frozen=True)class BettermodeEndpointConfig:# Root query field on the GraphQL schema (e.g. `posts`, `moderationItems`).query_field: str@@ -148,6 +210,9 @@ class BettermodeEndpointConfig:# Extra GraphQL variables beyond `limit`/`after`: name -> GraphQL type. Declared in the# query document and passed through when present in the request variables.extra_args: dict[str, str] = field(default_factory=dict)+ # Static values for the extra args — per-endpoint because the sort enums differ+ # (`PostListOrderByEnum` is camelCase, `SpaceMemberListOrderByEnum` is SCREAMING_CASE).+ base_variables: dict[str, object] = field(default_factory=dict)page_size: int = 50primary_keys: list[str] = field(default_factory=lambda: ["id"])incremental_fields: list[IncrementalField] = field(default_factory=list)@@ -155,6 +220,10 @@ class BettermodeEndpointConfig:partition_key: str | None = "createdAt"# Fan out one `replies(postId: ...)` connection per post that has replies.fan_out_replies: bool = False+ # Fan out one connection per space, for root fields that require `spaceId: ID!`.+ fan_out_spaces: bool = False+ # Root field returns a plain list instead of a Relay connection — no limit/after args.+ is_list: bool = FalseBETTERMODE_ENDPOINTS: dict[str, BettermodeEndpointConfig] = {@@ -187,6 +256,7 @@ BETTERMODE_ENDPOINTS: dict[str, BettermodeEndpointConfig] = {"orderBy": "PostListOrderByEnum","reverse": "Boolean",},+ base_variables={"orderBy": "createdAt", "reverse": False},page_size=30,fan_out_replies=True,),@@ -200,6 +270,43 @@ BETTERMODE_ENDPOINTS: dict[str, BettermodeEndpointConfig] = {query_field="moderationItems",node_fields=_MODERATION_NODE_FIELDS,),+ "space_members": BettermodeEndpointConfig(+ query_field="spaceMembers",+ node_fields=_SPACE_MEMBER_NODE_FIELDS,+ extra_args={"spaceId": "ID!", "orderBy": "SpaceMemberListOrderByEnum", "reverse": "Boolean"},+ base_variables={"orderBy": "CREATED_AT", "reverse": False},+ page_size=100,+ # A membership row is unique per space and member; `spaceId` is injected from the+ # parent space because SpaceMember itself exposes no scalar fields.+ primary_keys=["spaceId", "memberId"],+ partition_key=None,+ fan_out_spaces=True,+ ),+ "space_post_types": BettermodeEndpointConfig(+ query_field="spacePostTypes",+ node_fields=_SPACE_POST_TYPE_NODE_FIELDS,+ extra_args={"spaceId": "ID!"},+ page_size=100,+ primary_keys=["spaceId", "postTypeId"],+ partition_key=None,+ fan_out_spaces=True,+ ),+ "post_types": BettermodeEndpointConfig(+ query_field="postTypes",+ node_fields=_POST_TYPE_NODE_FIELDS,+ page_size=100,+ ),+ "collections": BettermodeEndpointConfig(+ query_field="collections",+ node_fields=_COLLECTION_NODE_FIELDS,+ is_list=True,+ ),+ "roles": BettermodeEndpointConfig(+ query_field="roles",+ node_fields=_ROLE_NODE_FIELDS,+ partition_key=None,+ is_list=True,+ ),}ENDPOINTS = tuple(BETTERMODE_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bettermode/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bettermode/source.pyindex 33a16973d25b..0b5f0ef06d87 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bettermode/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bettermode/source.py@@ -26,13 +26,32 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.can)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistryfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager-from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (+ SourceSchema,+ build_endpoint_schemas,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.bettermode import (BettermodeSourceConfig,)from products.warehouse_sources.backend.types import ExternalDataSourceType+# Fan-out endpoints cost one request per parent, so the schema picker says what a sync scales with.+_SCHEMA_DESCRIPTIONS: dict[str, str] = {+ "replies": (+ "Fetches direct replies of every post that has replies (one request per post), "+ "so syncs scale with the number of posts in the community"+ ),+ "space_members": (+ "Fetches the members of every space (one request per space), so syncs scale with the "+ "number of spaces in the community"+ ),+ "space_post_types": (+ "Fetches the post types enabled in every space (one request per space), so syncs scale "+ "with the number of spaces in the community"+ ),+}+@SourceRegistry.registerclass BettermodeSource(ResumableSource[BettermodeSourceConfig, BettermodeResumeConfig]):@@ -56,7 +75,7 @@ class BettermodeSource(ResumableSource[BettermodeSourceConfig, BettermodeResumeCcategory=DataWarehouseSourceCategory.CUSTOMER_SUPPORT,label="Bettermode",keywords=["tribe", "community"],- caption="""Connect your Bettermode (formerly Tribe) community to pull members, spaces, posts, replies, tags, and moderation items into the PostHog Data warehouse.+ caption="""Connect your Bettermode (formerly Tribe) community to pull members, spaces, space members, posts, replies, post types, tags, collections, roles, and moderation items into the PostHog Data warehouse.Create an app in the [Bettermode developer portal](https://developers.bettermode.com/), then copy its client ID and client secret. The app must be **published and installed on your community** before tokens can be issued.@@ -132,30 +151,7 @@ If your community is hosted in the EU (eu-central-1), select the EU region so reforce_refresh: bool = False,api_version: str | None = None,) -> list[SourceSchema]:- def _description(endpoint: str) -> str | None:- if endpoint == "replies":- return (- "Fetches direct replies of every post that has replies (one request per post), "- "so syncs scale with the number of posts in the community"- )- return None-- schemas = [- SourceSchema(- name=endpoint,- supports_incremental=INCREMENTAL_FIELDS.get(endpoint) is not None,- supports_append=INCREMENTAL_FIELDS.get(endpoint) is not None,- incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),- description=_description(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+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names, descriptions=_SCHEMA_DESCRIPTIONS)def validate_credentials(self,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bettermode/tests/test_bettermode.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bettermode/tests/test_bettermode.pyindex 15d0d711d042..1a4d13d60e15 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bettermode/tests/test_bettermode.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bettermode/tests/test_bettermode.py@@ -295,7 +295,7 @@ class TestBettermodeSourceResponse:class TestQueryDocuments:- @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ @pytest.mark.parametrize("endpoint", [name for name in ENDPOINTS if not BETTERMODE_ENDPOINTS[name].is_list])def test_query_declares_every_variable_it_passes(self, endpoint):config = BETTERMODE_ENDPOINTS[endpoint]query = _build_query(config)@@ -304,3 +304,109 @@ class TestQueryDocuments:for arg_name, gql_type in {"limit": "Int!", "after": "String", **config.extra_args}.items():assert f"${arg_name}: {gql_type}" in queryassert f"{arg_name}: ${arg_name}" in query++ @pytest.mark.parametrize("endpoint", [name for name in ENDPOINTS if not BETTERMODE_ENDPOINTS[name].is_list])+ def test_query_passes_every_static_variable_it_declares(self, endpoint):+ config = BETTERMODE_ENDPOINTS[endpoint]+ assert set(config.base_variables) <= set(config.extra_args)+++class TestListEndpoints:+ @pytest.mark.parametrize("endpoint", ["collections", "roles"])+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_single_request_yields_the_whole_list(self, mock_make_session, endpoint):+ query_field = BETTERMODE_ENDPOINTS[endpoint].query_field+ _, data_session = _mock_sessions(+ mock_make_session, [_response({"data": {query_field: [{"id": "a"}, {"id": "b"}]}})]+ )++ manager = _make_manager()+ batches = list(get_rows("us", "client", "secret", "net", endpoint, mock.MagicMock(), manager))++ assert [row["id"] for batch in batches for row in batch] == ["a", "b"]+ assert data_session.post.call_count == 1+ # `collections` and `roles` reject limit/after — they return the whole list.+ assert data_session.post.call_args.kwargs["json"]["variables"] == {}+ assert "$limit" not in data_session.post.call_args.kwargs["json"]["query"]+ manager.save_state.assert_not_called()++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_empty_list_yields_no_batches(self, mock_make_session):+ _mock_sessions(mock_make_session, [_response({"data": {"roles": []}})])++ assert list(get_rows("us", "client", "secret", "net", "roles", mock.MagicMock(), _make_manager())) == []+++class TestSpaceFanOut:+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_space_members_flattened_and_checkpointed_per_space(self, mock_make_session):+ _, data_session = _mock_sessions(+ mock_make_session,+ [+ _page("spaces", [{"id": "s1"}, {"id": "s2"}]),+ _page(+ "spaceMembers",+ [{"member": {"id": "m1"}, "role": {"id": "r1", "name": "Admin", "type": "admin"}}],+ end_cursor="cur-1",+ ),+ _page(+ "spaceMembers", [{"member": {"id": "m2"}, "role": {"id": "r2", "name": "Member", "type": "member"}}]+ ),+ # A membership whose member is no longer readable carries no usable key.+ _page("spaceMembers", [{"member": None, "role": None}, {"member": {"id": "m3"}, "role": {}}]),+ ],+ )++ manager = _make_manager()+ batches = list(get_rows("us", "client", "secret", "net", "space_members", mock.MagicMock(), manager))++ assert [row for batch in batches for row in batch] == [+ {"spaceId": "s1", "memberId": "m1", "roleId": "r1", "roleName": "Admin", "roleType": "admin"},+ {"spaceId": "s1", "memberId": "m2", "roleId": "r2", "roleName": "Member", "roleType": "member"},+ {"spaceId": "s2", "memberId": "m3", "roleId": None, "roleName": None, "roleType": None},+ ]+ member_calls = data_session.post.call_args_list[1:]+ assert [call.kwargs["json"]["variables"]["spaceId"] for call in member_calls] == ["s1", "s1", "s2"]+ assert member_calls[0].kwargs["json"]["variables"]["orderBy"] == "CREATED_AT"+ # Mid-space page checkpoint, then a bookmark advancing to the next space.+ saved = [call.args[0] for call in manager.save_state.call_args_list]+ assert [(state.after, state.space_id, state.post_id) for state in saved] == [+ ("cur-1", "s1", None),+ (None, "s2", None),+ ]++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_space_post_types_rows_pass_through_unmapped(self, mock_make_session):+ _, data_session = _mock_sessions(+ mock_make_session,+ [+ _page("spaces", [{"id": "s1"}]),+ _page("spacePostTypes", [{"spaceId": "s1", "postTypeId": "pt1", "whoCanPost": ["r1"]}]),+ ],+ )++ batches = list(get_rows("us", "client", "secret", "net", "space_post_types", mock.MagicMock(), _make_manager()))++ assert [row for batch in batches for row in batch] == [+ {"spaceId": "s1", "postTypeId": "pt1", "whoCanPost": ["r1"]}+ ]+ assert data_session.post.call_args.kwargs["json"]["variables"]["spaceId"] == "s1"++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_resumes_from_bookmarked_space(self, mock_make_session):+ _, data_session = _mock_sessions(+ mock_make_session,+ [+ _page("spaces", [{"id": "s1"}, {"id": "s2"}]),+ _page("spaceMembers", [{"member": {"id": "m9"}, "role": {"id": "r1"}}]),+ ],+ )++ manager = _make_manager(BettermodeResumeConfig(after="cur-mid", space_id="s2"))+ list(get_rows("us", "client", "secret", "net", "space_members", mock.MagicMock(), manager))++ member_calls = data_session.post.call_args_list[1:]+ assert len(member_calls) == 1+ variables = member_calls[0].kwargs["json"]["variables"]+ assert variables["spaceId"] == "s2"+ assert variables["after"] == "cur-mid"