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 lightfield import source (#72650)

Tom Owersd3b216071420
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 4d2cbccfb09a..6e1b0c83c555 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -326,6 +326,7 @@ the row lists both.
| leexi | HTTP | requests + `rest_source.RESTClient` | ✅ |
| lemlist | HTTP | requests | ✅ |
| less_annoying_crm | HTTP | requests | ✅ |
+| lightfield | HTTP | requests + `rest_source.RESTClient` | ✅ |
| lightspeed_retail | HTTP | requests | ✅ |
| linear | HTTP | requests | ✅ |
| linearb | HTTP | requests | ✅ |
@@ -810,7 +811,6 @@ doesn't conflict with concurrent PRs.
- lemon_squeezy
- lever
- liana
-- lightfield
- lingo_dev
- linkedin_pages
- linnworks
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/lightfield.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/lightfield.py
index eb323f9b3186..63de5b648f0b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/lightfield.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/lightfield.py
@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class LightfieldSourceConfig(config.Config):
- pass
+ api_key: str
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lightfield/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lightfield/canonical_descriptions.py
new file mode 100644
index 000000000000..50cc1a52e734
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lightfield/canonical_descriptions.py
@@ -0,0 +1,65 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+_COMMON_COLUMNS = {
+ "id": "Unique identifier for the record.",
+ "createdAt": "Timestamp when the record was created in Lightfield.",
+ "updatedAt": "Timestamp when the record was last updated in Lightfield.",
+ "fields": "Map of the record's field values, keyed by field slug; each entry carries a value and its valueType.",
+ "relationships": "Map of the record's relationships, keyed by relationship slug; each entry carries the cardinality, related object type, and related record IDs.",
+ "httpLink": "URL of the record in the Lightfield web app.",
+ "externalId": "Optional external identifier attached to the record via the API.",
+}
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "accounts": {
+ "description": "Companies and organizations tracked in the Lightfield CRM.",
+ "docs_url": "https://docs.lightfield.app/api/resources/account/methods/list/",
+ "columns": _COMMON_COLUMNS,
+ },
+ "contacts": {
+ "description": "People associated with accounts in the Lightfield CRM.",
+ "docs_url": "https://docs.lightfield.app/api/resources/contact/methods/list/",
+ "columns": _COMMON_COLUMNS,
+ },
+ "opportunities": {
+ "description": "Sales opportunities (deals) tracked in the Lightfield CRM.",
+ "docs_url": "https://docs.lightfield.app/api/resources/opportunity/methods/list/",
+ "columns": _COMMON_COLUMNS,
+ },
+ "meetings": {
+ "description": "Meetings recorded in Lightfield, including scheduling metadata and links to related records.",
+ "docs_url": "https://docs.lightfield.app/api/resources/meeting/methods/list/",
+ "columns": _COMMON_COLUMNS,
+ },
+ "tasks": {
+ "description": "To-do items and follow-ups tracked in Lightfield.",
+ "docs_url": "https://docs.lightfield.app/api/resources/task/methods/list/",
+ "columns": _COMMON_COLUMNS,
+ },
+ "notes": {
+ "description": "Free-form notes attached to records in Lightfield.",
+ "docs_url": "https://docs.lightfield.app/api/resources/note/methods/list/",
+ "columns": _COMMON_COLUMNS,
+ },
+ "lists": {
+ "description": "Saved lists of accounts, contacts, or opportunities in Lightfield.",
+ "docs_url": "https://docs.lightfield.app/api/resources/list/methods/list/",
+ "columns": _COMMON_COLUMNS,
+ },
+ "members": {
+ "description": "Members of the Lightfield organization (read-only).",
+ "docs_url": "https://docs.lightfield.app/api/resources/member/methods/list/",
+ "columns": _COMMON_COLUMNS,
+ },
+ "emails": {
+ "description": "Emails synced from connected mailboxes. List items exclude the message body; subjects may be redacted for metadata-only access.",
+ "docs_url": "https://docs.lightfield.app/api/resources/email/methods/list/",
+ "columns": {
+ **_COMMON_COLUMNS,
+ "accessLevel": "Access level for the email content: FULL or METADATA.",
+ "objectType": "Lightfield object type of the record.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lightfield/lightfield.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lightfield/lightfield.py
new file mode 100644
index 000000000000..003fbf41dcd0
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lightfield/lightfield.py
@@ -0,0 +1,101 @@
+from typing import Any
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (
+ RESTAPIConfig,
+ rest_api_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ OffsetPaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.lightfield.settings import (
+ LIGHTFIELD_ENDPOINTS,
+ LIGHTFIELD_PAGE_SIZE,
+)
+
+LIGHTFIELD_BASE_URL = "https://api.lightfield.app"
+REQUEST_TIMEOUT_SECONDS = 30
+
+
+def _version_headers(api_version: str) -> dict[str, str]:
+ # Every Lightfield request must carry the dated `Lightfield-Version` header.
+ return {
+ "Lightfield-Version": api_version,
+ "Accept": "application/json",
+ }
+
+
+def lightfield_source(
+ api_key: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ api_version: str,
+) -> SourceResponse:
+ endpoint_config = LIGHTFIELD_ENDPOINTS[endpoint]
+
+ config: RESTAPIConfig = {
+ "client": {
+ "base_url": LIGHTFIELD_BASE_URL,
+ "auth": {
+ "type": "bearer",
+ "token": api_key,
+ },
+ "headers": _version_headers(api_version),
+ # `totalCount` reflects the matching records at request time; the paginator also
+ # stops on a short page, which the docs give as the canonical termination signal.
+ "paginator": OffsetPaginator(limit=LIGHTFIELD_PAGE_SIZE, total_path="totalCount"),
+ },
+ "resource_defaults": {
+ "write_disposition": "replace",
+ },
+ "resources": [
+ {
+ "name": endpoint_config.name,
+ "table_name": endpoint_config.name,
+ "write_disposition": "replace",
+ "endpoint": {
+ "path": endpoint_config.path,
+ "data_selector": "data",
+ },
+ "table_format": "delta",
+ }
+ ],
+ }
+
+ resource = rest_api_resource(config, team_id, job_id, None)
+
+ return SourceResponse(
+ name=endpoint_config.name,
+ items=lambda: resource,
+ primary_keys=[endpoint_config.primary_key],
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime",
+ partition_format="month",
+ partition_keys=[endpoint_config.partition_key],
+ )
+
+
+def check_token(api_key: str, api_version: str) -> tuple[bool, list[str] | None, str | None]:
+ """Probe `/v1/auth/validate` (no scope required). Returns (valid, granted scopes, error)."""
+ session = make_tracked_session(redact_values=(api_key,))
+ res = session.get(
+ f"{LIGHTFIELD_BASE_URL}/v1/auth/validate",
+ headers={"Authorization": f"Bearer {api_key}", **_version_headers(api_version)},
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+
+ if res.status_code == 401:
+ return False, None, "Invalid Lightfield API key. Check the key and try again."
+ if res.status_code != 200:
+ return False, None, f"Lightfield returned an unexpected status ({res.status_code}) while validating the key."
+
+ body: dict[str, Any] = res.json()
+ if not body.get("active", False):
+ return False, None, "This Lightfield API key is no longer active. Generate a new key and reconnect."
+
+ raw_scopes = body.get("scopes")
+ scopes = [str(scope) for scope in raw_scopes] if isinstance(raw_scopes, list) else None
+ return True, scopes, None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lightfield/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lightfield/settings.py
new file mode 100644
index 000000000000..58e1fa18899a
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lightfield/settings.py
@@ -0,0 +1,44 @@
+from dataclasses import dataclass
+
+from products.warehouse_sources.backend.types import IncrementalField
+
+# Lightfield caps list-endpoint page size at 25 (`limit` defaults to 25, maximum 25).
+LIGHTFIELD_PAGE_SIZE = 25
+
+
+@dataclass
+class LightfieldEndpointConfig:
+ name: str
+ path: str
+ scope: str
+ primary_key: str = "id"
+ # `createdAt` is stable per record; `updatedAt` changes on every write and would
+ # rewrite partitions each sync.
+ partition_key: str = "createdAt"
+
+
+# Lightfield list endpoints only filter with `$fieldSlug[operator]=` on field slugs — there is no
+# documented filter on the top-level createdAt/updatedAt record properties and no sort parameter,
+# so a reliable server-side incremental cursor cannot be built. All endpoints are full refresh.
+#
+# Custom objects (`/v1/objects/{entitySlug}`) are deliberately not included: enumerating them
+# requires a live `listDefinitions` call at schema discovery, and the feature is plan-gated.
+LIGHTFIELD_ENDPOINTS: dict[str, LightfieldEndpointConfig] = {
+ "accounts": LightfieldEndpointConfig(name="accounts", path="/v1/accounts", scope="accounts:read"),
+ "contacts": LightfieldEndpointConfig(name="contacts", path="/v1/contacts", scope="contacts:read"),
+ "opportunities": LightfieldEndpointConfig(
+ name="opportunities", path="/v1/opportunities", scope="opportunities:read"
+ ),
+ "meetings": LightfieldEndpointConfig(name="meetings", path="/v1/meetings", scope="meetings:read"),
+ "tasks": LightfieldEndpointConfig(name="tasks", path="/v1/tasks", scope="tasks:read"),
+ "notes": LightfieldEndpointConfig(name="notes", path="/v1/notes", scope="notes:read"),
+ "lists": LightfieldEndpointConfig(name="lists", path="/v1/lists", scope="lists:read"),
+ "members": LightfieldEndpointConfig(name="members", path="/v1/members", scope="members:read"),
+ "emails": LightfieldEndpointConfig(name="emails", path="/v1/emails", scope="emails:read"),
+}
+
+ENDPOINTS = tuple(LIGHTFIELD_ENDPOINTS.keys())
+
+# No endpoint exposes a server-side timestamp filter (see the note above), so nothing is
+# advertised as an incremental candidate.
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lightfield/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lightfield/source.py
index a146d63285b6..959b5378cca1 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/lightfield/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lightfield/source.py
@@ -1,32 +1,161 @@
-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,
+ build_endpoint_schemas,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.lightfield import (
LightfieldSourceConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.lightfield.lightfield import (
+ check_token,
+ lightfield_source,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.lightfield.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ LIGHTFIELD_ENDPOINTS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
class LightfieldSource(SimpleSource[LightfieldSourceConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+ supported_versions = ("2026-03-01",)
+ default_version = "2026-03-01"
+ api_docs_url = "https://docs.lightfield.app"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.LIGHTFIELD
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://api.lightfield.app": "Your Lightfield API key is invalid or has been revoked. Please generate a new key and reconnect.",
+ "403 Client Error: Forbidden for url: https://api.lightfield.app": "Your Lightfield API key is missing a required scope. Please grant the read scope for the tables you want to sync and try again.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.lightfield.canonical_descriptions import ( # noqa: PLC0415 — lazy import keeps the catalog off the registry import path
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: LightfieldSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)
+
+ def validate_credentials(
+ self, config: LightfieldSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ valid, scopes, error = check_token(config.api_key, self.default_version)
+ if not valid:
+ return False, error
+
+ # At source-create (no schema_name) a live key is enough — users may only grant the
+ # scopes for the tables they intend to sync. Per-schema checks enforce the scope.
+ if schema_name is not None and scopes is not None:
+ endpoint = LIGHTFIELD_ENDPOINTS.get(schema_name)
+ if endpoint is not None and endpoint.scope not in scopes:
+ return (
+ False,
+ f"Your Lightfield API key is missing the `{endpoint.scope}` scope required to sync {schema_name}.",
+ )
+
+ return True, None
+
+ def get_endpoint_permissions(
+ self, config: LightfieldSourceConfig, team_id: int, endpoints: list[str]
+ ) -> dict[str, str | None]:
+ try:
+ valid, scopes, _ = check_token(config.api_key, self.default_version)
+ except Exception:
+ valid, scopes = False, None
+
+ # Only a definitive scope list may mark tables unreachable; anything else (throttle,
+ # 5xx, network blip) must not block the schema picker.
+ if not valid or scopes is None:
+ return dict.fromkeys(endpoints)
+
+ granted = set(scopes)
+ permissions: dict[str, str | None] = {}
+ for name in endpoints:
+ endpoint = LIGHTFIELD_ENDPOINTS.get(name)
+ if endpoint is None or endpoint.scope in granted:
+ permissions[name] = None
+ else:
+ permissions[name] = f"API key is missing the `{endpoint.scope}` scope"
+ return permissions
+
+ def source_for_pipeline(self, config: LightfieldSourceConfig, inputs: SourceInputs) -> SourceResponse:
+ return lightfield_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ team_id=inputs.team_id,
+ job_id=inputs.job_id,
+ api_version=self.resolve_api_version(inputs.api_version),
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.LIGHTFIELD,
category=DataWarehouseSourceCategory.CRM,
label="Lightfield",
+ caption="""Enter your Lightfield API key to pull your Lightfield CRM data into the PostHog Data warehouse.
+
+You can create an API key in your Lightfield settings (admin access required). Grant the read scope for each table you want to sync:
+
+- `accounts:read` - accounts
+- `contacts:read` - contacts
+- `opportunities:read` - opportunities
+- `meetings:read` - meetings
+- `tasks:read` - tasks
+- `notes:read` - notes
+- `lists:read` - lists
+- `members:read` - members
+- `emails:read` - emails
+""",
+ docsUrl="https://posthog.com/docs/cdp/sources/lightfield",
iconPath="/static/services/lightfield.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ releaseStatus=ReleaseStatus.ALPHA,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="sk_lf_...",
+ secret=True,
+ ),
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lightfield/tests/test_lightfield.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lightfield/tests/test_lightfield.py
new file mode 100644
index 000000000000..3a4678e2c686
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lightfield/tests/test_lightfield.py
@@ -0,0 +1,188 @@
+import json
+from collections.abc import Iterable
+from typing import Any, cast
+
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+from requests import Response
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.lightfield.lightfield import (
+ check_token,
+ lightfield_source,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.lightfield.settings import (
+ LIGHTFIELD_ENDPOINTS,
+ LIGHTFIELD_PAGE_SIZE,
+)
+
+
+def _make_http_response(body: Any, status_code: int = 200) -> Response:
+ resp = Response()
+ resp.status_code = status_code
+ resp._content = json.dumps(body).encode()
+ resp.headers["Content-Type"] = "application/json"
+ return resp
+
+
+def _record(record_id: str) -> dict[str, Any]:
+ return {
+ "id": record_id,
+ "createdAt": "2026-01-01T00:00:00Z",
+ "updatedAt": "2026-01-02T00:00:00Z",
+ "fields": {"$name": {"value": f"Record {record_id}", "valueType": "TEXT"}},
+ "relationships": {},
+ "httpLink": f"https://app.lightfield.app/accounts/{record_id}",
+ }
+
+
+def _page(record_ids: list[str], total_count: int) -> dict[str, Any]:
+ return {
+ "data": [_record(record_id) for record_id in record_ids],
+ "object": "list",
+ "totalCount": total_count,
+ }
+
+
+class TestLightfieldSourcePagination:
+ def _drive(self, responses: list[Response]) -> tuple[list[dict[str, Any]], list[dict[str, Any]], dict[str, str]]:
+ """Drive ``lightfield_source`` with a mocked HTTP session. Returns the params sent
+ with each request (shallow copies — the paginator mutates the Request in place
+ between pages), the rows yielded, and the session headers the client installed."""
+ sent_params: list[dict[str, Any]] = []
+ response_iter = iter(responses)
+
+ def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:
+ sent_params.append(dict(request.params))
+ return next(response_iter)
+
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
+ ) as MockSession:
+ mock_session = MockSession.return_value
+ mock_session.headers = {}
+ mock_session.prepare_request.side_effect = lambda req: req
+ mock_session.send.side_effect = fake_send
+
+ source_response = lightfield_source(
+ api_key="sk_lf_test",
+ endpoint="accounts",
+ team_id=123,
+ job_id="test_job",
+ api_version="2026-03-01",
+ )
+ rows = [row for page in cast(Iterable[Any], source_response.items()) for row in page]
+ return sent_params, rows, dict(mock_session.headers)
+
+ def test_paginates_with_offset_until_short_page(self) -> None:
+ first_page_ids = [f"acc_{i}" for i in range(LIGHTFIELD_PAGE_SIZE)]
+ responses = [
+ _make_http_response(_page(first_page_ids, total_count=30)),
+ _make_http_response(_page(["acc_25", "acc_26"], total_count=30)),
+ ]
+
+ sent_params, rows, _ = self._drive(responses)
+
+ assert [p.get("offset") for p in sent_params] == [0, LIGHTFIELD_PAGE_SIZE]
+ assert all(p.get("limit") == LIGHTFIELD_PAGE_SIZE for p in sent_params)
+ assert len(rows) == LIGHTFIELD_PAGE_SIZE + 2
+
+ def test_stops_at_total_count_without_extra_request(self) -> None:
+ # A full page whose totalCount equals the rows returned must not pay for a
+ # trailing empty-page request.
+ page_ids = [f"acc_{i}" for i in range(LIGHTFIELD_PAGE_SIZE)]
+ responses = [_make_http_response(_page(page_ids, total_count=LIGHTFIELD_PAGE_SIZE))]
+
+ sent_params, rows, _ = self._drive(responses)
+
+ assert len(sent_params) == 1
+ assert len(rows) == LIGHTFIELD_PAGE_SIZE
+
+ def test_short_first_page_makes_single_request(self) -> None:
+ responses = [_make_http_response(_page(["acc_1"], total_count=1))]
+
+ sent_params, rows, _ = self._drive(responses)
+
+ assert len(sent_params) == 1
+ assert [row["id"] for row in rows] == ["acc_1"]
+
+ def test_client_sends_required_version_header(self) -> None:
+ responses = [_make_http_response(_page([], total_count=0))]
+
+ _, _, headers = self._drive(responses)
+
+ assert headers["Lightfield-Version"] == "2026-03-01"
+
+
+class TestLightfieldSourceResponse:
+ @parameterized.expand([(name,) for name in LIGHTFIELD_ENDPOINTS])
+ def test_source_response_shape(self, endpoint: str) -> None:
+ source_response = lightfield_source(
+ api_key="sk_lf_test",
+ endpoint=endpoint,
+ team_id=123,
+ job_id="test_job",
+ api_version="2026-03-01",
+ )
+
+ assert source_response.name == endpoint
+ assert source_response.primary_keys == ["id"]
+ assert source_response.partition_keys == ["createdAt"]
+ assert source_response.partition_mode == "datetime"
+
+
+class TestCheckToken:
+ @parameterized.expand(
+ [
+ (
+ "active_key_with_scopes",
+ _make_http_response({"active": True, "scopes": ["accounts:read"], "tokenType": "api_key"}),
+ (True, ["accounts:read"], None),
+ ),
+ (
+ "active_key_without_scope_list",
+ _make_http_response({"active": True}),
+ (True, None, None),
+ ),
+ (
+ "inactive_key",
+ _make_http_response({"active": False, "scopes": []}),
+ (False, None, "This Lightfield API key is no longer active. Generate a new key and reconnect."),
+ ),
+ (
+ "unauthorized",
+ _make_http_response({"error": "unauthorized"}, status_code=401),
+ (False, None, "Invalid Lightfield API key. Check the key and try again."),
+ ),
+ (
+ "server_error",
+ _make_http_response({"error": "oops"}, status_code=503),
+ (False, None, "Lightfield returned an unexpected status (503) while validating the key."),
+ ),
+ ]
+ )
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.lightfield.lightfield.make_tracked_session"
+ )
+ def test_status_mapping(
+ self,
+ _name: str,
+ response: Response,
+ expected: tuple[bool, list[str] | None, str | None],
+ mock_session: MagicMock,
+ ) -> None:
+ mock_session.return_value.get.return_value = response
+
+ assert check_token("sk_lf_test", "2026-03-01") == expected
+
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.lightfield.lightfield.make_tracked_session"
+ )
+ def test_probe_sends_auth_and_version_headers(self, mock_session: MagicMock) -> None:
+ mock_session.return_value.get.return_value = _make_http_response({"active": True, "scopes": []})
+
+ check_token("sk_lf_test", "2026-03-01")
+
+ _, kwargs = mock_session.return_value.get.call_args
+ assert kwargs["headers"]["Authorization"] == "Bearer sk_lf_test"
+ assert kwargs["headers"]["Lightfield-Version"] == "2026-03-01"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lightfield/tests/test_lightfield_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lightfield/tests/test_lightfield_source.py
new file mode 100644
index 000000000000..10c5defaa754
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lightfield/tests/test_lightfield_source.py
@@ -0,0 +1,160 @@
+from unittest import mock
+
+from parameterized import parameterized
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.lightfield import (
+ LightfieldSourceConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.lightfield.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.lightfield.source import LightfieldSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+CHECK_TOKEN_PATH = "products.warehouse_sources.backend.temporal.data_imports.sources.lightfield.source.check_token"
+
+
+class TestLightfieldSource:
+ def setup_method(self):
+ self.source = LightfieldSource()
+ self.team_id = 123
+ self.config = LightfieldSourceConfig(api_key="sk_lf_test")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.LIGHTFIELD
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "Lightfield"
+ assert config.label == "Lightfield"
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/lightfield"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert not config.unreleasedSource
+ assert len(config.fields) == 1
+
+ api_key_field = config.fields[0]
+ assert isinstance(api_key_field, SourceFieldInputConfig)
+ assert api_key_field.name == "api_key"
+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD
+ assert api_key_field.required is True
+
+ def test_non_retryable_errors_matches_observed_error_message(self):
+ observed_error = "401 Client Error: Unauthorized for url: https://api.lightfield.app/v1/accounts?limit=25"
+
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable_errors)
+
+ @parameterized.expand(
+ [
+ ("stripe", "401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers"),
+ ("attio", "403 Client Error: Forbidden for url: https://api.attio.com/v2/self"),
+ ]
+ )
+ def test_non_retryable_errors_does_not_match_other_vendors(self, _name, other_vendor_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+
+ assert not any(key in other_vendor_error for key in non_retryable_errors)
+
+ def test_get_schemas_are_full_refresh_only(self):
+ schemas = self.source.get_schemas(self.config, self.team_id)
+
+ schema_names = {schema.name for schema in schemas}
+ assert schema_names == 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)
+
+ @parameterized.expand(
+ [
+ ("known_name", ["accounts"], ["accounts"]),
+ ("unknown_name", ["nonexistent"], []),
+ ]
+ )
+ def test_get_schemas_filtered_by_names(self, _name, names, expected):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=names)
+
+ assert [schema.name for schema in schemas] == expected
+
+ @parameterized.expand(
+ [
+ ("valid_key_no_schema", (True, ["accounts:read"], None), None, True, None),
+ ("invalid_key", (False, None, "Invalid Lightfield API key."), None, False, "Invalid Lightfield API key."),
+ ("schema_with_granted_scope", (True, ["accounts:read"], None), "accounts", True, None),
+ (
+ "schema_with_missing_scope",
+ (True, ["contacts:read"], None),
+ "accounts",
+ False,
+ "Your Lightfield API key is missing the `accounts:read` scope required to sync accounts.",
+ ),
+ ("schema_with_unknown_scopes", (True, None, None), "accounts", True, None),
+ ]
+ )
+ @mock.patch(CHECK_TOKEN_PATH)
+ def test_validate_credentials(self, _name, token_result, schema_name, expected_valid, expected_error, mock_check):
+ mock_check.return_value = token_result
+
+ is_valid, error = self.source.validate_credentials(self.config, self.team_id, schema_name=schema_name)
+
+ assert is_valid is expected_valid
+ assert error == expected_error
+ mock_check.assert_called_once_with(self.config.api_key, self.source.default_version)
+
+ @mock.patch(CHECK_TOKEN_PATH)
+ def test_get_endpoint_permissions_flags_missing_scopes(self, mock_check):
+ mock_check.return_value = (True, ["accounts:read", "tasks:read"], None)
+
+ permissions = self.source.get_endpoint_permissions(self.config, self.team_id, ["accounts", "contacts", "tasks"])
+
+ assert permissions == {
+ "accounts": None,
+ "contacts": "API key is missing the `contacts:read` scope",
+ "tasks": None,
+ }
+
+ @parameterized.expand(
+ [
+ ("scopes_unknown", (True, None, None)),
+ ("token_invalid", (False, None, "boom")),
+ ]
+ )
+ @mock.patch(CHECK_TOKEN_PATH)
+ def test_get_endpoint_permissions_never_blocks_without_scope_list(self, _name, token_result, mock_check):
+ mock_check.return_value = token_result
+
+ permissions = self.source.get_endpoint_permissions(self.config, self.team_id, ["accounts", "contacts"])
+
+ assert permissions == {"accounts": None, "contacts": None}
+
+ @mock.patch(CHECK_TOKEN_PATH)
+ def test_get_endpoint_permissions_swallows_probe_errors(self, mock_check):
+ mock_check.side_effect = Exception("network down")
+
+ permissions = self.source.get_endpoint_permissions(self.config, self.team_id, ["accounts"])
+
+ assert permissions == {"accounts": None}
+
+ @parameterized.expand(
+ [
+ ("no_pin_uses_default", None, "2026-03-01"),
+ ("pin_honored_verbatim", "2027-01-01", "2027-01-01"),
+ ]
+ )
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.lightfield.source.lightfield_source")
+ def test_source_for_pipeline_resolves_api_version(self, _name, pinned, expected_version, mock_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "accounts"
+ inputs.team_id = self.team_id
+ inputs.job_id = "job_1"
+ inputs.api_version = pinned
+
+ self.source.source_for_pipeline(self.config, inputs)
+
+ mock_source.assert_called_once_with(
+ api_key=self.config.api_key,
+ endpoint="accounts",
+ team_id=self.team_id,
+ job_id="job_1",
+ api_version=expected_version,
+ )