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 Bettermode post reaction participants table (#101121)

Tom Owers521fdaa42840
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 1fd887948a42..f159dc83374a 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
@@ -774,10 +774,10 @@ Diffed against: <https://api.bettermode.com/ (live GraphQL introspection of quer
- [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)
-- [ ] `postReactionParticipants` — per-reaction engagement records tied to posts we sync (medium)
+- [ ] `events` — skipped: no `events` root query in the current API. Community events are Post rows of an Event post type, already covered by the `posts` table; `EventType` in the schema is a webhook-event catalog descriptor, not a content collection.
+- [ ] `eventRegistrations / memberEventRegistrations` — skipped: no such query, object, input, or enum in the current API reference. RSVP data, where present, lives in post custom fields rather than a queryable registrations collection.
+- [ ] `activityLogs` — skipped: appears only in the legacy Tribe schema listing; the current reference documents no `ActivityLog` object type, so a GraphQL selection set can't be verified without live introspection. Flagged for follow-up when API access is available.
+- [x] `postReactionParticipants` — per-reaction engagement records tied to posts we sync (medium), added here
- [ ] `tagPosts` — post-to-tag join; we sync both tags and posts but not the link (medium)
- [ ] `analytics` — vendor's aggregated community analytics reports (medium)
- [ ] `chats / messages / chatParticipants` — direct messaging is an entire engagement channel currently missing (medium)
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.py
index f7a6871a36cc..48f1604cf126 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
@@ -64,6 +64,24 @@ query ParentSpaces($limit: Int!, $after: String) {
}
"""
+_PARENT_POST_REACTIONS_QUERY = """
+query ParentPostReactions($limit: Int!, $after: String) {
+ posts(limit: $limit, after: $after) {
+ pageInfo {
+ endCursor
+ hasNextPage
+ }
+ nodes {
+ id
+ reactions {
+ reaction
+ count
+ }
+ }
+ }
+}
+"""
+
class BettermodeRetryableError(Exception):
pass
@@ -85,6 +103,9 @@ class BettermodeResumeConfig:
post_id: str | None = None
# Same bookmark for space-scoped fan-outs (`space_members`, `space_post_types`).
space_id: str | None = None
+ # Reaction key currently being processed for the bookmarked post in the reaction
+ # participants fan-out. None for the other endpoints.
+ reaction: str | None = None
def _base_url(region: str) -> str:
@@ -396,6 +417,70 @@ def _get_space_scoped_rows(
yield from _fan_out_rows(execute, config, parent_ids, "spaceId", "space_id", resumable_source_manager, logger)
+def _get_post_reaction_participant_rows(
+ execute: Any,
+ config: BettermodeEndpointConfig,
+ resumable_source_manager: ResumableSourceManager[BettermodeResumeConfig],
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict[str, Any]]]:
+ """Fan out one `postReactionParticipants(postId, reaction)` connection per (post, reaction) pair.
+
+ The root query requires both a post and a reaction key, so the fan-out is two levels deep: a
+ cheap posts walk carries each post's reaction summary, and every reaction with a positive count
+ becomes a pair to enumerate. A participant node exposes only its member, so the post id and
+ reaction key are injected from the pair to complete the row. The bookmark is the (post, reaction)
+ pair (stable ids, not positions) so pairs added or removed between a crash and the retry can't
+ resume us into the wrong pair.
+ """
+ pairs: list[tuple[str, str]] = []
+ for nodes, _ in _iter_connection(execute, _PARENT_POST_REACTIONS_QUERY, "posts", {}, PARENT_PAGE_SIZE, None):
+ for node in nodes:
+ post_id = node["id"]
+ for detail in node.get("reactions") or []:
+ reaction = detail.get("reaction")
+ if reaction and (detail.get("count") or 0) > 0:
+ pairs.append((post_id, reaction))
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ remaining = pairs
+ resume_after: str | None = None
+ if resume is not None and resume.post_id is not None and resume.reaction is not None:
+ bookmark = (resume.post_id, resume.reaction)
+ if bookmark in pairs:
+ remaining = pairs[pairs.index(bookmark) :]
+ resume_after = resume.after
+ logger.debug(f"Bettermode: resuming postReactionParticipants from {bookmark}")
+
+ query = _build_query(config)
+ for index, (post_id, reaction) in enumerate(remaining):
+ variables = {"postId": post_id, "reaction": reaction}
+ for nodes, next_cursor in _iter_connection(
+ execute, query, config.query_field, variables, config.page_size, resume_after
+ ):
+ rows = []
+ for node in nodes:
+ member_id = (node.get("participant") or {}).get("id")
+ # A participant whose member is no longer readable carries no usable key.
+ if member_id:
+ rows.append({"postId": post_id, "reaction": reaction, "memberId": member_id})
+ 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, reaction=reaction)
+ )
+ resume_after = None
+
+ # Advance the bookmark so a crash between pairs resumes at the next one.
+ if index + 1 < len(remaining):
+ next_post_id, next_reaction = remaining[index + 1]
+ resumable_source_manager.save_state(
+ BettermodeResumeConfig(after=None, post_id=next_post_id, reaction=next_reaction)
+ )
+
+
def get_rows(
region: str,
client_id: str,
@@ -427,6 +512,10 @@ def get_rows(
yield from _get_space_scoped_rows(execute, config, resumable_source_manager, logger)
return
+ if config.fan_out_post_reactions:
+ yield from _get_post_reaction_participant_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(
diff --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.py
index 79ddd3995888..01387b64b620 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
@@ -131,6 +131,15 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"whoCanReply": "IDs of the space roles allowed to reply to posts of this type.",
},
},
+ "post_reaction_participants": {
+ "description": "Join table of the members who reacted to posts, one row per member, post, and reaction key.",
+ "docs_url": "https://developers.bettermode.com/docs/operations/reaction/queries/post-reaction-participants/",
+ "columns": {
+ "postId": "ID of the post that was reacted to.",
+ "reaction": "Reaction key the member left on the post (e.g. the emoji or reaction name).",
+ "memberId": "ID of the member who left the reaction.",
+ },
+ },
"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/",
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.py
index 4e07ab81b868..405edb0a242d 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
@@ -181,6 +181,14 @@ scopes
visible
"""
+# A PostReactionParticipant exposes only the reacting member; the post and reaction key that
+# complete the row come from the fan-out that reaches this connection.
+_POST_REACTION_PARTICIPANT_NODE_FIELDS = """
+participant {
+id
+}
+"""
+
_MODERATION_NODE_FIELDS = """
id
status
@@ -222,6 +230,9 @@ class BettermodeEndpointConfig:
fan_out_replies: bool = False
# Fan out one connection per space, for root fields that require `spaceId: ID!`.
fan_out_spaces: bool = False
+ # Fan out one `postReactionParticipants(postId, reaction)` connection per (post, reaction)
+ # pair, for the members who left each reaction on a post.
+ fan_out_post_reactions: bool = False
# Root field returns a plain list instead of a Relay connection — no limit/after args.
is_list: bool = False
@@ -296,6 +307,18 @@ BETTERMODE_ENDPOINTS: dict[str, BettermodeEndpointConfig] = {
node_fields=_POST_TYPE_NODE_FIELDS,
page_size=100,
),
+ "post_reaction_participants": BettermodeEndpointConfig(
+ query_field="postReactionParticipants",
+ node_fields=_POST_REACTION_PARTICIPANT_NODE_FIELDS,
+ extra_args={"postId": "ID!", "reaction": "ID!"},
+ page_size=100,
+ # A row is unique per post, reaction key, and member; `postId` and `reaction` are
+ # injected from the fan-out because the participant node carries only the member.
+ primary_keys=["postId", "reaction", "memberId"],
+ # PostReactionParticipant has no timestamp, so there is nothing stable to partition on.
+ partition_key=None,
+ fan_out_post_reactions=True,
+ ),
"collections": BettermodeEndpointConfig(
query_field="collections",
node_fields=_COLLECTION_NODE_FIELDS,
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.py
index 0b5f0ef06d87..4710808c2b4c 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
@@ -50,6 +50,10 @@ _SCHEMA_DESCRIPTIONS: dict[str, str] = {
"Fetches the post types enabled in every space (one request per space), so syncs scale "
"with the number of spaces in the community"
),
+ "post_reaction_participants": (
+ "Fetches the members who left each reaction on every post that has reactions (one request "
+ "per post and reaction), so syncs scale with the number of reacted posts in the community"
+ ),
}
@@ -75,7 +79,7 @@ class BettermodeSource(ResumableSource[BettermodeSourceConfig, BettermodeResumeC
category=DataWarehouseSourceCategory.CUSTOMER_SUPPORT,
label="Bettermode",
keywords=["tribe", "community"],
- 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.
+ caption="""Connect your Bettermode (formerly Tribe) community to pull members, spaces, space members, posts, replies, post reaction participants, 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.
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.py
index 1a4d13d60e15..813003a4ea1c 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
@@ -410,3 +410,75 @@ class TestSpaceFanOut:
variables = member_calls[0].kwargs["json"]["variables"]
assert variables["spaceId"] == "s2"
assert variables["after"] == "cur-mid"
+
+
+class TestPostReactionParticipantsFanOut:
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_fans_out_over_post_reaction_pairs(self, mock_make_session):
+ _, data_session = _mock_sessions(
+ mock_make_session,
+ [
+ # Parent enumeration: `love` has zero count and p2 has no reactions, so the only
+ # pairs to fetch are (p1, like) and (p3, wow).
+ _page(
+ "posts",
+ [
+ {"id": "p1", "reactions": [{"reaction": "like", "count": 2}, {"reaction": "love", "count": 0}]},
+ {"id": "p2", "reactions": []},
+ {"id": "p3", "reactions": [{"reaction": "wow", "count": 1}]},
+ ],
+ ),
+ _page("postReactionParticipants", [{"participant": {"id": "m1"}}], end_cursor="cur-1"),
+ # A participant whose member is no longer readable carries no usable key.
+ _page("postReactionParticipants", [{"participant": {"id": "m2"}}, {"participant": None}]),
+ _page("postReactionParticipants", [{"participant": {"id": "m3"}}]),
+ ],
+ )
+
+ manager = _make_manager()
+ batches = list(
+ get_rows("us", "client", "secret", "net", "post_reaction_participants", mock.MagicMock(), manager)
+ )
+
+ assert [row for batch in batches for row in batch] == [
+ {"postId": "p1", "reaction": "like", "memberId": "m1"},
+ {"postId": "p1", "reaction": "like", "memberId": "m2"},
+ {"postId": "p3", "reaction": "wow", "memberId": "m3"},
+ ]
+ participant_calls = data_session.post.call_args_list[1:]
+ assert [
+ (call.kwargs["json"]["variables"]["postId"], call.kwargs["json"]["variables"]["reaction"])
+ for call in participant_calls
+ ] == [("p1", "like"), ("p1", "like"), ("p3", "wow")]
+ # Mid-pair page checkpoint, then a bookmark advancing to the next (post, reaction) pair.
+ saved = [call.args[0] for call in manager.save_state.call_args_list]
+ assert [(state.after, state.post_id, state.reaction) for state in saved] == [
+ ("cur-1", "p1", "like"),
+ (None, "p3", "wow"),
+ ]
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_resumes_from_bookmarked_pair(self, mock_make_session):
+ _, data_session = _mock_sessions(
+ mock_make_session,
+ [
+ _page(
+ "posts",
+ [
+ {"id": "p1", "reactions": [{"reaction": "like", "count": 2}]},
+ {"id": "p3", "reactions": [{"reaction": "wow", "count": 1}]},
+ ],
+ ),
+ _page("postReactionParticipants", [{"participant": {"id": "m9"}}]),
+ ],
+ )
+
+ manager = _make_manager(BettermodeResumeConfig(after="cur-mid", post_id="p3", reaction="wow"))
+ list(get_rows("us", "client", "secret", "net", "post_reaction_participants", mock.MagicMock(), manager))
+
+ participant_calls = data_session.post.call_args_list[1:]
+ assert len(participant_calls) == 1
+ variables = participant_calls[0].kwargs["json"]["variables"]
+ assert variables["postId"] == "p3"
+ assert variables["reaction"] == "wow"
+ assert variables["after"] == "cur-mid"