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 inngest import source (#70715)

Tom Owers131baa61c40d
diff --git a/frontend/public/services/inngest.svg b/frontend/public/services/inngest.svg
new file mode 100644
index 000000000000..8fccff7565fb
--- /dev/null
+++ b/frontend/public/services/inngest.svg
@@ -0,0 +1,11 @@
+<svg width="192" height="192" viewBox="0 0 192 192" fill="none" xmlns="http://www.w3.org/2000/svg">
+<style>
+ path { fill: #292524; }
+ @media (prefers-color-scheme: dark) {
+ path { fill: #FAFAF9; }
+ }
+</style>
+<path d="M21.4072 129.294C19.0746 129.294 16.9123 127.809 16.17 125.48C12.2674 113.258 15.1639 103.03 25.2893 93.2901L66.5214 54.0971C72.8173 48.0345 81.6973 46.4805 89.7012 50.0446C97.6725 53.5966 102.419 61.1769 102.106 69.847V74.0609C102.106 77.0842 99.6441 79.5302 96.6097 79.5302C93.5753 79.5302 91.1129 77.0801 91.1129 74.0609V69.742C91.1129 69.6653 91.1129 69.5927 91.1169 69.52C91.2914 65.302 89.0845 61.7541 85.2104 60.0306C81.3363 58.307 77.2066 59.0296 74.1641 61.968C74.156 61.9761 74.1439 61.9882 74.1358 61.9963L32.9159 101.177C25.8816 107.946 24.0602 114.037 26.6565 122.166C27.5774 125.044 25.9749 128.12 23.0825 129.036C22.5268 129.21 21.9669 129.294 21.4152 129.294H21.4072Z"/>
+<path d="M112.284 144.019C109.371 144.019 106.41 143.397 103.562 142.13C95.591 138.578 90.8447 130.998 91.1571 122.327V118.142C91.1571 115.119 93.6195 112.673 96.6539 112.673C99.6883 112.673 102.151 115.123 102.151 118.142V122.432C102.151 122.509 102.151 122.582 102.147 122.658C101.972 126.876 104.179 130.424 108.053 132.148C111.927 133.871 116.057 133.149 119.099 130.21L160.031 91.0135C167.195 84.1194 169.025 78.0568 166.335 70.0971C165.37 67.2313 166.915 64.1314 169.796 63.1667C172.676 62.206 175.791 63.7439 176.761 66.6097C180.797 78.5573 177.824 89.1164 167.67 98.8884L126.746 138.077C122.698 141.985 117.566 144.023 112.284 144.023V144.019Z"/>
+<path d="M42.9198 143.918C39.6664 143.918 36.4211 143.332 33.3339 142.126C33.0337 142.008 32.7336 141.887 32.4374 141.758C29.6464 140.563 28.3604 137.346 29.5612 134.569C30.762 131.792 33.9952 130.513 36.7862 131.708C36.9728 131.788 37.1593 131.865 37.3459 131.938C42.8995 134.101 49.4267 132.818 54.3921 128.592C54.6274 128.378 55.4022 127.655 55.5077 127.554L129.485 57.451C129.485 57.451 131.075 55.9575 131.42 55.6709C136.45 51.4529 142.162 48.9262 147.939 48.3651C149.164 48.244 150.405 48.2077 151.626 48.2521C154.357 48.345 157.35 48.6356 160.604 50.1331C163.358 51.4045 164.559 54.6538 163.281 57.3985C162.003 60.1392 158.738 61.3339 155.979 60.0625C154.576 59.4167 153.18 59.2512 151.237 59.1866C150.491 59.1583 149.748 59.1826 149.01 59.2552C145.472 59.5983 141.862 61.2371 138.56 63.9939C138.296 64.232 137.237 65.2169 137.067 65.3743L63.0897 135.482C63.0897 135.482 61.8766 136.62 61.6089 136.85C56.2014 141.484 49.5443 143.918 42.9198 143.922V143.918Z"/>
+</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 d688bb33de60..e04764362c9c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -228,6 +228,7 @@ the row lists both.
| imagga | HTTP | requests | ✅ |
| incident_io | HTTP | requests | ✅ |
| inflowinventory | HTTP | requests | ✅ |
+| inngest | HTTP | requests | ✅ |
| insightly | HTTP | requests | ✅ |
| instatus | HTTP | requests | ✅ |
| intercom | HTTP | requests + `rest_source.RESTClient` | ✅ |
@@ -683,7 +684,6 @@ doesn't conflict with concurrent PRs.
- impact
- infisical
- infor_nexus
-- inngest
- insightful
- instagram
- instana
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 e9f3273b990e..22039ae2e82f 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
@@ -2041,7 +2041,8 @@ class InforNexusSourceConfig(config.Config):
@config.config
class InngestSourceConfig(config.Config):
- pass
+ signing_key: str
+ environment: str | None = None
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/inngest/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/inngest/canonical_descriptions.py
new file mode 100644
index 000000000000..4198a528fc6e
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/inngest/canonical_descriptions.py
@@ -0,0 +1,99 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Sourced from the official Inngest REST API reference: https://api-docs.inngest.com
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "events": {
+ "description": "An event received by Inngest, including its payload and receipt metadata.",
+ "docs_url": "https://api-docs.inngest.com/v1/events/ListEvents",
+ "columns": {
+ "internal_id": "Unique ULID Inngest assigned to the event on receipt; used internally and by the API.",
+ "accountID": "The Inngest account the event belongs to.",
+ "environmentID": "The Inngest environment the event was received in.",
+ "source": 'The origin of the event, e.g. "key" for an event key.',
+ "sourceID": "The ID of the key used to deliver the event.",
+ "received_at": "When the event was received by Inngest.",
+ "id": "The optional `id` field specified in the event by the sender.",
+ "name": "The `name` field specified in the event.",
+ "data": "The `data` payload specified in the event.",
+ "user": "The `user` field specified in the event.",
+ "ts": "The `ts` (unix millisecond) timestamp specified in the event.",
+ "v": "The `v` (version) field specified in the event.",
+ },
+ },
+ "function_runs": {
+ "description": "A function run triggered by an event, with its status, timing, and output.",
+ "docs_url": "https://api-docs.inngest.com/v1/events/ListEventRuns",
+ "columns": {
+ "run_id": "The ID of the function run.",
+ "run_started_at": "When the function run was scheduled.",
+ "ended_at": "If the function has ended, the end time; null while the run is still Running.",
+ "status": "The run status, e.g. Running, Completed, Failed, Cancelled.",
+ "output": "Data returned from the function handler, JSON-encoded when not already a string.",
+ "function_id": "The ID of the function that ran.",
+ "function_version": "The version of the function that ran.",
+ "environment_id": "The Inngest environment the run executed in.",
+ "event_id": "The internal ID of the triggering event, if the run was initialized via a single event.",
+ "batch_id": "The ID of the batch, if the run was initialized via a batch of events.",
+ "original_run_id": "The run ID of the original run, if this run is a replay.",
+ "cron": "The cron expression that scheduled the run, if it was initialized via a cron trigger.",
+ "event_received_at": "When the triggering event was received by Inngest (added by PostHog to drive incremental sync).",
+ },
+ },
+ "cancellations": {
+ "description": "A bulk cancellation, stopping function runs in a time range matching an optional expression.",
+ "docs_url": "https://api-docs.inngest.com/v1/cancellations/ListCancellations",
+ "columns": {
+ "id": "Unique identifier of the cancellation.",
+ "environment_id": "The Inngest environment the cancellation applies to.",
+ "function_internal_id": "Inngest's internal ID of the targeted function.",
+ "function_id": "The ID (slug) of the targeted function.",
+ "started_before": "Only runs started before this time are cancelled.",
+ "started_after": "Only runs started after this time are cancelled.",
+ "if": "Optional CEL expression limiting which runs are cancelled.",
+ },
+ },
+ "environments": {
+ "description": "An Inngest environment (production, test, or branch).",
+ "docs_url": "https://api-docs.inngest.com/v2/environments/FetchAccountEnvs",
+ "columns": {
+ "id": "Unique identifier of the environment.",
+ "name": "The environment name.",
+ "type": "The environment type: PRODUCTION, TEST, or BRANCH.",
+ "createdAt": "When the environment was created.",
+ "isArchived": "Whether the environment has been archived.",
+ },
+ },
+ "webhooks": {
+ "description": "An inbound webhook intake endpoint that transforms third-party payloads into Inngest events. The secret intake URL is not synced.",
+ "docs_url": "https://api-docs.inngest.com/v1/webhooks/ListWebhooks",
+ "columns": {
+ "id": "Unique identifier of the webhook endpoint.",
+ "name": "A custom descriptor for the webhook endpoint.",
+ "transform": "JavaScript transform turning the inbound request into an Inngest event payload.",
+ "created_at": "When the webhook endpoint was created.",
+ "updated_at": "When the webhook endpoint was last updated.",
+ },
+ },
+ "event_keys": {
+ "description": "An event key used to send events to Inngest. The secret key material is not synced.",
+ "docs_url": "https://api-docs.inngest.com/v2/keys/FetchAccountEventKeys",
+ "columns": {
+ "id": "Unique identifier of the event key.",
+ "name": "The event key's name.",
+ "environment": "The environment the event key belongs to.",
+ "createdAt": "When the event key was created.",
+ },
+ },
+ "signing_keys": {
+ "description": "A signing key used to authenticate Inngest API and SDK traffic. The secret key material is not synced.",
+ "docs_url": "https://api-docs.inngest.com/v2/keys/FetchAccountSigningKeys",
+ "columns": {
+ "id": "Unique identifier of the signing key.",
+ "name": "The signing key's name.",
+ "environment": "The environment the signing key belongs to.",
+ "createdAt": "When the signing key was created.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/inngest/inngest.posthog-doc.mdx b/products/warehouse_sources/backend/temporal/data_imports/sources/inngest/inngest.posthog-doc.mdx
new file mode 100644
index 000000000000..fe06f4a4fcd1
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/inngest/inngest.posthog-doc.mdx
@@ -0,0 +1,64 @@
+<!--
+This is the user-facing source documentation. It belongs in the posthog.com repo at
+contents/docs/cdp/sources/inngest.md (served at /docs/cdp/sources/inngest). 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 Inngest as a source
+sidebar: Docs
+showTitle: true
+availability: { free: full, selfServe: full, enterprise: full }
+sourceId: Inngest
+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 />
+
+[Inngest](https://www.inngest.com/) is a durable workflow engine: functions are triggered by events and run with steps, retries, and flow control.
+This connector pulls your Inngest data — events, function runs, bulk cancellations, environments, inbound webhook intake endpoints, and event/signing key inventories — into the PostHog Data warehouse so you can join it with your product data.
+
+Inngest retains event and run history for a plan-dependent window (from 24 hours up to 90 days), so a synced copy in PostHog doubles as durable history. Schedule frequent syncs to avoid gaps.
+
+## Prerequisites
+
+You need an Inngest account and the signing key for the environment you want to sync. Signing keys authenticate both the v1 and v2 REST APIs, so no additional scopes are required. (Dashboard API keys only work with the v2 API, which does not cover events and runs, so they can't be used here.)
+
+## Adding a data source
+
+<SourceSetupIntro />
+
+Inngest authenticates with a per-environment signing key (it starts with `signkey-`). Copy it from your [Inngest dashboard](https://app.inngest.com/) under **Settings** → **Signing key** and paste it into the **Signing key** field. To sync a branch environment, also enter its name in the optional **Environment** field.
+
+## Sync modes
+
+<SyncModes />
+
+**Events** sync append-only using the server-side `received_after` filter, backfilling up to 90 days of history on the first sync (bounded by your plan's retention). **Function runs** sync incrementally: they are discovered by walking the incoming event stream and looking up each event's runs, and each sync re-reads a trailing hour so recently-started runs pick up their final status. The other tables are small inventories with no server-side timestamp filter, so they sync as full refresh.
+
+Secret values are never synced: event keys and signing keys keep only their metadata (name, environment, creation time), and webhook intake URLs — which let anyone holding them submit events — are stripped too.
+
+## Configuration
+
+<SourceParameters />
+
+## Supported tables
+
+<SourceTables />
+
+## Troubleshooting
+
+- **401 Unauthorized** — the signing key is invalid or has been rotated. Copy the current signing key from your Inngest dashboard settings and reconnect.
+- **403 Forbidden** — the key is valid but does not have access to the requested environment. Check that the key matches the environment you entered and reconnect.
+- **Missing older events or runs** — Inngest's retention is plan-dependent (24 hours to 90 days). Data that aged out upstream before a sync ran cannot be backfilled, so keep syncs frequent.
+
+<TroubleshootingLink />
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/inngest/inngest.py b/products/warehouse_sources/backend/temporal/data_imports/sources/inngest/inngest.py
new file mode 100644
index 000000000000..0032db33deda
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/inngest/inngest.py
@@ -0,0 +1,428 @@
+import json
+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.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.inngest.settings import (
+ INNGEST_ENDPOINTS,
+ InngestEndpointConfig,
+)
+
+INNGEST_API_BASE_URL = "https://api.inngest.com"
+
+# Documented max for GET /v1/events (limit is 1-100).
+EVENTS_PAGE_SIZE = 100
+# First-sync backfill window. Inngest retention is plan-gated (24h free up to 90d enterprise), so
+# asking for the longest window just returns whatever history the plan still holds.
+DEFAULT_BACKFILL_DAYS = 90
+# Emit a fan-out progress log line every N events walked.
+FAN_OUT_PROGRESS_LOG_INTERVAL = 1000
+
+
+class InngestRetryableError(Exception):
+ pass
+
+
+class InngestResumeConfig:
+ # Cursor into the /v1/events walk: the internal_id (ULID) of the last event of the last page
+ # already yielded downstream.
+ cursor: str | None = None
+ # The walk's [received_after, received_before] window, pinned at walk start so a resumed
+ # attempt continues the exact same window instead of re-deriving it from a moved clock.
+ received_after: str | None = None
+ received_before: str | None = None
+
+
+def _get_headers(signing_key: str, environment: str | None) -> dict[str, str]:
+ headers = {
+ "Authorization": f"Bearer {signing_key}",
+ "Accept": "application/json",
+ }
+ if environment:
+ # Signing keys are per environment; the header targets branch/custom environments.
+ headers["X-Inngest-Env"] = environment
+ return headers
+
+
+@retry(
+ retry=retry_if_exception_type(
+ (
+ InngestRetryableError,
+ 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 InngestRetryableError(f"Inngest API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ # Log only status and URL — never the response body, which can echo arbitrary customer
+ # event payloads.
+ logger.error(f"Inngest API error: status={response.status_code}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def validate_credentials(signing_key: str, environment: str | None = None) -> bool:
+ """Probe the signing key with the cheapest v1 call (v1 is what the event-driven endpoints
+ need, and a signing key that passes v1 also authenticates v2)."""
+ try:
+ response = make_tracked_session(redact_values=(signing_key,), capture=False).get(
+ f"{INNGEST_API_BASE_URL}/v1/events",
+ headers=_get_headers(signing_key, environment),
+ params={"limit": 1},
+ timeout=10,
+ )
+ return response.status_code == 200
+ except Exception:
+ return False
+
+
+def _format_rfc3339(dt: datetime) -> str:
+ utc_dt = dt.replace(tzinfo=UTC) if dt.tzinfo is None else dt.astimezone(UTC)
+ return utc_dt.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
+
+
+def _coerce_datetime(value: Any) -> datetime | None:
+ if isinstance(value, datetime):
+ return value if value.tzinfo is not None else value.replace(tzinfo=UTC)
+ if isinstance(value, date):
+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC)
+ if isinstance(value, str):
+ try:
+ return _coerce_datetime(datetime.fromisoformat(value.replace("Z", "+00:00")))
+ except ValueError:
+ return None
+ return None
+
+
+def _event_window(should_use_incremental_field: bool, db_incremental_field_last_value: Any) -> tuple[str, str]:
+ """Compute the [received_after, received_before] RFC3339 window for a /v1/events walk.
+
+ `received_after` defaults to only 1 hour ago server-side, so it is always passed explicitly.
+ `received_before` is pinned to "now" so pagination pages over a fixed window while new events
+ keep arriving.
+ """
+ now = datetime.now(UTC)
+ after = (
+ _coerce_datetime(db_incremental_field_last_value)
+ if should_use_incremental_field and db_incremental_field_last_value
+ else None
+ )
+ if after is None:
+ after = now - timedelta(days=DEFAULT_BACKFILL_DAYS)
+ # A future-dated watermark (bad ts in source data) would produce an empty inverted window
+ # forever; clamp it so the sync self-heals.
+ if after > now:
+ after = now
+ return _format_rfc3339(after), _format_rfc3339(now)
+
+
+def _normalize_event(item: dict[str, Any]) -> dict[str, Any]:
+ # The v1 spec documents `receivedAt` amid otherwise snake_case event fields; accept either
+ # spelling (the live casing could not be curl-verified without credentials) and normalize to
+ # `received_at` so the incremental/partition column has one stable name.
+ camel = item.pop("receivedAt", None)
+ snake = item.pop("received_at", None)
+ item["received_at"] = camel if camel is not None else snake
+ return item
+
+
+def _normalize_run(run: dict[str, Any], event_received_at: Any) -> dict[str, Any]:
+ # `output` is whatever the function handler returned (object, array, scalar, or null);
+ # JSON-encode non-string values so the column keeps one stable type across rows.
+ output = run.get("output")
+ if output is not None and not isinstance(output, str):
+ run["output"] = json.dumps(output)
+ # The parent event's received time drives the incremental watermark: it tracks exactly how far
+ # the events walk has progressed, whereas a run's own timestamps can lag arbitrarily behind
+ # (debounced/scheduled runs) and would advance the watermark past unseen events.
+ run["event_received_at"] = event_received_at
+ return run
+
+
+def _iter_event_pages(
+ session: requests.Session,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[InngestResumeConfig],
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+) -> Iterator[tuple[list[dict[str, Any]], InngestResumeConfig | None]]:
+ """Walk /v1/events over a pinned received-time window, yielding (page rows, resume state).
+
+ The resume state is the checkpoint to persist once the page has been yielded downstream
+ (None on the final page). Consumers save it AFTER yielding so a crash re-yields the last
+ page rather than skipping it.
+ """
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume is not None and resume.received_after and resume.received_before:
+ received_after, received_before = resume.received_after, resume.received_before
+ cursor = resume.cursor
+ logger.debug(f"Inngest: resuming events walk from cursor={cursor}, window ends {received_before}")
+ else:
+ received_after, received_before = _event_window(should_use_incremental_field, db_incremental_field_last_value)
+ cursor = None
+
+ while True:
+ params: dict[str, Any] = {
+ "limit": EVENTS_PAGE_SIZE,
+ "received_after": received_after,
+ "received_before": received_before,
+ }
+ if cursor:
+ params["cursor"] = cursor
+ payload = _fetch(session, f"{INNGEST_API_BASE_URL}/v1/events", headers, logger, params=params)
+ items = payload.get("data") or []
+ # We could not curl-verify whether the cursor is inclusive or exclusive without
+ # credentials; drop the cursor event if the API returns it again.
+ rows = [_normalize_event(item) for item in items if item.get("internal_id") != cursor]
+ if not rows:
+ break
+
+ next_cursor = rows[-1].get("internal_id")
+ # A full page means there may be more; a same-or-missing cursor would loop forever, so
+ # treat it as the end of the walk.
+ has_more = len(items) == EVENTS_PAGE_SIZE and bool(next_cursor) and next_cursor != cursor
+ next_state = (
+ InngestResumeConfig(cursor=next_cursor, received_after=received_after, received_before=received_before)
+ if has_more
+ else None
+ )
+ yield rows, next_state
+
+ if not has_more:
+ break
+ cursor = next_cursor
+
+
+def _get_event_rows(
+ session: requests.Session,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[InngestResumeConfig],
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+) -> Iterator[list[dict[str, Any]]]:
+ for rows, next_state in _iter_event_pages(
+ session,
+ headers,
+ logger,
+ resumable_source_manager,
+ should_use_incremental_field,
+ db_incremental_field_last_value,
+ ):
+ yield rows
+ if next_state is not None:
+ resumable_source_manager.save_state(next_state)
+
+
+def _get_function_run_rows(
+ session: requests.Session,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[InngestResumeConfig],
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+) -> Iterator[list[dict[str, Any]]]:
+ """Fan out over the events walk, fetching each event's function runs.
+
+ Runs have no list endpoint of their own (v1 and v2 only expose runs per event), so this
+ one-request-per-event walk is the only way to enumerate them; after the first sync it is
+ bounded by the incremental received-time window. Events with no runs still advance the walk;
+ only events with runs contribute rows (and therefore to the watermark, computed from the
+ injected `event_received_at`). A per-sync request budget was deliberately NOT added: the
+ walk's ordering within the window is unverified, so stopping early could persist a watermark
+ past events never walked — silent data loss. Progress is made visible via the periodic log
+ below instead.
+ """
+ # A batch run is returned for every event in its batch, which would duplicate the run_id
+ # primary key within one sync. Bounded by the number of runs in the window.
+ seen_run_ids: set[str] = set()
+ events_walked = 0
+ runs_yielded = 0
+
+ for events, next_state in _iter_event_pages(
+ session,
+ headers,
+ logger,
+ resumable_source_manager,
+ should_use_incremental_field,
+ db_incremental_field_last_value,
+ ):
+ rows: list[dict[str, Any]] = []
+ for event in events:
+ internal_id = event.get("internal_id")
+ if not internal_id:
+ continue
+ payload = _fetch(session, f"{INNGEST_API_BASE_URL}/v1/events/{internal_id}/runs", headers, logger)
+ for run in payload.get("data") or []:
+ run_id = run.get("run_id")
+ if not run_id or run_id in seen_run_ids:
+ continue
+ seen_run_ids.add(run_id)
+ rows.append(_normalize_run(run, event.get("received_at")))
+ events_walked += 1
+ # Long stretches of run-less events yield no rows, so without this the sync looks
+ # stalled while it is really paying one lookup per event.
+ if events_walked % FAN_OUT_PROGRESS_LOG_INTERVAL == 0:
+ logger.info(
+ f"Inngest: function_runs fan-out progress: events_walked={events_walked}, "
+ f"runs_yielded={runs_yielded + len(rows)}"
+ )
+ runs_yielded += len(rows)
+ if rows:
+ yield rows
+ if next_state is not None:
+ resumable_source_manager.save_state(next_state)
+
+
+def _drop_redacted_fields(item: dict[str, Any], redacted_fields: tuple[str, ...]) -> dict[str, Any]:
+ for field_name in redacted_fields:
+ item.pop(field_name, None)
+ return item
+
+
+def _get_v2_list_rows(
+ session: requests.Session,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ config: InngestEndpointConfig,
+) -> Iterator[list[dict[str, Any]]]:
+ """Page a v2 list endpoint via its `page.cursor` / `page.hasMore` envelope.
+
+ No `limit` is passed: the documented defaults vary per endpoint and the maxima are
+ undocumented, so we accept the server default — these are small inventory lists.
+ """
+ cursor: str | None = None
+ while True:
+ params = {"cursor": cursor} if cursor else None
+ payload = _fetch(session, f"{INNGEST_API_BASE_URL}{config.path}", headers, logger, params=params)
+ items = payload.get("data") or []
+ rows = [_drop_redacted_fields(item, config.redacted_fields) for item in items if isinstance(item, dict)]
+ if rows:
+ yield rows
+
+ page = payload.get("page") or {}
+ next_cursor = page.get("cursor")
+ if not page.get("hasMore") or not next_cursor or next_cursor == cursor:
+ break
+ cursor = next_cursor
+
+
+def _get_v1_list_rows(
+ session: requests.Session,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ config: InngestEndpointConfig,
+) -> Iterator[list[dict[str, Any]]]:
+ payload = _fetch(session, f"{INNGEST_API_BASE_URL}{config.path}", headers, logger)
+ data = payload.get("data") if isinstance(payload, dict) else payload
+ # The v1 spec is ambiguous about whether these small lists come back as an array or a single
+ # object; handle both.
+ if isinstance(data, dict):
+ data = [data]
+ rows = [_drop_redacted_fields(item, config.redacted_fields) for item in data or [] if isinstance(item, dict)]
+ if rows:
+ yield rows
+
+
+def get_rows(
+ signing_key: str,
+ environment: str | None,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[InngestResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = INNGEST_ENDPOINTS[endpoint]
+ headers = _get_headers(signing_key, environment)
+ # One session reused across every page (and every per-event runs request) so urllib3 keeps the
+ # connection alive. Register the signing key for value-based redaction and disable sample
+ # capture: event payloads and run outputs carry arbitrary customer data the name-based
+ # scrubber can't sanitise.
+ session = make_tracked_session(redact_values=(signing_key,), capture=False)
+
+ if config.fan_out_runs_per_event:
+ yield from _get_function_run_rows(
+ session,
+ headers,
+ logger,
+ resumable_source_manager,
+ should_use_incremental_field,
+ db_incremental_field_last_value,
+ )
+ elif config.pagination == "events_cursor":
+ yield from _get_event_rows(
+ session,
+ headers,
+ logger,
+ resumable_source_manager,
+ should_use_incremental_field,
+ db_incremental_field_last_value,
+ )
+ elif config.pagination == "v2_cursor":
+ yield from _get_v2_list_rows(session, headers, logger, config)
+ else:
+ yield from _get_v1_list_rows(session, headers, logger, config)
+
+
+def inngest_source(
+ signing_key: str,
+ environment: str | None,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[InngestResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = INNGEST_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ signing_key=signing_key,
+ environment=environment,
+ 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,
+ ),
+ primary_keys=config.primary_keys,
+ # The events walk's ordering within the window is undocumented (and could not be
+ # curl-verified without credentials), so declare "desc": the watermark is then persisted
+ # only at successful job end from the max value seen, which is correct for any arrival
+ # order. Full-refresh endpoints keep the default.
+ sort_mode="desc" if config.pagination == "events_cursor" else "asc",
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="week" 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/inngest/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/inngest/settings.py
new file mode 100644
index 000000000000..cb0aa8f3d706
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/inngest/settings.py
@@ -0,0 +1,127 @@
+from dataclasses import dataclass, field
+from typing import Literal, Optional
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+
+@dataclass
+class InngestEndpointConfig:
+ name: str
+ path: str
+ # Primary key columns for the merge upsert. Must be unique table-wide.
+ primary_keys: list[str]
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Stable creation-style field to partition by (never a mutable field).
+ partition_key: Optional[str] = None
+ # How the endpoint pages:
+ # - "events_cursor": the /v1/events walk — `cursor` (last event internal_id) + `limit`,
+ # bounded by an explicit [received_after, received_before] window.
+ # - "v2_cursor": v2 envelope pagination — follow `page.cursor` while `page.hasMore`.
+ # - "none": a single request returning the full (small) list.
+ pagination: Literal["events_cursor", "v2_cursor", "none"] = "none"
+ # When True, the endpoint fans out over the incremental events walk, fetching
+ # GET /v1/events/{internal_id}/runs once per event.
+ fan_out_runs_per_event: bool = False
+ # Secret-bearing response fields dropped from every row before yielding — key material
+ # must never be synced into the warehouse.
+ redacted_fields: tuple[str, ...] = ()
+ # Per-schema default overlap window re-read on each incremental run (see SourceSchema).
+ default_incremental_lookback_seconds: Optional[int] = None
+ should_sync_default: bool = True
+
+
+# Endpoint catalog. Inngest's REST API lives at api.inngest.com (v1 + v2), authenticated with a
+# per-environment signing key (`Authorization: Bearer signkey-...`), which works on both API
+# versions; dashboard API keys only cover v2, which is why the source asks for a signing key.
+# Branch/custom environments are targeted with the `X-Inngest-Env` header.
+#
+# Only the event-driven endpoints sync incrementally: GET /v1/events takes `received_after` /
+# `received_before` RFC3339 bounds, a genuine server-side filter (and `received_after` defaults to
+# only 1 hour ago, so we always pass it explicitly). Function runs have no list endpoint of their
+# own — they are discovered by walking the events window and fetching each event's runs. The
+# remaining endpoints are small full-refresh inventories with no server-side timestamp filter.
+INNGEST_ENDPOINTS: dict[str, InngestEndpointConfig] = {
+ "events": InngestEndpointConfig(
+ name="events",
+ path="/v1/events",
+ # `internal_id` is the ULID Inngest assigns to every received event; the user-supplied
+ # `id` field is optional and only unique per sender.
+ primary_keys=["internal_id"],
+ partition_key="received_at",
+ pagination="events_cursor",
+ incremental_fields=[
+ {
+ "label": "received_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "received_at",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ ),
+ "function_runs": InngestEndpointConfig(
+ name="function_runs",
+ path="/v1/events/{internal_id}/runs",
+ primary_keys=["run_id"],
+ # `run_started_at` is when the run was scheduled and never changes; `event_received_at`
+ # (the injected incremental field) can differ per parent event for batch runs, so it is
+ # not safe as a partition key.
+ partition_key="run_started_at",
+ pagination="events_cursor",
+ fan_out_runs_per_event=True,
+ # Runs fetched while still Running keep that status until re-pulled; re-read a trailing
+ # hour each run so recently-discovered runs get their terminal status. Longer-lived runs
+ # only settle on a full refresh.
+ default_incremental_lookback_seconds=3600,
+ incremental_fields=[
+ {
+ "label": "event_received_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "event_received_at",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ ),
+ "cancellations": InngestEndpointConfig(
+ name="cancellations",
+ path="/v1/cancellations",
+ primary_keys=["id"],
+ pagination="none",
+ ),
+ "environments": InngestEndpointConfig(
+ name="environments",
+ path="/v2/envs",
+ primary_keys=["id"],
+ pagination="v2_cursor",
+ ),
+ # Inngest webhooks are inbound intake URLs that transform third-party payloads into Inngest
+ # events (not outbound notifications), so this is a plain config inventory. The intake URL is
+ # capability-bearing — anyone holding it can submit events that trigger functions — so it is
+ # stripped like key material.
+ "webhooks": InngestEndpointConfig(
+ name="webhooks",
+ path="/v1/webhooks",
+ primary_keys=["id"],
+ pagination="none",
+ redacted_fields=("url",),
+ ),
+ "event_keys": InngestEndpointConfig(
+ name="event_keys",
+ path="/v2/keys/events",
+ primary_keys=["id"],
+ pagination="v2_cursor",
+ redacted_fields=("key",),
+ ),
+ "signing_keys": InngestEndpointConfig(
+ name="signing_keys",
+ path="/v2/keys/signing",
+ primary_keys=["id"],
+ pagination="v2_cursor",
+ redacted_fields=("key",),
+ ),
+}
+
+ENDPOINTS = tuple(INNGEST_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in INNGEST_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/inngest/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/inngest/source.py
index e6fa67b08062..d98841cbd87f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/inngest/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/inngest/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.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 InngestSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.inngest.inngest import (
+ InngestResumeConfig,
+ inngest_source,
+ validate_credentials as validate_inngest_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.inngest.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ INNGEST_ENDPOINTS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class InngestSource(SimpleSource[InngestSourceConfig]):
+class InngestSource(ResumableSource[InngestSourceConfig, InngestResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.INNGEST
@@ -24,8 +48,123 @@ class InngestSource(SimpleSource[InngestSourceConfig]):
name=SchemaExternalDataSourceType.INNGEST,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="Inngest",
- iconPath="/static/services/inngest.png",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your Inngest signing key to pull your Inngest data into the PostHog Data warehouse.
+
+Find the signing key for your environment (it starts with `signkey-`) in your [Inngest dashboard](https://app.inngest.com/) under **Settings** → **Signing key**. A signing key authenticates both the v1 and v2 REST APIs, so no extra scopes are required. To pull a branch environment instead, also enter its name in the **Environment** field.
+
+Inngest retains event and run history for a plan-dependent window (from 24 hours up to 90 days), so schedule frequent syncs to keep a complete history in PostHog.""",
+ iconPath="/static/services/inngest.svg",
+ docsUrl="https://posthog.com/docs/cdp/sources/inngest",
keywords=["workflow", "queue", "durable execution", "events"],
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="signing_key",
+ label="Signing key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="signkey-prod-...",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="environment",
+ label="Environment",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="my-branch-env",
+ secret=False,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.inngest.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.inngest.com": "Your Inngest signing key is invalid or has been rotated. Copy the current signing key from your Inngest dashboard settings, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.inngest.com": "Your Inngest signing key does not have access to this environment. Check that the key matches the environment you are syncing, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: InngestSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ # Events are immutable once received — append-only is the only incremental-style mode.
+ append_only_endpoints = {"events"}
+ # Run rows mutate (status/output settle after the run ends) and the incremental lookback
+ # re-pulls a window each run; only merge dedupes those, append would duplicate them.
+ merge_only_endpoints = {"function_runs"}
+
+ def _description(endpoint: str) -> str | None:
+ if endpoint == "events":
+ return (
+ "Events received by Inngest. Retention is plan-dependent (24 hours to 90 days), "
+ "so sync frequently; the first sync backfills whatever your plan still retains"
+ )
+ if endpoint == "function_runs":
+ return (
+ "Function runs discovered via the events stream (one lookup per event). Status and "
+ "output are point-in-time; a trailing window is re-read each sync so recent runs "
+ "settle, but long-lived runs only update on a full refresh"
+ )
+ return None
+
+ def _build_schema(endpoint: str) -> SourceSchema:
+ endpoint_config = INNGEST_ENDPOINTS[endpoint]
+ has_incremental = bool(INCREMENTAL_FIELDS.get(endpoint))
+ return SourceSchema(
+ name=endpoint,
+ supports_incremental=has_incremental and endpoint not in append_only_endpoints,
+ supports_append=has_incremental and endpoint not in merge_only_endpoints,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ should_sync_default=endpoint_config.should_sync_default,
+ description=_description(endpoint),
+ default_incremental_lookback_seconds=endpoint_config.default_incremental_lookback_seconds,
+ )
+
+ 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: InngestSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if validate_inngest_credentials(config.signing_key, config.environment or None):
+ return True, None
+
+ return False, "Invalid Inngest signing key"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[InngestResumeConfig]:
+ return ResumableSourceManager[InngestResumeConfig](inputs, InngestResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: InngestSourceConfig,
+ resumable_source_manager: ResumableSourceManager[InngestResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return inngest_source(
+ signing_key=config.signing_key,
+ environment=config.environment or None,
+ 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,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/inngest/tests/test_inngest.py b/products/warehouse_sources/backend/temporal/data_imports/sources/inngest/tests/test_inngest.py
new file mode 100644
index 000000000000..bf9c314af72d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/inngest/tests/test_inngest.py
@@ -0,0 +1,384 @@
+import json
+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.inngest import inngest
+from products.warehouse_sources.backend.temporal.data_imports.sources.inngest.inngest import (
+ EVENTS_PAGE_SIZE,
+ InngestResumeConfig,
+ _event_window,
+ get_rows,
+ inngest_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.inngest.settings import INNGEST_ENDPOINTS
+
+
+class _FakeResumableManager:
+ def __init__(self, state: InngestResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[InngestResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> InngestResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: InngestResumeConfig) -> None:
+ self.saved.append(data)
+
+
+def _event(internal_id: str, received_at: str = "2026-07-10T10:00:00.000Z", **extra: Any) -> dict[str, Any]:
+ return {"internal_id": internal_id, "receivedAt": received_at, "name": "app/user.signed.up", **extra}
+
+
+def _run_rows(
+ endpoint: str,
+ fake_fetch: Any,
+ manager: _FakeResumableManager | None = None,
+ **incremental: Any,
+) -> tuple[list[dict], _FakeResumableManager]:
+ manager = manager or _FakeResumableManager()
+ rows: list[dict] = []
+ with patch.object(inngest, "_fetch", fake_fetch), patch.object(inngest, "make_tracked_session", MagicMock()):
+ for batch in get_rows(
+ signing_key="signkey-prod-test",
+ environment=None,
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ **incremental,
+ ):
+ rows.extend(batch)
+ return rows, manager
+
+
+class TestEventWindow:
+ @freeze_time("2026-07-14T12:00:00Z")
+ def test_first_sync_backfills_the_max_retention_window(self) -> None:
+ # received_after defaults to only 1 hour ago server-side, so leaving it off a first sync
+ # would silently drop everything older than an hour.
+ after, before = _event_window(should_use_incremental_field=False, db_incremental_field_last_value=None)
+ assert after == "2026-04-15T12:00:00.000Z"
+ assert before == "2026-07-14T12:00:00.000Z"
+
+ @parameterized.expand(
+ [
+ ("iso_string", "2026-07-10T08:30:00+00:00", "2026-07-10T08:30:00.000Z"),
+ ("iso_string_z", "2026-07-10T08:30:00.500Z", "2026-07-10T08:30:00.500Z"),
+ ]
+ )
+ @freeze_time("2026-07-14T12:00:00Z")
+ def test_incremental_run_advances_from_the_watermark(self, _name: str, value: Any, expected_after: str) -> None:
+ after, _ = _event_window(should_use_incremental_field=True, db_incremental_field_last_value=value)
+ assert after == expected_after
+
+ @freeze_time("2026-07-14T12:00:00Z")
+ def test_future_watermark_is_clamped_to_now(self) -> None:
+ # A future-dated watermark would produce an inverted window that returns nothing forever.
+ after, before = _event_window(
+ should_use_incremental_field=True, db_incremental_field_last_value="2027-01-01T00:00:00Z"
+ )
+ assert after == before == "2026-07-14T12:00:00.000Z"
+
+
+class TestEventsPagination:
+ def test_paginates_with_cursor_and_pinned_window(self) -> None:
+ # Every page must carry the explicit received_after/received_before window (the server
+ # default is 1 hour) plus the cursor from the previous page's last event.
+ pages = [
+ [_event(f"01A{i:03d}") for i in range(EVENTS_PAGE_SIZE)],
+ [_event("01B000"), _event("01B001")],
+ ]
+ seen_params: list[dict] = []
+
+ def fake_fetch(session: Any, url: str, headers: dict, logger: Any, params: dict | None = None) -> Any:
+ seen_params.append(dict(params or {}))
+ return {"data": pages[len(seen_params) - 1]}
+
+ rows, _ = _run_rows("events", fake_fetch)
+
+ assert len(rows) == EVENTS_PAGE_SIZE + 2
+ assert "cursor" not in seen_params[0]
+ assert seen_params[1]["cursor"] == "01A099"
+ for params in seen_params:
+ assert params["limit"] == EVENTS_PAGE_SIZE
+ assert params["received_after"]
+ assert params["received_before"]
+ # The window must not shift between pages while new events keep arriving.
+ assert seen_params[0]["received_before"] == seen_params[1]["received_before"]
+
+ @parameterized.expand(
+ [
+ ("empty_first_page", [[]], 0),
+ ("partial_page_stops", [[_event("01A000")]], 1),
+ ]
+ )
+ def test_pagination_terminates(self, _name: str, pages: list[list[dict]], expected_rows: int) -> None:
+ calls: list[int] = []
+
+ def fake_fetch(session: Any, url: str, headers: dict, logger: Any, params: dict | None = None) -> Any:
+ calls.append(1)
+ return {"data": pages[len(calls) - 1]}
+
+ rows, _ = _run_rows("events", fake_fetch)
+ assert len(rows) == expected_rows
+ assert len(calls) == 1
+
+ def test_state_saved_after_each_full_page_but_not_the_final_page(self) -> None:
+ # Saving before the yield would skip the last page on crash; saving on the final page would
+ # make a retry resume into an exhausted walk.
+ pages = [
+ [_event(f"01A{i:03d}") for i in range(EVENTS_PAGE_SIZE)],
+ [_event("01B000")],
+ ]
+ calls: list[int] = []
+
+ def fake_fetch(session: Any, url: str, headers: dict, logger: Any, params: dict | None = None) -> Any:
+ calls.append(1)
+ return {"data": pages[len(calls) - 1]}
+
+ _, manager = _run_rows("events", fake_fetch)
+ assert [s.cursor for s in manager.saved] == ["01A099"]
+ assert manager.saved[0].received_after and manager.saved[0].received_before
+
+ def test_resume_continues_the_saved_walk(self) -> None:
+ # A resumed attempt must reuse the saved cursor and pinned window, not re-derive a new
+ # window from the clock (which would re-fetch everything already yielded).
+ state = InngestResumeConfig(
+ cursor="01A099",
+ received_after="2026-07-01T00:00:00.000Z",
+ received_before="2026-07-14T00:00:00.000Z",
+ )
+ seen_params: list[dict] = []
+
+ def fake_fetch(session: Any, url: str, headers: dict, logger: Any, params: dict | None = None) -> Any:
+ seen_params.append(dict(params or {}))
+ return {"data": [_event("01B000")]}
+
+ _run_rows("events", fake_fetch, manager=_FakeResumableManager(state))
+ assert seen_params[0]["cursor"] == "01A099"
+ assert seen_params[0]["received_after"] == "2026-07-01T00:00:00.000Z"
+ assert seen_params[0]["received_before"] == "2026-07-14T00:00:00.000Z"
+
+ def test_cursor_event_returned_again_is_dropped(self) -> None:
+ # We couldn't verify whether the API's cursor is inclusive; re-yielding the cursor event
+ # would duplicate it in append mode, so it must be filtered out.
+ pages = [
+ [_event(f"01A{i:03d}") for i in range(EVENTS_PAGE_SIZE)],
+ [_event("01A099"), _event("01B000")],
+ ]
+ calls: list[int] = []
+
+ def fake_fetch(session: Any, url: str, headers: dict, logger: Any, params: dict | None = None) -> Any:
+ calls.append(1)
+ return {"data": pages[len(calls) - 1]}
+
+ rows, _ = _run_rows("events", fake_fetch)
+ assert [r["internal_id"] for r in rows].count("01A099") == 1
+
+ @parameterized.expand(
+ [
+ ("camel_case", {"internal_id": "01A000", "receivedAt": "2026-07-10T10:00:00.000Z"}),
+ ("snake_case", {"internal_id": "01A000", "received_at": "2026-07-10T10:00:00.000Z"}),
+ ]
+ )
+ def test_received_at_is_normalized_from_either_spelling(self, _name: str, item: dict) -> None:
+ # The v1 spec documents `receivedAt` amid snake_case fields and the live casing is
+ # unverified; the incremental/partition column must exist under one stable name either way.
+ def fake_fetch(session: Any, url: str, headers: dict, logger: Any, params: dict | None = None) -> Any:
+ return {"data": [dict(item)]}
+
+ rows, _ = _run_rows("events", fake_fetch)
+ assert rows[0]["received_at"] == "2026-07-10T10:00:00.000Z"
+ assert "receivedAt" not in rows[0]
+
+
+class TestFunctionRunsFanOut:
+ def test_fetches_runs_per_event_and_injects_event_received_at(self) -> None:
+ runs_by_event = {
+ "01A000": [{"run_id": "r1", "status": "Completed", "output": {"ok": True}}],
+ "01A001": [],
+ }
+
+ def fake_fetch(session: Any, url: str, headers: dict, logger: Any, params: dict | None = None) -> Any:
+ if url.endswith("/runs"):
+ internal_id = url.rsplit("/", 2)[-2]
+ return {"data": runs_by_event[internal_id]}
+ return {"data": [_event("01A000"), _event("01A001")]}
+
+ rows, _ = _run_rows("function_runs", fake_fetch)
+ assert len(rows) == 1
+ # The parent event's received time drives the incremental watermark; a run's own
+ # timestamps can lag behind (debounce) and would advance the watermark past unseen events.
+ assert rows[0]["event_received_at"] == "2026-07-10T10:00:00.000Z"
+ # Non-string outputs are JSON-encoded so the column keeps one stable type across rows.
+ assert rows[0]["output"] == json.dumps({"ok": True})
+
+ def test_batch_run_returned_for_every_event_is_deduped(self) -> None:
+ # A batch run appears under every event in its batch; duplicate run_id rows within one
+ # sync seed the Delta table with dupes that every later merge multi-matches.
+ def fake_fetch(session: Any, url: str, headers: dict, logger: Any, params: dict | None = None) -> Any:
+ if url.endswith("/runs"):
+ return {"data": [{"run_id": "r-batch", "status": "Completed", "output": None}]}
+ return {"data": [_event("01A000"), _event("01A001")]}
+
+ rows, _ = _run_rows("function_runs", fake_fetch)
+ assert [r["run_id"] for r in rows] == ["r-batch"]
+
+
+class TestV2ListPagination:
+ def test_follows_page_cursor_until_has_more_is_false(self) -> None:
+ pages = [
+ {"data": [{"id": "env-1"}], "page": {"cursor": "c2", "hasMore": True}},
+ {"data": [{"id": "env-2"}], "page": {"cursor": "c3", "hasMore": False}},
+ ]
+ seen_params: list[dict | None] = []
+
+ def fake_fetch(session: Any, url: str, headers: dict, logger: Any, params: dict | None = None) -> Any:
+ seen_params.append(params)
+ return pages[len(seen_params) - 1]
+
+ rows, _ = _run_rows("environments", fake_fetch)
+ assert [r["id"] for r in rows] == ["env-1", "env-2"]
+ assert seen_params == [None, {"cursor": "c2"}]
+
+ def test_repeated_cursor_breaks_the_loop(self) -> None:
+ # A server bug returning hasMore=True with the same cursor forever must not loop the sync.
+ def fake_fetch(session: Any, url: str, headers: dict, logger: Any, params: dict | None = None) -> Any:
+ return {"data": [{"id": "env-1"}], "page": {"cursor": "same", "hasMore": True}}
+
+ rows, _ = _run_rows("environments", fake_fetch)
+ assert len(rows) == 2 # first page + the one repeat before the guard trips
+
+ @parameterized.expand([("event_keys",), ("signing_keys",)])
+ def test_secret_key_material_is_never_synced(self, endpoint: str) -> None:
+ # The v2 key inventories return the raw `key` secret; syncing it would copy live
+ # credentials into the warehouse.
+ def fake_fetch(session: Any, url: str, headers: dict, logger: Any, params: dict | None = None) -> Any:
+ return {
+ "data": [{"id": "k1", "name": "prod key", "key": "signkey-prod-secretvalue"}],
+ "page": {"hasMore": False},
+ }
+
+ rows, _ = _run_rows(endpoint, fake_fetch)
+ assert rows == [{"id": "k1", "name": "prod key"}]
+
+
+class TestV1Lists:
+ @parameterized.expand(
+ [
+ ("list_payload", {"data": [{"id": "c1"}, {"id": "c2"}]}, ["c1", "c2"]),
+ # The v1 spec is ambiguous about single-object vs array envelopes for these lists.
+ ("single_object_payload", {"data": {"id": "c1"}}, ["c1"]),
+ ("empty", {"data": []}, []),
+ ]
+ )
+ def test_cancellations_handle_list_and_object_envelopes(
+ self, _name: str, payload: dict, expected_ids: list[str]
+ ) -> None:
+ def fake_fetch(session: Any, url: str, headers: dict, logger: Any, params: dict | None = None) -> Any:
+ return payload
+
+ rows, _ = _run_rows("cancellations", fake_fetch)
+ assert [r["id"] for r in rows] == expected_ids
+
+ def test_webhook_intake_url_is_never_synced(self) -> None:
+ # The intake URL is capability-bearing: anyone holding it can submit events that trigger
+ # Inngest functions, so it must not be copied into a warehouse table viewers can read.
+ def fake_fetch(session: Any, url: str, headers: dict, logger: Any, params: dict | None = None) -> Any:
+ return {"data": [{"id": "wh1", "name": "github intake", "url": "https://inn.gs/e/secret-intake-token"}]}
+
+ rows, _ = _run_rows("webhooks", fake_fetch)
+ assert rows == [{"id": "wh1", "name": "github intake"}]
+
+
+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(inngest, "make_tracked_session", return_value=session):
+ assert validate_credentials("signkey-prod-test") is expected
+
+ def test_environment_header_is_sent_when_configured(self) -> None:
+ # A branch environment's data is only reachable with the X-Inngest-Env header; dropping it
+ # would validate (and later sync) the production environment instead.
+ response = MagicMock()
+ response.status_code = 200
+ session = MagicMock()
+ session.get.return_value = response
+ with patch.object(inngest, "make_tracked_session", return_value=session):
+ validate_credentials("signkey-branch-test", "my-branch")
+ assert session.get.call_args.kwargs["headers"]["X-Inngest-Env"] == "my-branch"
+
+ def test_network_error_is_not_valid(self) -> None:
+ session = MagicMock()
+ session.get.side_effect = Exception("boom")
+ with patch.object(inngest, "make_tracked_session", return_value=session):
+ assert validate_credentials("signkey-prod-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(inngest._fetch.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]
+ result = inngest._fetch(session, "https://api.inngest.com/v1/events", {}, 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):
+ inngest._fetch(session, "https://api.inngest.com/v1/events", {}, MagicMock())
+ assert session.get.call_count == 1
+
+
+class TestSourceResponse:
+ @parameterized.expand(
+ [
+ # The event-walk endpoints must report "desc" so the watermark is persisted only at
+ # successful job end — the walk's arrival order within the window is unverified.
+ ("events", "desc", "received_at"),
+ ("function_runs", "desc", "run_started_at"),
+ ("cancellations", "asc", None),
+ ("environments", "asc", None),
+ ("webhooks", "asc", None),
+ ("event_keys", "asc", None),
+ ("signing_keys", "asc", None),
+ ]
+ )
+ def test_sort_mode_partition_and_primary_keys(
+ self, endpoint: str, expected_sort: str, partition_key: str | None
+ ) -> None:
+ response = inngest_source(
+ signing_key="signkey-prod-test",
+ environment=None,
+ 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 == INNGEST_ENDPOINTS[endpoint].primary_keys
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/inngest/tests/test_inngest_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/inngest/tests/test_inngest_source.py
new file mode 100644
index 000000000000..a068bd79fa18
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/inngest/tests/test_inngest_source.py
@@ -0,0 +1,160 @@
+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.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import InngestSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.inngest import source as source_module
+from products.warehouse_sources.backend.temporal.data_imports.sources.inngest.inngest import InngestResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.inngest.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.inngest.source import InngestSource
+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="received_at" if use_incremental else None,
+ incremental_field_type=None,
+ job_id="job-1",
+ logger=MagicMock(),
+ reset_pipeline=False,
+ )
+
+
+class TestInngestSource:
+ def setup_method(self) -> None:
+ self.source = InngestSource()
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.INNGEST
+
+ def test_source_config_fields(self) -> None:
+ config = self.source.get_source_config
+ assert [f.name for f in config.fields] == ["signing_key", "environment"]
+ signing_key, environment = config.fields
+ assert isinstance(signing_key, SourceFieldInputConfig)
+ assert signing_key.type == SourceFieldInputConfigType.PASSWORD
+ assert signing_key.required is True
+ assert signing_key.secret is True
+ assert isinstance(environment, SourceFieldInputConfig)
+ assert environment.required is False
+ assert environment.secret is False
+
+ 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.docsUrl == "https://posthog.com/docs/cdp/sources/inngest"
+
+ 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=["environments"])
+ assert [s.name for s in schemas] == ["environments"]
+
+ @parameterized.expand(
+ [
+ # Events are immutable, so append is the only incremental-style mode; run rows mutate
+ # (status settles after the run ends), so they are merge-only. Everything else is a
+ # small inventory with no server-side timestamp filter and syncs as full refresh.
+ ("events", False, True, ["received_at"]),
+ ("function_runs", True, False, ["event_received_at"]),
+ ("cancellations", False, False, []),
+ ("environments", False, False, []),
+ ("webhooks", False, False, []),
+ ("event_keys", False, False, []),
+ ("signing_keys", False, False, []),
+ ]
+ )
+ def test_incremental_support_per_endpoint(
+ self, endpoint: str, supports_incremental: bool, supports_append: 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
+ assert schema.supports_append is supports_append
+ assert [f["field"] for f in schema.incremental_fields] == incremental_fields
+
+ def test_function_runs_re_read_a_trailing_window(self) -> None:
+ # Runs fetched while still Running keep a stale status unless each incremental sync
+ # re-reads a trailing window; dropping the default lookback would freeze them forever.
+ schema = next(s for s in self.source.get_schemas(MagicMock(), team_id=1) if s.name == "function_runs")
+ assert schema.default_incremental_lookback_seconds == 3600
+
+ @parameterized.expand([("valid", True, True), ("invalid", False, False)])
+ def test_validate_credentials(self, _name: str, probe_result: bool, expected_ok: bool) -> None:
+ config = InngestSourceConfig(signing_key="signkey-prod-test", environment="branch-env")
+ with patch.object(source_module, "validate_inngest_credentials", return_value=probe_result) as mock_probe:
+ ok, error = self.source.validate_credentials(config, team_id=1)
+ assert ok is expected_ok
+ assert (error is None) is expected_ok
+ mock_probe.assert_called_once_with("signkey-prod-test", "branch-env")
+
+ @parameterized.expand(
+ [
+ ("unauthorized", "401 Client Error: Unauthorized for url: https://api.inngest.com/v1/events?limit=100"),
+ ("forbidden", "403 Client Error: Forbidden for url: https://api.inngest.com/v2/envs"),
+ ]
+ )
+ 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("events"))
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is InngestResumeConfig
+
+ def test_source_for_pipeline_plumbs_credentials_and_endpoint(self) -> None:
+ config = InngestSourceConfig(signing_key="signkey-prod-test", environment="branch-env")
+ inputs = _source_inputs("events", last_value="2026-07-01T00:00:00Z", use_incremental=True)
+ with patch.object(source_module, "inngest_source") as mock_source:
+ self.source.source_for_pipeline(config, MagicMock(), inputs)
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["signing_key"] == "signkey-prod-test"
+ assert kwargs["environment"] == "branch-env"
+ assert kwargs["endpoint"] == "events"
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == "2026-07-01T00:00:00Z"
+
+ def test_source_for_pipeline_normalizes_blank_environment_to_none(self) -> None:
+ # An empty-string environment must not be sent as an X-Inngest-Env header — the API would
+ # try to resolve a branch environment named "".
+ config = InngestSourceConfig(signing_key="signkey-prod-test", environment="")
+ with patch.object(source_module, "inngest_source") as mock_source:
+ self.source.source_for_pipeline(config, MagicMock(), _source_inputs("events"))
+ assert mock_source.call_args.kwargs["environment"] is None
+
+ def test_source_for_pipeline_omits_last_value_when_not_incremental(self) -> None:
+ # A stale watermark on a full-refresh run would wrongly narrow the events window.
+ config = InngestSourceConfig(signing_key="signkey-prod-test")
+ inputs = _source_inputs("events", last_value="2026-07-01T00:00:00Z", use_incremental=False)
+ with patch.object(source_module, "inngest_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)