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): sync appsignal apps, logs, metrics and traces (#99233)

Tom Owers9f22fc20a65c
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 658d881ca4a9..d712d75b2b93 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
@@ -454,14 +454,16 @@ Note: PostHog exposes three aggregate Pull API v5 reports (daily, geo, partners)
## Appsignal — gaps
-Today (5): `deploy_markers`, `error_samples`, `exception_incidents`, `performance_incidents`, `performance_samples`
+Today (11): `apps`, `deploy_markers`, `error_samples`, `exception_incidents`, `log_lines`, `metric_names`, `metric_timeseries`, `performance_incidents`, `performance_samples`, `performance_traces`, `trace_spans`
Diffed against: <https://docs.appsignal.com/api/v2/overview>
-- [ ] `organization { apps } (GraphQL app/site list)` — lookup resolving the app_id / site_id every other table is keyed by (high)
-- [ ] `POST /api/v2/logs/lines` — log lines are only available here — GraphQL exposes no log field at all (high)
-- [ ] `POST /api/v2/metrics/timeseries, /api/v2/metrics/list, /api/v2/metrics/names` — all custom and platform metric data plus the metric-name lookup; the GraphQL metrics API is deprecated (high)
-- [ ] `POST /api/v2/tracing/traces and /api/v2/tracing/trace (spans)` — distributed trace and span data underlying the samples we already sync (high)
+- [x] `organization { apps } (GraphQL app/site list)` — lookup resolving the app_id / site_id every other table is keyed by (high)
+- [x] `POST /api/v2/logs/lines` — log lines are only available here — GraphQL exposes no log field at all (high)
+- [x] `POST /api/v2/metrics/timeseries, GET /api/v2/metrics/names, GET /api/v2/metrics/type_and_tags` — all custom and platform metric data plus the metric-name lookup; the GraphQL metrics API is deprecated (high)
+- [ ] `POST /api/v2/metrics/list` — the same metric data aggregated into rows by a caller-chosen `group_by`; derivable in SQL from `metric_timeseries`, so it was skipped (low)
+- [x] `POST /api/v2/tracing/traces/performance and /api/v2/tracing/trace (spans)` — distributed trace and span data underlying the samples we already sync (high)
+- [ ] `POST /api/v2/tracing/traces/errors` — error traces, keyed by incident digest; no digest-listing endpoint appears on the published V2 reference (medium)
- [ ] `AnomalyIncident (GraphQL)` — anomaly/trigger incidents are a first-class incident type alongside exception and performance incidents we sync (high)
- [ ] `LogIncident (GraphQL)` — log-based incidents, the fourth incident type, otherwise invisible (medium)
- [ ] `POST /api/v2/deploys/stats` — throughput, mean and error_rate per revision — joins directly onto deploy_markers (medium)
@@ -470,7 +472,7 @@ Diffed against: <https://docs.appsignal.com/api/v2/overview>
- [ ] `uptime monitors (GraphQL)` — uptime check results, a separate monitoring signal from incidents (medium)
- [ ] `check-ins / cron (GraphQL)` — scheduled-job execution history — misses and late runs (medium)
-Note: AppSignal split its API in two: GraphQL for models (apps, incidents, markers, dashboards, alerts, uptime monitors, check-ins) and a REST Public API V2 for bulk data (metrics, logs, traces, Kubernetes, deploy stats). PostHog currently uses only the legacy /api/{app_id}/\*.json endpoints plus GraphQL incidents, so the entire V2 surface is unmapped. Anomaly and log incident types confirmed from the GraphQL mutations page; V2 routes confirmed from the per-page docs.
+Note: AppSignal split its API in two: GraphQL for models (apps, incidents, markers, dashboards, alerts, uptime monitors, check-ins) and a REST Public API V2 for bulk data (metrics, logs, traces, Kubernetes, deploy stats). PostHog reads the legacy /api/{app_id}/\*.json endpoints, GraphQL incidents and the app list, plus the V2 logs, metrics and tracing endpoints; Kubernetes, deploy stats and check-ins are still unmapped. Anomaly and log incident types confirmed from the GraphQL mutations page; V2 routes confirmed from the per-page docs.
## Appstack — adequate
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appsignal/appsignal.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appsignal/appsignal.py
index 6891c6f563af..193cadd574ef 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/appsignal/appsignal.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appsignal/appsignal.py
@@ -1,13 +1,15 @@
-import dataclasses
from collections import deque
from collections.abc import Iterator
-from datetime import UTC, date, datetime
+from datetime import UTC, date, datetime, timedelta
from typing import Any, NoReturn, Optional
+from urllib.parse import quote
import requests
from structlog.types import FilteringBoundLogger
from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+from posthog.dataclasses import frozen
+
from products.warehouse_sources.backend.temporal.data_imports.sources.appsignal.settings import (
APPSIGNAL_ENDPOINTS,
AppsignalEndpointConfig,
@@ -43,12 +45,14 @@ class AppsignalRetryableError(Exception):
pass
+@frozen
class AppsignalResumeConfig:
# REST windowed endpoints: epoch second the remaining walk starts from.
window_start: int | None = None
# GraphQL incident endpoints: offset of the next page to fetch.
offset: int | None = None
+ # V2 log lines: timestamp of the last line yielded, the keyset cursor of the next page.
+ cursor_time: str | None = None
def _to_epoch(value: Any) -> Optional[int]:
@@ -366,6 +370,647 @@ def _get_windowed_rows(
resumable_source_manager.save_state(AppsignalResumeConfig(window_start=next_start))
+# --- Public API V2 (https://appsignal.com/api/v2) -----------------------------------------
+# Logs, metrics and traces are only served by V2; the legacy /api/{app_id}/*.json endpoints
+# above do not expose them, and the GraphQL metrics API is deprecated.
+APPSIGNAL_V2_URL = f"{APPSIGNAL_BASE_URL}/api/v2"
+# Documented ceiling on `pagination.per_page` for the V2 list endpoints.
+V2_PAGE_SIZE = 100
+# Resolution the metric buckets are requested at. Pinning it keeps bucket timestamps stable
+# between syncs, so a re-read of the same range merges onto the same rows instead of seeding
+# a second set at a different granularity.
+METRICS_RESOLUTION = "HOURLY"
+METRICS_RESOLUTION_SECONDS = 3600
+METRICS_WINDOW_SECONDS = 7 * 24 * 3600
+# Selectors sent per timeseries request. One request can ask for many metrics at once, which
+# keeps the request count proportional to the time range rather than to the metric count.
+METRICS_SELECTORS_PER_REQUEST = 25
+# How far back a first metrics or traces sync reaches. Neither endpoint reports the account's
+# retention bound, and both clamp `from` to it server side, so the walk needs a lower bound of
+# its own instead of the EARLIEST_START used for the legacy endpoints.
+METRICS_INITIAL_LOOKBACK_SECONDS = 30 * 24 * 3600
+TRACES_INITIAL_LOOKBACK_SECONDS = 7 * 24 * 3600
+TRACES_WINDOW_SECONDS = 6 * 3600
+# Traces whose spans are fetched in one sync. Spans cost one request per trace, so a first
+# sync on a busy app is capped and the next sync continues from the watermark.
+MAX_SPAN_TRACES_PER_SYNC = 5_000
+SPAN_BATCH_TRACES = 100
+# AppSignal's metric types map onto the `Field` enum the timeseries selector asks for. A
+# measurement has no single natural field, so the mean is taken as the representative one.
+METRIC_TYPE_FIELDS = {"gauge": "gauge", "counter": "counter", "measurement": "mean"}
+
+
+def _parse_iso(value: Any) -> Optional[datetime]:
+ if not isinstance(value, str):
+ return None
+ try:
+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
+ except ValueError:
+ return None
+ return parsed.replace(tzinfo=UTC) if parsed.tzinfo is None else parsed
+
+
+def _format_iso(value: datetime) -> str:
+ return value.astimezone(UTC).isoformat().replace("+00:00", "Z")
+
+
+def _to_iso(epoch: int) -> str:
+ return _format_iso(datetime.fromtimestamp(epoch, tz=UTC))
+
+
+@frozen
+class TimeWindow:
+ since: int
+ before: int
+
+
+def _iter_windows(start: int, end: int, size: int) -> Iterator[TimeWindow]:
+ while start < end:
+ stop = min(start + size, end)
+ yield TimeWindow(since=start, before=stop)
+ start = stop
+
+
+def _resolve_walk_start(
+ config: AppsignalEndpointConfig,
+ resumable_source_manager: ResumableSourceManager[AppsignalResumeConfig],
+ logger: FilteringBoundLogger,
+ now: int,
+ initial_lookback_seconds: int,
+ overlap_seconds: int,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+) -> int:
+ start = now - initial_lookback_seconds
+ if should_use_incremental_field:
+ watermark = _to_epoch(db_incremental_field_last_value)
+ if watermark is not None:
+ start = watermark - overlap_seconds
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume is not None and resume.window_start is not None:
+ start = resume.window_start
+ logger.debug(f"AppSignal: resuming {config.name} from window_start={start}")
+
+ return start
+
+
+@retry(
+ retry=retry_if_exception_type((AppsignalRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRIES),
+ wait=wait_exponential_jitter(initial=1, max=60),
+ reraise=True,
+)
+def _fetch_v2(
+ session: requests.Session,
+ api_token: str,
+ path: str,
+ logger: FilteringBoundLogger,
+ body: Optional[dict[str, Any]] = None,
+) -> Any:
+ """Call a Public API V2 endpoint. A body means POST, no body means GET.
+
+ Returns the decoded body as-is: the V2 endpoints answer with a bare JSON array as often as
+ with an object, so the caller decides how to read it.
+ """
+ url = f"{APPSIGNAL_V2_URL}{path}"
+ try:
+ if body is None:
+ response = session.get(url, params={"token": api_token}, timeout=REQUEST_TIMEOUT_SECONDS)
+ else:
+ response = session.post(url, params={"token": api_token}, json=body, timeout=REQUEST_TIMEOUT_SECONDS)
+ except requests.RequestException as error:
+ _raise_scrubbed_transport_error(error, api_token, "V2 API")
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise AppsignalRetryableError(f"AppSignal V2 API error (retryable): status={response.status_code}, path={path}")
+
+ if not response.ok:
+ logger.error(f"AppSignal V2 API error: status={response.status_code}, path={path}")
+ _raise_for_status_scrubbed(response)
+
+ return response.json()
+
+
+_APPS_QUERY = """
+query OrganizationApps($appId: String!) {
+ app(id: $appId) {
+ organization {
+ id
+ name
+ slug
+ apps {
+ id
+ name
+ environment
+ platforms
+ languages
+ status
+ lastPushProcessedAt
+ createdAt
+ updatedAt
+ }
+ }
+ }
+}
+"""
+
+_LOG_SOURCES_QUERY = """
+query LogSources($appId: String!) {
+ app(id: $appId) {
+ logs {
+ sources {
+ id
+ }
+ }
+ }
+}
+"""
+
+
+def _get_app_rows(
+ session: requests.Session,
+ api_token: str,
+ app_id: str,
+ config: AppsignalEndpointConfig,
+ resumable_source_manager: ResumableSourceManager[AppsignalResumeConfig],
+ logger: FilteringBoundLogger,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ body = _fetch_graphql(session, api_token, _APPS_QUERY, {"appId": app_id}, logger)
+ app_node = (body.get("data") or {}).get("app")
+ if app_node is None:
+ raise Exception("AppSignal app not found: check that the app ID matches your AppSignal app")
+
+ # Scoped to the organization that owns the configured app. A personal token often reaches
+ # several organizations, and syncing those would expose apps this connection never named.
+ organization = app_node.get("organization") or {}
+ rows = [
+ {
+ **app,
+ "organizationId": organization.get("id"),
+ "organizationName": organization.get("name"),
+ "organizationSlug": organization.get("slug"),
+ }
+ for app in organization.get("apps") or []
+ if isinstance(app, dict)
+ ]
+ if rows:
+ yield rows
+
+
+def _get_log_source_ids(
+ session: requests.Session,
+ api_token: str,
+ app_id: str,
+ logger: FilteringBoundLogger,
+) -> list[str]:
+ body = _fetch_graphql(session, api_token, _LOG_SOURCES_QUERY, {"appId": app_id}, logger)
+ app = (body.get("data") or {}).get("app")
+ if app is None:
+ raise Exception("AppSignal app not found: check that the app ID matches your AppSignal app")
+
+ sources = ((app.get("logs") or {}).get("sources")) or []
+ return [source["id"] for source in sources if isinstance(source, dict) and source.get("id")]
+
+
+def _get_log_line_rows(
+ session: requests.Session,
+ api_token: str,
+ app_id: str,
+ config: AppsignalEndpointConfig,
+ resumable_source_manager: ResumableSourceManager[AppsignalResumeConfig],
+ logger: FilteringBoundLogger,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ """Walk log lines oldest-first through the V2 keyset cursor.
+
+ The cursor is the timestamp of the last line received, and the endpoint includes that
+ instant, so lines sharing it come back on the next page. They are filtered against the ids
+ already yielded, and the cursor only ever moves forward: a page ending on or before the
+ cursor cannot advance the walk on its own.
+ """
+ source_ids = _get_log_source_ids(session, api_token, app_id, logger)
+ if not source_ids:
+ logger.info("AppSignal: app has no log sources, nothing to sync")
+ return
+
+ # No cursor asks for the oldest page the account's retention still holds.
+ cursor: Optional[datetime] = None
+ if should_use_incremental_field:
+ watermark = _to_epoch(db_incremental_field_last_value)
+ if watermark is not None:
+ cursor = datetime.fromtimestamp(watermark - 1, tz=UTC)
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume is not None and resume.cursor_time is not None:
+ cursor = _parse_iso(resume.cursor_time)
+ logger.debug(f"AppSignal: resuming {config.name} from cursor_time={resume.cursor_time}")
+
+ # Ids already yielded at `cursor`, so that instant can be re-requested without duplicating.
+ seen_at_cursor: set[str] = set()
+
+ while True:
+ page = _fetch_v2(
+ session,
+ api_token,
+ "/logs/lines",
+ logger,
+ body={
+ "site_id": app_id,
+ "source_ids": source_ids,
+ "query": "",
+ "pagination": {
+ "per_page": V2_PAGE_SIZE,
+ "order": "ASC",
+ "cursor": {"time": _format_iso(cursor) if cursor is not None else None},
+ },
+ },
+ )
+ rows = [row for row in page or [] if isinstance(row, dict)]
+ if not rows:
+ break
+
+ fresh = [row for row in rows if row.get("id") not in seen_at_cursor]
+ if fresh:
+ yield fresh
+
+ last = _parse_iso(rows[-1].get("timestamp"))
+ if last is None:
+ break
+
+ if cursor is None or last > cursor:
+ cursor = last
+ seen_at_cursor = {row["id"] for row in rows if _parse_iso(row.get("timestamp")) == last and row.get("id")}
+ if fresh:
+ # Save AFTER yielding so a crash re-yields the last page rather than skipping it.
+ resumable_source_manager.save_state(AppsignalResumeConfig(cursor_time=_format_iso(cursor)))
+ if len(rows) < V2_PAGE_SIZE:
+ break
+ continue
+
+ if len(rows) < V2_PAGE_SIZE:
+ break
+
+ # A whole page landed on or before the cursor, so the keyset cursor cannot advance by
+ # itself and re-requesting would loop. Step past that instant instead; anything beyond a
+ # page at that exact timestamp cannot be reached through this API.
+ logger.warning(
+ f"AppSignal: more than {V2_PAGE_SIZE} log lines share timestamp {_format_iso(cursor)}, "
+ f"skipping the rest of that instant"
+ )
+ cursor = cursor + timedelta(milliseconds=1)
+ seen_at_cursor |= {row["id"] for row in rows if row.get("id")}
+
+
+def _iter_metric_definitions(
+ session: requests.Session,
+ api_token: str,
+ app_id: str,
+ logger: FilteringBoundLogger,
+) -> Iterator[dict[str, Any]]:
+ names = _fetch_v2(session, api_token, f"/metrics/names/{quote(app_id, safe='')}", logger)
+ for name in names or []:
+ if not isinstance(name, str):
+ continue
+ try:
+ detail = _fetch_v2(
+ session,
+ api_token,
+ f"/metrics/type_and_tags/{quote(app_id, safe='')}/{quote(name, safe='')}",
+ logger,
+ )
+ except requests.HTTPError as error:
+ # Documented 404: the metric stopped reporting between the two calls.
+ if error.response is None or error.response.status_code != 404:
+ raise
+ detail = {}
+ yield {
+ "name": name,
+ "metric_type": detail.get("metric_type"),
+ "available_tags": detail.get("available_tags") or [],
+ }
+
+
+def _get_metric_name_rows(
+ session: requests.Session,
+ api_token: str,
+ app_id: str,
+ config: AppsignalEndpointConfig,
+ resumable_source_manager: ResumableSourceManager[AppsignalResumeConfig],
+ logger: FilteringBoundLogger,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ rows = list(_iter_metric_definitions(session, api_token, app_id, logger))
+ if rows:
+ yield rows
+
+
+def _selector_tags(available_tags: Any) -> dict[str, str]:
+ """Build a tag filter that matches every series of a metric.
+
+ `available_tags` is documented both as a list of tag-key lists and, in the example
+ response, as a list of tag key/value objects. Both are read as the set of tag keys, and
+ each key is matched with the API's `*` wildcard so no series is filtered out.
+ """
+ keys: set[str] = set()
+ for combination in available_tags or []:
+ if isinstance(combination, dict):
+ keys.update(key for key in combination if isinstance(key, str))
+ elif isinstance(combination, list):
+ keys.update(key for key in combination if isinstance(key, str))
+ return dict.fromkeys(sorted(keys), "*")
+
+
+def _get_metric_timeseries_rows(
+ session: requests.Session,
+ api_token: str,
+ app_id: str,
+ config: AppsignalEndpointConfig,
+ resumable_source_manager: ResumableSourceManager[AppsignalResumeConfig],
+ logger: FilteringBoundLogger,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ """Walk every metric's buckets through ascending time windows.
+
+ Windows are the outer loop and metrics the inner one, so each yielded batch covers one
+ window and batches arrive oldest-first. That keeps `sort_mode="asc"` watermarking honest,
+ which per-metric walks would not: their timestamps restart with every metric.
+ """
+ selectors = []
+ for definition in _iter_metric_definitions(session, api_token, app_id, logger):
+ field_name = METRIC_TYPE_FIELDS.get(definition["metric_type"] or "")
+ if field_name is None:
+ continue
+ selectors.append(
+ {"name": definition["name"], "field": field_name, "tags": _selector_tags(definition["available_tags"])}
+ )
+ if not selectors:
+ return
+
+ now = int(datetime.now(UTC).timestamp())
+ start = _resolve_walk_start(
+ config,
+ resumable_source_manager,
+ logger,
+ now,
+ METRICS_INITIAL_LOOKBACK_SECONDS,
+ # Re-read the bucket the watermark sits in: it was still filling when it was synced,
+ # and the merge replaces it with the settled value.
+ METRICS_RESOLUTION_SECONDS,
+ should_use_incremental_field,
+ db_incremental_field_last_value,
+ )
+
+ for window in _iter_windows(start, now, METRICS_WINDOW_SECONDS):
+ rows: list[dict[str, Any]] = []
+ for offset in range(0, len(selectors), METRICS_SELECTORS_PER_REQUEST):
+ body = _fetch_v2(
+ session,
+ api_token,
+ "/metrics/timeseries",
+ logger,
+ body={
+ "site_id": app_id,
+ "from": _to_iso(window.since),
+ "to": _to_iso(window.before),
+ "resolution": METRICS_RESOLUTION,
+ "select": selectors[offset : offset + METRICS_SELECTORS_PER_REQUEST],
+ },
+ )
+ for serie in (body or {}).get("series") or []:
+ for point in serie.get("data") or []:
+ rows.append(
+ {
+ "series_id": serie.get("id"),
+ "metric_name": serie.get("name"),
+ "field": serie.get("field"),
+ "tags": serie.get("tags"),
+ "timestamp": point.get("timestamp"),
+ "value": point.get("value"),
+ }
+ )
+
+ if not rows:
+ continue
+
+ rows.sort(key=lambda row: _to_epoch(row.get("timestamp")) or 0)
+ yield rows
+ resumable_source_manager.save_state(AppsignalResumeConfig(window_start=window.before))
+
+
+def _iter_action_traces(
+ session: requests.Session,
+ api_token: str,
+ app_id: str,
+ namespace: str,
+ action_name: str,
+ since: int,
+ before: int,
+ logger: FilteringBoundLogger,
+) -> Iterator[dict[str, Any]]:
+ """Sweep one action's traces by splitting the window whenever a response comes back full.
+
+ `traces/performance` caps a response at `per_page` and its cursor only names the keyset
+ column, so a full response means the window was truncated rather than exhausted. Halving
+ the window is the only way to reach the rest.
+ """
+ windows: deque[tuple[int, int]] = deque([(since, before)])
+ while windows:
+ window_since, window_before = windows.popleft()
+ rows = (
+ _fetch_v2(
+ session,
+ api_token,
+ "/tracing/traces/performance",
+ logger,
+ body={
+ "site_ids": [app_id],
+ "namespace": namespace,
+ "action_name": action_name,
+ "from": _to_iso(window_since),
+ "to": _to_iso(window_before),
+ "pagination": {"per_page": V2_PAGE_SIZE, "order": "ASC", "cursor": "Time"},
+ },
+ )
+ or []
+ )
+ rows = [row for row in rows if isinstance(row, dict)]
+
+ if len(rows) >= V2_PAGE_SIZE and (window_before - window_since) >= 2 * MIN_WINDOW_SECONDS:
+ mid = (window_since + window_before) // 2
+ # The right child starts 1s early so a trace landing exactly on `mid` cannot fall
+ # between the halves if both bounds turn out exclusive. Dupes merge away.
+ windows.appendleft((max(mid - 1, window_since), window_before))
+ windows.appendleft((window_since, mid))
+ continue
+
+ if len(rows) >= V2_PAGE_SIZE:
+ logger.warning(
+ f"AppSignal: more than {V2_PAGE_SIZE} traces for {namespace}/{action_name} within "
+ f"[{window_since}, {window_before}], which is narrower than the walk can split"
+ )
+
+ yield from rows
+
+
+def _window_traces(
+ session: requests.Session,
+ api_token: str,
+ app_id: str,
+ since: int,
+ before: int,
+ logger: FilteringBoundLogger,
+) -> list[dict[str, Any]]:
+ """Collect every trace recorded in a window, oldest-first.
+
+ Traces are only reachable one action at a time, so the window's actions are swept first
+ and the result is sorted: rows arrive grouped by action, which is not a time order.
+ """
+ actions = (
+ _fetch_v2(
+ session,
+ api_token,
+ "/tracing/actions",
+ logger,
+ body={"site_id": app_id, "from": _to_iso(since), "to": _to_iso(before)},
+ )
+ or []
+ )
+
+ traces: list[dict[str, Any]] = []
+ for action in actions:
+ if not isinstance(action, dict):
+ continue
+ namespace, action_name = action.get("namespace"), action.get("action")
+ if not namespace or not action_name:
+ continue
+ traces.extend(_iter_action_traces(session, api_token, app_id, namespace, action_name, since, before, logger))
+
+ traces.sort(key=lambda trace: _to_epoch(trace.get("time")) or 0)
+ return traces
+
+
+def _get_performance_trace_rows(
+ session: requests.Session,
+ api_token: str,
+ app_id: str,
+ config: AppsignalEndpointConfig,
+ resumable_source_manager: ResumableSourceManager[AppsignalResumeConfig],
+ logger: FilteringBoundLogger,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ now = int(datetime.now(UTC).timestamp())
+ start = _resolve_walk_start(
+ config,
+ resumable_source_manager,
+ logger,
+ now,
+ TRACES_INITIAL_LOOKBACK_SECONDS,
+ 1,
+ should_use_incremental_field,
+ db_incremental_field_last_value,
+ )
+
+ for window in _iter_windows(start, now, TRACES_WINDOW_SECONDS):
+ traces = _window_traces(session, api_token, app_id, window.since, window.before, logger)
+ if not traces:
+ continue
+ yield traces
+ resumable_source_manager.save_state(AppsignalResumeConfig(window_start=window.before))
+
+
+def _get_trace_span_rows(
+ session: requests.Session,
+ api_token: str,
+ app_id: str,
+ config: AppsignalEndpointConfig,
+ resumable_source_manager: ResumableSourceManager[AppsignalResumeConfig],
+ logger: FilteringBoundLogger,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ """Fan spans out per trace, oldest trace first.
+
+ Spans cost one request per trace, so the sweep stops at MAX_SPAN_TRACES_PER_SYNC. Stopping
+ is safe because traces are processed in ascending `time` order: the watermark lands on the
+ last trace handled and the next sync picks up from there.
+ """
+ now = int(datetime.now(UTC).timestamp())
+ start = _resolve_walk_start(
+ config,
+ resumable_source_manager,
+ logger,
+ now,
+ TRACES_INITIAL_LOOKBACK_SECONDS,
+ 1,
+ should_use_incremental_field,
+ db_incremental_field_last_value,
+ )
+
+ traces_fetched = 0
+ for window in _iter_windows(start, now, TRACES_WINDOW_SECONDS):
+ spans: list[dict[str, Any]] = []
+ batch_traces = 0
+ capped = False
+ last_trace_time: Any = None
+
+ for trace in _window_traces(session, api_token, app_id, window.since, window.before, logger):
+ trace_id, trace_time = trace.get("trace_id"), trace.get("time")
+ if not trace_id:
+ continue
+ if traces_fetched >= MAX_SPAN_TRACES_PER_SYNC:
+ logger.warning(
+ f"AppSignal: reached the {MAX_SPAN_TRACES_PER_SYNC} trace limit for {config.name}, "
+ f"the next sync continues from the last trace handled"
+ )
+ capped = True
+ break
+
+ traces_fetched += 1
+ batch_traces += 1
+ last_trace_time = trace_time
+ rows = _fetch_v2(
+ session,
+ api_token,
+ "/tracing/trace",
+ logger,
+ body={"site_ids": [app_id], "trace_id": trace_id},
+ )
+ spans.extend({**row, "trace_time": trace_time} for row in rows or [] if isinstance(row, dict))
+
+ if batch_traces >= SPAN_BATCH_TRACES:
+ yield spans
+ resumable_source_manager.save_state(
+ AppsignalResumeConfig(window_start=_to_epoch(trace_time) or window.since)
+ )
+ spans, batch_traces = [], 0
+
+ if spans:
+ yield spans
+ if capped:
+ resumable_source_manager.save_state(
+ AppsignalResumeConfig(window_start=_to_epoch(last_trace_time) or window.since)
+ )
+ return
+ resumable_source_manager.save_state(AppsignalResumeConfig(window_start=window.before))
+
+
+_WALKERS = {
+ "apps": _get_app_rows,
+ "log_lines": _get_log_line_rows,
+ "metric_names": _get_metric_name_rows,
+ "metric_timeseries": _get_metric_timeseries_rows,
+ "performance_traces": _get_performance_trace_rows,
+ "trace_spans": _get_trace_span_rows,
+}
+
+
def get_rows(
api_token: str,
app_id: str,
@@ -380,6 +1025,20 @@ def get_rows(
# One session reused across every request so urllib3 keeps the connection alive.
session = make_tracked_session()
+ if config.api == "custom":
+ assert config.walker is not None
+ yield from _WALKERS[config.walker](
+ session,
+ api_token,
+ app_id,
+ config,
+ resumable_source_manager,
+ logger,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ )
+ return
+
if config.api == "graphql":
yield from _get_incident_rows(session, api_token, app_id, config, resumable_source_manager, logger)
return
@@ -420,7 +1079,7 @@ def appsignal_source(
db_incremental_field_last_value=db_incremental_field_last_value,
incremental_field=incremental_field,
),
- primary_keys=[config.primary_key],
+ primary_keys=list(config.primary_keys),
sort_mode="asc",
partition_count=1,
partition_size=1,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appsignal/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appsignal/canonical_descriptions.py
index 41fcb47c527f..4c0b15a2bd41 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/appsignal/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appsignal/canonical_descriptions.py
@@ -99,4 +99,103 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"exception": "Exception details; null for performance samples.",
},
},
+ "apps": {
+ "description": "An AppSignal app (site): the lookup that resolves the app ID every other AppSignal table is keyed by, with the organization that owns it.",
+ "docs_url": "https://appsignal.com/graphql/docs",
+ "columns": {
+ "id": "App ID, the identifier in the app's AppSignal URL.",
+ "name": "App name.",
+ "environment": "App environment (e.g. production, staging).",
+ "platforms": "Platforms AppSignal has seen reporting for this app.",
+ "languages": "Language integrations reporting for this app.",
+ "status": "App status.",
+ "lastPushProcessedAt": "Time AppSignal last received data for this app.",
+ "createdAt": "Time the app was created.",
+ "updatedAt": "Time the app was last updated.",
+ "organizationId": "ID of the organization the app belongs to.",
+ "organizationName": "Name of the organization the app belongs to.",
+ "organizationSlug": "Slug of the organization, as it appears in the AppSignal URL.",
+ },
+ },
+ "log_lines": {
+ "description": "A single log line collected by AppSignal log management. Only the Public API V2 serves log lines; the GraphQL API has no field for them.",
+ "docs_url": "https://docs.appsignal.com/api/v2/logs",
+ "columns": {
+ "id": "Identifier of the log line within its source.",
+ "timestamp": "Time the log line was recorded.",
+ "source_id": "ID of the log source the line came from.",
+ "severity": "Severity of the line (e.g. info, error).",
+ "message": "Message body of the log line.",
+ "hostname": "Host that emitted the line.",
+ "group": "Group the line belongs to.",
+ "json": "Raw structured (JSON) body of the log line, when available.",
+ "attributes": "Legacy typed key-value attributes. AppSignal is phasing these out in favor of json.",
+ },
+ },
+ "metric_names": {
+ "description": "The metric catalog for an app: one row per metric name, with its type and the tag keys it carries.",
+ "docs_url": "https://docs.appsignal.com/api/v2/metrics",
+ "columns": {
+ "name": "Metric name.",
+ "metric_type": "Category of the metric: gauge, counter or measurement.",
+ "available_tags": "Tag combinations available for this metric. Each entry is one valid combination.",
+ },
+ },
+ "metric_timeseries": {
+ "description": "One hourly bucket of one metric series. Covers custom and platform metrics; the GraphQL metrics API is deprecated, so V2 is the supported source.",
+ "docs_url": "https://docs.appsignal.com/api/v2/metrics",
+ "columns": {
+ "series_id": "Identifier of the series, composed of the metric name, its sorted tags and the field.",
+ "metric_name": "Metric name the series belongs to.",
+ "field": "Measurement taken from the metric (e.g. gauge, counter, mean).",
+ "tags": "Tag key-value pairs that distinguish this series from others with the same name.",
+ "timestamp": "Start of the hourly bucket this value covers.",
+ "value": "Numeric metric value for the bucket.",
+ },
+ },
+ "performance_traces": {
+ "description": "A distributed trace recorded for a performance action, summarized at its root span.",
+ "docs_url": "https://docs.appsignal.com/api/v2/traces",
+ "columns": {
+ "trace_id": "Identifier for the entire trace.",
+ "span_id": "Identifier for the root span.",
+ "site_id": "App the trace belongs to.",
+ "namespace": "Namespace the trace belongs to (e.g. web, background).",
+ "action_name": "Action name for the trace (e.g. POST /api/users).",
+ "revision": "Deployment revision active when the trace was recorded.",
+ "time": "Timestamp of the trace.",
+ "duration": "Total duration of the trace in milliseconds.",
+ "tags": "User-defined tags extracted from span attributes.",
+ "has_npo": "Whether an N+1 query was detected in this trace.",
+ },
+ },
+ "trace_spans": {
+ "description": "A single span of a distributed trace, with its timing, status and attributes.",
+ "docs_url": "https://docs.appsignal.com/api/v2/traces",
+ "columns": {
+ "trace_id": "Identifier for the entire trace.",
+ "span_id": "Identifier for this span.",
+ "parent_span_id": "Span ID of the parent span, empty for root spans.",
+ "trace_time": "Timestamp of the parent trace, added by PostHog so spans partition and sync by their trace.",
+ "start_time": "Time the span started.",
+ "end_time": "Time the span ended.",
+ "duration": "Duration of the span in milliseconds.",
+ "digest": "Hash digest identifying the span's operation.",
+ "site_id": "App the span belongs to.",
+ "service_name": "Service that produced the span.",
+ "namespace": "Namespace the span belongs to (e.g. web, background).",
+ "revision": "Deployment revision active when the span was recorded.",
+ "scope_name": "Instrumentation scope name, usually the library that produced the span.",
+ "scope_version": "Instrumentation scope version.",
+ "action_name": "Action name for the span.",
+ "span_name": "Low-cardinality name of the operation (e.g. HTTP GET).",
+ "span_kind": "Span kind (e.g. server, client, internal).",
+ "span_attributes": "Span-level attributes, such as HTTP headers or database statements.",
+ "resource_attributes": "Resource-level attributes, such as host and service metadata.",
+ "status_code": "OpenTelemetry status code: unset, ok or error.",
+ "status_message": "Status message, typically set on error.",
+ "trace_state": "W3C trace state header value.",
+ "subtrace_root": "Whether this span opens a separate service boundary.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appsignal/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appsignal/settings.py
index feb7d42ba2f8..f5c7c2486f84 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/appsignal/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appsignal/settings.py
@@ -1,15 +1,18 @@
-from dataclasses import dataclass, field
+from dataclasses import field
from typing import Literal, Optional
+from posthog.dataclasses import frozen
+
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
-@dataclass
+@frozen
class AppsignalEndpointConfig:
name: str
# "rest" endpoints page through time windows on AppSignal's legacy JSON API;
- # "graphql" endpoints walk the incident lists with limit/offset paging.
- api: Literal["rest", "graphql"]
+ # "graphql" endpoints walk the incident lists with limit/offset paging;
+ # "custom" endpoints name a walker in `appsignal.py` (see `walker`).
+ api: Literal["rest", "graphql", "custom"]
# REST-only: path template under appsignal.com with an {app_id} placeholder.
path: Optional[str] = None
# REST-only: key the list of rows is nested under in the response body.
@@ -23,7 +26,11 @@ class AppsignalEndpointConfig:
# selection set to request for each row.
graphql_field: Optional[str] = None
graphql_selection: Optional[str] = None
- primary_key: str = "id"
+ # Name of the walker that builds the rows for a "custom" endpoint. The Public API V2
+ # surface and the app list each need their own request and fan-out shape, so they cannot
+ # share the declarative "rest" and "graphql" paths.
+ walker: Optional[str] = None
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
# Field the time windows filter on (REST) — also the sort key within a yielded window.
cursor_field: Optional[str] = None
incremental_fields: list[IncrementalField] = field(default_factory=list)
@@ -138,6 +145,99 @@ APPSIGNAL_ENDPOINTS: dict[str, AppsignalEndpointConfig] = {
},
],
),
+ # Every table below is keyed by an app ID, so the app list is the lookup that resolves
+ # those IDs to a name, environment and organization. `viewer` is used rather than
+ # `organization(slug:)` because the source form asks for an app ID, never an org slug.
+ "apps": AppsignalEndpointConfig(
+ name="apps",
+ api="custom",
+ walker="apps",
+ partition_key="createdAt",
+ ),
+ # Log lines live only on the Public API V2: the GraphQL API exposes no log line field.
+ "log_lines": AppsignalEndpointConfig(
+ name="log_lines",
+ api="custom",
+ walker="log_lines",
+ # A log line ID is unique within its source, not across the sources of an app.
+ primary_keys=["source_id", "id"],
+ cursor_field="timestamp",
+ partition_key="timestamp",
+ immutable_rows=True,
+ incremental_fields=[
+ {
+ "label": "timestamp",
+ "type": IncrementalFieldType.DateTime,
+ "field": "timestamp",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ ),
+ # The metric catalog: one row per metric name, with its type and the tag keys it carries.
+ # This is what makes `metric_timeseries` readable, and it is the only way to discover
+ # which custom metrics an app reports.
+ "metric_names": AppsignalEndpointConfig(
+ name="metric_names",
+ api="custom",
+ walker="metric_names",
+ primary_keys=["name"],
+ ),
+ # All custom and platform metric data. The GraphQL metrics API is deprecated, so V2 is
+ # the only supported source for it.
+ "metric_timeseries": AppsignalEndpointConfig(
+ name="metric_timeseries",
+ api="custom",
+ walker="metric_timeseries",
+ # A series ID is composed of the metric name, its sorted tags and the field, so it is
+ # unique table-wide and a bucket is identified by the series plus its timestamp.
+ primary_keys=["series_id", "timestamp"],
+ cursor_field="timestamp",
+ partition_key="timestamp",
+ incremental_fields=[
+ {
+ "label": "timestamp",
+ "type": IncrementalFieldType.DateTime,
+ "field": "timestamp",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ ),
+ "performance_traces": AppsignalEndpointConfig(
+ name="performance_traces",
+ api="custom",
+ walker="performance_traces",
+ primary_keys=["site_id", "trace_id"],
+ cursor_field="time",
+ partition_key="time",
+ immutable_rows=True,
+ incremental_fields=[
+ {
+ "label": "time",
+ "type": IncrementalFieldType.DateTime,
+ "field": "time",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ ),
+ # Spans are fanned out per trace, so each row carries the parent trace's `time`. The
+ # sweep is driven by that field, and a span's own `start_time` can precede it.
+ "trace_spans": AppsignalEndpointConfig(
+ name="trace_spans",
+ api="custom",
+ walker="trace_spans",
+ primary_keys=["trace_id", "span_id"],
+ cursor_field="trace_time",
+ partition_key="trace_time",
+ immutable_rows=True,
+ incremental_fields=[
+ {
+ "label": "trace_time",
+ "type": IncrementalFieldType.DateTime,
+ "field": "trace_time",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ ),
}
ENDPOINTS = tuple(APPSIGNAL_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appsignal/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appsignal/source.py
index 40d4098f6bfc..55733c46d248 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/appsignal/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appsignal/source.py
@@ -61,7 +61,7 @@ class AppsignalSource(ResumableSource[AppsignalSourceConfig, AppsignalResumeConf
name=SchemaExternalDataSourceType.APPSIGNAL,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="AppSignal",
- caption="""Enter your AppSignal personal API token and app ID to pull your AppSignal error and performance data into the PostHog Data warehouse.
+ caption="""Enter your AppSignal personal API token and app ID to pull your AppSignal errors, performance data, logs, metrics and traces into the PostHog Data warehouse.
Your personal API token is in your [AppSignal personal settings](https://appsignal.com/users/edit) under "API key". The app ID is the identifier in your app's AppSignal URL: `https://appsignal.com/<organization>/sites/<app ID>`.""",
iconPath="/static/services/appsignal.png",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appsignal/tests/test_appsignal.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appsignal/tests/test_appsignal.py
index 6ed1641dcfa4..bcd9533fe965 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/appsignal/tests/test_appsignal.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appsignal/tests/test_appsignal.py
@@ -7,11 +7,16 @@ from unittest import mock
import requests
from products.warehouse_sources.backend.temporal.data_imports.sources.appsignal.appsignal import (
+ APPSIGNAL_GRAPHQL_URL,
+ APPSIGNAL_V2_URL,
AppsignalResumeConfig,
AppsignalRetryableError,
_fetch_graphql,
_fetch_json,
+ _fetch_v2,
+ _parse_iso,
_to_epoch,
+ _to_iso,
appsignal_source,
get_rows,
validate_credentials,
@@ -325,7 +330,7 @@ class TestAppsignalSourceResponse:
response = appsignal_source("token", "app-id", endpoint, mock.MagicMock(), _make_manager())
assert response.name == endpoint
- assert response.primary_keys == [config.primary_key]
+ assert response.primary_keys == list(config.primary_keys)
assert response.sort_mode == "asc"
if config.partition_key:
assert response.partition_mode == "datetime"
@@ -336,4 +341,357 @@ class TestAppsignalSourceResponse:
@pytest.mark.parametrize("config", list(APPSIGNAL_ENDPOINTS.values()))
def test_partition_keys_are_stable_creation_fields(self, config):
if config.partition_key:
- assert config.partition_key in {"created_at", "createdAt", "time"}
+ assert config.partition_key in {"created_at", "createdAt", "time", "timestamp", "trace_time"}
+
+
+def _v2_session(
+ graphql: Any = None,
+ post: dict[str, Any] | None = None,
+ get: dict[str, Any] | None = None,
+) -> mock.MagicMock:
+ """Fake a session that routes by URL: the GraphQL endpoint, V2 POST paths, V2 GET paths.
+
+ A handler is either a payload or a callable taking the request body and returning one.
+ """
+ post_handlers, get_handlers = post or {}, get or {}
+
+ def resolve(handler: Any, body: Any) -> Any:
+ return handler(body) if callable(handler) else handler
+
+ def do_post(url: str, params: Any = None, json: Any = None, timeout: Any = None) -> mock.MagicMock:
+ if url == APPSIGNAL_GRAPHQL_URL:
+ return _response(resolve(graphql, json) or {})
+ path = url.removeprefix(APPSIGNAL_V2_URL)
+ assert path in post_handlers, f"unexpected V2 POST {path}"
+ return _response(resolve(post_handlers[path], json))
+
+ def do_get(url: str, params: Any = None, timeout: Any = None) -> mock.MagicMock:
+ path = url.removeprefix(APPSIGNAL_V2_URL)
+ assert path in get_handlers, f"unexpected V2 GET {path}"
+ handler = get_handlers[path]
+ if isinstance(handler, int):
+ return _response({}, status_code=handler)
+ return _response(resolve(handler, None))
+
+ session = mock.MagicMock()
+ session.post.side_effect = do_post
+ session.get.side_effect = do_get
+ return session
+
+
+_LOG_SOURCES = {"data": {"app": {"logs": {"sources": [{"id": "src-1"}]}}}}
+
+
+def _at(line: dict[str, Any]) -> datetime:
+ parsed = _parse_iso(line["timestamp"])
+ assert parsed is not None
+ return parsed
+
+
+def _log_lines_handler(lines: list[dict[str, Any]]):
+ """Serve log lines oldest-first from an inclusive keyset cursor, as the V2 endpoint does."""
+
+ def handle(body: dict[str, Any]) -> list[dict[str, Any]]:
+ cursor = _parse_iso(body["pagination"]["cursor"]["time"])
+ matching = [line for line in lines if cursor is None or _at(line) >= cursor]
+ return matching[: body["pagination"]["per_page"]]
+
+ return handle
+
+
+class TestFetchV2:
+ @pytest.mark.parametrize("status_code", [429, 500, 503])
+ def test_transient_statuses_are_retryable(self, status_code):
+ session = mock.MagicMock()
+ session.post.return_value = _response({}, status_code=status_code)
+
+ with (
+ mock.patch.object(_fetch_v2.retry, "sleep", lambda _: None), # type: ignore[attr-defined]
+ pytest.raises(AppsignalRetryableError),
+ ):
+ _fetch_v2(session, "token", "/logs/lines", mock.MagicMock(), body={})
+
+ @pytest.mark.parametrize("status_code", [401, 403, 404, 422])
+ def test_client_statuses_are_terminal(self, status_code):
+ session = mock.MagicMock()
+ session.post.return_value = _response({}, status_code=status_code)
+
+ with pytest.raises(requests.HTTPError):
+ _fetch_v2(session, "token", "/logs/lines", mock.MagicMock(), body={})
+
+
+class TestAppRows:
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_apps_carry_their_organization(self, mock_session):
+ # Only the configured app's organization: a personal token often reaches several, and
+ # syncing those would expose apps this connection never named.
+ session = _v2_session(
+ graphql={
+ "data": {
+ "app": {
+ "organization": {
+ "id": "org-1",
+ "name": "Acme",
+ "slug": "acme",
+ "apps": [{"id": "a1", "name": "web"}, {"id": "a2", "name": "api"}],
+ }
+ }
+ }
+ }
+ )
+ mock_session.return_value = session
+
+ batches = list(get_rows("token", "app-id", "apps", mock.MagicMock(), _make_manager()))
+
+ assert [(row["id"], row["organizationSlug"]) for row in batches[0]] == [("a1", "acme"), ("a2", "acme")]
+ assert session.post.call_args.kwargs["json"]["variables"] == {"appId": "app-id"}
+
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_missing_app_raises_clear_error(self, mock_session):
+ mock_session.return_value = _v2_session(graphql={"data": {"app": None}})
+
+ with pytest.raises(Exception, match="AppSignal app not found"):
+ list(get_rows("token", "app-id", "apps", mock.MagicMock(), _make_manager()))
+
+
+class TestLogLineRows:
+ @mock.patch(f"{MODULE}.V2_PAGE_SIZE", 2)
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_boundary_line_is_not_yielded_twice(self, mock_session):
+ # The cursor is the last line's timestamp and the endpoint is inclusive of it, so the
+ # next page re-serves that line. Without the boundary filter it lands in the table twice.
+ lines = [{"id": str(n), "timestamp": f"2026-01-0{n}T00:00:00Z"} for n in (1, 2, 3)]
+ mock_session.return_value = _v2_session(graphql=_LOG_SOURCES, post={"/logs/lines": _log_lines_handler(lines)})
+
+ batches = list(get_rows("token", "app-id", "log_lines", mock.MagicMock(), _make_manager()))
+
+ assert [row["id"] for batch in batches for row in batch] == ["1", "2", "3"]
+
+ @mock.patch(f"{MODULE}.V2_PAGE_SIZE", 2)
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_full_page_on_one_instant_steps_past_it_instead_of_looping(self, mock_session):
+ # Every line shares a timestamp, so the keyset cursor cannot advance on its own and the
+ # walk would re-request the same page forever.
+ lines = [{"id": str(n), "timestamp": "2026-01-01T00:00:00Z"} for n in (1, 2, 3)]
+ mock_session.return_value = _v2_session(graphql=_LOG_SOURCES, post={"/logs/lines": _log_lines_handler(lines)})
+ logger = mock.MagicMock()
+
+ batches = list(get_rows("token", "app-id", "log_lines", logger, _make_manager()))
+
+ assert [row["id"] for batch in batches for row in batch] == ["1", "2"]
+ assert "share timestamp" in logger.warning.call_args.args[0]
+
+ @pytest.mark.parametrize(
+ "should_use_incremental_field, watermark, expected_cursor",
+ [(False, "2026-01-02T00:00:00Z", None), (True, "2026-01-02T00:00:00Z", "2026-01-01T23:59:59Z")],
+ )
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_first_page_cursor_follows_the_watermark(
+ self, mock_session, should_use_incremental_field, watermark, expected_cursor
+ ):
+ session = _v2_session(graphql=_LOG_SOURCES, post={"/logs/lines": []})
+ mock_session.return_value = session
+
+ list(
+ get_rows(
+ "token",
+ "app-id",
+ "log_lines",
+ mock.MagicMock(),
+ _make_manager(),
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=watermark,
+ )
+ )
+
+ body = session.post.call_args.kwargs["json"]
+ assert body["pagination"]["cursor"] == {"time": expected_cursor}
+ assert body["source_ids"] == ["src-1"]
+
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_app_without_log_sources_makes_no_query(self, mock_session):
+ session = _v2_session(graphql={"data": {"app": {"logs": {"sources": []}}}})
+ mock_session.return_value = session
+
+ assert list(get_rows("token", "app-id", "log_lines", mock.MagicMock(), _make_manager())) == []
+ assert session.post.call_count == 1
+
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_resumes_from_saved_cursor(self, mock_session):
+ lines = [{"id": "late", "timestamp": "2026-01-05T00:00:00Z"}]
+ session = _v2_session(graphql=_LOG_SOURCES, post={"/logs/lines": _log_lines_handler(lines)})
+ mock_session.return_value = session
+
+ manager = _make_manager(AppsignalResumeConfig(cursor_time="2026-01-04T00:00:00Z"))
+ list(get_rows("token", "app-id", "log_lines", mock.MagicMock(), manager))
+
+ assert session.post.call_args_list[1].kwargs["json"]["pagination"]["cursor"] == {"time": "2026-01-04T00:00:00Z"}
+
+
+class TestMetricRows:
+ _NAMES_PATH = "/metrics/names/app-id"
+
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_metric_without_type_does_not_abort_the_catalog(self, mock_session):
+ # type_and_tags 404s when a metric stops reporting between the two calls; the rest of
+ # the catalog must still sync.
+ mock_session.return_value = _v2_session(
+ get={
+ self._NAMES_PATH: ["cpu", "gone"],
+ "/metrics/type_and_tags/app-id/cpu": {"metric_type": "gauge", "available_tags": [["hostname"]]},
+ "/metrics/type_and_tags/app-id/gone": 404,
+ }
+ )
+
+ batches = list(get_rows("token", "app-id", "metric_names", mock.MagicMock(), _make_manager()))
+
+ assert batches[0] == [
+ {"name": "cpu", "metric_type": "gauge", "available_tags": [["hostname"]]},
+ {"name": "gone", "metric_type": None, "available_tags": []},
+ ]
+
+ @mock.patch(f"{MODULE}.METRICS_INITIAL_LOOKBACK_SECONDS", 3600)
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_timeseries_selectors_use_the_field_for_the_metric_type(self, mock_session):
+ session = _v2_session(
+ get={
+ self._NAMES_PATH: ["cpu", "requests", "latency", "unknown"],
+ "/metrics/type_and_tags/app-id/cpu": {"metric_type": "gauge", "available_tags": [["hostname"]]},
+ "/metrics/type_and_tags/app-id/requests": {"metric_type": "counter", "available_tags": []},
+ "/metrics/type_and_tags/app-id/latency": {
+ "metric_type": "measurement",
+ "available_tags": [{"namespace": "web"}],
+ },
+ "/metrics/type_and_tags/app-id/unknown": {"metric_type": "mystery", "available_tags": []},
+ },
+ post={"/metrics/timeseries": {"series": []}},
+ )
+ mock_session.return_value = session
+
+ list(get_rows("token", "app-id", "metric_timeseries", mock.MagicMock(), _make_manager()))
+
+ body = session.post.call_args.kwargs["json"]
+ assert body["resolution"] == "HOURLY"
+ assert body["select"] == [
+ {"name": "cpu", "field": "gauge", "tags": {"hostname": "*"}},
+ {"name": "requests", "field": "counter", "tags": {}},
+ {"name": "latency", "field": "mean", "tags": {"namespace": "*"}},
+ ]
+
+ @mock.patch(f"{MODULE}.METRICS_INITIAL_LOOKBACK_SECONDS", 3600)
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_series_are_flattened_into_ascending_point_rows(self, mock_session):
+ # Points restart at the window's start for every metric, so a batch built straight from
+ # the response order is not ascending and would corrupt the asc watermark.
+ mock_session.return_value = _v2_session(
+ get={
+ self._NAMES_PATH: ["cpu"],
+ "/metrics/type_and_tags/app-id/cpu": {"metric_type": "gauge", "available_tags": []},
+ },
+ post={
+ "/metrics/timeseries": {
+ "series": [
+ {
+ "id": "cpu/host=b/gauge",
+ "name": "cpu",
+ "field": "gauge",
+ "tags": {"host": "b"},
+ "data": [{"timestamp": "2026-01-01T02:00:00Z", "value": 4.0}],
+ },
+ {
+ "id": "cpu/host=a/gauge",
+ "name": "cpu",
+ "field": "gauge",
+ "tags": {"host": "a"},
+ "data": [{"timestamp": "2026-01-01T01:00:00Z", "value": 1.0}],
+ },
+ ]
+ }
+ },
+ )
+
+ batches = list(get_rows("token", "app-id", "metric_timeseries", mock.MagicMock(), _make_manager()))
+
+ assert [(row["series_id"], row["timestamp"], row["value"]) for row in batches[0]] == [
+ ("cpu/host=a/gauge", "2026-01-01T01:00:00Z", 1.0),
+ ("cpu/host=b/gauge", "2026-01-01T02:00:00Z", 4.0),
+ ]
+
+
+def _traces_handler(traces: list[dict[str, Any]]):
+ """Serve traces inside the requested window, truncated at `per_page` like the V2 endpoint."""
+
+ def handle(body: dict[str, Any]) -> list[dict[str, Any]]:
+ matching = [trace for trace in traces if body["from"] <= trace["time"] <= body["to"]]
+ return matching[: body["pagination"]["per_page"]]
+
+ return handle
+
+
+class TestTraceRows:
+ def _traces(self, count: int) -> list[dict[str, Any]]:
+ base = int(datetime.now(UTC).timestamp()) - 3000
+ return [
+ {"trace_id": str(offset), "site_id": "app-id", "time": _to_iso(base + offset * 100)}
+ for offset in range(count)
+ ]
+
+ @mock.patch(f"{MODULE}.V2_PAGE_SIZE", 2)
+ @mock.patch(f"{MODULE}.TRACES_INITIAL_LOOKBACK_SECONDS", 3600)
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_full_response_splits_the_window_until_every_trace_is_reached(self, mock_session):
+ # The response is capped at per_page and the cursor carries no position, so a full
+ # response means truncation. Without the split the extra traces never sync.
+ traces = self._traces(5)
+ mock_session.return_value = _v2_session(
+ post={
+ "/tracing/actions": [{"namespace": "web", "action": "UsersController#show"}],
+ "/tracing/traces/performance": _traces_handler(traces),
+ }
+ )
+
+ batches = list(get_rows("token", "app-id", "performance_traces", mock.MagicMock(), _make_manager()))
+
+ rows = [row for batch in batches for row in batch]
+ assert {row["trace_id"] for row in rows} == {"0", "1", "2", "3", "4"}
+ for batch in batches:
+ assert [row["time"] for row in batch] == sorted(row["time"] for row in batch)
+
+ @mock.patch(f"{MODULE}.TRACES_INITIAL_LOOKBACK_SECONDS", 3600)
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_spans_carry_the_parent_trace_time(self, mock_session):
+ traces = self._traces(2)
+ mock_session.return_value = _v2_session(
+ post={
+ "/tracing/actions": [{"namespace": "web", "action": "UsersController#show"}],
+ "/tracing/traces/performance": _traces_handler(traces),
+ "/tracing/trace": lambda body: [{"span_id": f"s-{body['trace_id']}", "trace_id": body["trace_id"]}],
+ }
+ )
+
+ batches = list(get_rows("token", "app-id", "trace_spans", mock.MagicMock(), _make_manager()))
+
+ assert [(row["span_id"], row["trace_time"]) for batch in batches for row in batch] == [
+ ("s-0", traces[0]["time"]),
+ ("s-1", traces[1]["time"]),
+ ]
+
+ @mock.patch(f"{MODULE}.MAX_SPAN_TRACES_PER_SYNC", 1)
+ @mock.patch(f"{MODULE}.TRACES_INITIAL_LOOKBACK_SECONDS", 3600)
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_span_cap_stops_the_sweep_and_checkpoints_the_last_trace(self, mock_session):
+ traces = self._traces(3)
+ mock_session.return_value = _v2_session(
+ post={
+ "/tracing/actions": [{"namespace": "web", "action": "UsersController#show"}],
+ "/tracing/traces/performance": _traces_handler(traces),
+ "/tracing/trace": lambda body: [{"span_id": f"s-{body['trace_id']}", "trace_id": body["trace_id"]}],
+ }
+ )
+ manager = _make_manager()
+
+ batches = list(get_rows("token", "app-id", "trace_spans", mock.MagicMock(), manager))
+
+ # Traces are handled oldest-first, so stopping early leaves the rest for the next sync.
+ assert [row["span_id"] for batch in batches for row in batch] == ["s-0"]
+ assert manager.save_state.call_args.args[0].window_start == _to_epoch(traces[0]["time"])
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appsignal/tests/test_appsignal_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appsignal/tests/test_appsignal_source.py
index 56d47fea304a..54014cf324dd 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/appsignal/tests/test_appsignal_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appsignal/tests/test_appsignal_source.py
@@ -51,9 +51,17 @@ class TestAppsignalSource:
assert {schema.name for schema in schemas} == set(ENDPOINTS)
incremental = {schema.name for schema in schemas if schema.supports_incremental}
- # Only the REST endpoints expose a server-side time filter; the GraphQL incident
- # lists don't, so they stay full refresh.
- assert incremental == {"deploy_markers", "error_samples", "performance_samples"}
+ # Only endpoints with a server-side time filter are incremental. The GraphQL incident
+ # and app lists have none, and neither does the metric-name catalog.
+ assert incremental == {
+ "deploy_markers",
+ "error_samples",
+ "performance_samples",
+ "log_lines",
+ "metric_timeseries",
+ "performance_traces",
+ "trace_spans",
+ }
def test_only_immutable_sample_tables_support_append(self):
schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}