Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): implement aviator import source (#70022)

Tom Owers4e0e254cace4
diff --git a/frontend/public/services/aviator.svg b/frontend/public/services/aviator.svg
new file mode 100644
index 000000000000..6f6f9d036bbc
--- /dev/null
+++ b/frontend/public/services/aviator.svg
@@ -0,0 +1,5 @@
+<svg width="256" height="256" viewBox="0 0 256 256" fill="none" xmlns="http://www.w3.org/2000/svg" aria-label="Aviator logo mark">
+ <rect width="256" height="256" rx="56" fill="#5B4CF0"/>
+ <path d="M196 60 60 118l52 22 18 54 24-38 42 32z" fill="#FFFFFF"/>
+ <path d="M112 140 196 60l-66 90z" fill="#C7BEFA"/>
+</svg>
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 2c98c6a93431..2a30b0527293 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -66,6 +66,7 @@ the row lists both.
| attentive | HTTP (webhook-first) | requests (webhook management) | ✅ |
| attio | HTTP | requests + `rest_source.RESTClient` | ✅ |
| aviationstack | HTTP | requests | ✅ |
+| aviator | HTTP | requests | ✅ |
| awin | HTTP | requests | ✅ |
| azure_devops | HTTP | requests | ✅ |
| bamboohr | HTTP | requests | ✅ |
@@ -479,7 +480,6 @@ doesn't conflict with concurrent PRs.
- apptivo
- appwrite
- auth0
-- aviator
- aws_cloudtrail
- azure_blob
- azure_table_storage
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aviator/aviator.posthog-doc.mdx b/products/warehouse_sources/backend/temporal/data_imports/sources/aviator/aviator.posthog-doc.mdx
new file mode 100644
index 000000000000..fdd3c419df8f
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aviator/aviator.posthog-doc.mdx
@@ -0,0 +1,68 @@
+<!--
+This is the user-facing source documentation. It belongs in the posthog.com repo at
+contents/docs/cdp/sources/aviator.md (served at /docs/cdp/sources/aviator). It is kept here only
+because a posthog.com checkout was not available when the source was implemented — copy it across and
+delete this file from this repo. Run `python manage.py audit_source_docs --docs-dir <posthog.com>/contents/docs/cdp/sources`
+once it lands.
+-->
+
+---
+
+title: Linking Aviator as a source
+sidebar: Docs
+showTitle: true
+availability: { free: full, selfServe: full, enterprise: full }
+sourceId: Aviator
+beta: true
+
+---
+
+import SourceSetupIntro from '../_snippets/source-setup-intro.mdx'
+import SyncModes from '../_snippets/sync-modes.mdx'
+import TroubleshootingLink from '../_snippets/dw-troubleshooting-link.mdx'
+import AlphaRelease from '../_snippets/alpha-release.mdx'
+
+<AlphaRelease />
+
+[Aviator](https://www.aviator.co/) is a developer productivity suite built around a merge queue for GitHub.
+This connector pulls your Aviator data — repositories, daily merge-queue analytics, currently queued pull
+requests, live queue depth, and merge-queue config history — into the PostHog Data warehouse so you can
+join it with your product and engineering data.
+
+## Prerequisites
+
+You need an Aviator account and a user access token. The token inherits your account's repository access,
+so no additional scopes are required.
+
+## Adding a data source
+
+<SourceSetupIntro />
+
+Aviator authenticates with a user access token (it starts with `av_uat_`). Create one from your
+[Aviator account settings](https://www.aviator.co/) and paste it into the **API token** field.
+
+## Sync modes
+
+<SyncModes />
+
+Only **Merge queue analytics** supports incremental sync — it advances a UTC date window (`start`/`end`)
+and re-reads a short trailing window each run, because recent daily aggregates can be revised. The other
+tables are current-state snapshots or small lists with no server-side timestamp filter, so they sync as
+full refresh.
+
+## Configuration
+
+<SourceParameters />
+
+## Supported tables
+
+<SourceTables />
+
+## Troubleshooting
+
+- **401 Unauthorized** — the API token is invalid or has been revoked. Create a new user access token in
+ your Aviator account settings and reconnect.
+- **403 Forbidden** — the token is valid but does not have access to a repository's data. Check the
+ token's repository access in Aviator and reconnect.
+
+<TroubleshootingLink />
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aviator/aviator.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aviator/aviator.py
new file mode 100644
index 000000000000..feed77b74f66
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aviator/aviator.py
@@ -0,0 +1,380 @@
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime, timedelta
+from typing import Any, Optional
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.batcher import Batcher
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.aviator.settings import (
+ AVIATOR_ENDPOINTS,
+ AviatorEndpointConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+
+AVIATOR_BASE_URL = "https://api.aviator.co/api/v1"
+
+# GET /repo is capped at 10 results per page (documented).
+REPO_PAGE_SIZE = 10
+# Bound the config-history paginator so a misbehaving API can't loop forever.
+CONFIG_HISTORY_MAX_PAGES = 1000
+# Re-pull a trailing window of daily analytics each incremental run: recent days' aggregates can
+# still be revised upstream. Merge dedupes the re-pulled days on the [repo, date] primary key.
+ANALYTICS_LOOKBACK_DAYS = 7
+# Series returned by GET /analytics. Each is a list of per-day objects carrying a `date` plus that
+# series' metric fields; we merge them into one row per date, prefixing each metric with its series
+# name (e.g. `time_in_queue_p50`) so the shared min/avg/pXX names don't collide.
+_ANALYTICS_SERIES = (
+ "time_in_queue",
+ "wait_times_to_queue",
+ "mergequeue_usage",
+ "blocked_reason",
+ "sync_frequency",
+)
+
+
+class AviatorRetryableError(Exception):
+ pass
+
+
+class AviatorResumeConfig:
+ # Stable "org/name" keys of the fan-out repositories already fully processed in an earlier
+ # attempt of this job. We resume by processing any repo NOT in this set, so a repo added between
+ # a crash and the retry is picked up (a positional bookmark would silently skip it, and — because
+ # fan-out persists the watermark only at successful job end — that skipped repo's older analytics
+ # would then never be fetched outside the trailing lookback window). Empty for the non-fan-out
+ # `repositories` endpoint, which is a short full-refresh list re-paginated from the start each run.
+ completed_repo_keys: list[str] = dataclasses.field(default_factory=list)
+
+
+def _get_headers(api_token: str) -> dict[str, str]:
+ return {
+ "Authorization": f"Bearer {api_token}",
+ "Content-Type": "application/json",
+ "Accept": "application/json",
+ }
+
+
+@retry(
+ retry=retry_if_exception_type(
+ (
+ AviatorRetryableError,
+ requests.ReadTimeout,
+ requests.ConnectionError,
+ requests.exceptions.ChunkedEncodingError,
+ )
+ ),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch(
+ session: requests.Session,
+ url: str,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ params: Optional[dict[str, Any]] = None,
+) -> Any:
+ response = session.get(url, headers=headers, params=params, timeout=60)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise AviatorRetryableError(f"Aviator API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ # Log only status and URL — never the response body. Aviator error bodies can echo
+ # request-specific data (config-history diffs, token-like values), which must not spill
+ # into application logs where access is broader than the source data itself.
+ logger.error(f"Aviator API error: status={response.status_code}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def validate_credentials(api_token: str) -> bool:
+ """Probe the token with the cheapest account-level call. GET /repo needs no extra scope, so a
+ 200 confirms the token is genuine; a 401 means it is invalid or revoked."""
+ try:
+ response = make_tracked_session(redact_values=(api_token,), capture=False).get(
+ f"{AVIATOR_BASE_URL}/repo", headers=_get_headers(api_token), params={"page": 1}, timeout=10
+ )
+ return response.status_code == 200
+ except Exception:
+ return False
+
+
+def _iter_repositories(
+ session: requests.Session, headers: dict[str, str], logger: FilteringBoundLogger
+) -> Iterator[dict[str, Any]]:
+ """Page through GET /repo yielding each {active, name, org, paused} object."""
+ page = 1
+ while True:
+ data = _fetch(session, f"{AVIATOR_BASE_URL}/repo", headers, logger, params={"page": page})
+ items = data if isinstance(data, list) else []
+ yield from items
+ # The list is short (10/page) and the last page is a partial (or empty) page.
+ if len(items) < REPO_PAGE_SIZE:
+ break
+ page += 1
+
+
+def _parse_date(value: Any) -> date:
+ if isinstance(value, datetime):
+ return value.date()
+ if isinstance(value, date):
+ return value
+ return datetime.strptime(str(value)[:10], "%Y-%m-%d").date()
+
+
+def _analytics_window(
+ config: AviatorEndpointConfig, should_use_incremental_field: bool, db_incremental_field_last_value: Any
+) -> tuple[str, str]:
+ """Compute the (start, end) YYYY-MM-DD window for a GET /analytics request."""
+ today = datetime.now(UTC).date()
+ if should_use_incremental_field and db_incremental_field_last_value:
+ # Advance from the stored watermark, minus a trailing safety window (recent aggregates get revised).
+ start = _parse_date(db_incremental_field_last_value) - timedelta(days=ANALYTICS_LOOKBACK_DAYS)
+ else:
+ start = today - timedelta(days=config.default_lookback_days or 365)
+ # A future-dated watermark (unexpected, but cheap to guard) would make start > end; clamp it.
+ if start > today:
+ start = today
+ return start.isoformat(), today.isoformat()
+
+
+def _flatten_analytics(repo: str, org: str, name: str, payload: dict[str, Any]) -> list[dict[str, Any]]:
+ """Merge the five daily analytics series into one row per date for a single repository."""
+ rows_by_date: dict[str, dict[str, Any]] = {}
+ for series_name in _ANALYTICS_SERIES:
+ series = payload.get(series_name)
+ if not isinstance(series, list):
+ continue
+ for item in series:
+ if not isinstance(item, dict):
+ continue
+ day = item.get("date")
+ if not day:
+ continue
+ row = rows_by_date.setdefault(day, {"repo": repo, "org": org, "name": name, "date": day})
+ for key, value in item.items():
+ if key == "date":
+ continue
+ row[f"{series_name}_{key}"] = value
+ return [rows_by_date[day] for day in sorted(rows_by_date)]
+
+
+def _extract_fan_out_rows(
+ session: requests.Session,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ endpoint: str,
+ config: AviatorEndpointConfig,
+ org: str,
+ name: str,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+) -> Iterator[dict[str, Any]]:
+ """Fetch one repository's rows for a fan-out endpoint, normalized to flat dicts."""
+ url = f"{AVIATOR_BASE_URL}{config.path}"
+
+ if endpoint == "merge_queue_analytics":
+ start, end = _analytics_window(config, should_use_incremental_field, db_incremental_field_last_value)
+ payload = _fetch(session, url, headers, logger, params={"repo": f"{org}/{name}", "start": start, "end": end})
+ yield from _flatten_analytics(f"{org}/{name}", org, name, payload)
+ return
+
+ if endpoint == "queued_pull_requests":
+ payload = _fetch(session, url, headers, logger, params={"org": org, "repo": name})
+ for pr in payload.get("pull_requests", []):
+ # `number` is part of the (org, repo, number) primary key. A row missing it would merge
+ # under a null key, silently collapsing every such PR in the repo into one row — skip it.
+ if pr.get("number") is None:
+ logger.warning(f"Aviator: skipping queued pull request without a number for {org}/{name}")
+ continue
+ pr.pop("repository", None) # Redundant with the injected org/repo below.
+ yield {**pr, "org": org, "repo": name}
+ return
+
+ if endpoint == "queue_stats":
+ payload = _fetch(session, url, headers, logger, params={"org": org, "repo": name})
+ depth = payload.get("depth", {})
+ yield {
+ "org": org,
+ "repo": name,
+ "queued": depth.get("queued"),
+ "processing": depth.get("processing"),
+ "waiting": depth.get("waiting"),
+ }
+ return
+
+ if endpoint == "config_history":
+ page = 1
+ while page <= CONFIG_HISTORY_MAX_PAGES:
+ payload = _fetch(session, url, headers, logger, params={"org": org, "repo": name, "page": page})
+ history = payload.get("history", [])
+ if not history:
+ break
+ for change in history:
+ # `applied_at` is part of the (org, repo, applied_at) primary key. A row missing it
+ # would merge under a null key, collapsing multiple config changes into one — skip it.
+ applied_at = change.get("applied_at")
+ if not applied_at:
+ logger.warning(f"Aviator: skipping config history entry without applied_at for {org}/{name}")
+ continue
+ applied_by = change.get("applied_by") or {}
+ yield {
+ "org": org,
+ "repo": name,
+ "applied_at": applied_at,
+ "commit_sha": change.get("commit_sha"),
+ "diff": change.get("diff"),
+ "applied_by_email": applied_by.get("email"),
+ "applied_by_gh_username": applied_by.get("gh_username"),
+ }
+ page += 1
+ else:
+ logger.warning(f"Aviator config_history hit the page cap ({CONFIG_HISTORY_MAX_PAGES}) for {org}/{name}")
+ return
+
+ raise ValueError(f"Unknown fan-out endpoint: {endpoint}")
+
+
+def _get_repository_rows(
+ session: requests.Session,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ batcher: Batcher,
+) -> Iterator[Any]:
+ for repo in _iter_repositories(session, headers, logger):
+ batcher.batch(repo)
+ if batcher.should_yield():
+ yield batcher.get_table()
+
+
+def _get_fan_out_rows(
+ session: requests.Session,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ batcher: Batcher,
+ resumable_source_manager: ResumableSourceManager[AviatorResumeConfig],
+ endpoint: str,
+ config: AviatorEndpointConfig,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+) -> Iterator[Any]:
+ repos = list(_iter_repositories(session, headers, logger))
+
+ # Resume by skipping only repos already fully processed in an earlier attempt of this job. Keyed
+ # on stable "org/name" (not a positional index) so a repo added between a crash and the retry is
+ # still processed rather than skipped — skipping it would strand its older rows, since fan-out
+ # persists the watermark only at successful job end. Within a repo we always re-fetch from the
+ # start, so this is at repo granularity only; merge dedupes any re-pulled rows on the primary key.
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ completed_repo_keys = list(resume.completed_repo_keys) if resume is not None else []
+ completed = set(completed_repo_keys)
+
+ for repo in repos:
+ org, name = repo.get("org"), repo.get("name")
+ if not org or not name:
+ continue
+ repo_key = f"{org}/{name}"
+ if repo_key in completed:
+ logger.debug(f"Aviator: skipping already-processed repo={repo_key} for {endpoint} fan-out")
+ continue
+
+ for row in _extract_fan_out_rows(
+ session,
+ headers,
+ logger,
+ endpoint,
+ config,
+ org,
+ name,
+ should_use_incremental_field,
+ db_incremental_field_last_value,
+ ):
+ batcher.batch(row)
+ if batcher.should_yield():
+ yield batcher.get_table()
+
+ # Mark this repo done so a crash resumes with the repos still owed. Saved AFTER yielding this
+ # repo's batches so a crash mid-repo re-processes it (merge dedupes) rather than skipping it.
+ completed_repo_keys.append(repo_key)
+ completed.add(repo_key)
+ resumable_source_manager.save_state(AviatorResumeConfig(completed_repo_keys=list(completed_repo_keys)))
+
+
+def get_rows(
+ api_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[AviatorResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+ incremental_field: str | None = None,
+) -> Iterator[Any]:
+ config = AVIATOR_ENDPOINTS[endpoint]
+ headers = _get_headers(api_token)
+ # One session reused across every page and every fan-out repo so urllib3 keeps the connection alive.
+ # Register the token for value-based redaction so it can't surface in logged URLs, and disable sample
+ # capture: responses carry arbitrary repository data (config-history diffs, PR titles, branch names)
+ # that the name-based scrubber can't sanitise, so it must never reach the HTTP sample bucket.
+ session = make_tracked_session(redact_values=(api_token,), capture=False)
+ batcher = Batcher(logger=logger)
+
+ if config.fan_out_over_repos:
+ yield from _get_fan_out_rows(
+ session,
+ headers,
+ logger,
+ batcher,
+ resumable_source_manager,
+ endpoint,
+ config,
+ should_use_incremental_field,
+ db_incremental_field_last_value,
+ )
+ else:
+ yield from _get_repository_rows(session, headers, logger, batcher)
+
+ if batcher.should_yield(include_incomplete_chunk=True):
+ yield batcher.get_table()
+
+
+def aviator_source(
+ api_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[AviatorResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+ incremental_field: str | None = None,
+) -> SourceResponse:
+ config = AVIATOR_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_token=api_token,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ incremental_field=incremental_field,
+ ),
+ primary_keys=config.primary_keys,
+ # Fan-out runs persist the incremental watermark only at successful job end (desc mode): a
+ # partial run's max date says nothing about repos it never reached, so per-batch persistence
+ # could advance the watermark past rows a crashed run still owes.
+ sort_mode="desc" if config.fan_out_over_repos else "asc",
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="month" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aviator/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aviator/canonical_descriptions.py
new file mode 100644
index 000000000000..b2b28c33ba4e
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aviator/canonical_descriptions.py
@@ -0,0 +1,96 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Descriptions sourced from Aviator's public JSON API docs (https://docs.aviator.co/api/reference/json-api).
+# Keyed by the endpoint/schema names returned by `get_schemas` (see settings.AVIATOR_ENDPOINTS).
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "repositories": {
+ "description": "GitHub repositories connected to Aviator, with their merge-queue status.",
+ "docs_url": "https://docs.aviator.co/api/reference/json-api",
+ "columns": {
+ "org": "GitHub organization that owns the repository.",
+ "name": "Repository name within the organization.",
+ "active": "Whether Aviator is actively managing the merge queue for this repository.",
+ "paused": "Whether merging of PRs is currently paused for this repository.",
+ },
+ },
+ "merge_queue_analytics": {
+ "description": "Daily merge-queue analytics per repository, merging Aviator's five daily aggregate series into one row per day.",
+ "docs_url": "https://docs.aviator.co/api/reference/json-api",
+ "columns": {
+ "repo": "Repository the analytics belong to, in orgname/reponame form.",
+ "org": "GitHub organization that owns the repository.",
+ "name": "Repository name within the organization.",
+ "date": "UTC day the aggregates cover (YYYY-MM-DD).",
+ "time_in_queue_min": "Minimum time a PR spent in the queue that day, in seconds.",
+ "time_in_queue_avg": "Average time PRs spent in the queue that day, in seconds.",
+ "time_in_queue_p50": "50th percentile time in queue that day, in seconds.",
+ "time_in_queue_p75": "75th percentile time in queue that day, in seconds.",
+ "time_in_queue_p90": "90th percentile time in queue that day, in seconds.",
+ "time_in_queue_p100": "Maximum (100th percentile) time in queue that day, in seconds.",
+ "wait_times_to_queue_min": "Minimum time to get added to a batch after pre-queue validation, in seconds.",
+ "wait_times_to_queue_avg": "Average time to get added to a batch after pre-queue validation, in seconds.",
+ "wait_times_to_queue_p50": "50th percentile wait time to be added to a batch, in seconds.",
+ "wait_times_to_queue_p75": "75th percentile wait time to be added to a batch, in seconds.",
+ "wait_times_to_queue_p90": "90th percentile wait time to be added to a batch, in seconds.",
+ "wait_times_to_queue_p100": "Maximum wait time to be added to a batch, in seconds.",
+ "mergequeue_usage_total": "Total number of PRs merged that day.",
+ "mergequeue_usage_merged_by_bot": "Number of PRs merged by the Aviator bot that day.",
+ "blocked_reason_merge_conflict": "PRs blocked that day due to a merge conflict.",
+ "blocked_reason_ci_failure": "PRs blocked that day due to a required CI check failure.",
+ "blocked_reason_manual_dequeue": "PRs manually removed from the queue that day.",
+ "blocked_reason_ci_timeout": "PRs blocked that day due to CI timing out.",
+ "blocked_reason_other": "PRs blocked that day for any other reason.",
+ "sync_frequency_min": "Minimum number of times a PR fetched its base branch that day.",
+ "sync_frequency_avg": "Average number of times a PR fetched its base branch that day.",
+ "sync_frequency_p50": "50th percentile number of base-branch syncs that day.",
+ "sync_frequency_p75": "75th percentile number of base-branch syncs that day.",
+ "sync_frequency_p90": "90th percentile number of base-branch syncs that day.",
+ "sync_frequency_p100": "Maximum number of base-branch syncs that day.",
+ },
+ },
+ "queued_pull_requests": {
+ "description": "Pull requests currently in the queued state for each repository (a live snapshot).",
+ "docs_url": "https://docs.aviator.co/api/reference/json-api",
+ "columns": {
+ "org": "GitHub organization that owns the repository.",
+ "repo": "Repository name the PR belongs to.",
+ "number": "Pull request number within the repository.",
+ "author": "GitHub username of the PR author.",
+ "base_branch": "Branch the PR targets.",
+ "head_branch": "Feature branch of the PR.",
+ "title": "Title of the pull request.",
+ "status": "Current queue status of the PR (e.g. queued, tagged, blocked).",
+ "queued": "Whether the PR is currently queued.",
+ "queued_at": "ISO 8601 timestamp for when the PR most recently entered the queue.",
+ "merged_at": "ISO 8601 timestamp for when the PR was merged, or null.",
+ "created_at": "ISO 8601 timestamp for when Aviator first observed the PR.",
+ "skip_line": "Whether the PR was queued to skip to the front of the line.",
+ },
+ },
+ "queue_stats": {
+ "description": "Live merge-queue depth per repository (a current-state snapshot).",
+ "docs_url": "https://docs.aviator.co/api/reference/json-api",
+ "columns": {
+ "org": "GitHub organization that owns the repository.",
+ "repo": "Repository name.",
+ "queued": "Total number of PRs currently in the queue (excludes not-yet-queued and blocked PRs).",
+ "processing": "Number of PRs actively being processed (draft PRs created in parallel mode).",
+ "waiting": "Number of PRs queued but not yet being processed.",
+ },
+ },
+ "config_history": {
+ "description": "History of merge-queue YAML config changes per repository, as diffs.",
+ "docs_url": "https://docs.aviator.co/api/reference/json-api",
+ "columns": {
+ "org": "GitHub organization that owns the repository.",
+ "repo": "Repository name.",
+ "applied_at": "ISO 8601 timestamp for when the config change was applied.",
+ "commit_sha": "Commit SHA of the change, present only when made via the GitHub repository.",
+ "diff": "Textual diff of the config change.",
+ "applied_by_email": "Email of the user who applied the change, present when made from the dashboard.",
+ "applied_by_gh_username": "GitHub username of the user who applied the change, present when made via GitHub.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aviator/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aviator/settings.py
new file mode 100644
index 000000000000..7c8d56999c91
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aviator/settings.py
@@ -0,0 +1,94 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+
+@dataclass
+class AviatorEndpointConfig:
+ name: str
+ path: str
+ # Primary key columns for the merge upsert. Fan-out endpoints aggregate rows from every
+ # repository, so their keys always include the repository (org/repo) to stay unique
+ # table-wide — a bare `number` or `date` would collide across repos.
+ primary_keys: list[str]
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Stable creation-style field to partition by (never a mutable `updated_at`).
+ partition_key: Optional[str] = None
+ # When True the endpoint is called once per repository discovered via GET /repo, injecting
+ # the repo's org/name into the request. When False it is a single top-level request.
+ fan_out_over_repos: bool = False
+ default_incremental_field: Optional[str] = None
+ # First-sync window (days) for date-windowed incremental endpoints, so the initial sync
+ # doesn't try to pull the entire history at once.
+ default_lookback_days: Optional[int] = None
+ # Whether the table is selected for sync by default in the schema picker.
+ should_sync_default: bool = True
+
+
+# Endpoint catalog. Aviator's public JSON API lives at api.aviator.co/api/v1 and is authenticated
+# with a self-serve user access token (`Authorization: Bearer av_uat_...`).
+#
+# Only `merge_queue_analytics` is synced incrementally: its GET /analytics endpoint is defined by a
+# `start`/`end` UTC date window, which is a genuine server-side filter (the endpoint returns per-day
+# aggregate rows bounded by that window). Every other endpoint is a current-state snapshot or a small
+# list with no reliable server-side timestamp filter, so it ships as full refresh. GET /config/history
+# documents optional `start`/`end` params, but we could not curl-verify that they actually filter
+# server-side (no test credentials), so it stays full refresh conservatively — config changes are
+# low volume, so re-reading them each sync is cheap.
+AVIATOR_ENDPOINTS: dict[str, AviatorEndpointConfig] = {
+ "repositories": AviatorEndpointConfig(
+ name="repositories",
+ path="/repo",
+ # GET /repo returns {active, name, org, paused} with no id; a repo is identified by org + name.
+ primary_keys=["org", "name"],
+ ),
+ "merge_queue_analytics": AviatorEndpointConfig(
+ name="merge_queue_analytics",
+ path="/analytics",
+ # One row per (repo, date) merging the endpoint's five daily series.
+ primary_keys=["repo", "date"],
+ partition_key="date",
+ fan_out_over_repos=True,
+ default_incremental_field="date",
+ # Merge-queue analytics are daily aggregates; a year of history is a reasonable first sync.
+ default_lookback_days=365,
+ incremental_fields=[
+ {
+ "label": "date",
+ "type": IncrementalFieldType.Date,
+ "field": "date",
+ "field_type": IncrementalFieldType.Date,
+ },
+ ],
+ ),
+ "queued_pull_requests": AviatorEndpointConfig(
+ name="queued_pull_requests",
+ path="/pull_request/queued",
+ # A snapshot of currently-queued PRs; PR number is unique within a repo, not globally.
+ primary_keys=["org", "repo", "number"],
+ partition_key="created_at",
+ fan_out_over_repos=True,
+ ),
+ "queue_stats": AviatorEndpointConfig(
+ name="queue_stats",
+ path="/queue/stats",
+ # Live queue depth: a single current-state row per repository.
+ primary_keys=["org", "repo"],
+ fan_out_over_repos=True,
+ ),
+ "config_history": AviatorEndpointConfig(
+ name="config_history",
+ path="/config/history",
+ # No id; a config change is identified by repo + when it was applied.
+ primary_keys=["org", "repo", "applied_at"],
+ partition_key="applied_at",
+ fan_out_over_repos=True,
+ ),
+}
+
+ENDPOINTS = tuple(AVIATOR_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in AVIATOR_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aviator/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aviator/source.py
index e0f93b0b0ac0..496d89a5fbfd 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aviator/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aviator/source.py
@@ -1,19 +1,43 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.aviator.aviator import (
+ AviatorResumeConfig,
+ aviator_source,
+ validate_credentials as validate_aviator_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.aviator.settings import (
+ AVIATOR_ENDPOINTS,
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import AviatorSourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class AviatorSource(SimpleSource[AviatorSourceConfig]):
+class AviatorSource(ResumableSource[AviatorSourceConfig, AviatorResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.AVIATOR
@@ -24,8 +48,94 @@ class AviatorSource(SimpleSource[AviatorSourceConfig]):
name=SchemaExternalDataSourceType.AVIATOR,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="Aviator",
- iconPath="/static/services/aviator.png",
- keywords=["merge queue", "pull requests", "ci", "developer productivity"],
- fields=cast(list[FieldType], []),
+ releaseStatus=ReleaseStatus.ALPHA,
unreleasedSource=True,
+ caption="""Enter your Aviator API token to pull your merge-queue data into the PostHog Data warehouse.
+
+Create a user access token (it starts with `av_uat_`) from your [Aviator account settings](https://www.aviator.co/), then paste it below. The token inherits your account's repository access, so no extra scopes are required.""",
+ iconPath="/static/services/aviator.svg",
+ docsUrl="https://posthog.com/docs/cdp/sources/aviator",
+ keywords=["merge queue", "pull requests", "ci", "developer productivity"],
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_token",
+ label="API token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="av_uat_...",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.aviator.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://api.aviator.co": "Your Aviator API token is invalid or has been revoked. Create a new user access token in your Aviator account settings, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.aviator.co": "Your Aviator API token is missing access to this data. Check the token's repository access in your Aviator account settings, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: AviatorSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ def _build_schema(endpoint: str) -> SourceSchema:
+ endpoint_config = AVIATOR_ENDPOINTS[endpoint]
+ has_incremental = bool(INCREMENTAL_FIELDS.get(endpoint))
+ return SourceSchema(
+ name=endpoint,
+ supports_incremental=has_incremental,
+ # Analytics rows are daily aggregates that get revised; incremental re-pulls a window
+ # that merge dedupes, so append (which would duplicate them) is never offered.
+ supports_append=False,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ should_sync_default=endpoint_config.should_sync_default,
+ )
+
+ schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+ return schemas
+
+ def validate_credentials(
+ self, config: AviatorSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if validate_aviator_credentials(config.api_token):
+ return True, None
+
+ return False, "Invalid Aviator API token"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[AviatorResumeConfig]:
+ return ResumableSourceManager[AviatorResumeConfig](inputs, AviatorResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: AviatorSourceConfig,
+ resumable_source_manager: ResumableSourceManager[AviatorResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return aviator_source(
+ api_token=config.api_token,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
+ incremental_field=inputs.incremental_field,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aviator/tests/test_aviator.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aviator/tests/test_aviator.py
new file mode 100644
index 000000000000..8cb77f5dfaf6
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aviator/tests/test_aviator.py
@@ -0,0 +1,423 @@
+from datetime import UTC, date, datetime
+from typing import Any
+
+import pytest
+from freezegun import freeze_time
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.aviator import aviator
+from products.warehouse_sources.backend.temporal.data_imports.sources.aviator.aviator import (
+ AviatorResumeConfig,
+ _analytics_window,
+ _flatten_analytics,
+ _iter_repositories,
+ aviator_source,
+ get_rows,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.aviator.settings import AVIATOR_ENDPOINTS
+
+
+class _FakeResumableManager:
+ def __init__(self, state: AviatorResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[AviatorResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> AviatorResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: AviatorResumeConfig) -> None:
+ self.saved.append(data)
+
+
+class TestFlattenAnalytics:
+ def test_merges_all_series_into_one_row_per_date(self) -> None:
+ # The five daily series share min/avg/pXX keys; merging without prefixing would clobber them,
+ # and dropping a series would silently lose columns. This is the source's core transform.
+ payload = {
+ "time_in_queue": [{"date": "2021-07-14", "min": 12, "p50": 23}],
+ "wait_times_to_queue": [{"date": "2021-07-14", "min": 5, "p50": 8.2}],
+ "mergequeue_usage": [{"date": "2021-07-14", "total": 52, "merged_by_bot": 40}],
+ "blocked_reason": [{"date": "2021-07-14", "merge_conflict": 2, "ci_failure": 4}],
+ "sync_frequency": [{"date": "2021-07-14", "min": 1, "p90": 3.2}],
+ }
+ rows = _flatten_analytics("aviator-co/testrepo", "aviator-co", "testrepo", payload)
+ assert rows == [
+ {
+ "repo": "aviator-co/testrepo",
+ "org": "aviator-co",
+ "name": "testrepo",
+ "date": "2021-07-14",
+ "time_in_queue_min": 12,
+ "time_in_queue_p50": 23,
+ "wait_times_to_queue_min": 5,
+ "wait_times_to_queue_p50": 8.2,
+ "mergequeue_usage_total": 52,
+ "mergequeue_usage_merged_by_bot": 40,
+ "blocked_reason_merge_conflict": 2,
+ "blocked_reason_ci_failure": 4,
+ "sync_frequency_min": 1,
+ "sync_frequency_p90": 3.2,
+ }
+ ]
+
+ def test_rows_are_sorted_by_date_and_span_multiple_days(self) -> None:
+ payload = {
+ "mergequeue_usage": [
+ {"date": "2021-07-15", "total": 3},
+ {"date": "2021-07-14", "total": 1},
+ ],
+ }
+ rows = _flatten_analytics("o/r", "o", "r", payload)
+ assert [r["date"] for r in rows] == ["2021-07-14", "2021-07-15"]
+
+ def test_missing_or_malformed_series_are_ignored(self) -> None:
+ # A partial response (only some series present, a non-list series, a dateless item) must not crash.
+ payload: dict[str, Any] = {
+ "time_in_queue": [{"date": "2021-07-14", "avg": 24}],
+ "sync_frequency": "unexpected",
+ "blocked_reason": [{"min": 1}],
+ }
+ rows = _flatten_analytics("o/r", "o", "r", payload)
+ assert rows == [{"repo": "o/r", "org": "o", "name": "r", "date": "2021-07-14", "time_in_queue_avg": 24}]
+
+
+class TestAnalyticsWindow:
+ @freeze_time("2026-06-15")
+ def test_first_sync_uses_default_lookback(self) -> None:
+ # No watermark: pull the configured history window (365 days) rather than an unbounded range.
+ config = AVIATOR_ENDPOINTS["merge_queue_analytics"]
+ start, end = _analytics_window(config, should_use_incremental_field=True, db_incremental_field_last_value=None)
+ assert start == "2025-06-15"
+ assert end == "2026-06-15"
+
+ @freeze_time("2026-06-15")
+ def test_incremental_run_rewinds_watermark_by_lookback(self) -> None:
+ # Recent daily aggregates get revised upstream, so each run must re-pull a trailing window;
+ # advancing straight from the watermark would freeze the last few days at stale values.
+ config = AVIATOR_ENDPOINTS["merge_queue_analytics"]
+ start, end = _analytics_window(
+ config, should_use_incremental_field=True, db_incremental_field_last_value=date(2026, 6, 10)
+ )
+ assert start == "2026-06-03" # 2026-06-10 minus the 7-day lookback
+ assert end == "2026-06-15"
+
+ @parameterized.expand(
+ [
+ ("date_object", date(2026, 6, 10), "2026-06-03"),
+ ("datetime_object", datetime(2026, 6, 10, 8, 30, tzinfo=UTC), "2026-06-03"),
+ ("iso_string", "2026-06-10T08:30:00+00:00", "2026-06-03"),
+ ]
+ )
+ def test_watermark_accepts_multiple_value_types(self, _name: str, value: Any, expected_start: str) -> None:
+ config = AVIATOR_ENDPOINTS["merge_queue_analytics"]
+ with freeze_time("2026-06-15"):
+ start, _ = _analytics_window(
+ config, should_use_incremental_field=True, db_incremental_field_last_value=value
+ )
+ assert start == expected_start
+
+ @freeze_time("2026-06-15")
+ def test_future_watermark_is_clamped_to_today(self) -> None:
+ # A future-dated watermark would otherwise make start > end and produce an invalid window.
+ config = AVIATOR_ENDPOINTS["merge_queue_analytics"]
+ start, end = _analytics_window(
+ config, should_use_incremental_field=True, db_incremental_field_last_value=date(2027, 1, 1)
+ )
+ assert start == "2026-06-15"
+ assert end == "2026-06-15"
+
+
+class TestIterRepositories:
+ @parameterized.expand(
+ [
+ # A short final page (< 10) signals the end, so the paginator stops without an extra request.
+ ("single_partial_page", [[{"org": "o", "name": "a"}, {"org": "o", "name": "b"}]], 1),
+ (
+ "full_then_partial_page",
+ [[{"org": "o", "name": f"r{i}"} for i in range(10)], [{"org": "o", "name": "last"}]],
+ 2,
+ ),
+ # Exactly-full final page forces one more request that returns empty, then stops.
+ (
+ "full_then_empty_page",
+ [[{"org": "o", "name": f"r{i}"} for i in range(10)], []],
+ 2,
+ ),
+ ]
+ )
+ def test_pagination_terminates(self, _name: str, pages: list[list[dict]], expected_calls: int) -> None:
+ calls: list[int] = []
+
+ def fake_fetch(session: Any, url: str, headers: dict, logger: Any, params: dict | None = None) -> Any:
+ page = (params or {}).get("page", 1)
+ calls.append(page)
+ return pages[page - 1]
+
+ with patch.object(aviator, "_fetch", fake_fetch):
+ repos = list(_iter_repositories(MagicMock(), {}, MagicMock()))
+
+ assert len(calls) == expected_calls
+ assert repos == [row for page in pages for row in page]
+
+
+def _run_fan_out(
+ endpoint: str,
+ fake_fetch: Any,
+ repos: list[dict],
+ manager: _FakeResumableManager,
+ monkeypatch: Any,
+ **incremental: Any,
+) -> list[dict]:
+ monkeypatch.setattr(aviator, "_iter_repositories", lambda *a, **k: iter(repos))
+ monkeypatch.setattr(aviator, "_fetch", fake_fetch)
+ rows: list[dict] = []
+ for table in get_rows(
+ api_token="av_uat_test",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ **incremental,
+ ):
+ rows.extend(table.to_pylist())
+ return rows
+
+
+class TestFanOutExtraction:
+ def test_queued_pull_requests_inject_org_repo_and_drop_nested_repository(self, monkeypatch: Any) -> None:
+ # PR number is unique only within a repo, so the injected org/repo are what make the
+ # composite primary key unique table-wide across the fan-out.
+ def fake_fetch(session: Any, url: str, headers: dict, logger: Any, params: dict | None = None) -> Any:
+ return {
+ "pull_requests": [
+ {"number": 89, "title": "fix", "repository": {"org": "o", "name": "r"}, "status": "queued"}
+ ]
+ }
+
+ rows = _run_fan_out(
+ "queued_pull_requests", fake_fetch, [{"org": "o", "name": "r"}], _FakeResumableManager(), monkeypatch
+ )
+ assert rows == [{"number": 89, "title": "fix", "status": "queued", "org": "o", "repo": "r"}]
+
+ def test_queued_pull_request_without_number_is_skipped(self, monkeypatch: Any) -> None:
+ # number is part of the (org, repo, number) primary key; a null-keyed row would collapse
+ # every numberless PR in the repo into a single persisted row, so such rows are dropped.
+ def fake_fetch(session: Any, url: str, headers: dict, logger: Any, params: dict | None = None) -> Any:
+ return {"pull_requests": [{"number": 7, "title": "keep"}, {"title": "no number"}]}
+
+ rows = _run_fan_out(
+ "queued_pull_requests", fake_fetch, [{"org": "o", "name": "r"}], _FakeResumableManager(), monkeypatch
+ )
+ assert [r["title"] for r in rows] == ["keep"]
+
+ def test_queue_stats_flattens_depth_object(self, monkeypatch: Any) -> None:
+ def fake_fetch(session: Any, url: str, headers: dict, logger: Any, params: dict | None = None) -> Any:
+ return {"depth": {"queued": 8, "processing": 2, "waiting": 6}}
+
+ rows = _run_fan_out(
+ "queue_stats", fake_fetch, [{"org": "o", "name": "r"}], _FakeResumableManager(), monkeypatch
+ )
+ assert rows == [{"org": "o", "repo": "r", "queued": 8, "processing": 2, "waiting": 6}]
+
+ def test_config_history_paginates_and_flattens_applied_by(self, monkeypatch: Any) -> None:
+ # Pagination must terminate on the first empty page; applied_by is flattened so the row is a
+ # flat record with the injected org/repo the endpoint's primary key needs.
+ page_payloads = {
+ 1: {
+ "history": [
+ {
+ "applied_at": "2022-11-16T17:21:41Z",
+ "commit_sha": "abc",
+ "diff": "x",
+ "applied_by": {"email": "[email protected]"},
+ }
+ ]
+ },
+ 2: {"history": []},
+ }
+ seen_pages: list[int] = []
+
+ def fake_fetch(session: Any, url: str, headers: dict, logger: Any, params: dict | None = None) -> Any:
+ page = (params or {}).get("page", 1)
+ seen_pages.append(page)
+ return page_payloads[page]
+
+ rows = _run_fan_out(
+ "config_history", fake_fetch, [{"org": "o", "name": "r"}], _FakeResumableManager(), monkeypatch
+ )
+ assert seen_pages == [1, 2]
+ assert rows == [
+ {
+ "org": "o",
+ "repo": "r",
+ "applied_at": "2022-11-16T17:21:41Z",
+ "commit_sha": "abc",
+ "diff": "x",
+ "applied_by_email": "[email protected]",
+ "applied_by_gh_username": None,
+ }
+ ]
+
+ def test_config_history_entry_without_applied_at_is_skipped(self, monkeypatch: Any) -> None:
+ # applied_at is part of the (org, repo, applied_at) primary key; a null-keyed row would
+ # collapse multiple config changes into one persisted row, so such rows are dropped.
+ def fake_fetch(session: Any, url: str, headers: dict, logger: Any, params: dict | None = None) -> Any:
+ page = (params or {}).get("page", 1)
+ if page == 1:
+ return {
+ "history": [
+ {"applied_at": "2022-11-16T17:21:41Z", "commit_sha": "keep"},
+ {"commit_sha": "no applied_at"},
+ ]
+ }
+ return {"history": []}
+
+ rows = _run_fan_out(
+ "config_history", fake_fetch, [{"org": "o", "name": "r"}], _FakeResumableManager(), monkeypatch
+ )
+ assert [r["commit_sha"] for r in rows] == ["keep"]
+
+ def test_analytics_fan_out_requests_repo_slug_and_window(self, monkeypatch: Any) -> None:
+ # The analytics call is only correct if it forwards repo=org/name plus the incremental window;
+ # a regression that dropped either would sync the wrong (or unbounded) data.
+ captured: dict[str, Any] = {}
+
+ def fake_fetch(session: Any, url: str, headers: dict, logger: Any, params: dict | None = None) -> Any:
+ captured.update(params or {})
+ return {"mergequeue_usage": [{"date": "2026-06-14", "total": 5}]}
+
+ with freeze_time("2026-06-15"):
+ rows = _run_fan_out(
+ "merge_queue_analytics",
+ fake_fetch,
+ [{"org": "aviator-co", "name": "testrepo"}],
+ _FakeResumableManager(),
+ monkeypatch,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=date(2026, 6, 10),
+ incremental_field="date",
+ )
+ assert captured == {"repo": "aviator-co/testrepo", "start": "2026-06-03", "end": "2026-06-15"}
+ assert rows == [
+ {
+ "repo": "aviator-co/testrepo",
+ "org": "aviator-co",
+ "name": "testrepo",
+ "date": "2026-06-14",
+ "mergequeue_usage_total": 5,
+ }
+ ]
+
+
+class TestFanOutResume:
+ def _fetch_stats(self, session: Any, url: str, headers: dict, logger: Any, params: dict | None = None) -> Any:
+ p = params or {}
+ return {"depth": {"queued": 1, "processing": 0, "waiting": 1, "_repo": p.get("repo")}}
+
+ def test_marks_each_repo_completed_as_it_finishes(self, monkeypatch: Any) -> None:
+ # State accumulates completed repo keys AFTER each repo's rows are yielded, so a crash resumes
+ # with only the repos still owed (and a crash mid-repo re-processes it, since merge dedupes).
+ manager = _FakeResumableManager()
+ repos = [{"org": "o", "name": "a"}, {"org": "o", "name": "b"}, {"org": "o", "name": "c"}]
+ _run_fan_out("queue_stats", self._fetch_stats, repos, manager, monkeypatch)
+ assert [s.completed_repo_keys for s in manager.saved] == [
+ ["o/a"],
+ ["o/a", "o/b"],
+ ["o/a", "o/b", "o/c"],
+ ]
+
+ def test_resume_skips_completed_repos(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager(AviatorResumeConfig(completed_repo_keys=["o/a"]))
+ repos = [{"org": "o", "name": "a"}, {"org": "o", "name": "b"}, {"org": "o", "name": "c"}]
+ rows = _run_fan_out("queue_stats", self._fetch_stats, repos, manager, monkeypatch)
+ assert [r["repo"] for r in rows] == ["b", "c"]
+
+ def test_resume_processes_repo_added_before_the_resume_point(self, monkeypatch: Any) -> None:
+ # A repo discovered ahead of already-completed ones on retry must NOT be skipped. A positional
+ # bookmark would drop it, and since the watermark only advances at successful job end, that
+ # repo's older analytics would never be fetched outside the trailing lookback window.
+ manager = _FakeResumableManager(AviatorResumeConfig(completed_repo_keys=["o/b"]))
+ repos = [{"org": "o", "name": "new"}, {"org": "o", "name": "b"}, {"org": "o", "name": "c"}]
+ rows = _run_fan_out("queue_stats", self._fetch_stats, repos, manager, monkeypatch)
+ assert [r["repo"] for r in rows] == ["new", "c"]
+
+ def test_resume_with_only_unknown_completed_keys_processes_all(self, monkeypatch: Any) -> None:
+ # A completed repo removed between runs must not strand the sync; every current repo runs.
+ manager = _FakeResumableManager(AviatorResumeConfig(completed_repo_keys=["o/gone"]))
+ repos = [{"org": "o", "name": "a"}, {"org": "o", "name": "b"}]
+ rows = _run_fan_out("queue_stats", self._fetch_stats, repos, manager, monkeypatch)
+ assert [r["repo"] for r in rows] == ["a", "b"]
+
+
+class TestValidateCredentials:
+ @parameterized.expand([("ok", 200, True), ("unauthorized", 401, False), ("forbidden", 403, False)])
+ def test_status_maps_to_validity(self, _name: str, status: int, expected: bool) -> None:
+ response = MagicMock()
+ response.status_code = status
+ session = MagicMock()
+ session.get.return_value = response
+ with patch.object(aviator, "make_tracked_session", return_value=session):
+ assert validate_credentials("av_uat_test") is expected
+
+ def test_network_error_is_not_valid(self) -> None:
+ session = MagicMock()
+ session.get.side_effect = Exception("boom")
+ with patch.object(aviator, "make_tracked_session", return_value=session):
+ assert validate_credentials("av_uat_test") is False
+
+
+class TestFetchRetries:
+ @parameterized.expand([("rate_limited", 429), ("server_error", 503)])
+ def test_retryable_status_codes_are_retried(self, _name: str, status: int) -> None:
+ bad = MagicMock(status_code=status)
+ good = MagicMock(status_code=200, ok=True)
+ good.json.return_value = {"ok": True}
+ session = MagicMock()
+ session.get.side_effect = [bad, good]
+
+ with patch.object(aviator._fetch.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]
+ result = aviator._fetch(session, "https://api.aviator.co/api/v1/repo", {}, MagicMock())
+
+ assert result == {"ok": True}
+ assert session.get.call_count == 2
+
+ def test_client_error_raises_without_retry(self) -> None:
+ import requests
+
+ bad = requests.Response()
+ bad.status_code = 401
+ session = MagicMock()
+ session.get.return_value = bad
+
+ with pytest.raises(requests.HTTPError):
+ aviator._fetch(session, "https://api.aviator.co/api/v1/repo", {}, MagicMock())
+ assert session.get.call_count == 1
+
+
+class TestSourceResponseSortMode:
+ @parameterized.expand(
+ [
+ ("repositories", "asc", None),
+ ("merge_queue_analytics", "desc", "date"),
+ ("queued_pull_requests", "desc", "created_at"),
+ ("queue_stats", "desc", None),
+ ("config_history", "desc", "applied_at"),
+ ]
+ )
+ def test_sort_mode_and_partition(self, endpoint: str, expected_sort: str, partition_key: str | None) -> None:
+ # Fan-out endpoints must report "desc" so the watermark persists only at successful job end;
+ # reverting to "asc" per-batch persistence lets a crashed run advance past unreached repos.
+ response = aviator_source(
+ api_token="av_uat_test",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ )
+ assert response.sort_mode == expected_sort
+ assert response.partition_keys == ([partition_key] if partition_key else None)
+ assert response.primary_keys == AVIATOR_ENDPOINTS[endpoint].primary_keys
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aviator/tests/test_aviator_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aviator/tests/test_aviator_source.py
new file mode 100644
index 000000000000..a990e5849526
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aviator/tests/test_aviator_source.py
@@ -0,0 +1,141 @@
+from typing import Optional
+
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs
+from products.warehouse_sources.backend.temporal.data_imports.sources.aviator import source as source_module
+from products.warehouse_sources.backend.temporal.data_imports.sources.aviator.aviator import AviatorResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.aviator.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.aviator.source import AviatorSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import AviatorSourceConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+def _source_inputs(
+ schema_name: str, last_value: Optional[object] = None, use_incremental: bool = False
+) -> SourceInputs:
+ return SourceInputs(
+ schema_name=schema_name,
+ schema_id="schema-1",
+ source_id="source-1",
+ team_id=1,
+ should_use_incremental_field=use_incremental,
+ db_incremental_field_last_value=last_value,
+ db_incremental_field_earliest_value=None,
+ incremental_field="date" if use_incremental else None,
+ incremental_field_type=None,
+ job_id="job-1",
+ logger=MagicMock(),
+ reset_pipeline=False,
+ )
+
+
+class TestAviatorSource:
+ def setup_method(self) -> None:
+ self.source = AviatorSource()
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.AVIATOR
+
+ def test_source_config_has_a_single_secret_token_field(self) -> None:
+ config = self.source.get_source_config
+ assert len(config.fields) == 1
+ field = config.fields[0]
+ assert isinstance(field, SourceFieldInputConfig)
+ assert field.name == "api_token"
+ assert field.type == SourceFieldInputConfigType.PASSWORD
+ assert field.required is True
+ assert field.secret is True
+
+ def test_source_config_is_alpha_and_unreleased(self) -> None:
+ # The source ships hidden (unreleasedSource) and labelled alpha; a regression that flipped
+ # either would expose an unfinished connector to every user.
+ config = self.source.get_source_config
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is True
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/aviator"
+
+ def test_lists_tables_without_credentials(self) -> None:
+ # get_schemas is a static, no-I/O catalog, so the public docs table list must render.
+ assert self.source.lists_tables_without_credentials is True
+
+ def test_get_schemas_returns_every_endpoint(self) -> None:
+ schemas = self.source.get_schemas(MagicMock(), team_id=1)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+
+ def test_get_schemas_filters_by_names(self) -> None:
+ schemas = self.source.get_schemas(MagicMock(), team_id=1, names=["queue_stats"])
+ assert [s.name for s in schemas] == ["queue_stats"]
+
+ @parameterized.expand(
+ [
+ # Only the date-windowed analytics endpoint has a genuine server-side filter, so it is the
+ # only incremental table; the snapshot/list endpoints are full refresh.
+ ("merge_queue_analytics", True, ["date"]),
+ ("repositories", False, []),
+ ("queued_pull_requests", False, []),
+ ("queue_stats", False, []),
+ ("config_history", False, []),
+ ]
+ )
+ def test_incremental_support_per_endpoint(
+ self, endpoint: str, supports_incremental: bool, incremental_fields: list[str]
+ ) -> None:
+ schema = next(s for s in self.source.get_schemas(MagicMock(), team_id=1) if s.name == endpoint)
+ assert schema.supports_incremental is supports_incremental
+ # Analytics rows are revised daily aggregates deduped by merge, so append is never offered.
+ assert schema.supports_append is False
+ assert [f["field"] for f in schema.incremental_fields] == incremental_fields
+
+ @parameterized.expand([("valid", True, True), ("invalid", False, False)])
+ def test_validate_credentials(self, _name: str, probe_result: bool, expected_ok: bool) -> None:
+ config = AviatorSourceConfig(api_token="av_uat_test")
+ with patch.object(source_module, "validate_aviator_credentials", return_value=probe_result):
+ ok, error = self.source.validate_credentials(config, team_id=1)
+ assert ok is expected_ok
+ assert (error is None) is expected_ok
+
+ @parameterized.expand(
+ [
+ ("unauthorized", "401 Client Error: Unauthorized for url: https://api.aviator.co/api/v1/repo"),
+ ("forbidden", "403 Client Error: Forbidden for url: https://api.aviator.co/api/v1/queue/stats"),
+ ]
+ )
+ def test_credential_errors_are_non_retryable(self, _name: str, observed_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable)
+
+ def test_get_resumable_source_manager_is_bound_to_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(_source_inputs("repositories"))
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is AviatorResumeConfig
+
+ def test_source_for_pipeline_plumbs_token_and_endpoint(self) -> None:
+ config = AviatorSourceConfig(api_token="av_uat_test")
+ inputs = _source_inputs("merge_queue_analytics", last_value="2026-06-10", use_incremental=True)
+ with patch.object(source_module, "aviator_source") as mock_source:
+ self.source.source_for_pipeline(config, MagicMock(), inputs)
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["api_token"] == "av_uat_test"
+ assert kwargs["endpoint"] == "merge_queue_analytics"
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == "2026-06-10"
+
+ def test_source_for_pipeline_omits_last_value_when_not_incremental(self) -> None:
+ # Passing a stale watermark on a full-refresh run would wrongly narrow the analytics window.
+ config = AviatorSourceConfig(api_token="av_uat_test")
+ inputs = _source_inputs("queue_stats", last_value="2026-06-10", use_incremental=False)
+ with patch.object(source_module, "aviator_source") as mock_source:
+ self.source.source_for_pipeline(config, MagicMock(), inputs)
+ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is None
+
+ def test_canonical_descriptions_cover_every_endpoint(self) -> None:
+ # Drift here (an endpoint renamed in settings but not here) silently drops the curated docs
+ # and falls back to LLM enrichment, so keep the two in lockstep.
+ descriptions = self.source.get_canonical_descriptions()
+ assert set(descriptions.keys()) == set(ENDPOINTS)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index 471ab9a311a9..a82105bdb22c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
@@ -388,7 +388,7 @@ class AviationstackSourceConfig(config.Config):
@config.config
class AviatorSourceConfig(config.Config):
- pass
+ api_token: str
@config.config