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): Decagon Agent Assist actions export table (#80183)

jake sciottod9466982125e
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/decagon/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/decagon/canonical_descriptions.py
index c9b6e7314795..691adad18e46 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/decagon/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/decagon/canonical_descriptions.py
@@ -21,4 +21,21 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"metadata": "Custom metadata attached to the conversation (e.g. user attributes).",
},
},
+ "agent_assist_actions": {
+ "description": (
+ "An Agent Assist action performed by a human support agent, one row per action. "
+ "An append-only event stream used to measure agent adoption of AI assist features."
+ ),
+ "docs_url": "https://docs.decagon.ai/api-reference/getting-started",
+ "columns": {
+ "created_at": "Timestamp at which the action was performed.",
+ "agent_name": "Name of the human support agent who performed the action.",
+ "action_name": "Name of the Agent Assist action that was performed.",
+ "ticket_id": "Identifier of the support ticket the action relates to.",
+ "detail": (
+ "Additional detail about the action, including the id of the conversation it "
+ "relates to. Present only when detail export is enabled for the team."
+ ),
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/decagon/decagon.py b/products/warehouse_sources/backend/temporal/data_imports/sources/decagon/decagon.py
index db8d1fb9d422..6e3e8d81798e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/decagon/decagon.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/decagon/decagon.py
@@ -11,7 +11,10 @@ from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_ex
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.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.decagon.settings import DECAGON_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.decagon.settings import (
+ DECAGON_ENDPOINTS,
+ DecagonEndpointConfig,
+)
DECAGON_BASE_URL = "https://api.decagon.ai"
@@ -20,13 +23,6 @@ REQUEST_TIMEOUT_SECONDS = 60
# Server-side page size of /conversation/export, per Decagon's docs.
DECAGON_PAGE_SIZE = 100
-# Decagon's export reference names the next-page response field three different ways:
-# `next_page_cursor` in the parameter prose, `next_cursor` in the official example code,
-# and `next_page_updated_after` in the example response. Production responses carry no
-# usable `next_page_cursor` (reading only that name made the walk stop after one page),
-# so accept every documented name. All of them feed the same `cursor` request param.
-NEXT_CURSOR_KEYS = ("next_page_cursor", "next_cursor", "next_page_updated_after")
-
# Decagon enforces a hard limit of 1 request/second across all API endpoints and
# automatically IP-bans gross violators, so requests are spaced client-side rather
# than relying on 429 backoff alone.
@@ -49,14 +45,22 @@ class DecagonRetryableError(Exception):
@dataclasses.dataclass
class DecagonResumeConfig:
- # The next-page export cursor returned by Decagon (see NEXT_CURSOR_KEYS).
- cursor: str
- # The incremental window the cursor belongs to. A resumed run must reissue exactly
- # these params alongside the cursor: the stored watermark can advance while a walk
- # is in flight, and pairing a recomputed min_timestamp with a cursor positioned
- # inside the old window would skip rows at the window boundary. Optional so states
- # saved before these fields existed still parse.
- min_timestamp: Optional[int] = None
+ # Position of the next unfetched page, one field per pagination mode: the next-page
+ # cursor ("cursor"), the next page number ("page"), or the next row offset ("offset").
+ cursor: Optional[str] = None
+ page: Optional[int] = None
+ offset: Optional[int] = None
+ # Rows already received across the walk ("page" mode). Counts what the server actually
+ # returned rather than page * page_size, so termination against the reported total
+ # stays exact even if the server caps the requested page size.
+ rows_walked: Optional[int] = None
+ # The incremental window the position belongs to, in the format the endpoint's
+ # incremental_param takes (the field is named after the exports' param). A resumed
+ # run must reissue exactly this alongside the position: the stored watermark can
+ # advance while a walk is in flight, and recomputing the window would pair a fresh
+ # lower bound with a position inside the old window. Optional so states saved before
+ # these fields existed still parse.
+ min_timestamp: Optional[int | str] = None
timestamp_filter: Optional[str] = None
@@ -83,12 +87,12 @@ def _get_headers(api_key: str) -> dict[str, str]:
def _to_epoch_seconds(value: Any) -> int:
- """Coerce an incremental watermark to Unix epoch seconds for the `min_timestamp` param.
+ """Coerce an incremental watermark to Unix epoch seconds.
- The watermark is stored from the ISO 8601 `updated_at` column, but the pipeline may hand
- it back as a datetime, a date, or an epoch number depending on how it round-tripped
- through storage. int() truncates any sub-second part, so the boundary second is
- re-fetched and the merge dedupes it on the primary key.
+ The watermark is stored from an ISO 8601 column, but the pipeline may hand it back as
+ a datetime, a date, or an epoch number depending on how it round-tripped through
+ storage. int() truncates any sub-second part, so the boundary second is re-fetched and
+ a merge dedupes it on the primary key.
"""
if isinstance(value, datetime):
dt = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)
@@ -98,10 +102,16 @@ def _to_epoch_seconds(value: Any) -> int:
return int(value)
-def _next_cursor(data: dict[str, Any]) -> Optional[str]:
+def _incremental_window_value(config: DecagonEndpointConfig, value: Any) -> int | str:
+ if config.incremental_param_format == "iso8601":
+ return datetime.fromtimestamp(_to_epoch_seconds(value), UTC).isoformat()
+ return _to_epoch_seconds(value)
+
+
+def _next_cursor(data: dict[str, Any], cursor_keys: tuple[str, ...]) -> Optional[str]:
# Skip falsy values rather than returning the first key present: a response that
# carries `next_page_cursor: null` alongside a populated alias must keep paginating.
- for key in NEXT_CURSOR_KEYS:
+ for key in cursor_keys:
value = data.get(key)
if value:
# Cursors can be integers (a last-updated epoch watermark in Decagon's example
@@ -111,7 +121,7 @@ def _next_cursor(data: dict[str, Any]) -> Optional[str]:
def validate_credentials(api_key: str) -> bool:
- """Probe the export endpoint (the only one this source calls) to confirm the key works."""
+ """Probe the conversations export (the cheapest authenticated read) to confirm the key works."""
try:
response = make_tracked_session(redact_values=(api_key,)).get(
f"{DECAGON_BASE_URL}/conversation/export",
@@ -139,30 +149,49 @@ def get_rows(
throttle = RequestThrottle()
resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
- cursor: Optional[str] = resume_config.cursor if resume_config else None
- min_timestamp: Optional[int] = None
+ cursor: Optional[str] = None
+ page = 1
+ offset = 0
+ rows_walked = 0
+ window_value: Optional[int | str] = None
timestamp_filter: Optional[str] = None
+
if resume_config:
- # Resume the walk exactly where it stopped: same window, same cursor. See the
+ cursor = resume_config.cursor
+ page = resume_config.page if resume_config.page is not None else 1
+ offset = resume_config.offset if resume_config.offset is not None else 0
+ rows_walked = resume_config.rows_walked if resume_config.rows_walked is not None else 0
+ # Resume the walk exactly where it stopped: same window, same position. See the
# DecagonResumeConfig field comments for why the window is not recomputed here.
- min_timestamp = resume_config.min_timestamp
+ window_value = resume_config.min_timestamp
timestamp_filter = resume_config.timestamp_filter
- logger.debug(f"Decagon: resuming {endpoint} from saved cursor")
- elif should_use_incremental_field and db_incremental_field_last_value is not None and incremental_field:
- filter_name = TIMESTAMP_FILTER_BY_FIELD.get(incremental_field)
- if filter_name:
- # min_timestamp takes epoch seconds (the vendor's own example is
- # `?min_timestamp=1782864000`). Whether the bound is inclusive is undocumented;
- # the truncation in _to_epoch_seconds re-fetches the boundary second either way,
- # and the merge dedupes it on the primary key.
- min_timestamp = _to_epoch_seconds(db_incremental_field_last_value)
- timestamp_filter = filter_name
+ logger.debug(f"Decagon: resuming {endpoint} from saved state")
+ elif (
+ should_use_incremental_field
+ and db_incremental_field_last_value is not None
+ and incremental_field
+ and config.incremental_param
+ ):
+ if config.timestamp_filter_param:
+ filter_name = TIMESTAMP_FILTER_BY_FIELD.get(incremental_field)
+ if filter_name:
+ window_value = _incremental_window_value(config, db_incremental_field_last_value)
+ timestamp_filter = filter_name
+ else:
+ logger.warning(
+ f"Decagon: incremental field {incremental_field} has no server-side timestamp "
+ f"filter; walking the full export instead"
+ )
else:
- logger.warning(
- f"Decagon: incremental field {incremental_field} has no server-side timestamp "
- f"filter; walking the full export instead"
- )
+ window_value = _incremental_window_value(config, db_incremental_field_last_value)
+ if config.primary_keys is None and isinstance(window_value, int):
+ # Keyless streams append without a merge to dedupe re-fetched rows, so an
+ # inclusive bound would re-import the watermark second on every sync and
+ # inflate counts indefinitely. Advance past it instead: an event landing in
+ # that same second after the walk read it is the rarer failure, and a full
+ # refresh trues the table up.
+ window_value += 1
@retry(
retry=retry_if_exception_type((DecagonRetryableError, requests.ReadTimeout, requests.ConnectionError)),
@@ -184,69 +213,136 @@ def get_rows(
return response.json()
- # A conversation that receives new messages re-enters the export stream on a later
- # page, so a single walk can emit the same conversation twice. Full-refresh writes
- # are plain appends (no primary-key merge), so re-emissions are skipped client-side;
- # the next sync picks up the newer version. Incremental writes merge on the primary
- # key and the writer keeps the last occurrence per key within a batch, so there the
- # re-emission must flow through (dropping it would keep the stale version) and the
- # set, which grows unboundedly across a large export, is not needed.
- seen_ids: Optional[set[str]] = None if should_use_incremental_field else set()
+ def save_position(**position: Any) -> None:
+ # Persisted only after a yield, so a crash re-yields the last batch rather than
+ # skipping it (the duplicate rows a resumed re-yield can produce are bounded to
+ # one page, and are cleaned up by the next full refresh or merged away on the
+ # primary key).
+ resumable_source_manager.save_state(
+ DecagonResumeConfig(min_timestamp=window_value, timestamp_filter=timestamp_filter, **position)
+ )
+
+ # A row can re-enter the stream on a later page of one walk (a conversation that
+ # receives new messages re-enters the export). Full-refresh writes are plain appends
+ # (no primary-key merge), so re-emissions are skipped client-side; the next sync picks
+ # up the newer version. Incremental writes merge on the primary key and the writer
+ # keeps the last occurrence per key within a batch, so there the re-emission must flow
+ # through (dropping it would keep the stale version) and the set, which grows
+ # unboundedly across a large export, is not needed. Keyless streams have nothing to
+ # dedupe on and always flow through.
+ seen_keys: Optional[set[tuple[Any, ...]]] = (
+ set() if config.primary_keys is not None and not should_use_incremental_field else None
+ )
while True:
- # An omitted cursor starts the stream at the oldest conversations.
- params: dict[str, str] = {"cursor": cursor} if cursor else {}
- if min_timestamp is not None and timestamp_filter is not None:
- params["min_timestamp"] = str(min_timestamp)
- params["timestamp_filter"] = timestamp_filter
- data = fetch_page(params)
+ params: dict[str, str] = dict(config.extra_params)
+ if config.pagination == "cursor":
+ # An omitted cursor starts the stream at the oldest rows.
+ if cursor:
+ params["cursor"] = cursor
+ elif config.pagination == "page":
+ params["page"] = str(page)
+ if config.page_size is not None:
+ params["page_size"] = str(config.page_size)
+ elif config.pagination == "offset":
+ params["offset"] = str(offset)
+ if config.page_size is not None:
+ params["limit"] = str(config.page_size)
+ if window_value is not None and config.incremental_param:
+ params[config.incremental_param] = str(window_value)
+ if timestamp_filter and config.timestamp_filter_param:
+ params[config.timestamp_filter_param] = timestamp_filter
+ data = fetch_page(params)
items = data.get(config.data_key) or []
- next_cursor = _next_cursor(data)
fresh: list[dict[str, Any]] = []
for item in items:
- # Direct access on purpose: conversation_id is the primary key, so a row
- # without one should fail the sync loudly rather than land in the warehouse
- # unkeyed and undeduplicatable.
- item_id = item["conversation_id"]
- if seen_ids is not None:
- if item_id in seen_ids:
- continue
- seen_ids.add(item_id)
+ if config.primary_keys is not None:
+ # Direct access on purpose: these fields are the primary key, so a row
+ # missing one should fail the sync loudly rather than land in the
+ # warehouse unkeyed and undeduplicatable.
+ key = tuple(item[k] for k in config.primary_keys)
+ if seen_keys is not None:
+ if key in seen_keys:
+ continue
+ seen_keys.add(key)
fresh.append(item)
+ if config.pagination == "single":
+ if fresh:
+ yield fresh
+ break
+
+ if config.pagination == "cursor":
+ next_cursor = _next_cursor(data, config.next_cursor_keys or ())
+ more = data.get(config.has_more_key) if config.has_more_key else None
+
+ if fresh:
+ yield fresh
+ if next_cursor and more is not False:
+ save_position(cursor=next_cursor)
+
+ if config.has_more_key is not None and not more:
+ break
+ # The next-page cursor is null once the stream is exhausted. Also stop if the
+ # server ever returns the cursor we just used, to guard against spinning on
+ # one page forever.
+ if not next_cursor or next_cursor == cursor:
+ if config.has_more_key is None and not next_cursor and len(items) >= DECAGON_PAGE_SIZE:
+ # A full page that ends the walk is legitimate only when the total row
+ # count happens to be a multiple of the page size; far more often it means
+ # Decagon renamed the pagination field again and rows were truncated.
+ logger.warning(
+ f"Decagon: {endpoint} stream ended on a full page of {len(items)} items without a "
+ f"next-page cursor (response keys: {sorted(data.keys())}). If the synced row count "
+ f"looks truncated, check the export pagination contract."
+ )
+ break
+
+ cursor = next_cursor
+ continue
+
+ total = data.get(config.total_key) if config.total_key else None
+
+ if config.pagination == "page":
+ # Terminate against the reported total using rows actually received, which
+ # stays exact even if the server caps the requested page size. A missing or
+ # malformed total falls back to short-page termination, the only end signal
+ # left besides an empty page.
+ rows_walked += len(items)
+ if isinstance(total, int | float):
+ exhausted = not items or rows_walked >= total
+ else:
+ exhausted = not items or (config.page_size is not None and len(items) < config.page_size)
+ if fresh:
+ yield fresh
+ if not exhausted:
+ save_position(page=page + 1, rows_walked=rows_walked)
+ if exhausted:
+ break
+ page += 1
+ continue
+
+ # Offset mode: advance by the rows actually received rather than by page_size, so
+ # a server that caps `limit` below what we asked still walks every row. The offset
+ # itself is the cumulative row count, so the total check needs no separate counter.
+ next_offset = offset + len(items)
+ if isinstance(total, int | float):
+ exhausted = not items or next_offset >= total
+ else:
+ exhausted = not items or (config.page_size is not None and len(items) < config.page_size)
if fresh:
yield fresh
- # Save state only after yielding, so a crash re-yields the last batch rather
- # than skipping it (the duplicate rows a resumed re-yield can produce are
- # bounded to one page, and are cleaned up by the next full refresh or merged
- # away on the primary key).
- if next_cursor:
- resumable_source_manager.save_state(
- DecagonResumeConfig(
- cursor=next_cursor,
- min_timestamp=min_timestamp,
- timestamp_filter=timestamp_filter,
- )
- )
-
- # The next-page cursor is null once the stream is exhausted. Also stop if the
- # server ever returns the cursor we just used, to guard against spinning on
- # one page forever.
- if not next_cursor or next_cursor == cursor:
- if not next_cursor and len(items) >= DECAGON_PAGE_SIZE:
- # A full page that ends the walk is legitimate only when the total row
- # count happens to be a multiple of the page size; far more often it means
- # Decagon renamed the pagination field again and rows were truncated.
- logger.warning(
- f"Decagon: {endpoint} stream ended on a full page of {len(items)} items without a "
- f"next-page cursor (response keys: {sorted(data.keys())}). If the synced row count "
- f"looks truncated, check the export pagination contract."
- )
+ if not exhausted:
+ save_position(offset=next_offset)
+ if exhausted:
break
+ offset = next_offset
- cursor = next_cursor
+ # Walked to completion, so drop any checkpoint: a retried attempt of this job would
+ # otherwise resume at the final page and append its rows again.
+ resumable_source_manager.clear_state()
def decagon_source(
@@ -259,6 +355,7 @@ def decagon_source(
incremental_field: Optional[str] = None,
) -> SourceResponse:
config = DECAGON_ENDPOINTS[endpoint]
+ partitioned = config.partition_key is not None
return SourceResponse(
name=endpoint,
@@ -272,12 +369,10 @@ def decagon_source(
incremental_field=incremental_field,
),
primary_keys=config.primary_keys,
- partition_count=1,
- partition_size=1,
- partition_mode="datetime",
- partition_format="month",
- partition_keys=[config.partition_key],
- # The export walks oldest to newest (`order` defaults to asc), so the pipeline can
- # checkpoint the incremental watermark as batches arrive.
- sort_mode="asc",
+ partition_count=1 if partitioned else None,
+ partition_size=1 if partitioned else None,
+ partition_mode="datetime" if partitioned else None,
+ partition_format="month" if partitioned else None,
+ partition_keys=[config.partition_key] if config.partition_key is not None else None,
+ sort_mode=config.sort_mode,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/decagon/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/decagon/settings.py
index f1ea4c37fb8e..20622371e5de 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/decagon/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/decagon/settings.py
@@ -1,7 +1,28 @@
-from dataclasses import dataclass
+from dataclasses import dataclass, field
+from typing import Literal, Optional
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+# How a list endpoint is walked:
+# - "cursor": a `cursor` request param fed from a next-page response field.
+# - "page": `page`/`page_size` request params, terminating on the response's total.
+# - "offset": `limit`/`offset` request params, terminating on the response's total.
+# - "single": one request returns the whole list, no pagination params.
+PaginationMode = Literal["cursor", "page", "offset", "single"]
+
+# Format of the value an endpoint's `incremental_param` takes. Decagon is not internally
+# consistent across endpoints: the exports take epoch seconds, and /admin_log/get types
+# its bounds loosely. Confirm per endpoint rather than generalizing.
+IncrementalParamFormat = Literal["epoch_seconds", "iso8601"]
+
+# Decagon's export reference names the conversations next-page response field three
+# different ways: `next_page_cursor` in the parameter prose, `next_cursor` in the official
+# example code, and `next_page_updated_after` in the example response. Production
+# responses carry no usable `next_page_cursor` (reading only that name made the walk stop
+# after one page), so accept every documented name. All of them feed the same `cursor`
+# request param.
+CONVERSATIONS_NEXT_CURSOR_KEYS = ("next_page_cursor", "next_cursor", "next_page_updated_after")
+
@dataclass
class DecagonEndpointConfig:
@@ -10,29 +31,60 @@ class DecagonEndpointConfig:
# Top-level key in the JSON response that holds the list of rows
# (e.g. `{"conversations": [...]}` -> `"conversations"`).
data_key: str
- primary_keys: list[str]
+ # None for streams with no documented unique id: they sync append-only, because a
+ # guessed composite key that turned out non-unique would silently merge distinct rows.
+ primary_keys: Optional[list[str]]
incremental_fields: list[IncrementalField]
- # Stable datetime field used for partitioning. Must never change for a row
- # (so `created_at`, never `updated_at`).
- partition_key: str
- # Whether the append sync type is offered alongside incremental. Streams whose
- # rows mutate in place must leave this False: appends would accumulate one copy
- # per mutation, and only a merge keeps the table at one row per primary key.
+ pagination: PaginationMode
+ # "cursor" mode: response fields that may carry the next-page cursor, tried in order.
+ next_cursor_keys: Optional[tuple[str, ...]] = None
+ # "cursor" mode: response field signalling whether more pages exist. When set, a falsy
+ # value ends the walk even if a cursor is present. None means the null cursor alone
+ # ends the walk.
+ has_more_key: Optional[str] = None
+ # "page"/"offset" modes: rows requested per page. None sends no size param and leaves
+ # the server default, in which case only an empty page ends the walk.
+ page_size: Optional[int] = None
+ # "page"/"offset" modes: response field carrying the total row count.
+ total_key: Optional[str] = None
+ # Stable datetime field used for partitioning, or None for tables with no timestamp.
+ # Must never change for a row (so `created_at`, never `updated_at`).
+ partition_key: Optional[str] = None
+ # Server-side query param that lower-bounds the incremental field, and the format its
+ # value takes. None means the endpoint has no server-side filter, so no incremental
+ # sync should be advertised for it.
+ incremental_param: Optional[str] = None
+ incremental_param_format: IncrementalParamFormat = "epoch_seconds"
+ # Param selecting which timestamp the bounds apply to (/conversation/export only).
+ timestamp_filter_param: Optional[str] = None
+ # Static query params always sent.
+ extra_params: dict[str, str] = field(default_factory=dict)
+ # Order rows arrive in when the endpoint documents one. "desc" is also the safe
+ # declaration for endpoints whose order is undocumented: the pipeline then defers the
+ # incremental watermark to the end of a successful run instead of checkpointing
+ # mid-run, so a wrong guess cannot make a resumed sync skip rows.
+ sort_mode: Literal["asc", "desc"] = "asc"
+ # Whether the append sync type is offered alongside incremental. Streams whose rows
+ # mutate in place must leave this False: appends would accumulate one copy per
+ # mutation, and only a merge keeps the table at one row per primary key.
supports_append: bool = False
+ # Whether the table is selected by default on a new source. False for tables that
+ # fan out row counts or sync data a team should opt into deliberately.
+ should_sync_default: bool = True
-# Decagon's syncable surface is a single stream: /conversation/export returns
-# conversations with their messages, CSAT ratings, tags, and metadata, up to 100
-# per page. Pagination is a `cursor` request param fed from a next-page response
-# field whose name varies across Decagon's own docs (see NEXT_CURSOR_KEYS in
-# decagon.py); it is null once the stream is exhausted. The export also accepts
-# min_timestamp/max_timestamp filters (epoch seconds), with `timestamp_filter`
-# selecting the field they bound: created_at (the default), updated_at, or
-# last_message_time. Rows always carry `updated_at` (ISO 8601), so the stream
-# syncs incrementally by filtering on updated_at and merging on conversation_id.
-# A conversation re-enters the export whenever it receives new messages, which is
-# why the vendor recommends upserting on conversation_id rather than appending.
+# Decagon's per-endpoint contracts differ enough that everything rides this catalog: four
+# pagination styles, per-endpoint primary keys and partitioning, and incremental filters
+# whose param names and value formats vary by endpoint.
DECAGON_ENDPOINTS: dict[str, DecagonEndpointConfig] = {
+ # /conversation/export returns conversations with their messages, CSAT ratings, tags,
+ # and metadata, up to 100 per page. It accepts min_timestamp/max_timestamp filters
+ # (epoch seconds), with `timestamp_filter` selecting the field they bound: created_at
+ # (the default), updated_at, or last_message_time. Rows always carry `updated_at`
+ # (ISO 8601), so the stream syncs incrementally by filtering on updated_at and merging
+ # on conversation_id. A conversation re-enters the export whenever it receives new
+ # messages, which is why the vendor recommends upserting on conversation_id rather
+ # than appending.
"conversations": DecagonEndpointConfig(
name="conversations",
path="/conversation/export",
@@ -46,10 +98,50 @@ DECAGON_ENDPOINTS: dict[str, DecagonEndpointConfig] = {
"field_type": IncrementalFieldType.DateTime,
}
],
+ pagination="cursor",
+ next_cursor_keys=CONVERSATIONS_NEXT_CURSOR_KEYS,
partition_key="created_at",
+ incremental_param="min_timestamp",
+ incremental_param_format="epoch_seconds",
+ timestamp_filter_param="timestamp_filter",
+ # The export documents `order` with an asc default, walking oldest to newest.
+ sort_mode="asc",
# A conversation row mutates in place whenever new messages arrive.
supports_append=False,
),
+ # /agent_assist/actions/export records every Agent Assist action a human support
+ # agent performed. It pages on next_cursor/has_more, which is a different contract
+ # from the conversations export. Events document no unique id, so the stream syncs
+ # append-only (windowed server-side on min_timestamp over created_at) rather than
+ # merging on a guessed composite key that could silently merge distinct actions.
+ # include_details adds a `detail` object (carrying detail.conversation_id, the join
+ # key to conversations) only when detail export is enabled for the team, so nothing
+ # may depend on it being present.
+ "agent_assist_actions": DecagonEndpointConfig(
+ name="agent_assist_actions",
+ path="/agent_assist/actions/export",
+ data_key="events",
+ primary_keys=None,
+ incremental_fields=[
+ {
+ "label": "created_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "created_at",
+ "field_type": IncrementalFieldType.DateTime,
+ }
+ ],
+ pagination="cursor",
+ next_cursor_keys=("next_cursor",),
+ has_more_key="has_more",
+ partition_key="created_at",
+ incremental_param="min_timestamp",
+ incremental_param_format="epoch_seconds",
+ extra_params={"include_details": "true"},
+ # This export documents no ordering, so desc is the safe declaration (see the
+ # field comment).
+ sort_mode="desc",
+ supports_append=True,
+ ),
}
ENDPOINTS = tuple(DECAGON_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/decagon/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/decagon/source.py
index ddc6dbbf7d8e..e5adbedc0c6a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/decagon/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/decagon/source.py
@@ -22,11 +22,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.decagon.de
decagon_source,
validate_credentials as validate_decagon_credentials,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.decagon.settings import (
- DECAGON_ENDPOINTS,
- ENDPOINTS,
- INCREMENTAL_FIELDS,
-)
+from products.warehouse_sources.backend.temporal.data_imports.sources.decagon.settings import DECAGON_ENDPOINTS
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.decagon import (
DecagonSourceConfig,
)
@@ -85,8 +81,8 @@ You can find your API key on the **Developer** page of the [Decagon dashboard](h
"Decagon dashboard and reconnect."
),
"403 Client Error: Forbidden": (
- "The Decagon API key does not have access to the conversation export. Check the key "
- "on the Developer page of the Decagon dashboard and reconnect."
+ "The Decagon API key does not have access to the endpoint behind this table. Check "
+ "the key on the Developer page of the Decagon dashboard and reconnect."
),
}
@@ -102,12 +98,15 @@ You can find your API key on the **Developer** page of the [Decagon dashboard](h
schemas = [
SourceSchema(
name=endpoint,
- supports_incremental=len(INCREMENTAL_FIELDS.get(endpoint, [])) > 0,
- supports_append=DECAGON_ENDPOINTS[endpoint].supports_append
- and len(INCREMENTAL_FIELDS.get(endpoint, [])) > 0,
- incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ # Incremental writes merge on the primary key, so a keyless stream can
+ # only offer append (gated per endpoint) or full refresh.
+ supports_incremental=endpoint_config.primary_keys is not None
+ and len(endpoint_config.incremental_fields) > 0,
+ supports_append=endpoint_config.supports_append and len(endpoint_config.incremental_fields) > 0,
+ incremental_fields=endpoint_config.incremental_fields,
+ should_sync_default=endpoint_config.should_sync_default,
)
- for endpoint in ENDPOINTS
+ for endpoint, endpoint_config in DECAGON_ENDPOINTS.items()
]
if names is not None:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/decagon/tests/test_decagon.py b/products/warehouse_sources/backend/temporal/data_imports/sources/decagon/tests/test_decagon.py
index d49fadd95c1e..893dd60f99f8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/decagon/tests/test_decagon.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/decagon/tests/test_decagon.py
@@ -16,8 +16,13 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.decagon.de
get_rows,
validate_credentials,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.decagon.settings import (
+ DECAGON_ENDPOINTS,
+ DecagonEndpointConfig,
+)
DECAGON_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.decagon.decagon"
+SETTINGS_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.decagon.settings"
def _make_response(body: dict[str, Any], status_code: int = 200) -> Response:
@@ -32,6 +37,33 @@ def _conversation(conversation_id: str) -> dict[str, Any]:
return {"conversation_id": conversation_id, "created_at": "2026-01-01T00:00:00Z"}
+def _drive_rows(
+ manager: MagicMock, responses: list[Response], endpoint: str = "conversations", **incremental_kwargs: Any
+) -> tuple[list[dict[str, Any]], list[list[dict[str, Any]]]]:
+ sent_params: list[dict[str, Any]] = []
+ response_iter = iter(responses)
+
+ def fake_get(_url: str, *, params: dict[str, Any], **_kwargs: Any) -> Response:
+ sent_params.append(dict(params or {}))
+ return next(response_iter)
+
+ with (
+ patch(f"{DECAGON_MODULE}.make_tracked_session") as mock_session,
+ patch(f"{DECAGON_MODULE}.time.sleep"),
+ ):
+ mock_session.return_value.get.side_effect = fake_get
+ batches = list(
+ get_rows(
+ api_key="key",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=manager,
+ **incremental_kwargs,
+ )
+ )
+ return sent_params, batches
+
+
class TestValidateCredentials:
@parameterized.expand(
[
@@ -64,28 +96,7 @@ class TestGetRows:
def _drive(
self, manager: MagicMock, responses: list[Response], **incremental_kwargs: Any
) -> tuple[list[dict[str, Any]], list[list[str]]]:
- """Drive get_rows with a mocked session; return (params sent per page, ids yielded per batch)."""
- sent_params: list[dict[str, Any]] = []
- response_iter = iter(responses)
-
- def fake_get(_url: str, *, params: dict[str, Any], **_kwargs: Any) -> Response:
- sent_params.append(dict(params or {}))
- return next(response_iter)
-
- with (
- patch(f"{DECAGON_MODULE}.make_tracked_session") as mock_session,
- patch(f"{DECAGON_MODULE}.time.sleep"),
- ):
- mock_session.return_value.get.side_effect = fake_get
- batches = list(
- get_rows(
- api_key="key",
- endpoint="conversations",
- logger=MagicMock(),
- resumable_source_manager=manager,
- **incremental_kwargs,
- )
- )
+ sent_params, batches = _drive_rows(manager, responses, **incremental_kwargs)
yielded_ids = [[item["conversation_id"] for item in batch] for batch in batches]
return sent_params, yielded_ids
@@ -121,6 +132,9 @@ class TestGetRows:
saved = [call.args[0] for call in manager.save_state.call_args_list]
assert saved == [DecagonResumeConfig(cursor=str(cursor_1)), DecagonResumeConfig(cursor=str(cursor_2))]
+ # A retried attempt of this completed job must start fresh, not resume at the
+ # final page and append its rows again.
+ manager.clear_state.assert_called_once()
def test_null_prose_cursor_key_does_not_mask_a_populated_alias(self) -> None:
manager = self._fresh_manager()
@@ -280,6 +294,216 @@ class TestGetRows:
assert e.response.status_code == 401
+def _synthetic_endpoint(**overrides: Any) -> DecagonEndpointConfig:
+ defaults: dict[str, Any] = {
+ "name": "synthetic",
+ "path": "/synthetic",
+ "data_key": "rows",
+ "primary_keys": ["id"],
+ "incremental_fields": [],
+ "pagination": "single",
+ }
+ defaults.update(overrides)
+ return DecagonEndpointConfig(**defaults)
+
+
+def _row(row_id: str) -> dict[str, Any]:
+ return {"id": row_id}
+
+
+def _fresh_manager() -> MagicMock:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+ return manager
+
+
+# The walker is config-driven, so each pagination mode is exercised through a synthetic
+# endpoint config rather than waiting for a real endpoint to adopt it.
+class TestPaginationModes:
+ def test_single_mode_makes_exactly_one_request_with_no_pagination_params(self) -> None:
+ cfg = _synthetic_endpoint(pagination="single", extra_params={"get_counts": "true"})
+ with patch.dict(DECAGON_ENDPOINTS, {"synthetic": cfg}):
+ manager = _fresh_manager()
+ responses = [_make_response({"rows": [_row("r1"), _row("r2")]})]
+ sent_params, batches = _drive_rows(manager, responses, endpoint="synthetic")
+ assert sent_params == [{"get_counts": "true"}]
+ assert [[r["id"] for r in b] for b in batches] == [["r1", "r2"]]
+ manager.save_state.assert_not_called()
+
+ def test_page_mode_terminates_on_total_counting_rows_actually_received(self) -> None:
+ # The server may cap the requested page_size; counting received rows against the
+ # total keeps termination exact instead of stopping after a "short" capped page.
+ cfg = _synthetic_endpoint(pagination="page", page_size=3, total_key="total")
+ with patch.dict(DECAGON_ENDPOINTS, {"synthetic": cfg}):
+ manager = _fresh_manager()
+ responses = [
+ _make_response({"rows": [_row("r1"), _row("r2")], "total": 5}),
+ _make_response({"rows": [_row("r3"), _row("r4")], "total": 5}),
+ _make_response({"rows": [_row("r5")], "total": 5}),
+ ]
+ sent_params, batches = _drive_rows(manager, responses, endpoint="synthetic")
+ assert sent_params == [
+ {"page": "1", "page_size": "3"},
+ {"page": "2", "page_size": "3"},
+ {"page": "3", "page_size": "3"},
+ ]
+ assert len(batches) == 3
+ saved = [call.args[0] for call in manager.save_state.call_args_list]
+ assert saved == [
+ DecagonResumeConfig(page=2, rows_walked=2),
+ DecagonResumeConfig(page=3, rows_walked=4),
+ ]
+
+ def test_page_mode_without_total_falls_back_to_short_page_termination(self) -> None:
+ cfg = _synthetic_endpoint(pagination="page", page_size=2, total_key="total")
+ with patch.dict(DECAGON_ENDPOINTS, {"synthetic": cfg}):
+ manager = _fresh_manager()
+ responses = [
+ _make_response({"rows": [_row("r1"), _row("r2")]}),
+ _make_response({"rows": [_row("r3")]}),
+ ]
+ sent_params, _ = _drive_rows(manager, responses, endpoint="synthetic")
+ assert len(sent_params) == 2
+
+ def test_page_mode_resume_continues_the_total_count(self) -> None:
+ # A resumed walk that restarted its row count at zero would keep requesting pages
+ # past the total the crashed run already walked through.
+ cfg = _synthetic_endpoint(pagination="page", page_size=2, total_key="total")
+ with patch.dict(DECAGON_ENDPOINTS, {"synthetic": cfg}):
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = DecagonResumeConfig(page=3, rows_walked=4)
+ responses = [_make_response({"rows": [_row("r5")], "total": 5})]
+ sent_params, _ = _drive_rows(manager, responses, endpoint="synthetic")
+ assert sent_params == [{"page": "3", "page_size": "2"}]
+
+ def test_offset_mode_advances_by_rows_received_and_terminates_on_total(self) -> None:
+ cfg = _synthetic_endpoint(pagination="offset", page_size=2, total_key="total")
+ with patch.dict(DECAGON_ENDPOINTS, {"synthetic": cfg}):
+ manager = _fresh_manager()
+ responses = [
+ _make_response({"rows": [_row("r1"), _row("r2")], "total": 3}),
+ _make_response({"rows": [_row("r3")], "total": 3}),
+ ]
+ sent_params, _ = _drive_rows(manager, responses, endpoint="synthetic")
+ assert sent_params == [
+ {"offset": "0", "limit": "2"},
+ {"offset": "2", "limit": "2"},
+ ]
+ saved = [call.args[0] for call in manager.save_state.call_args_list]
+ assert saved == [DecagonResumeConfig(offset=2)]
+
+ def test_cursor_mode_has_more_false_ends_the_walk_even_with_a_cursor_present(self) -> None:
+ # On endpoints that send has_more the flag is authoritative; following a leftover
+ # cursor would re-fetch or spin on the final page.
+ cfg = _synthetic_endpoint(pagination="cursor", next_cursor_keys=("next_cursor",), has_more_key="has_more")
+ with patch.dict(DECAGON_ENDPOINTS, {"synthetic": cfg}):
+ manager = _fresh_manager()
+ responses = [
+ _make_response({"rows": [_row("r1")], "next_cursor": "cur-1", "has_more": True}),
+ _make_response({"rows": [_row("r2")], "next_cursor": "cur-stale", "has_more": False}),
+ ]
+ sent_params, _ = _drive_rows(manager, responses, endpoint="synthetic")
+ assert sent_params == [{}, {"cursor": "cur-1"}]
+ saved = [call.args[0] for call in manager.save_state.call_args_list]
+ assert saved == [DecagonResumeConfig(cursor="cur-1")]
+
+ def test_keyless_stream_yields_rows_without_touching_a_primary_key(self) -> None:
+ # Streams with no documented id must not KeyError on a dedupe key they don't have.
+ cfg = _synthetic_endpoint(pagination="single", primary_keys=None)
+ with patch.dict(DECAGON_ENDPOINTS, {"synthetic": cfg}):
+ manager = _fresh_manager()
+ responses = [_make_response({"rows": [{"agent_name": "a"}, {"agent_name": "a"}]})]
+ _, batches = _drive_rows(manager, responses, endpoint="synthetic")
+ assert [len(b) for b in batches] == [2]
+
+ def test_composite_primary_key_dedupes_on_all_fields(self) -> None:
+ # Deduping on a subset of a composite key would silently drop distinct rows that
+ # share that subset.
+ cfg = _synthetic_endpoint(pagination="cursor", next_cursor_keys=("next_cursor",), primary_keys=["a", "b"])
+ with patch.dict(DECAGON_ENDPOINTS, {"synthetic": cfg}):
+ manager = _fresh_manager()
+ responses = [
+ _make_response({"rows": [{"a": 1, "b": 1}, {"a": 1, "b": 2}], "next_cursor": "c1"}),
+ _make_response({"rows": [{"a": 1, "b": 2}, {"a": 2, "b": 1}], "next_cursor": None}),
+ ]
+ _, batches = _drive_rows(manager, responses, endpoint="synthetic")
+ assert [len(b) for b in batches] == [2, 1]
+
+ def test_iso8601_incremental_param_format(self) -> None:
+ # Decagon's exports take epoch seconds but /admin_log/get types its bounds
+ # differently; the format field exists so the two cannot be conflated.
+ cfg = _synthetic_endpoint(
+ pagination="single",
+ incremental_param="start",
+ incremental_param_format="iso8601",
+ )
+ with patch.dict(DECAGON_ENDPOINTS, {"synthetic": cfg}):
+ manager = _fresh_manager()
+ responses = [_make_response({"rows": [_row("r1")]})]
+ sent_params, _ = _drive_rows(
+ manager,
+ responses,
+ endpoint="synthetic",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 1, 15, 12, 0, 5, tzinfo=UTC),
+ incremental_field="created_at",
+ )
+ assert sent_params == [{"start": "2026-01-15T12:00:05+00:00"}]
+
+
+class TestAgentAssistActions:
+ def test_walk_sends_details_flag_and_window_and_pages_on_has_more(self) -> None:
+ manager = _fresh_manager()
+ watermark = datetime(2026, 1, 15, 12, 0, 5, tzinfo=UTC)
+ # The bound is exclusive for this keyless stream: appends have no merge to dedupe
+ # a re-fetched watermark second, which would otherwise re-import it every sync.
+ epoch = str(int(watermark.timestamp()) + 1)
+ responses = [
+ _make_response(
+ {
+ "events": [{"agent_name": "a", "action_name": "x", "ticket_id": "t1"}],
+ "has_more": True,
+ "next_cursor": "cur-1",
+ }
+ ),
+ _make_response(
+ {
+ "events": [{"agent_name": "b", "action_name": "y", "ticket_id": "t2"}],
+ "has_more": False,
+ "next_cursor": None,
+ }
+ ),
+ ]
+ sent_params, batches = _drive_rows(
+ manager,
+ responses,
+ endpoint="agent_assist_actions",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=watermark,
+ incremental_field="created_at",
+ )
+
+ assert sent_params == [
+ {"include_details": "true", "min_timestamp": epoch},
+ {"include_details": "true", "min_timestamp": epoch, "cursor": "cur-1"},
+ ]
+ assert [len(b) for b in batches] == [1, 1]
+ saved = [call.args[0] for call in manager.save_state.call_args_list]
+ assert saved == [DecagonResumeConfig(cursor="cur-1", min_timestamp=int(epoch))]
+
+ def test_source_response_is_a_keyless_append_stream(self) -> None:
+ response = decagon_source(
+ api_key="key",
+ endpoint="agent_assist_actions",
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(spec=ResumableSourceManager),
+ )
+ assert response.primary_keys is None
+ assert response.partition_keys == ["created_at"]
+ assert response.sort_mode == "desc"
+
+
class TestToEpochSeconds:
# The pipeline hands the DateTime watermark back as a datetime, a date, or an epoch
# number depending on how it round-tripped through storage; the request boundary must
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/decagon/tests/test_decagon_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/decagon/tests/test_decagon_source.py
index e6e63da8563a..d4aaf31486bc 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/decagon/tests/test_decagon_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/decagon/tests/test_decagon_source.py
@@ -62,6 +62,13 @@ class TestDecagonSource:
assert conversations.supports_append is False
assert [f["field"] for f in conversations.incremental_fields] == ["updated_at"]
+ actions = next(s for s in schemas if s.name == "agent_assist_actions")
+ # No documented unique id means no merge key, so append (windowed on created_at)
+ # and full refresh are the only sync types that cannot lose or merge rows.
+ assert actions.supports_incremental is False
+ assert actions.supports_append is True
+ assert [f["field"] for f in actions.incremental_fields] == ["created_at"]
+
def test_get_schemas_filtered_by_names(self) -> None:
assert [s.name for s in self.source.get_schemas(self.config, self.team_id, names=["conversations"])] == [
"conversations"