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 knock schedules, objects, and message event tables (#113348)

Tom Owers0f29e7eb3af3
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 ec9922593b7a..53fa5296f408 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
@@ -4801,10 +4801,10 @@ Today (4): `messages`, `tenants`, `users`, `workflow_recipient_runs`
Diffed against: <https://docs.knock.app/llms.txt>
-- [ ] `messages/{id}/events` — per-message state transition history (sent, delivered, opened, clicked) — the deliverability fact table behind the messages we already sync (high)
-- [ ] `messages/{id}/delivery_logs` — provider-level request/response per delivery attempt; the only way to diagnose bounces and provider failures (high)
-- [ ] `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)
-- [ ] `schedules (list schedules)` — scheduled and recurring workflow runs, the forward-looking counterpart to workflow_recipient_runs (high)
+- [x] `messages/{id}/events` — per-message state transition history (sent, delivered, opened, clicked) — the deliverability fact table behind the messages we already sync (high)
+- [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)
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 8305e63ebdec..394d1280c20e 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
@@ -7,3 +7,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class KnockSourceConfig(config.Config):
api_key: str
+ object_collections: 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 2040c99cccc2..90762491989b 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
@@ -70,4 +70,59 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"updated_at": "Timestamp when the run was last updated.",
},
},
+ "objects": {
+ "description": "A non-user recipient (such as an account, project, or device) stored in a collection you configure on the source.",
+ "docs_url": "https://docs.knock.app/api-reference/objects/list",
+ "columns": {
+ "id": "Unique identifier for the object within its collection.",
+ "collection": "The collection this object belongs to.",
+ "properties": "The custom properties associated with the object.",
+ "created_at": "Timestamp when the object was created; may be null.",
+ "updated_at": "Timestamp when the object was last updated.",
+ },
+ },
+ "schedules": {
+ "description": "A recurring or one-off workflow execution scheduled for a user recipient.",
+ "docs_url": "https://docs.knock.app/api-reference/users/list_schedules",
+ "columns": {
+ "id": "Unique identifier for the schedule.",
+ "workflow": "The key of the workflow the schedule is applied to.",
+ "recipient": "The recipient the schedule runs for.",
+ "actor": "The user or object recorded as performing the action, when one was provided.",
+ "tenant": "The tenant the workflow is triggered for, when one was provided.",
+ "data": "Data passed into each workflow execution.",
+ "repeats": "The repeat rules for the schedule (frequency, interval, days, and time).",
+ "last_occurrence_at": "The last occurrence of the schedule.",
+ "next_occurrence_at": "The next occurrence of the schedule.",
+ "inserted_at": "Timestamp when the schedule was created.",
+ "updated_at": "Timestamp when the schedule was last updated.",
+ },
+ },
+ "message_events": {
+ "description": "A status change recorded on a message, such as sent, delivered, read, or link clicked.",
+ "docs_url": "https://docs.knock.app/api-reference/messages/list_events",
+ "columns": {
+ "id": "Unique identifier for the message event.",
+ "message_id": "The ID of the message the event belongs to.",
+ "message_inserted_at": "Timestamp when the message the event belongs to was created.",
+ "type": "The type of event (e.g. message.sent, message.delivered, message.read).",
+ "recipient": "The recipient of the message: a user ID string or an object reference.",
+ "data": "Additional data recorded with the event.",
+ "inserted_at": "Timestamp when the event was created.",
+ },
+ },
+ "message_delivery_logs": {
+ "description": "The request sent to a channel provider and the response it returned for one delivery attempt of a message.",
+ "docs_url": "https://docs.knock.app/api-reference/messages/list_delivery_logs",
+ "columns": {
+ "id": "Unique identifier for the delivery log.",
+ "message_id": "The ID of the message the delivery attempt belongs to.",
+ "message_inserted_at": "Timestamp when the message the delivery attempt belongs to was created.",
+ "environment_id": "The ID of the Knock environment the message was sent from.",
+ "service_name": "The name of the channel provider the request was sent to (e.g. Postmark).",
+ "request": "The HTTP request sent to the provider: method, host, path, query, headers, and body.",
+ "response": "The HTTP response returned by the provider: status, headers, and body.",
+ "inserted_at": "Timestamp when the delivery log was created.",
+ },
+ },
}
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 4bb714eb2249..fc29102c681c 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,16 +1,25 @@
import dataclasses
+from collections.abc import Iterator
from datetime import datetime
from typing import Any, Optional
+from urllib.parse import quote
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,
rest_api_resource,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ build_dependent_resource,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
JSONResponseCursorPaginator,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import EndpointResource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
+ ClientConfig,
+ 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.typings import SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.knock.settings import (
@@ -21,10 +30,17 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.knock.sett
DEFAULT_INCREMENTAL_START = "1970-01-01T00:00:00Z"
+NO_OBJECT_COLLECTIONS_ERROR = (
+ "The Knock objects table needs at least one object collection. "
+ "Add your collection keys in the source settings, then sync again."
+)
+
[email protected](frozen=True)
class KnockResumeConfig:
- after: str
+ after: str | None = None
+ # Set only by the objects table, which walks one collection after another.
+ collection: str | None = None
def _to_iso8601(value: Any) -> str:
@@ -33,7 +49,36 @@ def _to_iso8601(value: Any) -> str:
return str(value)
-def get_resource(endpoint: str, should_use_incremental_field: bool) -> EndpointResource:
+def parse_object_collections(object_collections: Optional[str]) -> list[str]:
+ if not object_collections:
+ return []
+ return list(dict.fromkeys(part.strip() for part in object_collections.split(",") if part.strip()))
+
+
+def _client_config(api_key: str) -> ClientConfig:
+ return {
+ "base_url": KNOCK_BASE_URL,
+ "auth": {
+ "type": "bearer",
+ "token": api_key,
+ },
+ "headers": {"Accept": "application/json"},
+ "paginator": JSONResponseCursorPaginator(cursor_path="page_info.after", cursor_param="after"),
+ }
+
+
+def _percent_encode_id(row: dict[str, Any]) -> dict[str, Any]:
+ # User ids are free-form strings and the fan-out binds them into the path unescaped.
+ row["id"] = quote(str(row["id"]), safe="")
+ return row
+
+
+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
+
+
+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}
@@ -55,7 +100,7 @@ def get_resource(endpoint: str, should_use_incremental_field: bool) -> EndpointR
if should_use_incremental_field
else "replace",
"endpoint": {
- "path": config.path,
+ "path": path or config.path,
"params": params,
"data_selector": config.data_selector,
# Fail loud if Knock ever changes the response envelope key instead of
@@ -66,6 +111,94 @@ def get_resource(endpoint: str, should_use_incremental_field: bool) -> EndpointR
}
+def _fanout_items(
+ api_key: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ db_incremental_field_last_value: Optional[Any],
+ should_use_incremental_field: bool,
+) -> Any:
+ endpoint_config = ENDPOINTS_CONFIG[endpoint]
+ fanout = endpoint_config.fanout
+ assert fanout is not None
+ parent_config = ENDPOINTS_CONFIG[fanout.parent_name]
+
+ if should_use_incremental_field and endpoint_config.incremental_param and db_incremental_field_last_value:
+ fanout = dataclasses.replace(
+ fanout, parent_params={endpoint_config.incremental_param: _to_iso8601(db_incremental_field_last_value)}
+ )
+
+ # 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(
+ endpoint_configs=ENDPOINTS_CONFIG,
+ child_endpoint=endpoint,
+ fanout=fanout,
+ client_config=_client_config(api_key),
+ path_format_values={},
+ team_id=team_id,
+ job_id=job_id,
+ db_incremental_field_last_value=None,
+ should_use_incremental_field=should_use_incremental_field,
+ 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},
+ parent_data_map=_percent_encode_id if fanout.parent_name == "users" else None,
+ page_size_param="page_size",
+ )
+
+
+def _objects_items(
+ api_key: str,
+ collections: list[str],
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[KnockResumeConfig],
+) -> Iterator[Any]:
+ start_index = 0
+ 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)
+ start_after = resume_config.after
+
+ for index in range(start_index, len(collections)):
+ collection = collections[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))
+
+ def save_checkpoint(state: Optional[dict[str, Any]], _collection: str = collection) -> None:
+ if state and state.get("cursor"):
+ resumable_source_manager.save_state(
+ KnockResumeConfig(after=str(state["cursor"]), collection=_collection)
+ )
+
+ 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='')}",
+ )
+ ],
+ }
+ yield from rest_api_resource(
+ config,
+ team_id,
+ job_id,
+ None,
+ resume_hook=save_checkpoint,
+ initial_paginator_state={"cursor": after} if after else None,
+ )
+
+
def knock_source(
api_key: str,
endpoint: str,
@@ -74,49 +207,55 @@ def knock_source(
resumable_source_manager: ResumableSourceManager[KnockResumeConfig],
db_incremental_field_last_value: Optional[Any],
should_use_incremental_field: bool = False,
+ object_collections: Optional[str] = None,
) -> SourceResponse:
endpoint_config = ENDPOINTS_CONFIG[endpoint]
- config: RESTAPIConfig = {
- "client": {
- "base_url": KNOCK_BASE_URL,
- "auth": {
- "type": "bearer",
- "token": api_key,
- },
- "headers": {"Accept": "application/json"},
- "paginator": JSONResponseCursorPaginator(cursor_path="page_info.after", cursor_param="after"),
- },
- "resource_defaults": {},
- "resources": [get_resource(endpoint, should_use_incremental_field)],
- }
+ items: Any
+ if endpoint_config.fanout is not None:
+ resource = _fanout_items(
+ 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)
+ else:
+ config: RESTAPIConfig = {
+ "client": _client_config(api_key),
+ "resource_defaults": {},
+ "resources": [get_resource(endpoint, should_use_incremental_field)],
+ }
- initial_paginator_state: Optional[dict[str, Any]] = None
- if resumable_source_manager.can_resume():
- resume_config = resumable_source_manager.load_state()
- if resume_config is not None:
- initial_paginator_state = {"cursor": resume_config.after}
-
- def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
- # Only persist when there's a next page to resume to; the Redis TTL
- # handles cleanup on completion.
- if state and state.get("cursor"):
- resumable_source_manager.save_state(KnockResumeConfig(after=str(state["cursor"])))
-
- resource = rest_api_resource(
- config,
- team_id,
- job_id,
- db_incremental_field_last_value,
- resume_hook=save_checkpoint,
- initial_paginator_state=initial_paginator_state,
- )
+ initial_paginator_state: Optional[dict[str, Any]] = None
+ if resumable_source_manager.can_resume():
+ resume_config = resumable_source_manager.load_state()
+ if resume_config is not None and resume_config.after:
+ initial_paginator_state = {"cursor": resume_config.after}
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ # Only persist when there's a next page to resume to; the Redis TTL
+ # handles cleanup on completion.
+ if state and state.get("cursor"):
+ resumable_source_manager.save_state(KnockResumeConfig(after=str(state["cursor"])))
+
+ resource = rest_api_resource(
+ config,
+ team_id,
+ job_id,
+ db_incremental_field_last_value,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )
+ items = lambda: resource
has_partition_key = endpoint_config.partition_key is not None
return SourceResponse(
name=endpoint,
- items=lambda: resource,
+ items=items,
primary_keys=list(endpoint_config.primary_keys),
partition_count=1 if has_partition_key else None,
partition_size=1 if has_partition_key else None,
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 21984acbd142..299f166c2a65 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
@@ -1,5 +1,9 @@
from dataclasses import dataclass, field
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ DependentEndpointConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import ResponseAction
from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SortMode
from products.warehouse_sources.backend.types import IncrementalField
@@ -12,6 +16,7 @@ KNOCK_PAGE_SIZE = 50
@dataclass(frozen=True)
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).
@@ -23,6 +28,33 @@ class KnockEndpointConfig:
# Stable datetime field to partition on; None disables partitioning.
partition_key: str | None = None
sort_mode: SortMode = "desc"
+ # Set on an endpoint reached by fanning out over a parent list endpoint, one child
+ # request per parent row.
+ fanout: DependentEndpointConfig | None = None
+ # Cleared for a table too expensive to sync unless the user asks for it.
+ should_sync_default: bool = True
+ default_incremental_lookback_seconds: int | None = None
+ page_size: int = KNOCK_PAGE_SIZE
+
+ @property
+ def default_incremental_field(self) -> str | None:
+ return self.incremental_fields[0]["field"] if self.incremental_fields else None
+
+
+# A parent deleted between the parent listing and its child fetch 404s; skip it rather
+# than failing the whole fan-out.
+_SKIP_DELETED_PARENT: list[ResponseAction] = [{"status_code": 404, "action": "ignore"}]
+
+
+def _message_fanout() -> DependentEndpointConfig:
+ return DependentEndpointConfig(
+ parent_name="messages",
+ resolve_param="message_id",
+ resolve_field="id",
+ include_from_parent=["id", "inserted_at"],
+ parent_field_renames={"id": "message_id", "inserted_at": "message_inserted_at"},
+ child_response_actions=_SKIP_DELETED_PARENT,
+ )
# Knock's list endpoints document "most recent first" ordering where they state one at
@@ -33,6 +65,7 @@ ENDPOINTS_CONFIG: dict[str, KnockEndpointConfig] = {
# Message delivery log — the highest-volume stream. `inserted_at[gte]` is a
# documented server-side filter, so incremental sync genuinely reduces pages.
"messages": KnockEndpointConfig(
+ name="messages",
path="/v1/messages",
data_selector="items",
incremental_fields=[incremental_field("inserted_at")],
@@ -42,24 +75,80 @@ ENDPOINTS_CONFIG: dict[str, KnockEndpointConfig] = {
# Identified recipients. No server-side updated-since filter exists, so full
# refresh only. `created_at` is nullable on users, so no partition key.
"users": KnockEndpointConfig(
+ name="users",
path="/v1/users",
data_selector="entries",
),
# Tenants (per-customer notification scoping). Small table, no server-side
# timestamp filter — full refresh only.
"tenants": KnockEndpointConfig(
+ name="tenants",
path="/v1/tenants",
data_selector="entries",
),
# Per-recipient workflow executions. `starting_at` is a documented server-side
# filter on when the run started, which tracks `inserted_at`.
"workflow_recipient_runs": KnockEndpointConfig(
+ name="workflow_recipient_runs",
path="/v1/workflow_recipient_runs",
data_selector="items",
incremental_fields=[incremental_field("inserted_at")],
incremental_param="starting_at",
partition_key="inserted_at",
),
+ # Non-user recipients. Knock has no endpoint that lists collections, so the table
+ # walks the collection names the user configures on the source. Object ids are only
+ # unique within a collection, and `created_at` is nullable, so no partition key.
+ "objects": KnockEndpointConfig(
+ name="objects",
+ path="/v1/objects/{collection}",
+ data_selector="entries",
+ primary_keys=("collection", "id"),
+ ),
+ # `GET /v1/schedules` requires a workflow key and the secret API key cannot list
+ # workflows, so schedules are read per user instead. Schedules whose recipient is an
+ # object are not reachable this way.
+ "schedules": KnockEndpointConfig(
+ name="schedules",
+ path="/v1/users/{user_id}/schedules",
+ data_selector="entries",
+ partition_key="inserted_at",
+ fanout=DependentEndpointConfig(
+ parent_name="users",
+ resolve_param="user_id",
+ resolve_field="id",
+ include_from_parent=[],
+ child_response_actions=_SKIP_DELETED_PARENT,
+ ),
+ should_sync_default=False,
+ ),
+ # Per-message child endpoints take no timestamp filter, so incremental syncs window
+ # the parent `messages` walk on the parent's `inserted_at` instead. The lookback picks
+ # up events and retries that land on a message after it was created.
+ "message_events": KnockEndpointConfig(
+ name="message_events",
+ path="/v1/messages/{message_id}/events",
+ 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,
+ default_incremental_lookback_seconds=3 * 24 * 60 * 60,
+ ),
+ "message_delivery_logs": KnockEndpointConfig(
+ name="message_delivery_logs",
+ path="/v1/messages/{message_id}/delivery_logs",
+ 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,
+ default_incremental_lookback_seconds=24 * 60 * 60,
+ ),
}
ENDPOINTS = tuple(ENDPOINTS_CONFIG.keys())
@@ -67,3 +156,9 @@ ENDPOINTS = tuple(ENDPOINTS_CONFIG.keys())
INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
name: config.incremental_fields for name, config in ENDPOINTS_CONFIG.items()
}
+
+INCREMENTAL_LOOKBACK_SECONDS: dict[str, int] = {
+ name: config.default_incremental_lookback_seconds
+ for name, config in ENDPOINTS_CONFIG.items()
+ if config.default_incremental_lookback_seconds is not None
+}
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 137705ef7f73..6f31a566e7c2 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
@@ -20,13 +20,17 @@ 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_OBJECT_COLLECTIONS_ERROR,
KnockResumeConfig,
knock_source,
+ parse_object_collections,
validate_credentials as validate_knock_credentials,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.knock.settings import (
ENDPOINTS,
+ ENDPOINTS_CONFIG,
INCREMENTAL_FIELDS,
+ INCREMENTAL_LOOKBACK_SECONDS,
)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@@ -44,6 +48,7 @@ class KnockSource(ResumableSource[KnockSourceConfig, KnockResumeConfig]):
return {
"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,
}
def get_canonical_descriptions(self) -> CanonicalDescriptions:
@@ -62,7 +67,15 @@ class KnockSource(ResumableSource[KnockSourceConfig, KnockResumeConfig]):
force_refresh: bool = False,
api_version: str | None = None,
) -> list[SourceSchema]:
- return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)
+ 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))
+ return build_endpoint_schemas(
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ names,
+ should_sync_default=should_sync_default,
+ default_incremental_lookback_seconds=INCREMENTAL_LOOKBACK_SECONDS,
+ )
def validate_credentials(
self, config: KnockSourceConfig, team_id: int, schema_name: Optional[str] = None, api_version: str | None = None
@@ -85,6 +98,7 @@ class KnockSource(ResumableSource[KnockSourceConfig, KnockResumeConfig]):
job_id=inputs.job_id,
resumable_source_manager=resumable_source_manager,
should_use_incremental_field=inputs.should_use_incremental_field,
+ object_collections=config.object_collections,
db_incremental_field_last_value=inputs.db_incremental_field_last_value
if inputs.should_use_incremental_field
else None,
@@ -112,6 +126,15 @@ class KnockSource(ResumableSource[KnockSourceConfig, KnockResumeConfig]):
placeholder="sk_...",
secret=True,
),
+ SourceFieldInputConfig(
+ name="object_collections",
+ label="Object collections",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="accounts, projects",
+ 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.",
+ ),
],
),
)
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 54c3bc5b897e..0331ad42e7b5 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
@@ -3,6 +3,7 @@ from collections.abc import Iterable
from datetime import datetime
from typing import Any, Optional, cast
+import pytest
from unittest.mock import MagicMock, patch
from parameterized import parameterized
@@ -11,6 +12,7 @@ from requests import Response
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
from products.warehouse_sources.backend.temporal.data_imports.sources.knock.knock import (
+ NO_OBJECT_COLLECTIONS_ERROR,
KnockResumeConfig,
get_resource,
knock_source,
@@ -62,6 +64,8 @@ class TestKnockSourceTransport:
responses: list[Response],
should_use_incremental_field: bool = False,
db_incremental_field_last_value: Optional[Any] = None,
+ object_collections: Optional[str] = None,
+ sent_urls: Optional[list[str]] = None,
) -> tuple[SourceResponse, list[dict[str, Any]], list[dict[str, Any]]]:
# Capture shallow copies of request.params at send-time: the Request object is
# mutated in place by the paginator between pages.
@@ -70,6 +74,8 @@ class TestKnockSourceTransport:
def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:
sent_params.append(dict(request.params or {}))
+ if sent_urls is not None:
+ sent_urls.append(request.url)
return next(response_iter)
with patch(
@@ -88,6 +94,7 @@ class TestKnockSourceTransport:
resumable_source_manager=manager,
db_incremental_field_last_value=db_incremental_field_last_value,
should_use_incremental_field=should_use_incremental_field,
+ object_collections=object_collections,
)
rows = [row for chunk in cast(Iterable[Any], source_response.items()) for row in chunk]
return source_response, sent_params, rows
@@ -163,25 +170,153 @@ class TestKnockSourceTransport:
@parameterized.expand(
[
- ("messages", ["inserted_at"]),
- ("workflow_recipient_runs", ["inserted_at"]),
- ("users", None),
- ("tenants", None),
+ ("messages", ["inserted_at"], ["id"]),
+ ("workflow_recipient_runs", ["inserted_at"], ["id"]),
+ ("users", None, ["id"]),
+ ("tenants", None, ["id"]),
+ # Child ids are only guaranteed unique per parent, so the parent id joins the key.
+ ("message_events", ["inserted_at"], ["message_id", "id"]),
+ ("message_delivery_logs", ["inserted_at"], ["message_id", "id"]),
+ ("objects", None, ["collection", "id"]),
]
)
- def test_source_response_partitioning_and_sort_mode(self, endpoint: str, partition_keys: list[str] | None) -> None:
+ def test_source_response_partitioning_and_sort_mode(
+ self, endpoint: str, partition_keys: list[str] | None, primary_keys: list[str]
+ ) -> None:
manager = MagicMock(spec=ResumableSourceManager)
manager.can_resume.return_value = False
- source_response, _, _ = self._drive(endpoint, manager, [_page(endpoint, [], after=None)])
+ fanout = ENDPOINTS_CONFIG[endpoint].fanout
+ first_page = _page(fanout.parent_name if fanout else endpoint, [], after=None)
+ source_response, _, _ = self._drive(endpoint, manager, [first_page], object_collections="accounts")
- assert source_response.primary_keys == ["id"]
+ assert source_response.primary_keys == primary_keys
# Knock lists return newest-first, so the pipeline must not checkpoint the
# watermark per batch.
assert source_response.sort_mode == "desc"
assert source_response.partition_keys == partition_keys
assert source_response.partition_mode == ("datetime" if partition_keys else None)
+ @parameterized.expand(
+ [
+ ("message_events", "events"),
+ ("message_delivery_logs", "delivery_logs"),
+ ]
+ )
+ def test_message_fanout_windows_parent_walk_and_tags_child_rows(self, endpoint: str, child_path: str) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+ sent_urls: list[str] = []
+
+ responses = [
+ _page("messages", [{"id": "m1", "inserted_at": "2026-06-01T00:00:00Z"}], after="cursor-1"),
+ _make_http_response({"items": [{"id": "e1", "inserted_at": "2026-06-01T00:00:05Z"}], "page_info": {}}),
+ _page("messages", [{"id": "m2", "inserted_at": "2026-06-02T00:00:00Z"}], after=None),
+ _make_http_response({"items": [{"id": "e1", "inserted_at": "2026-06-02T00:00:05Z"}], "page_info": {}}),
+ ]
+ _, sent_params, rows = self._drive(
+ endpoint,
+ manager,
+ responses,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 5, 1, 12, 30),
+ sent_urls=sent_urls,
+ )
+
+ assert [url.rsplit("/v1/", 1)[1] for url in sent_urls] == [
+ "messages",
+ f"messages/m1/{child_path}",
+ "messages",
+ f"messages/m2/{child_path}",
+ ]
+ # The child endpoints take no timestamp filter, so the watermark bounds the parent walk.
+ assert sent_params[0]["inserted_at[gte]"] == "2026-05-01T12:30:00"
+ assert sent_params[2]["after"] == "cursor-1"
+ assert all("inserted_at[gte]" not in params for params in sent_params[1::2])
+ assert [(r["message_id"], r["id"], r["message_inserted_at"]) for r in rows] == [
+ ("m1", "e1", "2026-06-01T00:00:00Z"),
+ ("m2", "e1", "2026-06-02T00:00:00Z"),
+ ]
+
+ def test_message_fanout_full_refresh_walks_every_message(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [
+ _page("messages", [{"id": "m1", "inserted_at": "2026-06-01T00:00:00Z"}], after=None),
+ _make_http_response({"items": [{"id": "e1"}], "page_info": {}}),
+ ]
+ _, sent_params, _ = self._drive("message_events", manager, responses)
+
+ assert set(sent_params[0]) == {"page_size"}
+
+ def test_schedules_fan_out_over_percent_encoded_user_ids(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+ sent_urls: list[str] = []
+
+ responses = [
+ _page("users", [{"id": "team/jane"}], after=None),
+ _make_http_response({"entries": [{"id": "s1"}], "page_info": {}}),
+ ]
+ _, _, rows = self._drive("schedules", manager, responses, sent_urls=sent_urls)
+
+ assert sent_urls[1].endswith("/v1/users/team%2Fjane/schedules")
+ assert [row["id"] for row in rows] == ["s1"]
+
+ def test_objects_walk_each_configured_collection(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+ sent_urls: list[str] = []
+
+ responses = [
+ _page("objects", [{"id": "a1", "collection": "accounts"}], after="cursor-1"),
+ _page("objects", [{"id": "a2", "collection": "accounts"}], after=None),
+ _page("objects", [{"id": "p1", "collection": "projects"}], after=None),
+ ]
+ _, sent_params, rows = self._drive(
+ "objects", manager, responses, object_collections=" accounts, projects,accounts ", sent_urls=sent_urls
+ )
+
+ assert [url.rsplit("/v1/", 1)[1] for url in sent_urls] == ["objects/accounts"] * 2 + ["objects/projects"]
+ assert [p.get("after") for p in sent_params] == [None, "cursor-1", None]
+ assert [row["id"] for row in rows] == ["a1", "a2", "p1"]
+ saved = [call.args[0] for call in manager.save_state.call_args_list]
+ assert saved == [
+ KnockResumeConfig(collection="accounts"),
+ KnockResumeConfig(after="cursor-1", collection="accounts"),
+ KnockResumeConfig(collection="projects"),
+ ]
+
+ def test_objects_resume_skips_finished_collections(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = KnockResumeConfig(after="cursor-7", collection="projects")
+ sent_urls: list[str] = []
+
+ responses = [_page("objects", [{"id": "p8", "collection": "projects"}], after=None)]
+ _, sent_params, _ = self._drive(
+ "objects", manager, responses, object_collections="accounts,projects", sent_urls=sent_urls
+ )
+
+ assert [url.rsplit("/v1/", 1)[1] for url in sent_urls] == ["objects/projects"]
+ assert sent_params[0]["after"] == "cursor-7"
+
+ @parameterized.expand([(None,), ("",), (" , ",)])
+ def test_objects_without_collections_fails_with_actionable_error(self, object_collections: str | None) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+
+ with pytest.raises(ValueError, match=NO_OBJECT_COLLECTIONS_ERROR):
+ knock_source(
+ api_key="sk_test",
+ endpoint="objects",
+ team_id=123,
+ job_id="test_job",
+ resumable_source_manager=manager,
+ db_incremental_field_last_value=None,
+ object_collections=object_collections,
+ )
+
class TestValidateCredentials:
@parameterized.expand(
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 e362d329883f..7546c8506ac5 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
@@ -2,13 +2,16 @@ from typing import Any
from unittest.mock import MagicMock
+from parameterized import parameterized
+
from products.warehouse_sources.backend.temporal.data_imports.sources.knock.settings import ENDPOINTS
from products.warehouse_sources.backend.temporal.data_imports.sources.knock.source import KnockSource
-def _config(api_key: str = "sk_test") -> Any:
+def _config(api_key: str = "sk_test", object_collections: str | None = None) -> Any:
config = MagicMock()
config.api_key = api_key
+ config.object_collections = object_collections
return config
@@ -17,13 +20,24 @@ class TestGetSchemas:
schemas = {s.name: s for s in KnockSource().get_schemas(_config(), team_id=1)}
assert set(schemas) == set(ENDPOINTS)
# Only messages (inserted_at[gte]) and workflow_recipient_runs (starting_at)
- # have a genuine server-side timestamp filter.
+ # have a genuine server-side timestamp filter; the message fan-outs ride the
+ # messages filter on their parent walk.
assert {name for name, s in schemas.items() if s.supports_incremental} == {
"messages",
"workflow_recipient_runs",
+ "message_events",
+ "message_delivery_logs",
}
assert [f["field"] for f in schemas["messages"].incremental_fields] == ["inserted_at"]
assert [f["field"] for f in schemas["workflow_recipient_runs"].incremental_fields] == ["inserted_at"]
+ assert [f["field"] for f in schemas["message_events"].incremental_fields] == ["message_inserted_at"]
+
+ @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
+ ) -> 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
def test_lists_tables_without_credentials(self) -> None:
# Static endpoint catalog (no I/O) — public docs render the table list.