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): add n8n project users, folders, test runs and insights tables (#115424)

Tom Owers93788d90f33d
diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
index 2b5986cdfddd..9392d362ce15 100644
--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
@@ -798,8 +798,6 @@
1 products/warehouse_sources/backend/temporal/data_imports/sources/mux/mux.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/mux/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/my_hours/settings.py
-1 products/warehouse_sources/backend/temporal/data_imports/sources/n8n/n8n.py
-1 products/warehouse_sources/backend/temporal/data_imports/sources/n8n/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/netlify/netlify.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/netlify/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/new_relic/new_relic.py
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index 27cc8c63c184..af7630e03aa7 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -5773,10 +5773,10 @@ Today (6): `executions`, `projects`, `tags`, `users`, `variables`, `workflows`
Diffed against: <https://raw.githubusercontent.com/n8n-io/n8n/master/packages/cli/src/public-api/v1/openapi.yml>
-- [ ] `/insights/summary` — n8n's headline metrics (total/failed executions, run time saved) over a date range, filterable by project (high)
-- [ ] `/projects/{projectId}/users` — project membership join table with roles — resolves who owns which project (medium)
-- [ ] `/projects/{projectId}/folders` — folder hierarchy workflows are organized into; lookup for workflow parentFolder ids (medium)
-- [ ] `/workflows/{id}/test-runs (+ /test-runs/{runId}/test-cases)` — evaluation run results per workflow — pass/fail history for AI workflow testing (medium)
+- [x] `/insights/summary` — n8n's headline metrics (total/failed executions, run time saved) over a date range, filterable by project (high)
+- [x] `/projects/{projectId}/users` — project membership join table with roles — resolves who owns which project (medium)
+- [x] `/projects/{projectId}/folders` — folder hierarchy workflows are organized into; lookup for workflow parentFolder ids (medium)
+- [x] `/workflows/{id}/test-runs (+ /test-runs/{runId}/test-cases)` — evaluation run results per workflow — pass/fail history for AI workflow testing (medium)
- [ ] `/data-tables and /data-tables/{dataTableId}/rows` — user-defined data tables and their rows, queried as ordinary warehouse tables (medium)
- [ ] `/data-tables/{dataTableId}/columns` — column metadata needed to type the data-table rows (low)
- [ ] `/community-packages` — installed community node inventory for auditing what workflows depend on (low)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/n8n/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/n8n/canonical_descriptions.py
index 7fea87344992..dab800b5d962 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/n8n/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/n8n/canonical_descriptions.py
@@ -91,4 +91,86 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"type": "The project's type (e.g. personal or team).",
},
},
+ "project_users": {
+ "description": "Members of each project, one row per user and project, with the user's role in that project.",
+ "docs_url": "https://docs.n8n.io/api/api-reference/",
+ "columns": {
+ "projectId": "The project the user is a member of.",
+ "id": "Unique identifier for the user.",
+ "email": "The user's email address.",
+ "firstName": "The user's first name.",
+ "lastName": "The user's last name.",
+ "role": "The user's role in the project (e.g. project:admin, project:viewer).",
+ "createdAt": "Time at which the user was created.",
+ "updatedAt": "Time at which the user was last updated.",
+ },
+ },
+ "folders": {
+ "description": "Folders that organize workflows inside each project.",
+ "docs_url": "https://docs.n8n.io/api/api-reference/",
+ "columns": {
+ "projectId": "The project the folder belongs to.",
+ "id": "Unique identifier for the folder.",
+ "name": "The folder's name.",
+ "parentFolderId": "Identifier of the parent folder, or null for a folder at the project root.",
+ "parentFolder": "The parent folder's id, name, and parent folder id.",
+ "homeProject": "The project the folder belongs to.",
+ "tags": "Tags assigned to the folder.",
+ "workflowCount": "Number of workflows in the folder.",
+ "subFolderCount": "Number of folders in the folder.",
+ "path": "Names of every folder from the project root down to this folder.",
+ "createdAt": "Time at which the folder was created.",
+ "updatedAt": "Time at which the folder was last updated.",
+ },
+ },
+ "test_runs": {
+ "description": "Evaluation test runs of each workflow.",
+ "docs_url": "https://docs.n8n.io/api/api-reference/",
+ "columns": {
+ "workflowId": "The workflow the test run evaluated.",
+ "id": "Unique identifier for the test run.",
+ "status": "Status of the test run (new, running, completed, error, or cancelled).",
+ "runAt": "Time at which the test run started.",
+ "completedAt": "Time at which the test run finished.",
+ "metrics": "Metrics aggregated across the run's test cases.",
+ "errorCode": "Error code when the test run failed.",
+ "errorDetails": "Details of the error when the test run failed.",
+ "finalResult": "Overall result of the run (success, error, or warning), set once it completes.",
+ "testCaseCount": "Number of test cases in the run.",
+ "createdAt": "Time at which the test run was created.",
+ "updatedAt": "Time at which the test run was last updated.",
+ },
+ },
+ "test_cases": {
+ "description": "Per-case results of each evaluation test run.",
+ "docs_url": "https://docs.n8n.io/api/api-reference/",
+ "columns": {
+ "workflowId": "The workflow the test run evaluated.",
+ "testRunId": "The test run the case belongs to.",
+ "id": "Unique identifier for the test case.",
+ "status": "Status of the test case (e.g. running, success, error, warning, or cancelled).",
+ "runAt": "Time at which the test case started.",
+ "completedAt": "Time at which the test case finished.",
+ "metrics": "Metrics the test case produced.",
+ "errorCode": "Error code when the test case failed.",
+ "errorDetails": "Details of the error when the test case failed.",
+ "inputs": "Input data for the test case.",
+ "outputs": "Output data the test case produced.",
+ "executionId": "Identifier of the workflow execution behind the test case, if it is still retained.",
+ },
+ },
+ "insights_summary": {
+ "description": "Headline execution metrics for the instance, one row per UTC day.",
+ "docs_url": "https://docs.n8n.io/api/api-reference/",
+ "columns": {
+ "date": "The UTC day the metrics cover.",
+ "startDate": "Start of the day the metrics cover.",
+ "endDate": "End of the day the metrics cover.",
+ "total": "Number of production executions in the day, with the change against the previous day.",
+ "failed": "Number of failed production executions in the day, with the change against the previous day.",
+ "failureRate": "Ratio of failed to total production executions in the day.",
+ "timeSaved": "Minutes of manual work the day's executions saved.",
+ "averageRunTime": "Average execution run time in the day, in milliseconds.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/n8n/n8n.py b/products/warehouse_sources/backend/temporal/data_imports/sources/n8n/n8n.py
index 0355b9e626a9..729eba844dd6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/n8n/n8n.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/n8n/n8n.py
@@ -1,32 +1,60 @@
import dataclasses
-from typing import Any, Optional
+from collections.abc import Callable, Iterable, Iterator
+from datetime import UTC, date, datetime, time, timedelta
+from typing import Any, Optional, cast
from urllib.parse import urlencode, urlparse
+from requests import Response
+
from posthog.cloud_utils import is_cloud
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.datetime_utils import parse_datetime_value
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.rest_source import (
RESTAPIConfig,
rest_api_resource,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.config_setup import (
+ make_parent_key_name,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ build_chained_resource,
+ build_dependent_resource,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ BasePaginator,
JSONResponseCursorPaginator,
+ OffsetPaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.resource import Resource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
+ ClientConfig,
+ Endpoint,
+ EndpointResource,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.n8n.settings import (
+ INSIGHTS_BACKFILL_DAYS,
N8N_API_PATH,
N8N_ENDPOINTS,
- PAGE_SIZE,
+ N8nEndpointConfig,
)
+INSIGHTS_REQUEST_TIMEOUT = 60
+_ISO_UTC = "%Y-%m-%dT%H:%M:%S.000Z"
+
[email protected](frozen=True)
class N8nResumeConfig:
# The `nextCursor` token to fetch the next page. None means "start from the
# first page" — used both on a fresh sync and when the bookmark predates any page.
next_cursor: Optional[str] = None
+ # Framework fan-out checkpoint ({"completed": [...], "current": ..., "child_state": ...}).
+ fanout_state: Optional[dict[str, Any]] = None
+ # Next UTC day (ISO date) the insights summary walk fetches.
+ next_date: Optional[str] = None
def normalize_host(host: str) -> str:
@@ -81,6 +109,181 @@ def _build_url(base_url: str, params: dict[str, Any]) -> str:
return f"{base_url}?{urlencode(params)}"
+def _client_config(host: str, api_key: str) -> ClientConfig:
+ return {
+ "base_url": _base_url(host),
+ # Auth (the X-N8N-API-KEY header) is supplied via the framework auth config so its
+ # value is redacted from logs and raised errors; only the non-secret Accept header here.
+ "headers": {"Accept": "application/json"},
+ "auth": {"type": "api_key", "api_key": api_key, "name": "X-N8N-API-KEY", "location": "header"},
+ # n8n cursor pagination: `nextCursor` in the body, echoed back as the `cursor` query
+ # param. A null/absent nextCursor terminates.
+ "paginator": JSONResponseCursorPaginator(cursor_path="nextCursor", cursor_param="cursor"),
+ # `host` is user-supplied, so pin redirects off so validation and the outbound request
+ # stay on the same target (SSRF defense-in-depth).
+ "allow_redirects": False,
+ }
+
+
+def _list_params(config: N8nEndpointConfig) -> dict[str, Any]:
+ params: dict[str, Any] = dict(config.extra_params)
+ # The offset paginator sends its own `take`/`skip`, so only cursor endpoints take `limit`.
+ if config.paginator == "cursor":
+ params["limit"] = config.page_size
+ return params
+
+
+def _list_endpoint_extra(config: N8nEndpointConfig) -> Endpoint:
+ paginator: BasePaginator
+ if config.paginator == "offset":
+ paginator = OffsetPaginator(limit=config.page_size, offset_param="skip", limit_param="take", total_path="count")
+ else:
+ paginator = JSONResponseCursorPaginator(cursor_path="nextCursor", cursor_param="cursor")
+ return {
+ "paginator": paginator,
+ "data_selector": "data",
+ # `data` is the required envelope field; a 200 body without it means the
+ # response shape changed — fail loud instead of silently syncing 0 rows.
+ "data_selector_required": True,
+ }
+
+
+def _list_endpoint(config: N8nEndpointConfig, params: dict[str, Any] | None = None) -> Endpoint:
+ endpoint: Endpoint = {"path": config.path, "params": params if params is not None else _list_params(config)}
+ endpoint.update(_list_endpoint_extra(config))
+ return endpoint
+
+
+def _chained_resource(config: N8nEndpointConfig, client_config: ClientConfig, team_id: int, job_id: str) -> Resource:
+ """Build a grandparent -> parent -> child chain (workflows -> test runs -> test cases)."""
+ fanout = config.fanout
+ assert fanout is not None
+ middle_config = N8N_ENDPOINTS[fanout.parent_name]
+ root_fanout = middle_config.fanout
+ assert root_fanout is not None
+ root_config = N8N_ENDPOINTS[root_fanout.parent_name]
+
+ root_resource: EndpointResource = {
+ "name": root_config.name,
+ "table_name": root_config.name,
+ "write_disposition": "replace",
+ "endpoint": _list_endpoint(root_config),
+ "table_format": "delta",
+ }
+ middle_endpoint = _list_endpoint(
+ middle_config,
+ {
+ **_list_params(middle_config),
+ root_fanout.resolve_param: {
+ "type": "resolve",
+ "resource": root_config.name,
+ "field": root_fanout.resolve_field,
+ },
+ },
+ )
+ middle_endpoint["response_actions"] = root_fanout.child_response_actions
+ middle_resource: EndpointResource = {
+ "name": middle_config.name,
+ "table_name": middle_config.name,
+ "write_disposition": "replace",
+ # Carries the grandparent id onto each middle row so the child path can bind it.
+ "include_from_parent": root_fanout.include_from_parent,
+ "endpoint": middle_endpoint,
+ "table_format": "delta",
+ }
+ child_endpoint = _list_endpoint(
+ config,
+ {
+ **_list_params(config),
+ root_fanout.resolve_param: {
+ "type": "resolve",
+ "resource": middle_config.name,
+ "field": make_parent_key_name(root_config.name, root_fanout.resolve_field),
+ },
+ fanout.resolve_param: {"type": "resolve", "resource": middle_config.name, "field": fanout.resolve_field},
+ },
+ )
+ child_endpoint["response_actions"] = fanout.child_response_actions
+ child_resource: EndpointResource = {
+ "name": config.name,
+ "table_name": config.name,
+ "write_disposition": "replace",
+ "include_from_parent": fanout.include_from_parent,
+ "endpoint": child_endpoint,
+ "table_format": "delta",
+ }
+
+ return cast(
+ Resource,
+ build_chained_resource(
+ resources=[root_resource, middle_resource, child_resource],
+ child_name=config.name,
+ parent_name=middle_config.name,
+ parent_field_renames=fanout.parent_field_renames,
+ client_config=client_config,
+ team_id=team_id,
+ job_id=job_id,
+ ),
+ )
+
+
+def _insights_window(day: date) -> dict[str, str]:
+ start = datetime.combine(day, time.min, tzinfo=UTC)
+ end = start + timedelta(days=1)
+ return {"startDate": start.strftime(_ISO_UTC), "endDate": end.strftime(_ISO_UTC)}
+
+
+def _insights_summary_rows(
+ host: str,
+ api_key: str,
+ resumable_source_manager: ResumableSourceManager[N8nResumeConfig],
+ db_incremental_field_last_value: Optional[Any],
+) -> Iterator[list[dict[str, Any]]]:
+ """Yield one insights summary row per UTC day, oldest first, up to and including today."""
+ session = make_tracked_session(redact_values=(api_key,), allow_redirects=False)
+ headers = _get_headers(api_key)
+ url = f"{_base_url(host)}{N8N_ENDPOINTS['insights_summary'].path}"
+ today = datetime.now(UTC).date()
+
+ def fetch(day: date) -> Response:
+ return session.get(_build_url(url, _insights_window(day)), headers=headers, timeout=INSIGHTS_REQUEST_TIMEOUT)
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ last_value = parse_datetime_value(db_incremental_field_last_value)
+ start: Optional[date] = None
+ if resume is not None and resume.next_date is not None:
+ start = date.fromisoformat(resume.next_date)
+ elif last_value is not None:
+ # Re-fetch the watermark day: it was still in progress when the last sync read it.
+ start = last_value.date()
+
+ backfill_starts = [today - timedelta(days=days) for days in INSIGHTS_BACKFILL_DAYS]
+ candidates = backfill_starts if start is None else [start, *(d for d in backfill_starts if d > start)]
+
+ day = candidates[0]
+ response = fetch(day)
+ for candidate in candidates[1:]:
+ if response.status_code != 403:
+ break
+ resumable_source_manager.safe_point()
+ day = candidate
+ response = fetch(day)
+
+ while True:
+ # A 403 here means even the shortest window is refused, so the key lacks `insights:read`.
+ response.raise_for_status()
+ window = _insights_window(day)
+ row = {"date": day.isoformat(), **window, **response.json()}
+ next_day = day + timedelta(days=1)
+ if next_day <= today:
+ resumable_source_manager.save_state(N8nResumeConfig(next_date=next_day.isoformat()))
+ yield [row]
+ if next_day > today:
+ return
+ day = next_day
+ response = fetch(day)
+
+
def n8n_source(
host: str,
api_key: str,
@@ -92,43 +295,59 @@ def n8n_source(
) -> SourceResponse:
config = N8N_ENDPOINTS[endpoint]
- params: dict[str, Any] = {"limit": PAGE_SIZE, **config.extra_params}
+ if endpoint == "insights_summary":
+ return _source_response(
+ config,
+ lambda: _insights_summary_rows(host, api_key, resumable_source_manager, db_incremental_field_last_value),
+ )
+
+ client_config = _client_config(host, api_key)
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+
+ if config.fanout is not None and N8N_ENDPOINTS[config.fanout.parent_name].fanout is not None:
+ # A two-level chain carries no resume state; see build_chained_resource.
+ chained = _chained_resource(config, client_config, team_id, job_id)
+ return _source_response(config, lambda: chained, chained.column_hints)
+
+ if config.fanout is not None:
+ parent_config = N8N_ENDPOINTS[config.fanout.parent_name]
+
+ def save_fanout_state(state: Optional[dict[str, Any]]) -> None:
+ if state:
+ resumable_source_manager.save_state(N8nResumeConfig(fanout_state=state))
+
+ dependent = cast(
+ Resource,
+ build_dependent_resource(
+ endpoint_configs=N8N_ENDPOINTS,
+ child_endpoint=endpoint,
+ fanout=dataclasses.replace(config.fanout, parent_params=_list_params(parent_config)),
+ client_config=client_config,
+ path_format_values={},
+ team_id=team_id,
+ job_id=job_id,
+ db_incremental_field_last_value=None,
+ # Page size params differ per endpoint (`limit` vs `take`), so they go in the params below.
+ page_size_param=None,
+ parent_endpoint_extra=_list_endpoint_extra(parent_config),
+ child_endpoint_extra=_list_endpoint_extra(config),
+ child_params_extra=_list_params(config),
+ resume_hook=save_fanout_state,
+ initial_paginator_state=resume.fanout_state if resume is not None else None,
+ ),
+ )
+ return _source_response(config, lambda: dependent, dependent.column_hints)
rest_config: RESTAPIConfig = {
- "client": {
- "base_url": _base_url(host),
- # Auth (the X-N8N-API-KEY header) is supplied via the framework auth config so its
- # value is redacted from logs and raised errors; only the non-secret Accept header here.
- "headers": {"Accept": "application/json"},
- "auth": {"type": "api_key", "api_key": api_key, "name": "X-N8N-API-KEY", "location": "header"},
- # n8n cursor pagination: `nextCursor` in the body, echoed back as the `cursor` query
- # param. A null/absent nextCursor terminates.
- "paginator": JSONResponseCursorPaginator(cursor_path="nextCursor", cursor_param="cursor"),
- # `host` is user-supplied, so pin redirects off so validation and the outbound request
- # stay on the same target (SSRF defense-in-depth).
- "allow_redirects": False,
- },
+ "client": client_config,
"resource_defaults": {},
- "resources": [
- {
- "name": endpoint,
- "endpoint": {
- "path": config.path,
- "params": params,
- "data_selector": "data",
- # `data` is the required envelope field; a 200 body without it means the
- # response shape changed — fail loud instead of silently syncing 0 rows.
- "data_selector_required": True,
- },
- }
- ],
+ "resources": [{"name": endpoint, "endpoint": _list_endpoint(config)}],
}
initial_paginator_state: Optional[dict[str, Any]] = None
- if resumable_source_manager.can_resume():
- resume = resumable_source_manager.load_state()
- if resume is not None and resume.next_cursor is not None:
- initial_paginator_state = {"cursor": resume.next_cursor}
+ if resume is not None and resume.next_cursor is not None:
+ initial_paginator_state = {"cursor": resume.next_cursor}
def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
# Persist only when a next page remains; save AFTER a page is yielded so a crash re-yields
@@ -145,16 +364,24 @@ def n8n_source(
initial_paginator_state=initial_paginator_state,
)
+ return _source_response(config, lambda: resource, resource.column_hints)
+
+
+def _source_response(
+ config: N8nEndpointConfig,
+ items: Callable[[], Iterable[Any]],
+ column_hints: Optional[dict[str, Any]] = None,
+) -> SourceResponse:
return SourceResponse(
- name=endpoint,
- items=lambda: resource,
+ name=config.name,
+ items=items,
primary_keys=list(config.primary_keys),
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,
- column_hints=resource.column_hints,
+ column_hints=column_hints,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/n8n/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/n8n/settings.py
index 296c81d2daa1..92dc21b44285 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/n8n/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/n8n/settings.py
@@ -1,5 +1,12 @@
from dataclasses import dataclass, field
-from typing import Optional
+from typing import Literal, Optional
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ DependentEndpointConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import ResponseAction
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
+from products.warehouse_sources.backend.types import IncrementalField
# n8n's public REST API is served per-instance under this base path.
N8N_API_PATH = "/api/v1"
@@ -8,8 +15,12 @@ N8N_API_PATH = "/api/v1"
# request the max to minimize round trips on large instances.
PAGE_SIZE = 250
+# n8n caps how far back insights reach per license plan and answers 403 beyond that.
+# A backfill tries the longest window first and steps down until the instance accepts one.
+INSIGHTS_BACKFILL_DAYS = (365, 90, 30, 7)
+
-@dataclass
+@dataclass(frozen=True)
class N8nEndpointConfig:
name: str
path: str
@@ -19,6 +30,18 @@ class N8nEndpointConfig:
partition_key: Optional[str] = None
# Extra query params sent on every list request for this endpoint.
extra_params: dict[str, str] = field(default_factory=dict)
+ # Folders page with skip/take and a total `count`; every other list endpoint uses a cursor.
+ paginator: Literal["cursor", "offset"] = "cursor"
+ page_size: int = PAGE_SIZE
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ default_incremental_field: Optional[str] = None
+ # Set on endpoints whose path needs an id from a parent endpoint's rows. A parent that
+ # itself fans out makes a two-level chain.
+ fanout: Optional[DependentEndpointConfig] = None
+
+
+# A parent row deleted between its listing and the child fetch 404s; skip it instead of failing.
+_IGNORE_404: list[ResponseAction] = [{"status_code": 404, "action": "ignore"}]
N8N_ENDPOINTS: dict[str, N8nEndpointConfig] = {
@@ -58,6 +81,77 @@ N8N_ENDPOINTS: dict[str, N8nEndpointConfig] = {
name="projects",
path="/projects",
),
+ "project_users": N8nEndpointConfig(
+ name="project_users",
+ path="/projects/{projectId}/users",
+ primary_keys=["projectId", "id"],
+ partition_key="createdAt",
+ fanout=DependentEndpointConfig(
+ parent_name="projects",
+ resolve_param="projectId",
+ resolve_field="id",
+ include_from_parent=["id"],
+ parent_field_renames={"id": "projectId"},
+ child_response_actions=_IGNORE_404,
+ ),
+ ),
+ # The default sort is updatedAt desc, which shifts offset pages when a folder changes
+ # mid-sync, so sort on the immutable createdAt instead.
+ "folders": N8nEndpointConfig(
+ name="folders",
+ path="/projects/{projectId}/folders",
+ primary_keys=["projectId", "id"],
+ partition_key="createdAt",
+ extra_params={"sortBy": "createdAt:asc"},
+ paginator="offset",
+ fanout=DependentEndpointConfig(
+ parent_name="projects",
+ resolve_param="projectId",
+ resolve_field="id",
+ include_from_parent=["id"],
+ parent_field_renames={"id": "projectId"},
+ child_response_actions=_IGNORE_404,
+ ),
+ ),
+ "test_runs": N8nEndpointConfig(
+ name="test_runs",
+ path="/workflows/{workflowId}/test-runs",
+ primary_keys=["workflowId", "id"],
+ partition_key="createdAt",
+ fanout=DependentEndpointConfig(
+ parent_name="workflows",
+ resolve_param="workflowId",
+ resolve_field="id",
+ include_from_parent=["id"],
+ parent_field_renames={"id": "workflowId"},
+ child_response_actions=_IGNORE_404,
+ ),
+ ),
+ # Test cases carry no createdAt, so they go unpartitioned.
+ "test_cases": N8nEndpointConfig(
+ name="test_cases",
+ path="/workflows/{workflowId}/test-runs/{runId}/test-cases",
+ primary_keys=["testRunId", "id"],
+ fanout=DependentEndpointConfig(
+ parent_name="test_runs",
+ resolve_param="runId",
+ resolve_field="id",
+ include_from_parent=["id", "_workflows_id"],
+ parent_field_renames={"id": "testRunId", "_workflows_id": "workflowId"},
+ child_response_actions=_IGNORE_404,
+ ),
+ ),
+ # The summary endpoint returns one aggregate object for a date range. We request one UTC
+ # day per call so the table holds one row per day, and the startDate/endDate filter makes
+ # incremental syncs fetch only the days since the last run.
+ "insights_summary": N8nEndpointConfig(
+ name="insights_summary",
+ path="/insights/summary",
+ primary_keys=["date"],
+ partition_key="startDate",
+ incremental_fields=[incremental_field("startDate")],
+ default_incremental_field="startDate",
+ ),
}
ENDPOINTS = tuple(N8N_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/n8n/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/n8n/source.py
index ee21a016b5db..bee8811c153d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/n8n/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/n8n/source.py
@@ -55,7 +55,7 @@ class N8nSource(ResumableSource[N8nSourceConfig, N8nResumeConfig], ValidateDatab
Works with n8n Cloud and self-hosted instances. Enter your instance URL (e.g. `https://myorg.app.n8n.cloud`) and an API key created under **Settings > n8n API**.
-Some tables (users, projects, variables) require an owner/admin key or an Enterprise plan; deselect them if your key can't access them.""",
+Some tables (users, projects, project users, folders, variables) require an owner/admin key or an Enterprise plan; deselect them if your key can't access them.""",
iconPath="/static/services/n8n.png",
docsUrl="https://posthog.com/docs/cdp/sources/n8n",
releaseStatus=ReleaseStatus.ALPHA,
@@ -104,14 +104,14 @@ Some tables (users, projects, variables) require an owner/admin key or an Enterp
force_refresh: bool = False,
api_version: str | None = None,
) -> list[SourceSchema]:
- # n8n's public API exposes no server-side timestamp filter, so every table
+ # Only the insights summary takes a server-side date filter; every list endpoint
# is full refresh only.
schemas = [
SourceSchema(
name=endpoint,
- supports_incremental=False,
+ supports_incremental=bool(N8N_ENDPOINTS[endpoint].incremental_fields),
supports_append=False,
- incremental_fields=[],
+ incremental_fields=list(N8N_ENDPOINTS[endpoint].incremental_fields),
detected_primary_keys=list(N8N_ENDPOINTS[endpoint].primary_keys),
)
for endpoint in ENDPOINTS
@@ -161,5 +161,7 @@ Some tables (users, projects, variables) require an owner/admin key or an Enterp
team_id=inputs.team_id,
job_id=inputs.job_id,
resumable_source_manager=resumable_source_manager,
- db_incremental_field_last_value=None, # every n8n endpoint is full refresh
+ 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/n8n/tests/test_n8n.py b/products/warehouse_sources/backend/temporal/data_imports/sources/n8n/tests/test_n8n.py
index a0c4f8b4bc11..f3488d8fec61 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/n8n/tests/test_n8n.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/n8n/tests/test_n8n.py
@@ -1,10 +1,13 @@
import json
from typing import Any
+from urllib.parse import parse_qs, urlparse
import pytest
+import time_machine
from unittest import mock
-from requests import Response
+from parameterized import parameterized
+from requests import HTTPError, Response
from products.warehouse_sources.backend.temporal.data_imports.sources.n8n.n8n import (
N8nResumeConfig,
@@ -31,6 +34,15 @@ def _response(
return resp
+def _json_response(body: dict[str, Any], status_code: int = 200) -> Response:
+ resp = Response()
+ resp.status_code = status_code
+ resp.reason = "Forbidden" if status_code == 403 else "OK"
+ resp.url = "https://n.example.com/api/v1/insights/summary"
+ resp._content = json.dumps(body).encode()
+ return resp
+
+
def _make_manager(resume_state: N8nResumeConfig | None = None) -> mock.MagicMock:
manager = mock.MagicMock()
manager.can_resume.return_value = resume_state is not None
@@ -38,7 +50,7 @@ def _make_manager(resume_state: N8nResumeConfig | None = None) -> mock.MagicMock
return manager
-def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:
+def _wire(session: mock.MagicMock, responses: list[Response], urls: list[str] | None = None) -> list[dict[str, Any]]:
"""Wire a mock session and return a list that captures each request's params AT SEND TIME.
``request.params`` is a single dict mutated in place across pages, so inspecting it after the run
@@ -49,6 +61,8 @@ def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str,
def _prepare(request: Any) -> mock.MagicMock:
param_snapshots.append(dict(request.params or {}))
+ if urls is not None:
+ urls.append(request.url)
return mock.MagicMock()
session.prepare_request.side_effect = _prepare
@@ -175,3 +189,106 @@ class TestGetRows:
# A 200 body without "data" means the response shape changed — fail loud, not silently 0 rows.
with pytest.raises(ValueError, match="matched nothing"):
_rows(_source("workflows", _make_manager()))
+
+
+class TestFanOut:
+ @parameterized.expand(
+ [
+ (
+ "project_users",
+ _response([{"id": "u1", "email": "[email protected]"}], next_cursor=None),
+ "/projects/p1/users",
+ {"limit": 250},
+ ),
+ (
+ "folders",
+ _json_response({"count": 1, "data": [{"id": "f1", "name": "Ops"}]}),
+ "/projects/p1/folders",
+ {"sortBy": "createdAt:asc", "skip": 0, "take": 250},
+ ),
+ ]
+ )
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_project_children_carry_project_id(self, endpoint, child_response, child_path, child_params, MockSession):
+ session = MockSession.return_value
+ urls: list[str] = []
+ params = _wire(session, [_response([{"id": "p1", "name": "Team"}], next_cursor=None), child_response], urls)
+
+ rows = _rows(_source(endpoint, _make_manager()))
+
+ assert [row["projectId"] for row in rows] == ["p1"]
+ assert urls[1].endswith(child_path)
+ assert params[1] == child_params
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_test_cases_bind_workflow_and_run_ids(self, MockSession):
+ session = MockSession.return_value
+ urls: list[str] = []
+ _wire(
+ session,
+ [
+ _response([{"id": "w1"}], next_cursor=None),
+ _response([{"id": "r1", "status": "completed"}], next_cursor=None),
+ _response([{"id": "c1", "status": "success"}], next_cursor=None),
+ ],
+ urls,
+ )
+
+ rows = _rows(_source("test_cases", _make_manager()))
+
+ assert urls[2].endswith("/workflows/w1/test-runs/r1/test-cases")
+ assert [(row["workflowId"], row["testRunId"], row["id"]) for row in rows] == [("w1", "r1", "c1")]
+
+
+def _summary(total: int) -> dict[str, Any]:
+ return {"total": {"value": total, "deviation": None, "unit": "count"}}
+
+
+class TestInsightsSummary:
+ @parameterized.expand(
+ [
+ # The 3-day backfill exceeds the license, so the walk steps down to the 1-day one.
+ ("backfill_steps_down_past_license_limit", None, None, ["2026-10-09", "2026-10-11", "2026-10-12"]),
+ ("incremental_refetches_watermark_day", "2026-10-11T00:00:00Z", None, ["2026-10-11", "2026-10-12"]),
+ ("resume_starts_at_saved_day", None, "2026-10-12", ["2026-10-12"]),
+ ]
+ )
+ @time_machine.travel("2026-10-12T15:00:00Z", tick=False)
+ @mock.patch(f"{_MODULE}.INSIGHTS_BACKFILL_DAYS", (3, 1))
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_walks_one_day_per_request_up_to_today(self, _name, last_value, resume_date, requested_days, mock_session):
+ responses = [_json_response(_summary(day)) for day in range(len(requested_days))]
+ if requested_days[0] == "2026-10-09":
+ responses[0] = _json_response({"message": "license"}, status_code=403)
+ mock_session.return_value.get.side_effect = responses
+ manager = _make_manager(N8nResumeConfig(next_date=resume_date) if resume_date else None)
+
+ rows = _rows(
+ n8n_source(
+ "https://n.example.com",
+ "key",
+ "insights_summary",
+ team_id=1,
+ job_id="j",
+ resumable_source_manager=manager,
+ db_incremental_field_last_value=last_value,
+ )
+ )
+
+ urls = [call.args[0] for call in mock_session.return_value.get.call_args_list]
+ assert [parse_qs(urlparse(url).query)["startDate"][0][:10] for url in urls] == requested_days
+ synced_days = [day for day in requested_days if day != "2026-10-09"]
+ assert [row["date"] for row in rows] == synced_days
+ assert rows[-1]["endDate"] == "2026-10-13T00:00:00.000Z"
+ # Every day but today stages the next day before its row is yielded.
+ saved = [call.args[0].next_date for call in manager.save_state.call_args_list]
+ assert saved == synced_days[1:]
+
+ @time_machine.travel("2026-10-12T15:00:00Z", tick=False)
+ @mock.patch(f"{_MODULE}.INSIGHTS_BACKFILL_DAYS", (3, 1))
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_refused_at_every_window_raises_forbidden(self, mock_session):
+ mock_session.return_value.get.side_effect = [_json_response({}, status_code=403)] * 2
+
+ with pytest.raises(HTTPError, match="403 Client Error: Forbidden for url"):
+ _rows(_source("insights_summary", _make_manager()))