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 kernel import source (#69997)

Tom Owersb3db0b99938d
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 115fa87f8252..cff21f805d4a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -236,6 +236,7 @@ the row lists both.
| justsift | HTTP | requests | ✅ |
| k6_cloud | HTTP | requests | ✅ |
| katana | HTTP | requests | ✅ |
+| kernel | HTTP | requests | ✅ |
| klaviyo | HTTP | requests | ✅ |
| lago | HTTP | requests | ✅ |
| launchdarkly | HTTP | requests | ✅ |
@@ -627,7 +628,6 @@ doesn't conflict with concurrent PRs.
- kafka
- kapa_ai
- keka
-- kernel
- kickscale
- kisi
- kissmetrics
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 7aad3dc86ebd..6ad99a4d8a58 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
@@ -1981,7 +1981,7 @@ class KekaSourceConfig(config.Config):
@config.config
class KernelSourceConfig(config.Config):
- pass
+ api_key: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kernel/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kernel/canonical_descriptions.py
new file mode 100644
index 000000000000..d01009ccfd62
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kernel/canonical_descriptions.py
@@ -0,0 +1,46 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Table-level descriptions are sourced from Kernel's public API docs. Column coverage is kept to the
+# fields we're confident about (ids); the rest fall back to LLM enrichment, since the full column set
+# was not verified against a live API for this alpha release.
+_DOCS_URL = "https://docs.onkernel.com"
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "apps": {
+ "description": "A deployed browser-automation app registered in your Kernel organization.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Unique identifier for the app.",
+ },
+ },
+ "deployments": {
+ "description": "A deployment of a Kernel app, including its status and region.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Unique identifier for the deployment.",
+ },
+ },
+ "invocations": {
+ "description": "A single action run, including its status, input payload, output, and start/finish timestamps.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Unique identifier for the invocation.",
+ },
+ },
+ "browsers": {
+ "description": "A cloud browser session run on Kernel infrastructure. Includes active and soft-deleted sessions.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Unique identifier for the browser session.",
+ },
+ },
+ "profiles": {
+ "description": "A saved browser profile persisting cookies, storage, and authentication state across sessions.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Unique identifier for the profile.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kernel/kernel.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kernel/kernel.py
new file mode 100644
index 000000000000..2be07f52b250
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kernel/kernel.py
@@ -0,0 +1,211 @@
+from collections.abc import Iterator
+from typing import Any
+from urllib.parse import urlencode
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.batcher import Batcher
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.kernel.settings import (
+ KERNEL_ENDPOINTS,
+ SENSITIVE_FIELDS,
+ KernelEndpointConfig,
+)
+
+KERNEL_BASE_URL = "https://api.onkernel.com"
+
+# Kernel caps list page size at 100 (1-100, default 20).
+PAGE_SIZE = 100
+
+
+class KernelRetryableError(Exception):
+ pass
+
+
+class KernelUnexpectedResponseError(Exception):
+ """Raised when a list response is neither a JSON array nor a recognized wrapped shape.
+
+ Every endpoint is a full refresh, so a body we can't parse must fail loudly: treating it
+ as an empty page would let the sync "succeed" with zero rows and overwrite the existing
+ warehouse table with nothing.
+ """
+
+ pass
+
+
+def _get_headers(api_key: str) -> dict[str, str]:
+ return {
+ "Authorization": f"Bearer {api_key}",
+ "Accept": "application/json",
+ }
+
+
+def _build_url(path: str, params: dict[str, Any]) -> str:
+ query = urlencode(params)
+ return f"{KERNEL_BASE_URL}{path}?{query}" if query else f"{KERNEL_BASE_URL}{path}"
+
+
+def _extract_items(body: Any) -> list[dict[str, Any]]:
+ """Pull the row list out of a Kernel list response.
+
+ Kernel signals pagination through headers (X-Has-More / X-Next-Offset), so the body is
+ expected to be a bare JSON array. We defensively also accept the common wrapped shapes
+ ({"data": [...]} etc.) since this has not been verified against a live API. An empty array
+ (or empty wrapped list) is a legitimate "no more rows" signal. Any other shape is
+ unexpected, and we raise rather than return [] - a silent empty result would let a full
+ refresh overwrite the table with zero rows.
+ """
+ if isinstance(body, list):
+ return body
+ if isinstance(body, dict):
+ for key in ("data", "items", "results", "records"):
+ value = body.get(key)
+ if isinstance(value, list):
+ return value
+ raise KernelUnexpectedResponseError(f"Unexpected Kernel list response shape: {type(body).__name__}")
+
+
+def _redact_sensitive_fields(item: Any) -> Any:
+ """Drop credential-bearing fields (see SENSITIVE_FIELDS) before a row is batched.
+
+ Kernel objects are written to the warehouse verbatim, so env vars and token-bearing
+ live-view / CDP URLs would otherwise be queryable by any project user. `item` is untyped
+ JSON, so non-dict rows pass through untouched.
+ """
+ if not isinstance(item, dict):
+ return item
+ return {key: value for key, value in item.items() if key.lower() not in SENSITIVE_FIELDS}
+
+
+def _next_page(headers: Any, current_offset: int, page_len: int) -> tuple[bool, int]:
+ """Return (has_more, next_offset) from the response headers, falling back to offset math."""
+ has_more_header = str(headers.get("X-Has-More", "")).strip().lower()
+ if has_more_header in ("true", "false"):
+ has_more = has_more_header == "true"
+ else:
+ # No header: assume more pages only while a full page came back.
+ has_more = page_len >= PAGE_SIZE
+
+ next_offset_header = headers.get("X-Next-Offset")
+ if next_offset_header is not None:
+ try:
+ return has_more, int(next_offset_header)
+ except (TypeError, ValueError):
+ pass
+ return has_more, current_offset + page_len
+
+
+@retry(
+ retry=retry_if_exception_type(
+ (
+ KernelRetryableError,
+ requests.ReadTimeout,
+ requests.ConnectionError,
+ requests.exceptions.ChunkedEncodingError,
+ )
+ ),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch_page(
+ session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger
+) -> requests.Response:
+ response = session.get(url, headers=headers, timeout=60)
+
+ # Kernel returns 429 with a Retry-After per-organization rate limit; honor it via retry backoff.
+ if response.status_code == 429 or response.status_code >= 500:
+ raise KernelRetryableError(f"Kernel API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"Kernel API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response
+
+
+def validate_credentials(api_key: str) -> tuple[bool, int | None]:
+ """Probe a cheap list endpoint. Returns (ok, status_code); status is None on transport failure."""
+ url = _build_url("/apps", {"limit": 1})
+ try:
+ # capture=False: Kernel responses carry secret-bearing fields (see SENSITIVE_FIELDS)
+ # that the generic HTTP-sample scrubber does not know to redact.
+ response = make_tracked_session(capture=False).get(url, headers=_get_headers(api_key), timeout=10)
+ except Exception:
+ return False, None
+ return response.status_code == 200, response.status_code
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+) -> Iterator[Any]:
+ config = KERNEL_ENDPOINTS[endpoint]
+ headers = _get_headers(api_key)
+ batcher = Batcher(logger=logger, chunk_size=2000, chunk_size_bytes=100 * 1024 * 1024)
+ # One session reused across every page so urllib3 keeps the connection alive.
+ # capture=False: Kernel responses carry secret-bearing fields (see SENSITIVE_FIELDS) that the
+ # generic HTTP-sample scrubber does not know to redact, and sampling happens before redaction.
+ session = make_tracked_session(capture=False)
+
+ # Full refresh only: no resumable offset state. A crashed sync restarts from offset 0 and
+ # the pipeline overwrites the table on the first chunk, so re-fetched pages never duplicate
+ # rows (full-refresh appends have no primary-key dedupe, so resuming mid-table would).
+ offset = 0
+ while True:
+ params: dict[str, Any] = {"limit": PAGE_SIZE, "offset": offset, **config.extra_params}
+ url = _build_url(config.path, params)
+ response = _fetch_page(session, url, headers, logger)
+ items = _extract_items(response.json())
+
+ has_more, next_offset = _next_page(response.headers, offset, len(items))
+
+ if not items:
+ # An empty page doesn't necessarily mean the end - the API may signal more pages
+ # via X-Has-More. Keep going, but stop if the offset can't advance (an empty page
+ # with no X-Next-Offset would otherwise loop forever on the same request).
+ if not has_more or next_offset <= offset:
+ break
+ offset = next_offset
+ continue
+
+ for item in items:
+ batcher.batch(_redact_sensitive_fields(item))
+
+ if batcher.should_yield():
+ yield batcher.get_table()
+
+ if not has_more:
+ break
+
+ offset = next_offset
+
+ if batcher.should_yield(include_incomplete_chunk=True):
+ yield batcher.get_table()
+
+
+def kernel_source(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+) -> SourceResponse:
+ endpoint_config: KernelEndpointConfig = KERNEL_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ endpoint=endpoint,
+ logger=logger,
+ ),
+ primary_keys=endpoint_config.primary_keys,
+ # Full refresh for every endpoint (see settings.py) - no incremental watermark to order,
+ # so the default ascending sort_mode is fine. Partitioning is left to the pipeline's
+ # auto-detection (falls back to created_at when present); revisit once the live schema is
+ # confirmed and a stable partition key per endpoint can be verified.
+ sort_mode="asc",
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kernel/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kernel/settings.py
new file mode 100644
index 000000000000..c78a02b56f5a
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kernel/settings.py
@@ -0,0 +1,67 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+
+@dataclass
+class KernelEndpointConfig:
+ name: str
+ path: str
+ # Kernel object ids are globally unique per resource, so `id` is the natural key.
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ # Extra query params merged into every request (e.g. browsers needs status=all to
+ # include soft-deleted sessions - the list defaults to status=active otherwise).
+ extra_params: dict[str, str] = field(default_factory=dict)
+ should_sync_default: bool = True
+ description: Optional[str] = None
+
+
+# All Kernel list endpoints share offset pagination (limit/offset query params, X-Has-More /
+# X-Next-Offset response headers). None of these are synced incrementally: Kernel documents a
+# `since` filter on /invocations, but it could not be verified against a live API for this alpha
+# release (server-side filtering and response ordering both need a smoke test before the pipeline
+# can trust a watermark), so every table ships as a full refresh. See kernel.py for the follow-up note.
+KERNEL_ENDPOINTS: dict[str, KernelEndpointConfig] = {
+ "apps": KernelEndpointConfig(
+ name="apps",
+ path="/apps",
+ description="Deployed browser-automation apps registered in your Kernel organization.",
+ ),
+ "deployments": KernelEndpointConfig(
+ name="deployments",
+ path="/deployments",
+ description="Deployment history for your apps, including status and region.",
+ ),
+ "invocations": KernelEndpointConfig(
+ name="invocations",
+ path="/invocations",
+ description="Action run history: status, payload, output, and start/finish timestamps.",
+ ),
+ "browsers": KernelEndpointConfig(
+ name="browsers",
+ path="/browsers",
+ # /browsers defaults to status=active; status=all also returns soft-deleted sessions.
+ extra_params={"status": "all"},
+ description="Cloud browser sessions, including active and soft-deleted sessions.",
+ ),
+ "profiles": KernelEndpointConfig(
+ name="profiles",
+ path="/profiles",
+ description="Saved browser profiles (persisted cookies, storage, and auth state).",
+ ),
+}
+
+ENDPOINTS = tuple(KERNEL_ENDPOINTS.keys())
+
+# Credential-bearing fields stripped from every Kernel row before it lands in the warehouse.
+# Kernel app/deployment objects carry `env_vars`; browser objects expose CDP / live-view URLs
+# that embed short-lived access tokens. Importing them verbatim would let anyone who can query
+# the synced table recover deployment secrets or attach to a live browser session. Matched
+# case-insensitively against top-level keys (values here must be lowercase).
+SENSITIVE_FIELDS: frozenset[str] = frozenset(
+ {
+ "env_vars",
+ "cdp_ws_url",
+ "webdriver_ws_url",
+ "browser_live_view_url",
+ }
+)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kernel/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kernel/source.py
index b03b94356885..63b509742c5c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/kernel/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kernel/source.py
@@ -1,19 +1,37 @@
-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.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+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.schema import SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import KernelSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.kernel.kernel import (
+ kernel_source,
+ validate_credentials as validate_kernel_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.kernel.settings import ENDPOINTS, KERNEL_ENDPOINTS
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
class KernelSource(SimpleSource[KernelSourceConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog - safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.KERNEL
@@ -24,8 +42,86 @@ class KernelSource(SimpleSource[KernelSourceConfig]):
name=SchemaExternalDataSourceType.KERNEL,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="Kernel",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your Kernel API key to sync your Kernel browser-infrastructure data into the PostHog Data warehouse.
+
+You can create an API key in your [Kernel dashboard](https://dashboard.onkernel.com) under API keys. Kernel keys are long-lived and grant organization-wide read access.""",
iconPath="/static/services/kernel.png",
+ docsUrl="https://posthog.com/docs/cdp/sources/kernel",
keywords=["browser", "automation", "agents", "infrastructure"],
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="sk_...",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.kernel.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.onkernel.com": "Your Kernel API key is invalid or has been revoked. Create a new key in your Kernel dashboard, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.onkernel.com": "Your Kernel API key does not have access to this data. Check the key's permissions in your Kernel dashboard, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: KernelSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ def _build_schema(endpoint: str) -> SourceSchema:
+ endpoint_config = KERNEL_ENDPOINTS[endpoint]
+ return SourceSchema(
+ name=endpoint,
+ # Full refresh only - Kernel's server-side time filters are unverified for this
+ # alpha release, so no incremental/append sync mode is offered yet.
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=[],
+ should_sync_default=endpoint_config.should_sync_default,
+ description=endpoint_config.description,
+ )
+
+ 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: KernelSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ ok, status = validate_kernel_credentials(config.api_key)
+ if ok:
+ return True, None
+
+ # A valid token that lacks scope for one endpoint must not block source creation - the user
+ # may only intend to sync the tables they can reach. Only reject 403 when probing a specific
+ # schema; sync-time 403s are handled by get_non_retryable_errors().
+ if status == 403 and schema_name is None:
+ return True, None
+
+ return False, "Invalid Kernel API key"
+
+ def source_for_pipeline(self, config: KernelSourceConfig, inputs: SourceInputs) -> SourceResponse:
+ return kernel_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kernel/tests/test_kernel.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kernel/tests/test_kernel.py
new file mode 100644
index 000000000000..c372b5405c34
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kernel/tests/test_kernel.py
@@ -0,0 +1,243 @@
+from typing import Any
+
+import pytest
+from unittest import mock
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.kernel.kernel import (
+ PAGE_SIZE,
+ KernelRetryableError,
+ KernelUnexpectedResponseError,
+ _extract_items,
+ _next_page,
+ _redact_sensitive_fields,
+ get_rows,
+ kernel_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.kernel.settings import ENDPOINTS, KERNEL_ENDPOINTS
+
+_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.kernel.kernel"
+
+
+def _response(
+ items: Any, *, status_code: int = 200, has_more: bool | None = None, next_offset: int | None = None
+) -> mock.MagicMock:
+ resp = mock.MagicMock()
+ resp.json.return_value = items
+ resp.status_code = status_code
+ resp.ok = 200 <= status_code < 400
+ resp.text = "error"
+ headers: dict[str, str] = {}
+ if has_more is not None:
+ headers["X-Has-More"] = "true" if has_more else "false"
+ if next_offset is not None:
+ headers["X-Next-Offset"] = str(next_offset)
+ resp.headers = headers
+ return resp
+
+
+class TestExtractItems:
+ @pytest.mark.parametrize(
+ "body, expected",
+ [
+ ([{"id": "a"}], [{"id": "a"}]),
+ ([], []),
+ ({"data": [{"id": "b"}]}, [{"id": "b"}]),
+ ({"items": [{"id": "c"}]}, [{"id": "c"}]),
+ ({"results": [{"id": "d"}]}, [{"id": "d"}]),
+ ({"data": []}, []),
+ ],
+ )
+ def test_recognized_shapes(self, body: Any, expected: list[dict]) -> None:
+ assert _extract_items(body) == expected
+
+ @pytest.mark.parametrize("body", [{"unexpected": [{"id": "e"}]}, {}, None, "oops", 42])
+ def test_unexpected_shape_raises(self, body: Any) -> None:
+ # A body we can't parse must fail loudly - returning [] would let a full refresh
+ # overwrite the table with zero rows.
+ with pytest.raises(KernelUnexpectedResponseError):
+ _extract_items(body)
+
+
+class TestRedactSensitiveFields:
+ def test_strips_credential_bearing_keys_case_insensitively(self) -> None:
+ item = {
+ "id": "b1",
+ "env_vars": {"SECRET": "x"},
+ "CDP_WS_URL": "wss://token@example",
+ "webdriver_ws_url": "wss://jwt@example",
+ "browser_live_view_url": "https://token@example",
+ "region": "us",
+ }
+ assert _redact_sensitive_fields(item) == {"id": "b1", "region": "us"}
+
+
+class TestNextPage:
+ @pytest.mark.parametrize(
+ "headers, page_len, expected",
+ [
+ # Header wins over offset math.
+ ({"X-Has-More": "true", "X-Next-Offset": "300"}, 100, (True, 300)),
+ ({"X-Has-More": "false"}, 100, (False, 100)),
+ # No header: keep paging only while a full page came back.
+ ({}, PAGE_SIZE, (True, PAGE_SIZE)),
+ ({}, 5, (False, 5)),
+ # Malformed next-offset falls back to offset + page_len.
+ ({"X-Has-More": "true", "X-Next-Offset": "not-a-number"}, 100, (True, 100)),
+ ],
+ )
+ def test_next_page(self, headers: dict[str, str], page_len: int, expected: tuple[bool, int]) -> None:
+ assert _next_page(headers, current_offset=0, page_len=page_len) == expected
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ "status_code, expected_ok",
+ [(200, True), (401, False), (403, False), (500, False)],
+ )
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_status_mapping(self, mock_session: Any, status_code: int, expected_ok: bool) -> None:
+ response = mock.MagicMock()
+ response.status_code = status_code
+ mock_session.return_value.get.return_value = response
+
+ ok, status = validate_credentials("sk_test")
+ assert ok is expected_ok
+ assert status == status_code
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_sends_bearer_auth(self, mock_session: Any) -> None:
+ response = mock.MagicMock()
+ response.status_code = 200
+ mock_session.return_value.get.return_value = response
+
+ validate_credentials("sk_test")
+
+ headers = mock_session.return_value.get.call_args.kwargs["headers"]
+ assert headers["Authorization"] == "Bearer sk_test"
+ # Kernel responses carry secrets the generic sampler can't scrub, so capture must be off.
+ assert mock_session.call_args.kwargs["capture"] is False
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_transport_failure_returns_none_status(self, mock_session: Any) -> None:
+ mock_session.return_value.get.side_effect = Exception("boom")
+ assert validate_credentials("sk_test") == (False, None)
+
+
+class TestGetRows:
+ def _collect(self, endpoint: str) -> list[dict]:
+ rows: list[dict] = []
+ for table in get_rows("sk_test", endpoint, mock.MagicMock()):
+ rows.extend(table.to_pylist())
+ return rows
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_single_page_full_refresh(self, mock_session: Any) -> None:
+ mock_session.return_value.get.return_value = _response([{"id": "a1"}, {"id": "a2"}], has_more=False)
+
+ rows = self._collect("apps")
+
+ assert rows == [{"id": "a1"}, {"id": "a2"}]
+ assert mock_session.return_value.get.call_count == 1
+ # Kernel responses carry secrets the generic sampler can't scrub, so capture must be off.
+ assert mock_session.call_args.kwargs["capture"] is False
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_offset_pagination_follows_next_offset_header(self, mock_session: Any) -> None:
+ mock_session.return_value.get.side_effect = [
+ _response([{"id": "a1"}], has_more=True, next_offset=100),
+ _response([{"id": "a2"}], has_more=False),
+ ]
+
+ rows = self._collect("deployments")
+
+ assert rows == [{"id": "a1"}, {"id": "a2"}]
+ urls = [call.kwargs.get("url") or call.args[0] for call in mock_session.return_value.get.call_args_list]
+ assert "offset=0" in urls[0]
+ assert "offset=100" in urls[1]
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_empty_first_page_yields_nothing(self, mock_session: Any) -> None:
+ mock_session.return_value.get.return_value = _response([], has_more=False)
+ assert self._collect("profiles") == []
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_empty_page_with_more_pages_keeps_paging(self, mock_session: Any) -> None:
+ # An empty page that still reports X-Has-More must not end the sync early.
+ mock_session.return_value.get.side_effect = [
+ _response([], has_more=True, next_offset=100),
+ _response([{"id": "a1"}], has_more=False),
+ ]
+ assert self._collect("apps") == [{"id": "a1"}]
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_empty_page_without_advancing_offset_terminates(self, mock_session: Any) -> None:
+ # Empty page claiming more pages but with no way to advance the offset must stop,
+ # not loop forever re-fetching the same request.
+ mock_session.return_value.get.return_value = _response([], has_more=True)
+ assert self._collect("apps") == []
+ assert mock_session.return_value.get.call_count == 1
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_browsers_requests_all_statuses(self, mock_session: Any) -> None:
+ mock_session.return_value.get.return_value = _response([{"id": "b1"}], has_more=False)
+
+ self._collect("browsers")
+
+ url = mock_session.return_value.get.call_args.args[0]
+ assert "status=all" in url
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_sensitive_fields_are_stripped_from_rows(self, mock_session: Any) -> None:
+ mock_session.return_value.get.return_value = _response(
+ [{"id": "b1", "browser_live_view_url": "https://token@example", "region": "us"}], has_more=False
+ )
+
+ rows = self._collect("browsers")
+
+ assert rows == [{"id": "b1", "region": "us"}]
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_unexpected_response_shape_raises(self, mock_session: Any) -> None:
+ mock_session.return_value.get.return_value = _response({"unexpected": [{"id": "a1"}]}, has_more=False)
+
+ with pytest.raises(KernelUnexpectedResponseError):
+ self._collect("apps")
+
+ @mock.patch("time.sleep")
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_retries_retryable_status_then_succeeds(self, mock_session: Any, _sleep: Any) -> None:
+ mock_session.return_value.get.side_effect = [
+ _response(None, status_code=500),
+ _response(None, status_code=429),
+ _response([{"id": "a1"}], has_more=False),
+ ]
+
+ rows = self._collect("apps")
+
+ assert rows == [{"id": "a1"}]
+ assert mock_session.return_value.get.call_count == 3
+
+ @mock.patch("time.sleep")
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_retries_exhausted_raises(self, mock_session: Any, _sleep: Any) -> None:
+ mock_session.return_value.get.return_value = _response(None, status_code=503)
+
+ with pytest.raises(KernelRetryableError):
+ self._collect("apps")
+
+ assert mock_session.return_value.get.call_count == 5
+
+
+class TestKernelSourceResponse:
+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
+ def test_response_metadata_per_endpoint(self, endpoint: str) -> None:
+ config = KERNEL_ENDPOINTS[endpoint]
+ response = kernel_source("sk_test", endpoint, mock.MagicMock())
+
+ assert response.name == endpoint
+ assert response.primary_keys == config.primary_keys
+ assert response.sort_mode == "asc"
+ # Partitioning is left to the pipeline's auto-detection for this alpha release.
+ assert response.partition_mode is None
+ assert response.partition_keys is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kernel/tests/test_kernel_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kernel/tests/test_kernel_source.py
new file mode 100644
index 000000000000..84c4dd54f3aa
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kernel/tests/test_kernel_source.py
@@ -0,0 +1,131 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import KernelSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.kernel.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.kernel.source import KernelSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+_SOURCE_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.kernel.source"
+
+
+class TestKernelSource:
+ def setup_method(self) -> None:
+ self.source = KernelSource()
+ self.team_id = 123
+ self.config = KernelSourceConfig(api_key="sk_test")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.KERNEL
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+
+ assert config.name.value == "Kernel"
+ assert config.label == "Kernel"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/kernel"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["api_key"]
+
+ def test_generated_config_parses_api_key(self) -> None:
+ # Guards the hand-checked generated_configs.py edit: the form field must map to `api_key`.
+ config = KernelSourceConfig.from_dict({"api_key": "sk_123"})
+ assert config.api_key == "sk_123"
+
+ def test_api_key_field_is_secret_password(self) -> None:
+ config = self.source.get_source_config
+ api_key_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")
+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD
+ assert api_key_field.secret is True
+ assert api_key_field.required is True
+
+ def test_lists_tables_without_credentials(self) -> None:
+ # get_schemas is a static endpoint catalog, so the public docs can render the table list.
+ assert self.source.lists_tables_without_credentials is True
+ documented = {t["name"] for t in self.source.get_documented_tables()}
+ assert documented == set(ENDPOINTS)
+
+ def test_canonical_descriptions_cover_every_endpoint(self) -> None:
+ descriptions = self.source.get_canonical_descriptions()
+ assert set(descriptions.keys()) == set(ENDPOINTS)
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.onkernel.com/apps?limit=1",
+ "403 Client Error: Forbidden for url: https://api.onkernel.com/invocations?limit=100&offset=0",
+ ],
+ )
+ def test_non_retryable_errors_match_auth_failures(self, observed_error: str) -> None:
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable_errors)
+
+ @pytest.mark.parametrize(
+ "other_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers",
+ "500 Server Error for url: https://api.onkernel.com/apps",
+ ],
+ )
+ def test_non_retryable_errors_ignore_unrelated(self, other_error: str) -> None:
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert not any(key in other_error for key in non_retryable_errors)
+
+ def test_get_schemas_are_full_refresh_only(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+
+ assert {schema.name for schema in schemas} == set(ENDPOINTS)
+ assert all(not schema.supports_incremental for schema in schemas)
+ assert all(not schema.supports_append for schema in schemas)
+ assert all(schema.incremental_fields == [] for schema in schemas)
+
+ def test_get_schemas_filtered_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["invocations"])
+ assert [s.name for s in schemas] == ["invocations"]
+
+ def test_get_schemas_unknown_name_returns_empty(self) -> None:
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ @pytest.mark.parametrize(
+ "probe_result, schema_name, expected_valid",
+ [
+ # Valid token.
+ ((True, 200), None, True),
+ # Bad token is always rejected.
+ ((False, 401), None, False),
+ # A 403 at source-create means valid token / missing scope - do not block creation.
+ ((False, 403), None, True),
+ # A 403 while probing a specific schema is a real scope failure for that table.
+ ((False, 403), "invocations", False),
+ ((False, None), None, False),
+ ],
+ )
+ @mock.patch(f"{_SOURCE_MODULE}.validate_kernel_credentials")
+ def test_validate_credentials(
+ self,
+ mock_validate: mock.MagicMock,
+ probe_result: tuple[bool, int | None],
+ schema_name: str | None,
+ expected_valid: bool,
+ ) -> None:
+ mock_validate.return_value = probe_result
+
+ is_valid, _error = self.source.validate_credentials(self.config, self.team_id, schema_name=schema_name)
+
+ assert is_valid is expected_valid
+ mock_validate.assert_called_once_with("sk_test")
+
+ @mock.patch(f"{_SOURCE_MODULE}.kernel_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_kernel_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "invocations"
+
+ self.source.source_for_pipeline(self.config, inputs)
+
+ kwargs = mock_kernel_source.call_args.kwargs
+ assert kwargs["api_key"] == "sk_test"
+ assert kwargs["endpoint"] == "invocations"