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 4 missing tables to the Knock source (#117274)

Tom Owers144c62e6a674
diff --git a/posthog/test/repo_invariants/source_wrapped_resource_baseline.txt b/posthog/test/repo_invariants/source_wrapped_resource_baseline.txt
index 05d365e29dc6..87535bd6c11c 100644
--- a/posthog/test/repo_invariants/source_wrapped_resource_baseline.txt
+++ b/posthog/test/repo_invariants/source_wrapped_resource_baseline.txt
@@ -30,7 +30,6 @@ hugging_face/hugging_face.py::_repo_pages
imperva/imperva.py::imperva_source.items
intercom/intercom.py::intercom_source.iter_resource
invoiceninja/invoiceninja.py::invoiceninja_source.items
-knock/knock.py::_objects_items
lago/lago.py::lago_source.items
leadfeeder/leadfeeder.py::_unified_account_ids
metabase/metabase.py::get_rows
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 e9cb07612e64..c15d9876efaf 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
@@ -6866,14 +6866,14 @@ Diffed against: <https://docs.knock.app/llms.txt>
- [x] `messages/{id}/delivery_logs` — provider-level request/response per delivery attempt; the only way to diagnose bounces and provider failures (high)
- [x] `objects (list objects in a collection)` — non-user recipients (accounts, projects, devices) — the lookup that resolves object recipient IDs appearing on messages and subscriptions (high)
- [x] `schedules (list schedules)` — scheduled and recurring workflow runs, the forward-looking counterpart to workflow_recipient_runs (high)
-- [ ] `messages/{id}/activities` — the trigger activities (actor, recipient, data) that produced a message — links notifications back to the originating event (medium)
-- [ ] `objects/{collection}/{id}/subscriptions and users/{id}/subscriptions` — membership table mapping recipients to the objects they subscribe to; drives audience sizing (medium)
-- [ ] `audiences/{key}/members` — audience membership, a straightforward analytical join for targeting analysis (medium)
-- [ ] `users/{id}/preferences and objects preferences` — per-recipient notification preference sets — needed to explain why recipients were skipped (medium)
+- [x] `messages/{id}/activities` — the trigger activities (actor, recipient, data) that produced a message — links notifications back to the originating event (medium)
+- [x] `objects/{collection}/{id}/subscriptions and users/{id}/subscriptions` — membership table mapping recipients to the objects they subscribe to; drives audience sizing (medium)
+- [x] `audiences/{key}/members` — audience membership, a straightforward analytical join for targeting analysis (medium)
+- [x] `users/{id}/preferences and objects preferences` — per-recipient notification preference sets — needed to explain why recipients were skipped (medium)
- [ ] `users/{id}/feeds (list feed items)` — in-app feed items per user, for in-app channel engagement analysis (medium)
- [ ] `bulk_operations (get bulk operation)` — status of bulk identify/subscribe jobs, useful for sync auditing (low)
-Note: Knock has no publicly downloadable OpenAPI file (docs.knock.app/openapi.json returns the docs SPA), but llms.txt enumerates every api-reference page and is authoritative. Caveat for whoever implements `objects`: there is no global list-all-objects endpoint — listing requires a collection key per request, so the table would need collection names as config or dynamic discovery. The message sub-resources (events, delivery_logs, activities) likewise require iterating message IDs, which is expensive but is where the deliverability data lives.
+Note: Knock has no publicly downloadable OpenAPI file (docs.knock.app/openapi.json returns the docs SPA), but llms.txt enumerates every api-reference page and is authoritative. Caveat for whoever implements `objects`: there is no global list-all-objects endpoint — listing requires a collection key per request, so the table would need collection names as config or dynamic discovery. The message sub-resources (events, delivery_logs, activities) likewise require iterating message IDs, which is expensive but is where the deliverability data lives. The subscriptions and preferences tables (`user_subscriptions`, `user_preferences`) fan out over users only; the object-side endpoints would need a two-level walk over configured collections and their objects. Audiences cannot be listed either, so `audience_members` reads the audience keys configured on the source.
## Knowbe4 — gaps
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/knock.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/knock.py
index 394d1280c20e..4c5d35ac4248 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/knock.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/knock.py
@@ -8,3 +8,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
class KnockSourceConfig(config.Config):
api_key: str
object_collections: str | None = None
+ audience_keys: str | None = None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/knock/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/knock/canonical_descriptions.py
index 90762491989b..9fad9b4ce90c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/knock/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/knock/canonical_descriptions.py
@@ -125,4 +125,56 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"inserted_at": "Timestamp when the delivery log was created.",
},
},
+ "message_activities": {
+ "description": "A workflow trigger that produced a message, with the actor, recipient, and trigger data. A batched message has one activity for each trigger in the batch.",
+ "docs_url": "https://docs.knock.app/api-reference/messages/list_activities",
+ "columns": {
+ "id": "Unique identifier for the activity.",
+ "message_id": "The ID of the message the activity produced.",
+ "message_inserted_at": "Timestamp when the message the activity produced was created.",
+ "actor": "The actor who performed the activity.",
+ "recipient": "The recipient of the notification: a user or an object.",
+ "data": "The workflow trigger `data` payload associated with the activity.",
+ "inserted_at": "Timestamp when the activity was created.",
+ "updated_at": "Timestamp when the activity was last updated.",
+ },
+ },
+ "user_subscriptions": {
+ "description": "A subscription of a user to an object. Workflows triggered for the object notify its subscribers.",
+ "docs_url": "https://docs.knock.app/api-reference/users/list_subscriptions",
+ "columns": {
+ "user_id": "The ID of the subscribed user.",
+ "object_collection": "The collection of the object the user subscribes to.",
+ "object_id": "The ID of the object the user subscribes to.",
+ "object": "The object the user subscribes to.",
+ "recipient": "The subscribed recipient.",
+ "properties": "The custom properties associated with the subscription relationship.",
+ "inserted_at": "Timestamp when the subscription was created.",
+ "updated_at": "Timestamp when the subscription was last updated.",
+ },
+ },
+ "user_preferences": {
+ "description": "A set of notification preferences of a user. A user has a default preference set and can have one per tenant.",
+ "docs_url": "https://docs.knock.app/api-reference/users/list_preferences",
+ "columns": {
+ "id": "Unique identifier for the preference set (`default`, or the tenant ID for a per-tenant set).",
+ "user_id": "The ID of the user the preference set belongs to.",
+ "categories": "Preference settings keyed by workflow category.",
+ "channel_types": "Preference settings keyed by channel type.",
+ "channels": "Preference settings keyed by channel ID.",
+ "workflows": "Preference settings keyed by workflow key.",
+ "commercial_subscribed": "Whether the user receives commercial workflow notifications, or the conditions that decide it at send time.",
+ },
+ },
+ "audience_members": {
+ "description": "A user who is a member of an audience. A user can be a member once for each tenant.",
+ "docs_url": "https://docs.knock.app/api-reference/audiences/list_members",
+ "columns": {
+ "audience_key": "The key of the audience.",
+ "user_id": "The ID of the member user.",
+ "user": "The member user.",
+ "tenant": "The ID of the tenant the membership is scoped to.",
+ "added_at": "Timestamp when the user was added to the audience.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/knock/knock.py b/products/warehouse_sources/backend/temporal/data_imports/sources/knock/knock.py
index fc29102c681c..7f387b96d080 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/knock/knock.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/knock/knock.py
@@ -1,8 +1,8 @@
import dataclasses
-from collections.abc import Iterator
+from collections.abc import Callable, Iterator
from datetime import datetime
-from typing import Any, Optional
-from urllib.parse import quote
+from typing import Any, Optional, cast
+from urllib.parse import quote, unquote
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 (
@@ -15,10 +15,13 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
JSONResponseCursorPaginator,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.resource import Resource
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
ClientConfig,
+ Endpoint,
EndpointResource,
IncrementalConfig,
+ PaginatorConfig,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
@@ -26,6 +29,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.knock.sett
ENDPOINTS_CONFIG,
KNOCK_BASE_URL,
KNOCK_PAGE_SIZE,
+ KnockEndpointConfig,
)
DEFAULT_INCREMENTAL_START = "1970-01-01T00:00:00Z"
@@ -35,11 +39,17 @@ NO_OBJECT_COLLECTIONS_ERROR = (
"Add your collection keys in the source settings, then sync again."
)
+NO_AUDIENCE_KEYS_ERROR = (
+ "The Knock audience members table needs at least one audience key. "
+ "Add your audience keys in the source settings, then sync again."
+)
+
@dataclasses.dataclass(frozen=True)
class KnockResumeConfig:
after: str | None = None
- # Set only by the objects table, which walks one collection after another.
+ # Set only by the objects and audience members tables, which walk one configured
+ # collection or audience key after another.
collection: str | None = None
@@ -49,10 +59,10 @@ def _to_iso8601(value: Any) -> str:
return str(value)
-def parse_object_collections(object_collections: Optional[str]) -> list[str]:
- if not object_collections:
+def parse_key_list(keys: Optional[str]) -> list[str]:
+ if not keys:
return []
- return list(dict.fromkeys(part.strip() for part in object_collections.split(",") if part.strip()))
+ return list(dict.fromkeys(part.strip() for part in keys.split(",") if part.strip()))
def _client_config(api_key: str) -> ClientConfig:
@@ -73,6 +83,38 @@ def _percent_encode_id(row: dict[str, Any]) -> dict[str, Any]:
return row
+def _decode_user_id(row: dict[str, Any]) -> dict[str, Any]:
+ # The fan-out tags child rows with the parent id after `_percent_encode_id` ran on it.
+ row["user_id"] = unquote(row["user_id"])
+ return row
+
+
+def _shape_user_subscription(row: dict[str, Any]) -> dict[str, Any]:
+ row = _decode_user_id(row)
+ subscribed_object = row.get("object") or {}
+ row["object_collection"] = subscribed_object.get("collection")
+ row["object_id"] = subscribed_object.get("id")
+ return row
+
+
+_FANOUT_CHILD_ROW_MAPS: dict[str, Callable[[dict[str, Any]], dict[str, Any]]] = {
+ "user_subscriptions": _shape_user_subscription,
+ "user_preferences": _decode_user_id,
+}
+
+
+def _paginator_override(config: KnockEndpointConfig) -> PaginatorConfig | None:
+ if config.data_selector is None:
+ return "single_page"
+ if not config.documents_pagination:
+ # The spec documents no cursor param here; fail loud if Knock returns a cursor it
+ # then ignores, rather than re-reading the first page forever.
+ return JSONResponseCursorPaginator(
+ cursor_path="page_info.after", cursor_param="after", raise_on_repeated_cursor=True
+ )
+ return None
+
+
def _no_child_window(_incremental_field: str) -> Optional[IncrementalConfig]:
# The child endpoints take no timestamp filter, so the window goes on the parent walk.
return None
@@ -81,7 +123,7 @@ def _no_child_window(_incremental_field: str) -> Optional[IncrementalConfig]:
def get_resource(endpoint: str, should_use_incremental_field: bool, path: str | None = None) -> EndpointResource:
config = ENDPOINTS_CONFIG[endpoint]
- params: dict[str, Any] = {"page_size": KNOCK_PAGE_SIZE}
+ params: dict[str, Any] = {"page_size": KNOCK_PAGE_SIZE} if config.documents_pagination else {}
if should_use_incremental_field and config.incremental_param and config.incremental_fields:
params[config.incremental_param] = {
"type": "incremental",
@@ -90,6 +132,18 @@ def get_resource(endpoint: str, should_use_incremental_field: bool, path: str |
"convert": _to_iso8601,
}
+ endpoint_config: Endpoint = {
+ "path": path or config.path,
+ "params": params,
+ "data_selector": config.data_selector,
+ # Fail loud if Knock ever changes the response envelope key instead of
+ # silently syncing 0 rows.
+ "data_selector_required": True,
+ }
+ paginator = _paginator_override(config)
+ if paginator is not None:
+ endpoint_config["paginator"] = paginator
+
return {
"name": endpoint,
"table_name": endpoint,
@@ -99,14 +153,7 @@ def get_resource(endpoint: str, should_use_incremental_field: bool, path: str |
}
if should_use_incremental_field
else "replace",
- "endpoint": {
- "path": path or config.path,
- "params": params,
- "data_selector": config.data_selector,
- # Fail loud if Knock ever changes the response envelope key instead of
- # silently syncing 0 rows.
- "data_selector_required": True,
- },
+ "endpoint": endpoint_config,
"table_format": "delta",
}
@@ -129,9 +176,14 @@ def _fanout_items(
fanout, parent_params={endpoint_config.incremental_param: _to_iso8601(db_incremental_field_last_value)}
)
+ child_endpoint_extra: Endpoint = {"data_selector": endpoint_config.data_selector, "data_selector_required": True}
+ paginator = _paginator_override(endpoint_config)
+ if paginator is not None:
+ child_endpoint_extra["paginator"] = paginator
+
# No resume hook: the framework's per-parent checkpoint lists every parent completed so far,
# which grows without bound on message- and user-sized parents.
- return build_dependent_resource(
+ resource = build_dependent_resource(
endpoint_configs=ENDPOINTS_CONFIG,
child_endpoint=endpoint,
fanout=fanout,
@@ -144,15 +196,28 @@ def _fanout_items(
incremental_field=endpoint_config.default_incremental_field,
incremental_config_factory=_no_child_window,
parent_endpoint_extra={"data_selector": parent_config.data_selector, "data_selector_required": True},
- child_endpoint_extra={"data_selector": endpoint_config.data_selector, "data_selector_required": True},
+ child_endpoint_extra=child_endpoint_extra,
parent_data_map=_percent_encode_id if fanout.parent_name == "users" else None,
- page_size_param="page_size",
+ # The size param is shared by the parent and the child. Knock's default page size is
+ # the same as KNOCK_PAGE_SIZE, so leaving it off keeps the parent walk unchanged.
+ page_size_param="page_size" if endpoint_config.documents_pagination else None,
)
+ child_row_map = _FANOUT_CHILD_ROW_MAPS.get(endpoint)
+ return cast(Resource, resource).add_map(child_row_map) if child_row_map is not None else resource
+
+def _tag_audience_key(audience_key: str) -> Callable[[dict[str, Any]], dict[str, Any]]:
+ def _tag(row: dict[str, Any]) -> dict[str, Any]:
+ row["audience_key"] = audience_key
+ return row
-def _objects_items(
+ return _tag
+
+
+def _keyed_items(
api_key: str,
- collections: list[str],
+ endpoint: str,
+ keys: list[str],
team_id: int,
job_id: str,
resumable_source_manager: ResumableSourceManager[KnockResumeConfig],
@@ -161,42 +226,46 @@ def _objects_items(
start_after: str | None = None
if resumable_source_manager.can_resume():
resume_config = resumable_source_manager.load_state()
- if resume_config is not None and resume_config.collection in collections:
- start_index = collections.index(resume_config.collection)
+ if resume_config is not None and resume_config.collection in keys:
+ start_index = keys.index(resume_config.collection)
start_after = resume_config.after
- for index in range(start_index, len(collections)):
- collection = collections[index]
+ for index in range(start_index, len(keys)):
+ key = keys[index]
after = start_after if index == start_index else None
if after is None:
- # Every row of the earlier collections is already yielded, so a resume can start here.
- resumable_source_manager.save_state(KnockResumeConfig(collection=collection))
+ # Every row of the earlier keys is already yielded, so a resume can start here.
+ resumable_source_manager.save_state(KnockResumeConfig(collection=key))
- def save_checkpoint(state: Optional[dict[str, Any]], _collection: str = collection) -> None:
+ def save_checkpoint(state: Optional[dict[str, Any]], _key: str = key) -> None:
if state and state.get("cursor"):
- resumable_source_manager.save_state(
- KnockResumeConfig(after=str(state["cursor"]), collection=_collection)
- )
+ resumable_source_manager.save_state(KnockResumeConfig(after=str(state["cursor"]), collection=_key))
+
+ resource = get_resource(
+ endpoint,
+ should_use_incremental_field=False,
+ path=ENDPOINTS_CONFIG[endpoint].path.replace("{key}", quote(key, safe="")),
+ )
+ if endpoint == "audience_members":
+ # Member rows don't say which audience they belong to.
+ resource["data_map"] = _tag_audience_key(key)
config: RESTAPIConfig = {
"client": _client_config(api_key),
"resource_defaults": {},
- "resources": [
- get_resource(
- "objects",
- should_use_incremental_field=False,
- path=f"/v1/objects/{quote(collection, safe='')}",
- )
- ],
+ "resources": [resource],
}
- yield from rest_api_resource(
+ for page in rest_api_resource(
config,
team_id,
job_id,
None,
resume_hook=save_checkpoint,
initial_paginator_state={"cursor": after} if after else None,
- )
+ ):
+ yield page
+ # The page is handed on in full and nothing is buffered, so a hand-off loses no rows.
+ resumable_source_manager.safe_point()
def knock_source(
@@ -208,6 +277,7 @@ def knock_source(
db_incremental_field_last_value: Optional[Any],
should_use_incremental_field: bool = False,
object_collections: Optional[str] = None,
+ audience_keys: Optional[str] = None,
) -> SourceResponse:
endpoint_config = ENDPOINTS_CONFIG[endpoint]
@@ -217,11 +287,11 @@ def knock_source(
api_key, endpoint, team_id, job_id, db_incremental_field_last_value, should_use_incremental_field
)
items = lambda: resource
- elif endpoint == "objects":
- collections = parse_object_collections(object_collections)
- if not collections:
- raise ValueError(NO_OBJECT_COLLECTIONS_ERROR)
- items = lambda: _objects_items(api_key, collections, team_id, job_id, resumable_source_manager)
+ elif endpoint in ("objects", "audience_members"):
+ keys = parse_key_list(object_collections if endpoint == "objects" else audience_keys)
+ if not keys:
+ raise ValueError(NO_OBJECT_COLLECTIONS_ERROR if endpoint == "objects" else NO_AUDIENCE_KEYS_ERROR)
+ items = lambda: _keyed_items(api_key, endpoint, keys, team_id, job_id, resumable_source_manager)
else:
config: RESTAPIConfig = {
"client": _client_config(api_key),
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/knock/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/knock/settings.py
index 299f166c2a65..6b52cad3c8b9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/knock/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/knock/settings.py
@@ -19,8 +19,9 @@ class KnockEndpointConfig:
name: str
path: str
# Knock wraps list responses in `entries` on most endpoints but `items` on
- # messages and workflow recipient runs (per the vendor OpenAPI spec).
- data_selector: str
+ # messages and workflow recipient runs (per the vendor OpenAPI spec). None marks an
+ # endpoint that returns a bare, unpaginated JSON array.
+ data_selector: str | None
primary_keys: tuple[str, ...] = ("id",)
incremental_fields: list[IncrementalField] = field(default_factory=list)
# Request param carrying the server-side lower-bound timestamp filter.
@@ -35,6 +36,8 @@ class KnockEndpointConfig:
should_sync_default: bool = True
default_incremental_lookback_seconds: int | None = None
page_size: int = KNOCK_PAGE_SIZE
+ # False for an endpoint whose spec documents no `page_size` or `after` param.
+ documents_pagination: bool = True
@property
def default_incremental_field(self) -> str | None:
@@ -46,6 +49,17 @@ class KnockEndpointConfig:
_SKIP_DELETED_PARENT: list[ResponseAction] = [{"status_code": 404, "action": "ignore"}]
+def _user_fanout() -> DependentEndpointConfig:
+ return DependentEndpointConfig(
+ parent_name="users",
+ resolve_param="user_id",
+ resolve_field="id",
+ include_from_parent=["id"],
+ parent_field_renames={"id": "user_id"},
+ child_response_actions=_SKIP_DELETED_PARENT,
+ )
+
+
def _message_fanout() -> DependentEndpointConfig:
return DependentEndpointConfig(
parent_name="messages",
@@ -101,7 +115,7 @@ ENDPOINTS_CONFIG: dict[str, KnockEndpointConfig] = {
# unique within a collection, and `created_at` is nullable, so no partition key.
"objects": KnockEndpointConfig(
name="objects",
- path="/v1/objects/{collection}",
+ path="/v1/objects/{key}",
data_selector="entries",
primary_keys=("collection", "id"),
),
@@ -149,6 +163,53 @@ ENDPOINTS_CONFIG: dict[str, KnockEndpointConfig] = {
should_sync_default=False,
default_incremental_lookback_seconds=24 * 60 * 60,
),
+ # The trigger activities a message was produced from. A batched message carries several,
+ # and one activity can feed several messages, so the message id joins the key. Knock
+ # creates a batched message only when its batch window closes, so no lookback is needed.
+ "message_activities": KnockEndpointConfig(
+ name="message_activities",
+ path="/v1/messages/{message_id}/activities",
+ data_selector="items",
+ primary_keys=("message_id", "id"),
+ incremental_fields=[incremental_field("message_inserted_at")],
+ incremental_param="inserted_at[gte]",
+ partition_key="inserted_at",
+ fanout=_message_fanout(),
+ should_sync_default=False,
+ ),
+ # The objects each user subscribes to. Subscriptions carry no id of their own, so the key
+ # is the user plus the object reference. Subscriptions whose recipient is an object are
+ # not reachable this way.
+ "user_subscriptions": KnockEndpointConfig(
+ name="user_subscriptions",
+ path="/v1/users/{user_id}/subscriptions",
+ data_selector="entries",
+ primary_keys=("user_id", "object_collection", "object_id"),
+ partition_key="inserted_at",
+ fanout=_user_fanout(),
+ should_sync_default=False,
+ ),
+ # Every preference set of each user. Preference set ids (e.g. `default`, or a tenant id)
+ # repeat across users.
+ "user_preferences": KnockEndpointConfig(
+ name="user_preferences",
+ path="/v1/users/{user_id}/preferences",
+ data_selector=None,
+ primary_keys=("user_id", "id"),
+ fanout=_user_fanout(),
+ should_sync_default=False,
+ documents_pagination=False,
+ ),
+ # Knock has no endpoint that lists audiences, so the table walks the audience keys the
+ # user configures on the source. A user can be a member once per tenant.
+ "audience_members": KnockEndpointConfig(
+ name="audience_members",
+ path="/v1/audiences/{key}/members",
+ data_selector="entries",
+ primary_keys=("audience_key", "user_id", "tenant"),
+ partition_key="added_at",
+ documents_pagination=False,
+ ),
}
ENDPOINTS = tuple(ENDPOINTS_CONFIG.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/knock/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/knock/source.py
index ba7b19a284bb..d2159cfe9b1a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/knock/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/knock/source.py
@@ -21,10 +21,11 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.sch
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.knock import KnockSourceConfig
from products.warehouse_sources.backend.temporal.data_imports.sources.knock.knock import (
+ NO_AUDIENCE_KEYS_ERROR,
NO_OBJECT_COLLECTIONS_ERROR,
KnockResumeConfig,
knock_source,
- parse_object_collections,
+ parse_key_list,
validate_credentials as validate_knock_credentials,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.knock.settings import (
@@ -69,6 +70,7 @@ class KnockSource(ResumableSource[KnockSourceConfig, KnockResumeConfig]):
"401 Client Error: Unauthorized for url": "Your Knock API key is invalid or has been revoked. Please generate a new secret key in the Knock dashboard and reconnect.",
"403 Client Error: Forbidden for url": "Your Knock API key does not have access to this resource. Please check the key belongs to the right environment.",
NO_OBJECT_COLLECTIONS_ERROR: None,
+ NO_AUDIENCE_KEYS_ERROR: None,
}
def get_canonical_descriptions(self) -> CanonicalDescriptions:
@@ -88,7 +90,8 @@ class KnockSource(ResumableSource[KnockSourceConfig, KnockResumeConfig]):
api_version: str | None = None,
) -> list[SourceSchema]:
should_sync_default = {name: endpoint.should_sync_default for name, endpoint in ENDPOINTS_CONFIG.items()}
- should_sync_default["objects"] = bool(parse_object_collections(config.object_collections))
+ should_sync_default["objects"] = bool(parse_key_list(config.object_collections))
+ should_sync_default["audience_members"] = bool(parse_key_list(config.audience_keys))
return build_endpoint_schemas(
ENDPOINTS,
INCREMENTAL_FIELDS,
@@ -119,6 +122,7 @@ class KnockSource(ResumableSource[KnockSourceConfig, KnockResumeConfig]):
resumable_source_manager=resumable_source_manager,
should_use_incremental_field=inputs.should_use_incremental_field,
object_collections=config.object_collections,
+ audience_keys=config.audience_keys,
db_incremental_field_last_value=inputs.db_incremental_field_last_value
if inputs.should_use_incremental_field
else None,
@@ -155,6 +159,15 @@ class KnockSource(ResumableSource[KnockSourceConfig, KnockResumeConfig]):
secret=False,
caption="Comma-separated object collection keys to sync into the `objects` table. Knock can't list collections, so the `objects` table only syncs the collections you enter here.",
),
+ SourceFieldInputConfig(
+ name="audience_keys",
+ label="Audience keys",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="beta-users, enterprise-admins",
+ secret=False,
+ caption="Comma-separated audience keys to sync into the `audience_members` table. Knock can't list audiences, so the `audience_members` table only syncs the audiences you enter here.",
+ ),
],
),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/knock/tests/test_knock.py b/products/warehouse_sources/backend/temporal/data_imports/sources/knock/tests/test_knock.py
index dac742e54f0a..1f71a57b37d5 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/knock/tests/test_knock.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/knock/tests/test_knock.py
@@ -11,6 +11,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.tes
)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.knock import KnockSourceConfig
from products.warehouse_sources.backend.temporal.data_imports.sources.knock.knock import (
+ NO_AUDIENCE_KEYS_ERROR,
NO_OBJECT_COLLECTIONS_ERROR,
KnockResumeConfig,
get_resource,
@@ -49,8 +50,11 @@ class TestGetResource:
class TestKnockSourceTransport:
@staticmethod
- def _driver(object_collections: str | None = None) -> SourceDriver:
- return SourceDriver(KnockSource(), KnockSourceConfig(api_key="sk_test", object_collections=object_collections))
+ def _driver(object_collections: str | None = None, audience_keys: str | None = None) -> SourceDriver:
+ return SourceDriver(
+ KnockSource(),
+ KnockSourceConfig(api_key="sk_test", object_collections=object_collections, audience_keys=audience_keys),
+ )
@parameterized.expand(
[
@@ -136,6 +140,7 @@ class TestKnockSourceTransport:
[
("message_events", "events"),
("message_delivery_logs", "delivery_logs"),
+ ("message_activities", "activities"),
]
)
def test_message_fanout_windows_parent_walk_and_tags_child_rows(self, endpoint: str, child_path: str) -> None:
@@ -196,6 +201,84 @@ class TestKnockSourceTransport:
assert result.paths[1] == "/v1/users/team%2Fjane/schedules"
assert [row["id"] for row in result.rows] == ["s1"]
+ @parameterized.expand(
+ [
+ (
+ "user_subscriptions",
+ "/v1/users/team%2Fjane/subscriptions",
+ ScriptedResponse(
+ json={
+ "entries": [
+ {
+ "object": {"collection": "accounts", "id": "acct_1"},
+ "recipient": {"id": "team/jane"},
+ "inserted_at": "2026-06-01T00:00:00Z",
+ }
+ ],
+ "page_info": {"after": None},
+ }
+ ),
+ "50",
+ {"user_id": "team/jane", "object_collection": "accounts", "object_id": "acct_1"},
+ ),
+ # Preferences come back as a bare array with no pagination params documented.
+ (
+ "user_preferences",
+ "/v1/users/team%2Fjane/preferences",
+ ScriptedResponse(json=[{"id": "default", "channel_types": {"email": True}}]),
+ None,
+ {"user_id": "team/jane", "id": "default"},
+ ),
+ ]
+ )
+ def test_user_fanout_tags_rows_with_decoded_user_id(
+ self,
+ endpoint: str,
+ child_path: str,
+ child_response: ScriptedResponse,
+ page_size: str | None,
+ expected: dict[str, Any],
+ ) -> None:
+ result = self._driver().run(endpoint, [_page("users", [{"id": "team/jane"}], after=None), child_response])
+
+ assert result.raised is None
+ assert result.paths == ["/v1/users", child_path]
+ assert [request.param("page_size") for request in result.requests] == [page_size, page_size]
+ assert len(result.rows) == 1
+ assert {key: result.rows[0].get(key) for key in expected} == expected
+
+ def test_audience_members_walk_each_configured_audience(self) -> None:
+ result = self._driver(audience_keys="beta, vip/1").run(
+ "audience_members",
+ [
+ _page("audience_members", [{"user_id": "u1", "tenant": None}], after="cursor-1"),
+ _page("audience_members", [{"user_id": "u2", "tenant": "t1"}], after=None),
+ _page("audience_members", [{"user_id": "u1", "tenant": None}], after=None),
+ ],
+ )
+
+ assert result.raised is None
+ assert result.paths == ["/v1/audiences/beta/members"] * 2 + ["/v1/audiences/vip%2F1/members"]
+ assert result.params("after") == [None, "cursor-1", None]
+ assert result.params("page_size") == [None] * 3
+ assert [(row["audience_key"], row["user_id"]) for row in result.rows] == [
+ ("beta", "u1"),
+ ("beta", "u2"),
+ ("vip/1", "u1"),
+ ]
+
+ def test_audience_members_fails_when_knock_ignores_the_cursor(self) -> None:
+ result = self._driver(audience_keys="beta").run(
+ "audience_members",
+ [
+ _page("audience_members", [{"user_id": "u1"}], after="cursor-1"),
+ _page("audience_members", [{"user_id": "u1"}], after="cursor-1"),
+ ],
+ )
+
+ assert isinstance(result.raised, ValueError)
+ assert len(result.requests) == 2
+
def test_objects_walk_each_configured_collection(self) -> None:
result = self._driver(object_collections=" accounts, projects,accounts ").run(
"objects",
@@ -227,12 +310,28 @@ class TestKnockSourceTransport:
assert result.paths == ["/v1/objects/projects"]
assert result.requests[0].param("after") == "cursor-7"
- @parameterized.expand([(None,), ("",), (" , ",)])
- def test_objects_without_collections_fails_with_actionable_error(self, object_collections: str | None) -> None:
- result = self._driver(object_collections=object_collections).run("objects", [])
+ @parameterized.expand(
+ [
+ ("objects", None, NO_OBJECT_COLLECTIONS_ERROR),
+ ("objects", "", NO_OBJECT_COLLECTIONS_ERROR),
+ ("objects", " , ", NO_OBJECT_COLLECTIONS_ERROR),
+ ("audience_members", None, NO_AUDIENCE_KEYS_ERROR),
+ ("audience_members", " , ", NO_AUDIENCE_KEYS_ERROR),
+ ]
+ )
+ def test_keyed_table_without_keys_fails_with_actionable_error(
+ self, endpoint: str, keys: str | None, expected_error: str
+ ) -> None:
+ # Each table reads its own field, so the other field's keys must not stand in for it.
+ driver = (
+ self._driver(object_collections=keys, audience_keys="beta")
+ if endpoint == "objects"
+ else self._driver(object_collections="accounts", audience_keys=keys)
+ )
+ result = driver.run(endpoint, [])
assert isinstance(result.raised, ValueError)
- assert str(result.raised) == NO_OBJECT_COLLECTIONS_ERROR
+ assert str(result.raised) == expected_error
class TestValidateCredentials:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/knock/tests/test_knock_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/knock/tests/test_knock_source.py
index bddc6e449595..3cc2e622098e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/knock/tests/test_knock_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/knock/tests/test_knock_source.py
@@ -7,17 +7,28 @@ from parameterized import parameterized
from products.warehouse_sources.backend.temporal.data_imports.sources.knock.source import KnockSource
-def _config(api_key: str = "sk_test", object_collections: str | None = None) -> Any:
+def _config(api_key: str = "sk_test", object_collections: str | None = None, audience_keys: str | None = None) -> Any:
config = MagicMock()
config.api_key = api_key
config.object_collections = object_collections
+ config.audience_keys = audience_keys
return config
class TestGetSchemas:
- @parameterized.expand([(None, False), ("", False), ("accounts", True)])
- def test_objects_syncs_by_default_only_once_collections_are_configured(
- self, object_collections: str | None, expected: bool
+ @parameterized.expand(
+ [
+ ("objects", "object_collections", None, False),
+ ("objects", "object_collections", "", False),
+ ("objects", "object_collections", "accounts", True),
+ ("audience_members", "audience_keys", None, False),
+ ("audience_members", "audience_keys", " , ", False),
+ ("audience_members", "audience_keys", "beta", True),
+ ]
+ )
+ def test_keyed_table_syncs_by_default_only_once_keys_are_configured(
+ self, table: str, field: str, keys: str | None, expected: bool
) -> None:
- schemas = {s.name: s for s in KnockSource().get_schemas(_config(object_collections=object_collections), 1)}
- assert schemas["objects"].should_sync_default is expected
+ config = _config(object_collections=keys) if field == "object_collections" else _config(audience_keys=keys)
+ schemas = {s.name: s for s in KnockSource().get_schemas(config, 1)}
+ assert schemas[table].should_sync_default is expected