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(warehouse-sources): add kernel audit log, proxy, pool and project tables (#113318)

Tom Owerse6ddd6aeca08
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 53fa5296f408..e252b5cad9c7 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
@@ -4759,13 +4759,13 @@ Today (5): `apps`, `browsers`, `deployments`, `invocations`, `profiles`
Diffed against: <https://docs.onkernel.com/llms.txt>
-- [ ] `audit-logs (list audit logs)` — organization-wide event history — the only cross-resource activity log the API offers (high)
-- [ ] `browser-pools (list browser pools)` — lookup resolving the pool a browser session was leased from; also carries pool sizing config for utilization analysis (medium)
-- [ ] `projects (list projects)` — lookup resolving the project ID carried on apps, deployments, browsers, proxies and extensions (medium)
+- [x] `audit-logs (list audit logs)` — organization-wide event history — the only cross-resource activity log the API offers (high)
+- [x] `browser-pools (list browser pools)` — lookup resolving the pool a browser session was leased from; also carries pool sizing config for utilization analysis (medium)
+- [x] `projects (list projects)` — lookup resolving the project ID carried on apps, deployments, browsers, proxies and extensions (medium)
- [ ] `browser-replays (list browser session replays)` — replay records per browser session, linking runs to recorded evidence (medium)
- [ ] `managed-auth (list auth connections)` — auth connection inventory with health state, joinable to profiles we already sync (medium)
- [ ] `managed-auth (get auth connection event timeline)` — chronological login/re-auth/health-check events per connection — state transition history (medium)
-- [ ] `proxies (list proxies)` — lookup resolving proxy IDs referenced by browser sessions (medium)
+- [x] `proxies (list proxies)` — lookup resolving proxy IDs referenced by browser sessions (medium)
- [ ] `invocations/{id}/browsers` — join table mapping invocations to the browser sessions they created (low)
- [ ] `extensions (list browser extensions)` — extension inventory per project (low)
- [x] `browsers/{id_or_name}/telemetry/events` — archived per-session telemetry events (console, network, page, interaction) within the 30-day retention window (medium)
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
index 43bd1e03bdca..33b6dc1def8a 100644
--- 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
@@ -57,4 +57,64 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"truncated": "True if the data field was truncated due to size limits.",
},
},
+ "browser_pools": {
+ "description": "A pool of identically configured, pre-warmed browsers that sessions are acquired from and released back to.",
+ "docs_url": "https://kernel.sh/docs/api-reference/browser-pools/list-browser-pools",
+ "columns": {
+ "id": "Unique identifier for the browser pool.",
+ "name": "Browser pool name, if set.",
+ "region": "Geographic region of the browser pool. Fixed once the pool is created.",
+ "acquired_count": "Number of browsers currently acquired from the pool.",
+ "available_count": "Number of browsers currently available in the pool.",
+ "browser_pool_config": "Configuration used to create all browsers in this pool, including its size.",
+ "profile_id": "Resolved profile ID the pool is attached to. Omitted when no profile is attached.",
+ "extension_ids": "Resolved extension IDs attached to the pool, in configured load order.",
+ "created_at": "Timestamp when the browser pool was created.",
+ },
+ },
+ "proxies": {
+ "description": "A proxy configuration for routing browser traffic, with its latest health check result.",
+ "docs_url": "https://kernel.sh/docs/api-reference/proxies/list-proxies",
+ "columns": {
+ "id": "Unique identifier for the proxy.",
+ "name": "Readable name of the proxy.",
+ "type": "Proxy type: datacenter, isp, residential, mobile, or custom.",
+ "protocol": "Protocol to use for the proxy connection.",
+ "status": "Current health status of the proxy.",
+ "ip_address": "IP address that the proxy uses when making requests.",
+ "last_checked": "Timestamp of the last health check performed on this proxy.",
+ "config": "Configuration specific to the proxy type, such as target country or custom host and port.",
+ "bypass_hosts": "Hostnames that bypass the proxy and connect directly.",
+ },
+ },
+ "projects": {
+ "description": "A project that isolates resources and access within a Kernel organization.",
+ "docs_url": "https://kernel.sh/docs/api-reference/projects/list-projects",
+ "columns": {
+ "id": "Unique project identifier.",
+ "name": "Project name, unique within the organization.",
+ "status": "Project status.",
+ "created_at": "When the project was created.",
+ "updated_at": "When the project was last updated.",
+ },
+ },
+ "audit_logs": {
+ "description": "An authenticated API request made against the Kernel organization, recorded in the audit log.",
+ "docs_url": "https://kernel.sh/docs/api-reference/audit-logs/list-audit-logs",
+ "columns": {
+ "id": "Synthetic identifier derived from the record contents. Kernel does not return an id for audit records.",
+ "timestamp": "UTC time when the request was received.",
+ "auth_strategy": "Authentication strategy used for the request.",
+ "user_id": "ID of the authenticated user, if any.",
+ "email": "Email of the authenticated user at request time, if any.",
+ "method": "HTTP method.",
+ "path": "Request path.",
+ "route": "Matched API route pattern, if available.",
+ "status": "HTTP response status code.",
+ "domain": "Request host.",
+ "duration_ms": "Request duration in milliseconds.",
+ "client_ip": "Client IP address.",
+ "user_agent": "User agent header.",
+ },
+ },
}
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
index 994338a2599f..938d446c9e32 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/kernel/kernel.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kernel/kernel.py
@@ -1,6 +1,10 @@
+import json
+import hashlib
+from collections import Counter
from collections.abc import Iterator
from datetime import UTC, datetime, timedelta
-from typing import Any
+from functools import partial
+from typing import Any, Optional
from urllib.parse import quote, urlencode
import requests
@@ -24,11 +28,20 @@ KERNEL_BASE_URL = "https://api.onkernel.com"
# Kernel caps list page size at 100 (1-100, default 20).
PAGE_SIZE = 100
+AUDIT_LOGS_ENDPOINT = "audit_logs"
+AUDIT_LOG_MAX_WINDOW = timedelta(days=28)
+AUDIT_LOG_MIN_WINDOW = timedelta(hours=1)
+AUDIT_LOG_RETENTION = timedelta(days=365)
+
class KernelRetryableError(Exception):
pass
+class KernelResourceDisabledError(Exception):
+ pass
+
+
class KernelUnexpectedResponseError(Exception):
"""Raised when a list response is neither a JSON array nor a recognized wrapped shape.
@@ -72,7 +85,43 @@ def _extract_items(body: Any) -> list[dict[str, Any]]:
raise KernelUnexpectedResponseError(f"Unexpected Kernel list response shape: {type(body).__name__}")
-def _redact_sensitive_fields(item: Any) -> Any:
+def _error_code(response: requests.Response) -> Optional[str]:
+ try:
+ body = response.json()
+ except ValueError:
+ return None
+ code = body.get("code") if isinstance(body, dict) else None
+ return code if isinstance(code, str) else None
+
+
+def _parse_datetime(value: Any) -> Optional[datetime]:
+ if isinstance(value, str):
+ try:
+ value = datetime.fromisoformat(value)
+ except ValueError:
+ return None
+ if not isinstance(value, datetime):
+ return None
+ return value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)
+
+
+def _format_datetime(value: datetime) -> str:
+ return value.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S.%fZ")
+
+
+def _add_audit_log_ids(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ """Give each audit record a deterministic id, including duplicate copies."""
+ seen: Counter[str] = Counter()
+ for row in rows:
+ if "id" in row:
+ continue
+ digest = hashlib.sha256(json.dumps(row, sort_keys=True, default=str).encode()).hexdigest()
+ row["id"] = f"{digest}-{seen[digest]}"
+ seen[digest] += 1
+ return rows
+
+
+def _redact_sensitive_fields(item: Any, nested_sensitive_fields: Optional[dict[str, frozenset[str]]] = None) -> 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
@@ -81,7 +130,12 @@ def _redact_sensitive_fields(item: Any) -> Any:
"""
if not isinstance(item, dict):
return item
- return {key: value for key, value in item.items() if key.lower() not in SENSITIVE_FIELDS}
+ redacted = {key: value for key, value in item.items() if key.lower() not in SENSITIVE_FIELDS}
+ for parent, keys in (nested_sensitive_fields or {}).items():
+ nested = redacted.get(parent)
+ if isinstance(nested, dict):
+ redacted[parent] = {key: value for key, value in nested.items() if key.lower() not in keys}
+ return redacted
def _next_page(headers: Any, current_offset: int, page_len: int) -> tuple[bool, int]:
@@ -121,6 +175,7 @@ def _fetch_page(
headers: dict[str, str],
logger: FilteringBoundLogger,
allow_not_found: bool = False,
+ empty_on_error_code: Optional[str] = None,
) -> requests.Response:
response = session.get(url, headers=headers, timeout=60)
@@ -131,6 +186,9 @@ def _fetch_page(
if allow_not_found and response.status_code == 404:
return response
+ if empty_on_error_code is not None and response.status_code == 404 and _error_code(response) == empty_on_error_code:
+ raise KernelResourceDisabledError(empty_on_error_code)
+
if not response.ok:
logger.error(f"Kernel API error: status={response.status_code}, body={response.text}, url={url}")
response.raise_for_status()
@@ -150,6 +208,71 @@ def validate_credentials(api_key: str) -> tuple[bool, int | None]:
return response.status_code == 200, response.status_code
+def _fetch_audit_log_page(
+ session: requests.Session,
+ headers: dict[str, str],
+ start: datetime,
+ end: datetime,
+ page_token: Optional[str],
+ logger: FilteringBoundLogger,
+) -> tuple[list[dict[str, Any]], Optional[str]]:
+ params: dict[str, Any] = {"start": _format_datetime(start), "end": _format_datetime(end), "limit": PAGE_SIZE}
+ if page_token:
+ params["page_token"] = page_token
+ response = _fetch_page(session, _build_url(KERNEL_ENDPOINTS[AUDIT_LOGS_ENDPOINT].path, params), headers, logger)
+ items = _extract_items(response.json())
+ has_more = str(response.headers.get("X-Has-More", "")).strip().lower()
+ next_token = response.headers.get("X-Next-Page-Token")
+ if has_more == "false" or not next_token:
+ return items, None
+ return items, str(next_token)
+
+
+def _iter_audit_log_windows(
+ session: requests.Session, headers: dict[str, str], start: datetime, end: datetime, logger: FilteringBoundLogger
+) -> Iterator[list[dict[str, Any]]]:
+ windows: list[tuple[datetime, datetime]] = []
+ window_start = start
+ while window_start < end:
+ windows.append((window_start, min(window_start + AUDIT_LOG_MAX_WINDOW, end)))
+ window_start += AUDIT_LOG_MAX_WINDOW
+ pending = list(reversed(windows))
+ while pending:
+ window_start, window_end = pending.pop()
+ rows, next_token = _fetch_audit_log_page(session, headers, window_start, window_end, None, logger)
+ if next_token is not None and window_end - window_start > AUDIT_LOG_MIN_WINDOW:
+ midpoint = window_start + (window_end - window_start) / 2
+ pending.append((midpoint, window_end))
+ pending.append((window_start, midpoint))
+ continue
+ while next_token is not None:
+ page, next_token = _fetch_audit_log_page(session, headers, window_start, window_end, next_token, logger)
+ rows.extend(page)
+ if rows:
+ rows.sort(key=lambda row: _parse_datetime(row.get("timestamp")) or datetime.min.replace(tzinfo=UTC))
+ yield _add_audit_log_ids(rows)
+
+
+def get_audit_log_rows(
+ api_key: str, logger: FilteringBoundLogger, db_incremental_field_last_value: Optional[Any] = None
+) -> Iterator[Any]:
+ headers = _get_headers(api_key)
+ batcher = Batcher(logger=logger, chunk_size=2000, chunk_size_bytes=100 * 1024 * 1024)
+ session = make_tracked_session(capture=False)
+ end = datetime.now(UTC)
+ start = end - AUDIT_LOG_RETENTION
+ last_value = _parse_datetime(db_incremental_field_last_value)
+ if last_value is not None and last_value > start:
+ start = last_value
+ for rows in _iter_audit_log_windows(session, headers, start, end, logger):
+ for row in rows:
+ batcher.batch(row)
+ if batcher.should_yield():
+ yield batcher.get_table()
+ if batcher.should_yield(include_incomplete_chunk=True):
+ yield batcher.get_table()
+
+
def _iter_list_items(
session: requests.Session,
headers: dict[str, str],
@@ -163,7 +286,10 @@ def _iter_list_items(
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)
+ try:
+ response = _fetch_page(session, url, headers, logger, empty_on_error_code=config.empty_on_error_code)
+ except KernelResourceDisabledError:
+ break
items = _extract_items(response.json())
has_more, next_offset = _next_page(response.headers, offset, len(items))
@@ -304,7 +430,10 @@ def get_rows(
if endpoint == BROWSER_TELEMETRY_EVENTS:
items: Iterator[Any] = _iter_browser_telemetry_events(session, headers, logger)
else:
- items = (_redact_sensitive_fields(item) for item in _iter_list_items(session, headers, config, logger))
+ items = (
+ _redact_sensitive_fields(item, config.nested_sensitive_fields)
+ for item in _iter_list_items(session, headers, config, logger)
+ )
for item in items:
batcher.batch(item)
@@ -319,20 +448,25 @@ def kernel_source(
api_key: str,
endpoint: str,
logger: FilteringBoundLogger,
+ db_incremental_field_last_value: Optional[Any] = None,
) -> SourceResponse:
endpoint_config: KernelEndpointConfig = KERNEL_ENDPOINTS[endpoint]
-
- return SourceResponse(
- name=endpoint,
- items=lambda: get_rows(
+ items = (
+ partial(
+ get_audit_log_rows,
api_key=api_key,
- endpoint=endpoint,
logger=logger,
- ),
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ )
+ if endpoint == AUDIT_LOGS_ENDPOINT
+ else partial(get_rows, api_key=api_key, endpoint=endpoint, logger=logger)
+ )
+ return SourceResponse(
+ name=endpoint,
+ items=items,
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",
+ partition_mode="datetime" if endpoint_config.partition_key else None,
+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,
+ partition_format="month" if endpoint_config.partition_key else None,
)
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
index b42c979887c6..26488931c475 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/kernel/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kernel/settings.py
@@ -1,8 +1,11 @@
from dataclasses import dataclass, field
from typing import Optional
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
+from products.warehouse_sources.backend.types import IncrementalField
-@dataclass
+
+@dataclass(frozen=True)
class KernelEndpointConfig:
name: str
path: str
@@ -11,12 +14,20 @@ class KernelEndpointConfig:
# 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)
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ partition_key: Optional[str] = None
+ # Credential keys dropped from one nested object, keyed by the top-level field that holds it.
+ nested_sensitive_fields: dict[str, frozenset[str]] = field(default_factory=dict)
+ # Error `code` in a 404 body that means the resource is switched off for the organization,
+ # so the table is empty rather than broken.
+ empty_on_error_code: Optional[str] = None
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
+# Kernel list endpoints share offset pagination (limit/offset query params, X-Has-More /
+# X-Next-Offset response headers), except audit_logs (see kernel.py). Only audit_logs syncs
+# incrementally, on its required server-side `start` filter. 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.
@@ -57,6 +68,34 @@ KERNEL_ENDPOINTS: dict[str, KernelEndpointConfig] = {
should_sync_default=False,
description="Archived telemetry events (console, network, page, interaction, and more) captured by your browser sessions during Kernel's 30-day retention window.",
),
+ "browser_pools": KernelEndpointConfig(
+ name="browser_pools",
+ path="/browser_pools",
+ description="Browser pools, with their size, live acquired/available counts, and browser configuration.",
+ ),
+ "proxies": KernelEndpointConfig(
+ name="proxies",
+ path="/proxies",
+ # Proxy authentication credentials must not reach the warehouse.
+ nested_sensitive_fields={"config": frozenset({"password", "username"})},
+ description="Proxy configurations that browser sessions route traffic through, with health status.",
+ ),
+ "projects": KernelEndpointConfig(
+ name="projects",
+ path="/org/projects",
+ empty_on_error_code="projects_disabled",
+ description="Projects that isolate resources within your Kernel organization.",
+ ),
+ "audit_logs": KernelEndpointConfig(
+ name="audit_logs",
+ path="/audit-logs",
+ # Audit records carry no id; kernel.py derives a synthetic `id` from the record contents.
+ incremental_fields=[incremental_field("timestamp")],
+ partition_key="timestamp",
+ # Audit logs need a Start-Up or Enterprise plan and record every API request, so they are opt-in.
+ should_sync_default=False,
+ description="Organization-wide audit log of authenticated API requests: who called which endpoint, when, and the response status.",
+ ),
}
ENDPOINTS = tuple(KERNEL_ENDPOINTS.keys())
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 57720b554471..f6048a5795b8 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
@@ -86,11 +86,13 @@ You can create an API key in your [Kernel dashboard](https://dashboard.onkernel.
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,
+ # Only audit_logs has a server-side time filter (its required `start`). The other
+ # endpoints stay full refresh, since their time filters are unverified for this
+ # alpha release. Append is not offered: an incremental audit-log sync re-reads
+ # the records at the watermark, which merge dedupes and append would duplicate.
+ supports_incremental=bool(endpoint_config.incremental_fields),
supports_append=False,
- incremental_fields=[],
+ incremental_fields=endpoint_config.incremental_fields,
should_sync_default=endpoint_config.should_sync_default,
description=endpoint_config.description,
)
@@ -125,4 +127,7 @@ You can create an API key in your [Kernel dashboard](https://dashboard.onkernel.
api_key=config.api_key,
endpoint=inputs.schema_name,
logger=inputs.logger,
+ 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/kernel/tests/test_kernel.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kernel/tests/test_kernel.py
index 878c1f2f5722..63eb91adbe26 100644
--- 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
@@ -4,15 +4,20 @@ from typing import Any
from urllib.parse import parse_qs, urlparse
import pytest
+import time_machine
from unittest import mock
+import requests
+
from products.warehouse_sources.backend.temporal.data_imports.sources.kernel.kernel import (
+ AUDIT_LOG_MAX_WINDOW,
PAGE_SIZE,
KernelRetryableError,
KernelUnexpectedResponseError,
_extract_items,
_next_page,
_redact_sensitive_fields,
+ get_audit_log_rows,
get_rows,
kernel_source,
validate_credentials,
@@ -190,15 +195,53 @@ class TestGetRows:
url = mock_session.return_value.get.call_args.args[0]
assert "status=all" in url
+ @pytest.mark.parametrize(
+ "endpoint, item, expected",
+ [
+ (
+ "browsers",
+ {"id": "b1", "browser_live_view_url": "https://token@example", "region": "us"},
+ {"id": "b1", "region": "us"},
+ ),
+ (
+ "proxies",
+ {
+ "id": "p1",
+ "type": "custom",
+ "config": {"host": "proxy.example.com", "port": 8080, "username": "user", "password": "x"},
+ },
+ # The batcher stores nested objects as JSON strings.
+ {"id": "p1", "type": "custom", "config": '{"host":"proxy.example.com","port":8080}'},
+ ),
+ ],
+ )
@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
- )
+ def test_sensitive_fields_are_stripped_from_rows(
+ self, mock_session: Any, endpoint: str, item: dict[str, Any], expected: dict[str, Any]
+ ) -> None:
+ mock_session.return_value.get.return_value = _response([item], has_more=False)
- rows = self._collect("browsers")
+ rows = self._collect(endpoint)
- assert rows == [{"id": "b1", "region": "us"}]
+ assert rows == [expected]
+
+ @pytest.mark.parametrize(
+ "error_code, expect_error",
+ [("projects_disabled", False), ("not_found", True)],
+ )
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_projects_404_is_empty_only_when_projects_are_disabled(
+ self, mock_session: Any, error_code: str, expect_error: bool
+ ) -> None:
+ response = _response({"code": error_code, "message": "nope"}, status_code=404)
+ response.raise_for_status.side_effect = requests.HTTPError("404 Client Error", response=response)
+ mock_session.return_value.get.return_value = response
+
+ if expect_error:
+ with pytest.raises(requests.HTTPError):
+ self._collect("projects")
+ else:
+ assert self._collect("projects") == []
@mock.patch(f"{_MODULE}.make_tracked_session")
def test_unexpected_response_shape_raises(self, mock_session: Any) -> None:
@@ -354,6 +397,113 @@ class TestKernelSourceResponse:
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
+ if endpoint == "audit_logs":
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == ["timestamp"]
+ else:
+ # 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
+
+
+_NOW = datetime(2026, 6, 1, tzinfo=UTC)
+
+
+def _audit_record(at: datetime, path: str = "/browsers") -> dict[str, Any]:
+ return {
+ "timestamp": at.strftime("%Y-%m-%dT%H:%M:%S.%fZ"),
+ "auth_strategy": "api_key",
+ "user_id": "user_1",
+ "email": "[email protected]",
+ "method": "GET",
+ "path": path,
+ "route": path,
+ "status": 200,
+ "domain": "api.example.com",
+ "duration_ms": 12,
+ "client_ip": "192.0.2.1",
+ "user_agent": "test-agent",
+ }
+
+
+def _fake_audit_log_api(records: list[dict[str, Any]], requested_windows: list[timedelta]) -> Any:
+ def get(url: str, headers: dict[str, str], timeout: int) -> mock.MagicMock:
+ query = parse_qs(urlparse(url).query)
+ start = datetime.fromisoformat(query["start"][0])
+ end = datetime.fromisoformat(query["end"][0])
+ requested_windows.append(end - start)
+ in_window = sorted(
+ (r for r in records if start <= datetime.fromisoformat(r["timestamp"]) < end),
+ key=lambda r: r["timestamp"],
+ reverse=True,
+ )
+ offset = int(query.get("page_token", ["0"])[0])
+ page = [dict(r) for r in in_window[offset : offset + PAGE_SIZE]]
+ has_more = offset + PAGE_SIZE < len(in_window)
+ response = _response(page, has_more=has_more)
+ if has_more:
+ response.headers["X-Next-Page-Token"] = str(offset + PAGE_SIZE)
+ return response
+
+ return get
+
+
+class TestAuditLogRows:
+ def _collect(self, last_value: Any = None) -> list[dict]:
+ rows: list[dict] = []
+ for table in get_audit_log_rows("sk_test", mock.MagicMock(), db_incremental_field_last_value=last_value):
+ rows.extend(table.to_pylist())
+ return rows
+
+ @time_machine.travel(_NOW, tick=False)
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_returns_every_record_once_oldest_first(self, mock_session: Any) -> None:
+ busy_hour = _NOW - timedelta(days=3)
+ records = [
+ _audit_record(_NOW - timedelta(days=300)),
+ _audit_record(_NOW - timedelta(days=40)),
+ *(_audit_record(busy_hour + timedelta(seconds=i)) for i in range(PAGE_SIZE + 50)),
+ # Two indistinguishable requests in the same instant must stay two rows.
+ _audit_record(_NOW - timedelta(hours=2), path="/apps"),
+ _audit_record(_NOW - timedelta(hours=2), path="/apps"),
+ ]
+ requested_windows: list[timedelta] = []
+ mock_session.return_value.get.side_effect = _fake_audit_log_api(records, requested_windows)
+
+ rows = self._collect()
+
+ assert len(rows) == len(records)
+ timestamps = [datetime.fromisoformat(r["timestamp"]) for r in rows]
+ assert timestamps == sorted(timestamps)
+ assert len({r["id"] for r in rows}) == len(records)
+ assert max(requested_windows) <= AUDIT_LOG_MAX_WINDOW
+
+ # A later incremental sync re-reads records at the watermark; they must keep their ids
+ # so merge dedupes them.
+ mock_session.return_value.get.side_effect = _fake_audit_log_api(records, [])
+ rerun = self._collect(last_value=_NOW - timedelta(hours=2))
+ assert {r["id"] for r in rerun} == {r["id"] for r in rows[-2:]}
+
+ @pytest.mark.parametrize(
+ "last_value, expected_start",
+ [
+ (None, _NOW - timedelta(days=365)),
+ (_NOW - timedelta(days=2), _NOW - timedelta(days=2)),
+ ("2026-05-30T00:00:00Z", datetime(2026, 5, 30, tzinfo=UTC)),
+ # Kernel keeps one year of audit logs, so an older watermark starts at the retention edge.
+ (_NOW - timedelta(days=500), _NOW - timedelta(days=365)),
+ ],
+ )
+ @time_machine.travel(_NOW, tick=False)
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_search_starts_at_watermark_or_retention_edge(
+ self, mock_session: Any, last_value: Any, expected_start: datetime
+ ) -> None:
+ mock_session.return_value.get.return_value = _response([], has_more=False)
+
+ self._collect(last_value=last_value)
+
+ first_query = parse_qs(urlparse(mock_session.return_value.get.call_args_list[0].args[0]).query)
+ assert datetime.fromisoformat(first_query["start"][0]) == expected_start
+ last_query = parse_qs(urlparse(mock_session.return_value.get.call_args_list[-1].args[0]).query)
+ assert datetime.fromisoformat(last_query["end"][0]) == _NOW
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
index 3c8ee10ab684..5b566ef853b8 100644
--- 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
@@ -47,13 +47,13 @@ class TestKernelSource:
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)
+ def test_only_audit_logs_syncs_incrementally(self) -> None:
+ schemas = {schema.name: schema for schema in 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)
+ assert set(schemas) == set(ENDPOINTS)
+ assert {name for name, schema in schemas.items() if schema.supports_incremental} == {"audit_logs"}
+ assert [field["field"] for field in schemas["audit_logs"].incremental_fields] == ["timestamp"]
+ assert all(not schema.supports_append for schema in schemas.values())
def test_get_schemas_filtered_by_names(self) -> None:
schemas = self.source.get_schemas(self.config, self.team_id, names=["invocations"])