: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(warehouse-sources): add AppSignal incident and tracing tables (#100949)
Tom Owers0fccd28f6180
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.mdindex 451f6caee81f..3a3939307cc1 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,7 +454,7 @@ Note: PostHog exposes three aggregate Pull API v5 reports (daily, geo, partners)## Appsignal — gaps-Today (11): `apps`, `deploy_markers`, `error_samples`, `exception_incidents`, `log_lines`, `metric_names`, `metric_timeseries`, `performance_incidents`, `performance_samples`, `performance_traces`, `trace_spans`+Today (18): `anomaly_incidents`, `apps`, `deploy_markers`, `deploy_stats`, `error_samples`, `exception_incidents`, `log_incidents`, `log_lines`, `metric_names`, `metric_timeseries`, `performance_actions`, `performance_incidents`, `performance_samples`, `performance_traces`, `service_edges`, `slow_event_actions`, `slow_events`, `trace_spans`Diffed against: <https://docs.appsignal.com/api/v2/overview>@@ -464,15 +464,15 @@ Diffed against: <https://docs.appsignal.com/api/v2/overview>- [ ] `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)-- [ ] `POST /api/v2/tracing/actions and service-dependency/slow-event endpoints` — aggregated per-action performance and downstream dependency breakdown (medium)+- [x] `AnomalyIncident (GraphQL)` — anomaly/trigger incidents are a first-class incident type alongside exception and performance incidents we sync (high)+- [x] `LogIncident (GraphQL)` — log-based incidents, the fourth incident type, otherwise invisible (medium)+- [x] `POST /api/v2/deploys/stats` — throughput, mean and error_rate per revision — joins directly onto deploy_markers (medium)+- [x] `POST /api/v2/tracing/actions and service-dependency/slow-event endpoints` — aggregated per-action performance and downstream dependency breakdown (medium)- [ ] `POST /api/v2/kubernetes/nodes and /api/v2/kubernetes/pods` — node and pod resource metrics for correlating app incidents with infrastructure (medium)- [ ] `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 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.+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, all four GraphQL incident types and the app list, plus the V2 logs, metrics, deploy-stats and tracing endpoints; Kubernetes, uptime monitors and check-ins are still unmapped. `POST /api/v2/tracing/action_edges` is deliberately skipped: its `namespace` argument takes a "<service>/<namespace>" pair and no endpoint we sync reports the service half, so site_edges covers service dependencies instead.## Appstack — adequatediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appsignal/appsignal.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appsignal/appsignal.pyindex 193cadd574ef..58f459944756 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,5 +1,5 @@from collections import deque-from collections.abc import Iterator+from collections.abc import Callable, Iteratorfrom datetime import UTC, date, datetime, timedeltafrom typing import Any, NoReturn, Optionalfrom urllib.parse import quote@@ -301,6 +301,7 @@ def _get_windowed_rows(logger: FilteringBoundLogger,should_use_incremental_field: bool = False,db_incremental_field_last_value: Any = None,+ initial_start: Optional[int] = None,) -> Iterator[list[dict[str, Any]]]:"""Walk a legacy REST endpoint through ascending time windows.@@ -317,7 +318,9 @@ def _get_windowed_rows(url = f"{APPSIGNAL_BASE_URL}{config.path.format(app_id=app_id)}"now = int(datetime.now(UTC).timestamp())- start = EARLIEST_START+ # `initial_start` only floors a first sync; a watermark always wins, so a long pause never+ # skips the rows between the watermark and the floor.+ start = EARLIEST_START if initial_start is None else initial_startif should_use_incremental_field:watermark = _to_epoch(db_incremental_field_last_value)if watermark is not None:@@ -398,6 +401,23 @@ 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"}+# Bucket the tracing aggregates are read at. Hourly matches the metrics resolution, so an+# action's throughput lines up with the metric series recorded beside it.+AGGREGATE_BUCKET_SECONDS = 3600+AGGREGATE_INITIAL_LOOKBACK_SECONDS = 7 * 24 * 3600+# Slow events are a ranked "worst operations" list rather than a series, so they are bucketed by+# day: a finer grain would multiply the per-digest fan-out below for no extra signal.+SLOW_EVENT_BUCKET_SECONDS = 24 * 3600+SLOW_EVENT_INITIAL_LOOKBACK_SECONDS = 30 * 24 * 3600+# Documented default for the slow-events `limit`, sent explicitly so the bucket size is pinned.+SLOW_EVENTS_LIMIT = 100+# Digests whose actions are fetched in one sync. Each costs a request, so a first sync on a busy+# app is capped and the next sync continues from the last completed bucket.+MAX_SLOW_EVENT_DIGESTS_PER_SYNC = 1_000+# How far back a first deploy-stats sync reaches, and how many revisions it stats. Deploy markers+# go back to the app's first deploy and each revision costs a request.+DEPLOY_STATS_INITIAL_LOOKBACK_SECONDS = 90 * 24 * 3600+MAX_DEPLOY_STATS_PER_SYNC = 2_000def _parse_iso(value: Any) -> Optional[datetime]:@@ -431,6 +451,16 @@ def _iter_windows(start: int, end: int, size: int) -> Iterator[TimeWindow]:start = stop+def _iter_aligned_windows(start: int, end: int, size: int) -> Iterator[TimeWindow]:+ """Windows snapped to a fixed epoch grid, for endpoints that aggregate over their range.++ An aggregate row is identified by the bucket it covers, so the grid has to be the same on+ every sync. Starting at an arbitrary `start` would shift the boundaries and seed a second+ set of rows for a range already synced.+ """+ yield from _iter_windows(start - start % size, end, size)++def _resolve_walk_start(config: AppsignalEndpointConfig,resumable_source_manager: ResumableSourceManager[AppsignalResumeConfig],@@ -803,6 +833,27 @@ def _get_metric_timeseries_rows(resumable_source_manager.save_state(AppsignalResumeConfig(window_start=window.before))+def _fetch_actions(+ session: requests.Session,+ api_token: str,+ app_id: str,+ since: int,+ before: int,+ logger: FilteringBoundLogger,+) -> list[dict[str, Any]]:+ actions = (+ _fetch_v2(+ session,+ api_token,+ "/tracing/actions",+ logger,+ body={"site_id": app_id, "from": _to_iso(since), "to": _to_iso(before)},+ )+ or []+ )+ return [action for action in actions if isinstance(action, dict)]++def _iter_action_traces(session: requests.Session,api_token: str,@@ -871,21 +922,8 @@ def _window_traces(Traces are only reachable one action at a time, so the window's actions are swept firstand 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+ for action in _fetch_actions(session, api_token, app_id, since, before, logger):namespace, action_name = action.get("namespace"), action.get("action")if not namespace or not action_name:continue@@ -1001,12 +1039,348 @@ def _get_trace_span_rows(resumable_source_manager.save_state(AppsignalResumeConfig(window_start=window.before))+def _fetch_deploy_stats(+ session: requests.Session,+ api_token: str,+ app_id: str,+ revision: str,+ logger: FilteringBoundLogger,+) -> dict[str, Any]:+ try:+ stats = _fetch_v2(+ session,+ api_token,+ "/deploys/stats",+ logger,+ body={"site_id": app_id, "revision": revision},+ )+ except requests.HTTPError as error:+ # A revision that served no requests, or whose data has aged out of retention, has no+ # statistics to report. The marker still belongs in the table.+ if error.response is None or error.response.status_code not in (404, 422):+ raise+ stats = None+ return {+ "throughput": (stats or {}).get("throughput"),+ "mean": (stats or {}).get("mean"),+ "error_rate": (stats or {}).get("error_rate"),+ }+++def _walk_aggregate_windows(+ config: AppsignalEndpointConfig,+ resumable_source_manager: ResumableSourceManager[AppsignalResumeConfig],+ logger: FilteringBoundLogger,+ bucket_seconds: int,+ initial_lookback_seconds: int,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+ build_rows: Callable[[TimeWindow, str], list[dict[str, Any]]],+) -> Iterator[list[dict[str, Any]]]:+ """Drive an aggregating endpoint over the fixed bucket grid, oldest bucket first.++ `build_rows` is handed the bucket's range and the ISO timestamp identifying it. No overlap is+ applied to the watermark: it is already the newest bucket's timestamp, and flooring it to the+ grid re-reads exactly that bucket, which was still filling when it synced.+ """+ now = int(datetime.now(UTC).timestamp())+ start = _resolve_walk_start(+ config,+ resumable_source_manager,+ logger,+ now,+ initial_lookback_seconds,+ 0,+ should_use_incremental_field,+ db_incremental_field_last_value,+ )++ for window in _iter_aligned_windows(start, now, bucket_seconds):+ rows = build_rows(window, _to_iso(window.since))+ if rows:+ yield rows+ resumable_source_manager.save_state(AppsignalResumeConfig(window_start=window.before))+++def _fetch_slow_events(+ session: requests.Session,+ api_token: str,+ app_id: str,+ window: TimeWindow,+ logger: FilteringBoundLogger,+) -> list[dict[str, Any]]:+ events = (+ _fetch_v2(+ session,+ api_token,+ "/tracing/slow_events",+ logger,+ body={+ "site_id": app_id,+ "from": _to_iso(window.since),+ "to": _to_iso(window.before),+ "limit": SLOW_EVENTS_LIMIT,+ },+ )+ or []+ )+ return [event for event in events if isinstance(event, dict) and event.get("digest")]+++def _get_deploy_stats_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 deploy statistics out over the app's deploy markers.++ `/deploys/stats` answers for one revision at a time and there is no revision listing, so the+ markers walk enumerates them. One row per marker, so the table joins onto `deploy_markers.id`+ and its `created_at` stays fixed even when a revision is deployed more than once.+ """+ now = int(datetime.now(UTC).timestamp())+ stats_by_revision: dict[str, dict[str, Any]] = {}+ windows_done = 0++ for markers in _get_windowed_rows(+ session,+ api_token,+ app_id,+ APPSIGNAL_ENDPOINTS["deploy_markers"],+ resumable_source_manager,+ logger,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ initial_start=now - DEPLOY_STATS_INITIAL_LOOKBACK_SECONDS,+ ):+ # The budget is spent between windows, never inside one. Leaving a window part-done+ # would lose its checkpoint, and a window holding the whole budget would then be redone+ # from the start on every sync without the walk ever reaching the windows after it.+ if windows_done and len(stats_by_revision) >= MAX_DEPLOY_STATS_PER_SYNC:+ logger.warning(+ f"AppSignal: reached the {MAX_DEPLOY_STATS_PER_SYNC} revision limit for {config.name}, "+ f"the next sync continues from the last completed window"+ )+ return++ rows: list[dict[str, Any]] = []+ for marker in markers:+ marker_id, revision = marker.get("id"), marker.get("revision")+ if not marker_id or not revision:+ continue++ stats = stats_by_revision.get(revision)+ if stats is None:+ stats = _fetch_deploy_stats(session, api_token, app_id, revision, logger)+ stats_by_revision[revision] = stats++ rows.append(+ {+ "marker_id": marker_id,+ "revision": revision,+ "created_at": marker.get("created_at"),+ "short_revision": marker.get("short_revision"),+ **stats,+ }+ )++ if rows:+ yield rows+ windows_done += 1+++def _get_performance_action_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]]]:+ def build_rows(window: TimeWindow, bucket: str) -> list[dict[str, Any]]:+ actions = _fetch_actions(session, api_token, app_id, window.since, window.before, logger)+ return [+ {**action, "timestamp": bucket} for action in actions if action.get("namespace") and action.get("action")+ ]++ yield from _walk_aggregate_windows(+ config,+ resumable_source_manager,+ logger,+ AGGREGATE_BUCKET_SECONDS,+ AGGREGATE_INITIAL_LOOKBACK_SECONDS,+ should_use_incremental_field,+ db_incremental_field_last_value,+ build_rows,+ )+++def _get_service_edge_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]]]:+ """Flatten the site's dependency graph into one row per peer service.++ The response groups edges under `upstream`, `downstream` and `internal`, and the same peer+ can appear in more than one group, so the group name is kept as `direction` and is part of+ the primary key.+ """++ def build_rows(window: TimeWindow, bucket: str) -> list[dict[str, Any]]:+ body = (+ _fetch_v2(+ session,+ api_token,+ "/tracing/site_edges",+ logger,+ body={"site_id": app_id, "from": _to_iso(window.since), "to": _to_iso(window.before)},+ )+ or {}+ )+ rows: list[dict[str, Any]] = []+ for direction in ("upstream", "downstream", "internal"):+ for edge in body.get(direction) or []:+ if not isinstance(edge, dict) or not edge.get("service"):+ continue+ rows.append({**edge, "direction": direction, "timestamp": bucket})+ return rows++ yield from _walk_aggregate_windows(+ config,+ resumable_source_manager,+ logger,+ AGGREGATE_BUCKET_SECONDS,+ AGGREGATE_INITIAL_LOOKBACK_SECONDS,+ should_use_incremental_field,+ db_incremental_field_last_value,+ build_rows,+ )+++def _get_slow_event_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]]]:+ def build_rows(window: TimeWindow, bucket: str) -> list[dict[str, Any]]:+ return [+ {**event, "timestamp": bucket} for event in _fetch_slow_events(session, api_token, app_id, window, logger)+ ]++ yield from _walk_aggregate_windows(+ config,+ resumable_source_manager,+ logger,+ SLOW_EVENT_BUCKET_SECONDS,+ SLOW_EVENT_INITIAL_LOOKBACK_SECONDS,+ should_use_incremental_field,+ db_incremental_field_last_value,+ build_rows,+ )+++def _get_slow_event_action_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 the actions of each slow event out per digest, oldest bucket first.++ A digest costs a request, so the sweep stops once it has spent+ MAX_SLOW_EVENT_DIGESTS_PER_SYNC of them. The budget is checked between buckets, never+ inside one: a bucket abandoned part-way keeps no checkpoint, so a single bucket holding the+ whole budget would be redone from the start on every sync and the walk would never advance.+ Finishing the bucket overshoots by at most the digests it holds.+ """+ now = int(datetime.now(UTC).timestamp())+ start = _resolve_walk_start(+ config,+ resumable_source_manager,+ logger,+ now,+ SLOW_EVENT_INITIAL_LOOKBACK_SECONDS,+ 0,+ should_use_incremental_field,+ db_incremental_field_last_value,+ )++ digests_fetched = 0+ buckets_done = 0+ for window in _iter_aligned_windows(start, now, SLOW_EVENT_BUCKET_SECONDS):+ if buckets_done and digests_fetched >= MAX_SLOW_EVENT_DIGESTS_PER_SYNC:+ logger.warning(+ f"AppSignal: reached the {MAX_SLOW_EVENT_DIGESTS_PER_SYNC} digest limit for {config.name}, "+ f"the next sync continues from the last completed bucket"+ )+ return++ bucket = _to_iso(window.since)+ rows: list[dict[str, Any]] = []++ for event in _fetch_slow_events(session, api_token, app_id, window, logger):+ digests_fetched += 1+ digest = event["digest"]+ actions = (+ _fetch_v2(+ session,+ api_token,+ "/tracing/slow_events/actions",+ logger,+ body={+ "site_id": app_id,+ "from": _to_iso(window.since),+ "to": _to_iso(window.before),+ "digest": digest,+ },+ )+ or []+ )+ rows.extend(+ {**action, "digest": digest, "timestamp": bucket}+ for action in actions+ if isinstance(action, dict) and action.get("namespace") and action.get("action_name")+ )++ if rows:+ yield rows+ resumable_source_manager.save_state(AppsignalResumeConfig(window_start=window.before))+ buckets_done += 1++_WALKERS = {"apps": _get_app_rows,+ "deploy_stats": _get_deploy_stats_rows,"log_lines": _get_log_line_rows,"metric_names": _get_metric_name_rows,"metric_timeseries": _get_metric_timeseries_rows,+ "performance_actions": _get_performance_action_rows,"performance_traces": _get_performance_trace_rows,+ "service_edges": _get_service_edge_rows,+ "slow_events": _get_slow_event_rows,+ "slow_event_actions": _get_slow_event_action_rows,"trace_spans": _get_trace_span_rows,}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.pyindex 4c0b15a2bd41..5071b1ac0a37 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@@ -52,6 +52,111 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"hasNPlusOne": "Whether any of the last 5 deploys contained an N+1 query for this action.",},},+ "anomaly_incidents": {+ "description": "An anomaly incident: an alert trigger on a metric firing, with the trigger that opened it and the tags of the matching metric.",+ "docs_url": "https://appsignal.com/graphql/docs",+ "columns": {+ "id": "Unique identifier for the incident.",+ "number": "Human-facing incident number, unique within the app.",+ "count": "Total number of occurrences recorded for this incident.",+ "state": "Triage state of the incident: OPEN, CLOSED, or WIP.",+ "severity": "Severity assigned to the incident.",+ "notificationFrequency": "How often AppSignal notifies about this incident.",+ "description": "Description of the incident, or steps to solve the issue.",+ "digests": "Digests of the metrics that make up this incident.",+ "lastOccurredAt": "Time the incident last occurred.",+ "createdAt": "Time the incident was first created.",+ "updatedAt": "Time the incident was last updated.",+ "alertState": "State of the alert: OPEN, CLOSED, WARMUP, COOLDOWN, UNTRACKED, or ARCHIVED.",+ "tags": "Tags of the metric that matched the trigger.",+ "trigger": "Alert trigger that opened the incident, with its name, kind, metric name and compared field.",+ },+ },+ "log_incidents": {+ "description": "A log incident: a log line trigger firing, with the trigger's query and the last log line that matched it.",+ "docs_url": "https://appsignal.com/graphql/docs",+ "columns": {+ "id": "Unique identifier for the incident.",+ "number": "Human-facing incident number, unique within the app.",+ "count": "Total number of log lines recorded for this incident.",+ "state": "Triage state of the incident: OPEN, CLOSED, or WIP.",+ "severity": "Severity assigned to the incident.",+ "notificationFrequency": "How often AppSignal notifies about this incident.",+ "description": "Description of the incident, or steps to solve the issue.",+ "digests": "Digests of the log lines that make up this incident.",+ "lastOccurredAt": "Time the incident last occurred.",+ "createdAt": "Time the incident was first created.",+ "updatedAt": "Time the incident was last updated.",+ "trigger": "Log line trigger that opened the incident, with its name, query, severities and log source IDs.",+ "logLine": "Most recent log line that matched the trigger.",+ },+ },+ "deploy_stats": {+ "description": "Throughput, mean response time and error rate for the revision of one deploy marker.",+ "docs_url": "https://docs.appsignal.com/api/v2/deploys",+ "columns": {+ "marker_id": "Deploy marker the statistics were read for. Joins onto deploy_markers.id.",+ "revision": "Git revision or deploy identifier the statistics cover.",+ "short_revision": "Shortened form of the revision.",+ "created_at": "Time the deploy marker was created.",+ "throughput": "Total request count recorded for the revision.",+ "mean": "Average response time for the revision, in milliseconds.",+ "error_rate": "Percentage of requests that errored, from 0 to 100.",+ },+ },+ "performance_actions": {+ "description": "Per-action performance, aggregated into hourly buckets: how often each action ran, how long it took and how often it failed.",+ "docs_url": "https://docs.appsignal.com/api/v2/traces",+ "columns": {+ "timestamp": "Start of the hourly bucket the aggregates cover.",+ "namespace": "Namespace the action belongs to (e.g. web, background).",+ "action": "Action name (e.g. POST /api/users).",+ "digest": "Hash digest identifying the action.",+ "mean": "Average duration of the action in the bucket, in milliseconds.",+ "throughput": "Number of times the action ran in the bucket.",+ "error_rate": "Percentage of runs that errored, from 0 to 100.",+ "has_npo": "Whether an N+1 query was detected for the action.",+ },+ },+ "service_edges": {+ "description": "One hourly bucket of traffic between this app and a peer service, as seen through distributed tracing.",+ "docs_url": "https://docs.appsignal.com/api/v2/traces",+ "columns": {+ "timestamp": "Start of the hourly bucket the aggregates cover.",+ "direction": "Which side of the app the peer sits on: upstream (caller), downstream (callee), or internal.",+ "service": "Name of the peer service.",+ "count": "Number of requests exchanged with the peer in the bucket.",+ "error_count": "Number of those requests that errored.",+ "mean": "Average duration of the requests, in milliseconds.",+ "p_90": "90th percentile duration, in milliseconds.",+ "p_95": "95th percentile duration, in milliseconds.",+ },+ },+ "slow_events": {+ "description": "A slow operation inside traces, such as a slow database query, ranked by its impact over a daily bucket.",+ "docs_url": "https://docs.appsignal.com/api/v2/traces",+ "columns": {+ "timestamp": "Start of the daily bucket the aggregates cover.",+ "digest": "Hash digest identifying the slow operation.",+ "count": "Number of times the operation ran in the bucket.",+ "mean": "Average duration of the operation, in milliseconds.",+ "impact": "Impact score AppSignal ranks slow events by.",+ "attributes": "Span attributes describing the operation, such as the database statement.",+ },+ },+ "slow_event_actions": {+ "description": "An action a slow operation appears in, with an example trace to open.",+ "docs_url": "https://docs.appsignal.com/api/v2/traces",+ "columns": {+ "timestamp": "Start of the daily bucket the counts cover.",+ "digest": "Digest of the slow operation. Join to slow_events on timestamp and digest.",+ "namespace": "Namespace the action belongs to (e.g. web, background).",+ "action_name": "Action the slow operation ran in.",+ "count": "Number of times the operation ran in this action.",+ "trace_id": "Example trace containing the operation.",+ "start_time": "Start time of the operation in that example trace.",+ },+ },"deploy_markers": {"description": "A deploy marker: an application release tracked by AppSignal, with the error rate observed while it was live.","docs_url": "https://docs.appsignal.com/api/markers.html",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.pyindex f5c7c2486f84..f17cfe620088 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@@ -60,6 +60,22 @@ _INCIDENT_SHARED_FIELDS = """updatedAt"""+# Anomaly and log incidents carry no `namespace` or `actionNames`, so they cannot share+# `_INCIDENT_SHARED_FIELDS`. These are the fields the Incident interface holds for every type.+_INCIDENT_COMMON_FIELDS = """+ id+ number+ count+ state+ severity+ notificationFrequency+ description+ digests+ lastOccurredAt+ createdAt+ updatedAt+"""+APPSIGNAL_ENDPOINTS: dict[str, AppsignalEndpointConfig] = {# Exception incidents are mutable aggregates (count, state, lastOccurredAt keep changing)# and the GraphQL list has no server-side timestamp filter, so they sync full refresh only.@@ -85,6 +101,58 @@ APPSIGNAL_ENDPOINTS: dict[str, AppsignalEndpointConfig] = {meantotalDurationhasNPlusOne+""",+ partition_key="createdAt",+ ),+ # The remaining two incident types. `anomalyIncidents` and `logIncidents` sit beside+ # `exceptionIncidents` on the App type, and each has the same `paginated*` companion, so they+ # are walked with the documented limit/offset/order arguments. AppSignal publishes no argument+ # list for either field, so that is read from the resolver family rather than from the docs.+ "anomaly_incidents": AppsignalEndpointConfig(+ name="anomaly_incidents",+ api="graphql",+ graphql_field="anomalyIncidents",+ graphql_selection=_INCIDENT_COMMON_FIELDS+ + """+ alertState+ tags {+ key+ value+ }+ trigger {+ id+ name+ kind+ description+ metricName+ field+ }+""",+ partition_key="createdAt",+ ),+ "log_incidents": AppsignalEndpointConfig(+ name="log_incidents",+ api="graphql",+ graphql_field="logIncidents",+ graphql_selection=_INCIDENT_COMMON_FIELDS+ + """+ trigger {+ id+ name+ description+ query+ severities+ sourceIds+ actionType+ }+ logLine {+ id+ timestamp+ severity+ hostname+ group+ message+ }""",partition_key="createdAt",),@@ -109,6 +177,25 @@ APPSIGNAL_ENDPOINTS: dict[str, AppsignalEndpointConfig] = {},],),+ # Per-revision throughput, mean and error rate. `/api/v2/deploys/stats` answers for one+ # revision at a time and AppSignal publishes no revision listing, so the deploy markers are+ # the only enumeration of them — one row per marker, which joins onto `deploy_markers.id`.+ "deploy_stats": AppsignalEndpointConfig(+ name="deploy_stats",+ api="custom",+ walker="deploy_stats",+ primary_keys=["marker_id"],+ cursor_field="created_at",+ partition_key="created_at",+ incremental_fields=[+ {+ "label": "created_at",+ "type": IncrementalFieldType.DateTime,+ "field": "created_at",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+ ),# Samples are immutable once recorded; `time` is a UNIX epoch integer that the API's# `since`/`before` params filter on server-side."error_samples": AppsignalEndpointConfig(@@ -238,6 +325,79 @@ APPSIGNAL_ENDPOINTS: dict[str, AppsignalEndpointConfig] = {},],),+ # Every table below aggregates over the time range it is asked for, so a row is a fixed+ # bucket rather than an event. Buckets are aligned to the epoch: a re-read of a range lands+ # on the same `timestamp` and merges onto the same rows instead of seeding shifted ones.+ # The newest bucket is still filling when it syncs, and settles on the next sync.+ "performance_actions": AppsignalEndpointConfig(+ name="performance_actions",+ api="custom",+ walker="performance_actions",+ primary_keys=["timestamp", "namespace", "action"],+ cursor_field="timestamp",+ partition_key="timestamp",+ incremental_fields=[+ {+ "label": "timestamp",+ "type": IncrementalFieldType.DateTime,+ "field": "timestamp",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+ ),+ # Service dependency edges for the app, from `/api/v2/tracing/site_edges`. The per-action+ # `action_edges` endpoint is not synced: its `namespace` argument takes a "<service>/<namespace>"+ # pair, and no endpoint we sync reports the service half of it.+ "service_edges": AppsignalEndpointConfig(+ name="service_edges",+ api="custom",+ walker="service_edges",+ primary_keys=["timestamp", "direction", "service"],+ cursor_field="timestamp",+ partition_key="timestamp",+ incremental_fields=[+ {+ "label": "timestamp",+ "type": IncrementalFieldType.DateTime,+ "field": "timestamp",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+ ),+ "slow_events": AppsignalEndpointConfig(+ name="slow_events",+ api="custom",+ walker="slow_events",+ primary_keys=["timestamp", "digest"],+ cursor_field="timestamp",+ partition_key="timestamp",+ incremental_fields=[+ {+ "label": "timestamp",+ "type": IncrementalFieldType.DateTime,+ "field": "timestamp",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+ ),+ # The actions each slow event appears in, fanned out per digest over the same buckets as+ # `slow_events`.+ "slow_event_actions": AppsignalEndpointConfig(+ name="slow_event_actions",+ api="custom",+ walker="slow_event_actions",+ primary_keys=["timestamp", "digest", "namespace", "action_name"],+ cursor_field="timestamp",+ partition_key="timestamp",+ incremental_fields=[+ {+ "label": "timestamp",+ "type": IncrementalFieldType.DateTime,+ "field": "timestamp",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+ ),}ENDPOINTS = tuple(APPSIGNAL_ENDPOINTS.keys())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.pyindex bcd9533fe965..4aeb13a6afd9 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,6 +7,7 @@ from unittest import mockimport requestsfrom products.warehouse_sources.backend.temporal.data_imports.sources.appsignal.appsignal import (+ AGGREGATE_BUCKET_SECONDS,APPSIGNAL_GRAPHQL_URL,APPSIGNAL_V2_URL,AppsignalResumeConfig,@@ -14,6 +15,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.appsignal._fetch_graphql,_fetch_json,_fetch_v2,+ _iter_aligned_windows,_parse_iso,_to_epoch,_to_iso,@@ -695,3 +697,239 @@ class TestTraceRows:# 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"])+++class TestAlignedWindows:+ def test_buckets_snap_to_the_grid_wherever_the_walk_starts(self):+ # An aggregate row is identified by the bucket it covers. Two syncs resuming at different+ # offsets inside a bucket have to produce the same boundaries, or the second one seeds a+ # parallel set of rows for a range already synced instead of merging onto it.+ end = 1_000_000 + 4 * 3600+ from_edge = [window.since for window in _iter_aligned_windows(997_200, end, 3600)]+ from_middle = [window.since for window in _iter_aligned_windows(997_200 + 91, end, 3600)]++ assert from_edge == from_middle+ assert all(since % 3600 == 0 for since in from_edge)+++class TestPerformanceActionRows:+ @mock.patch(f"{MODULE}.AGGREGATE_INITIAL_LOOKBACK_SECONDS", 2 * 3600)+ @mock.patch(f"{MODULE}.make_tracked_session")+ def test_rows_are_stamped_with_the_bucket_they_were_read_for(self, mock_session):+ session = _v2_session(+ post={+ "/tracing/actions": [+ {"namespace": "web", "action": "UsersController#show", "mean": 12.0},+ # No action name, so the row could not be keyed and must not reach the table.+ {"namespace": "web", "mean": 3.0},+ ]+ }+ )+ mock_session.return_value = session++ batches = list(get_rows("token", "app-id", "performance_actions", mock.MagicMock(), _make_manager()))++ rows = [row for batch in batches for row in batch]+ assert {row["action"] for row in rows} == {"UsersController#show"}+ requested_from = [call.kwargs["json"]["from"] for call in session.post.call_args_list]+ assert [row["timestamp"] for row in rows] == requested_from+ assert all((_to_epoch(value) or 0) % AGGREGATE_BUCKET_SECONDS == 0 for value in requested_from)++ @mock.patch(f"{MODULE}.AGGREGATE_INITIAL_LOOKBACK_SECONDS", 2 * 3600)+ @mock.patch(f"{MODULE}.make_tracked_session")+ def test_watermark_re_reads_its_own_bucket(self, mock_session):+ # The newest bucket was still filling when it synced, so the watermark's bucket has to be+ # read again and merged; starting after it would freeze a partial aggregate.+ watermark = _to_iso(1_000_000 - 1_000_000 % AGGREGATE_BUCKET_SECONDS)+ session = _v2_session(post={"/tracing/actions": []})+ mock_session.return_value = session++ list(+ get_rows(+ "token",+ "app-id",+ "performance_actions",+ mock.MagicMock(),+ _make_manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=watermark,+ )+ )++ assert session.post.call_args_list[0].kwargs["json"]["from"] == watermark+++class TestServiceEdgeRows:+ @mock.patch(f"{MODULE}.AGGREGATE_INITIAL_LOOKBACK_SECONDS", 3600)+ @mock.patch(f"{MODULE}.make_tracked_session")+ def test_the_same_peer_in_two_directions_stays_two_rows(self, mock_session):+ # A service both calls us and is called by us, so the group it came from is what tells the+ # two apart — collapsing them would merge the pair onto one primary key.+ mock_session.return_value = _v2_session(+ post={+ "/tracing/site_edges": {+ "upstream": [{"service": "gateway", "count": 3}],+ "downstream": [{"service": "gateway", "count": 5}],+ "internal": [{"count": 1}],+ }+ }+ )++ batches = list(get_rows("token", "app-id", "service_edges", mock.MagicMock(), _make_manager()))++ rows = [row for batch in batches for row in batch]+ assert {(row["direction"], row["service"], row["count"]) for row in rows} == {+ ("upstream", "gateway", 3),+ ("downstream", "gateway", 5),+ }+++class TestSlowEventRows:+ _EVENTS = [{"digest": "d1", "impact": 9}, {"digest": "d2", "impact": 2}]++ def _session(self) -> mock.MagicMock:+ return _v2_session(+ post={+ "/tracing/slow_events": self._EVENTS,+ "/tracing/slow_events/actions": lambda body: [+ {"namespace": "web", "action_name": f"action-for-{body['digest']}", "count": 1}+ ],+ }+ )++ @mock.patch(f"{MODULE}.SLOW_EVENT_BUCKET_SECONDS", 3600)+ @mock.patch(f"{MODULE}.SLOW_EVENT_INITIAL_LOOKBACK_SECONDS", 900)+ @mock.patch(f"{MODULE}.make_tracked_session")+ def test_actions_carry_the_digest_they_were_fanned_out_from(self, mock_session):+ # The digest is only in the request, so without it on the row nothing joins the action+ # back to its slow event.+ mock_session.return_value = self._session()++ batches = list(get_rows("token", "app-id", "slow_event_actions", mock.MagicMock(), _make_manager()))++ rows = [row for batch in batches for row in batch]+ assert {(row["digest"], row["action_name"]) for row in rows} == {+ ("d1", "action-for-d1"),+ ("d2", "action-for-d2"),+ }+ assert {row["timestamp"] for row in rows} == {row["timestamp"] for row in rows if row["digest"] == "d1"}++ @mock.patch(f"{MODULE}.MAX_SLOW_EVENT_DIGESTS_PER_SYNC", 1)+ @mock.patch(f"{MODULE}.SLOW_EVENT_BUCKET_SECONDS", 3600)+ @mock.patch(f"{MODULE}.SLOW_EVENT_INITIAL_LOOKBACK_SECONDS", 2 * 3600)+ @mock.patch(f"{MODULE}.make_tracked_session")+ def test_digest_cap_stops_between_buckets_so_the_walk_advances(self, mock_session):+ # Stopping inside a bucket would leave it uncheckpointed, and a bucket holding the whole+ # budget would then be redone from the start on every sync, reaching no later bucket.+ mock_session.return_value = self._session()+ manager = _make_manager()+ logger = mock.MagicMock()++ batches = list(get_rows("token", "app-id", "slow_event_actions", logger, manager))++ assert [row["digest"] for batch in batches for row in batch] == ["d1", "d2"]+ manager.save_state.assert_called_once()+ assert "digest limit" in logger.warning.call_args.args[0]+++def _deploy_stats_session(markers: list[dict[str, Any]], stats: Any) -> mock.MagicMock:+ """Serve the legacy markers endpoint over GET and `/deploys/stats` over POST.++ `stats` is a payload, a status code to fail with, or a callable taking the revision.+ """++ def do_get(url: str, params: dict[str, Any] | None = None, timeout: Any = None) -> mock.MagicMock:+ params = params or {}+ since, before = int(params.get("from", 0)), int(params.get("to", 2**62))+ matching = [marker for marker in markers if since <= (_to_epoch(marker["created_at"]) or 0) <= before]+ if params.get("count_only"):+ return _response({"count": len(matching)})+ return _response({"markers": matching[: int(params["limit"])]})++ def do_post(url: str, params: Any = None, json: Any = None, timeout: Any = None) -> mock.MagicMock:+ assert url == f"{APPSIGNAL_V2_URL}/deploys/stats"+ payload = stats(json["revision"]) if callable(stats) else stats+ if isinstance(payload, int):+ return _response({"error": "Not found"}, status_code=payload)+ return _response(payload)++ session = mock.MagicMock()+ session.get.side_effect = do_get+ session.post.side_effect = do_post+ return session+++class TestDeployStatsRows:+ def _markers(self, revisions: list[str]) -> list[dict[str, Any]]:+ base = int(datetime.now(UTC).timestamp()) - 10_000+ return [+ {"id": f"m{offset}", "revision": revision, "created_at": _to_iso(base + offset * 10)}+ for offset, revision in enumerate(revisions)+ ]++ @mock.patch(f"{MODULE}.make_tracked_session")+ def test_every_marker_gets_a_row_but_a_repeated_revision_costs_one_request(self, mock_session):+ # Redeploying the same revision is common, and the stats endpoint answers per revision, so+ # a request per marker would double the API cost for an identical answer.+ markers = self._markers(["abc123", "abc123", "def456"])+ session = _deploy_stats_session(markers, {"throughput": 10, "mean": 5.0, "error_rate": 1.5})+ mock_session.return_value = session++ batches = list(get_rows("token", "app-id", "deploy_stats", mock.MagicMock(), _make_manager()))++ rows = [row for batch in batches for row in batch]+ assert [(row["marker_id"], row["revision"], row["throughput"]) for row in rows] == [+ ("m0", "abc123", 10),+ ("m1", "abc123", 10),+ ("m2", "def456", 10),+ ]+ assert [call.kwargs["json"]["revision"] for call in session.post.call_args_list] == ["abc123", "def456"]++ @pytest.mark.parametrize("status_code", [404, 422])+ @mock.patch(f"{MODULE}.make_tracked_session")+ def test_a_revision_without_statistics_still_yields_its_marker(self, mock_session, status_code):+ # A deploy that served no requests, or whose data aged out of retention, has no stats to+ # report — dropping the row would lose the deploy from the table entirely.+ mock_session.return_value = _deploy_stats_session(self._markers(["abc123"]), status_code)++ batches = list(get_rows("token", "app-id", "deploy_stats", mock.MagicMock(), _make_manager()))++ assert [(row["marker_id"], row["throughput"]) for batch in batches for row in batch] == [("m0", None)]++ @mock.patch(f"{MODULE}.MAX_DEPLOY_STATS_PER_SYNC", 1)+ @mock.patch(f"{MODULE}.WINDOW_PAGE_LIMIT", 1)+ @mock.patch(f"{MODULE}.make_tracked_session")+ def test_revision_cap_stops_between_windows_so_the_walk_advances(self, mock_session):+ # Same reason as the slow-event digest cap: a window abandoned part-way keeps no+ # checkpoint, so the next sync would redo it and never reach the windows after it.+ markers = self._markers(["r0", "r1", "r2"])+ session = _deploy_stats_session(markers, {"throughput": 1})+ mock_session.return_value = session+ manager = _make_manager()++ batches = list(get_rows("token", "app-id", "deploy_stats", mock.MagicMock(), manager))++ assert [row["marker_id"] for batch in batches for row in batch] == ["m0"]+ assert manager.save_state.call_count == 1++ @mock.patch(f"{MODULE}.make_tracked_session")+ def test_a_watermark_older_than_the_initial_lookback_still_wins(self, mock_session):+ # The lookback only floors a first sync. Clamping an older watermark up to it would skip+ # every deploy in between when a source has been paused.+ watermark = int(datetime.now(UTC).timestamp()) - 400 * 24 * 3600+ session = _deploy_stats_session([], {})+ mock_session.return_value = session++ list(+ get_rows(+ "token",+ "app-id",+ "deploy_stats",+ mock.MagicMock(),+ _make_manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=watermark,+ )+ )++ assert session.get.call_args_list[0].kwargs["params"]["from"] == watermark - 1diff --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.pyindex 54014cf324dd..49bd10814cc9 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@@ -55,11 +55,16 @@ class TestAppsignalSource:# and app lists have none, and neither does the metric-name catalog.assert incremental == {"deploy_markers",+ "deploy_stats","error_samples","performance_samples","log_lines","metric_timeseries",+ "performance_actions","performance_traces",+ "service_edges",+ "slow_events",+ "slow_event_actions","trace_spans",}@@ -71,6 +76,9 @@ class TestAppsignalSource:# Deploy markers mutate after creation (exception counts accumulate) — merge only.assert schemas["deploy_markers"].supports_append is Falseassert schemas["exception_incidents"].supports_append is False+ # The newest bucket of an aggregate is still filling when it syncs, so it must merge.+ assert schemas["performance_actions"].supports_append is False+ assert schemas["slow_events"].supports_append is Falsedef test_incremental_schemas_advertise_their_fields(self):schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}