: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(warehouse-sources): add lightfield custom objects and definitions tables (#114506)
Tom Owers1d805e93ebf3
diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txtindex d4a83c09bca7..7c344c30b37f 100644--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt@@ -760,7 +760,6 @@1 products/warehouse_sources/backend/temporal/data_imports/sources/lever/lever.py1 products/warehouse_sources/backend/temporal/data_imports/sources/lever/settings.py1 products/warehouse_sources/backend/temporal/data_imports/sources/lightdash/settings.py-1 products/warehouse_sources/backend/temporal/data_imports/sources/lightfield/settings.py1 products/warehouse_sources/backend/temporal/data_imports/sources/linear/linear.py1 products/warehouse_sources/backend/temporal/data_imports/sources/linear/settings.py1 products/warehouse_sources/backend/temporal/data_imports/sources/linearb/linearb.pydiff --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.mdindex 4fbfe33164ac..3d5345df4b30 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@@ -5159,8 +5159,8 @@ Today (9): `accounts`, `contacts`, `emails`, `lists`, `meetings`, `members`, `noDiffed against: <https://docs.lightfield.app/api/resources/object/methods/list/>-- [ ] `objects/{entitySlug} (custom object records)` — customer-defined CRM objects - the only entity type with records that PostHog does not expose at all (high)-- [ ] `{resource}/definitions (account, contact, opportunity, meeting, note, task, object)` — field/attribute definitions - the lookup that resolves the custom field slugs appearing inside the fields map on every record we already sync (medium)+- [x] `objects/{entitySlug} (custom object records)` — customer-defined CRM objects - the only entity type with records that PostHog does not expose at all (high)+- [x] `{resource}/definitions (account, contact, opportunity, meeting, note, task, object)` — field/attribute definitions - the lookup that resolves the custom field slugs appearing inside the fields map on every record we already sync (medium)Note: Lightfield's full resource list is account, contact, email, file, list, meeting, member, note, object, opportunity, task (plus auth/merge helpers), so PostHog already covers 9 of 11. Custom objects are addressed dynamically by entitySlug (GET /v1/objects/{entitySlug}), so implementing them requires discovering the slugs at sync time rather than a static table list. File endpoints were excluded as uploads/plumbing.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.pyindex 50cc1a52e734..50cd726f5ff2 100644--- 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@@ -62,4 +62,40 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"objectType": "Lightfield object type of the record.",},},+ "custom_objects": {+ "description": "Records of the customer-defined custom object types in Lightfield, across every type the API key can read.",+ "docs_url": "https://docs.lightfield.app/api/resources/object/methods/list/",+ "columns": {+ **_COMMON_COLUMNS,+ "objectType": "Slug of the custom object type the record belongs to.",+ },+ },+ "field_definitions": {+ "description": "Field definitions for each Lightfield object type, including system and custom fields. Resolves the field slugs used as keys in the fields map of each record.",+ "docs_url": "https://docs.lightfield.app/using-the-api/fields-and-relationships/",+ "columns": {+ "ownerObjectType": "Object type the field belongs to, such as account, contact, or a custom object slug.",+ "key": "Field key as it appears in the fields map of a record. System fields start with $.",+ "id": "Unique identifier of the field definition.",+ "label": "Human-readable display name of the field.",+ "description": "Description of the field, or null.",+ "valueType": "Data type of the field, such as TEXT, NUMBER, CURRENCY, or SINGLE_SELECT.",+ "typeConfiguration": "Type-specific configuration, such as select options, currency code, or uniqueness.",+ "readOnly": "True for fields that the API cannot write, such as AI-generated summaries.",+ },+ },+ "relationship_definitions": {+ "description": "Relationship definitions for each Lightfield object type. Resolves the relationship keys used in the relationships map of each record.",+ "docs_url": "https://docs.lightfield.app/using-the-api/fields-and-relationships/",+ "columns": {+ "ownerObjectType": "Object type the relationship belongs to, such as account, contact, or a custom object slug.",+ "objectType": "Type of the related object, such as account or contact.",+ "key": "Relationship key as it appears in the relationships map of a record. System relationships start with $.",+ "id": "Unique identifier of the relationship definition.",+ "label": "Human-readable display name of the relationship.",+ "description": "Description of the relationship, or null.",+ "cardinality": "Whether the relationship is HAS_ONE or HAS_MANY.",+ "directions": "Directional metadata for a self-referential relationship.",+ },+ },}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.pyindex f727b7b82c71..36f719d65b3e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/lightfield/lightfield.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lightfield/lightfield.py@@ -1,17 +1,30 @@+from collections.abc import Callable, Iterable, Iteratorfrom typing import Any+from urllib.parse import quotefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_sessionfrom 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.auth import BearerTokenAuth+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.config_setup import (+ create_response_hooks,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (OffsetPaginator,+ SinglePagePaginator,)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import RESTClientfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.lightfield.settings import (+ CUSTOM_OBJECTS_ENDPOINT,+ DEFINITION_ENDPOINTS,LIGHTFIELD_ENDPOINTS,LIGHTFIELD_PAGE_SIZE,+ STANDARD_DEFINITION_RESOURCES,+ LightfieldDefinitionResource,+ LightfieldEndpointConfig,)LIGHTFIELD_BASE_URL = "https://api.lightfield.app"@@ -26,6 +39,81 @@ def _version_headers(api_version: str) -> dict[str, str]:}+def _client(api_key: str, api_version: str) -> RESTClient:+ return RESTClient(+ base_url=LIGHTFIELD_BASE_URL,+ headers=_version_headers(api_version),+ auth=BearerTokenAuth(token=api_key),+ )+++def _object_path(object_type: str) -> str:+ return f"/v1/objects/{quote(object_type, safe='')}"+++def _list_custom_object_types(client: RESTClient, *, tolerate_denied: bool) -> list[str]:+ # The definitions tables still sync the standard types when custom objects are not+ # available to the key or the workspace plan.+ hooks = (+ create_response_hooks([{"status_code": 403, "action": "ignore"}, {"status_code": 404, "action": "ignore"}])+ if tolerate_denied+ else None+ )+ return [+ str(item["objectType"])+ for page in client.paginate(+ path="/v1/objects", paginator=SinglePagePaginator(), data_selector="data", hooks=hooks+ )+ for item in page+ if item.get("objectType")+ ]+++def _custom_object_records(client: RESTClient) -> Iterator[list[dict[str, Any]]]:+ for object_type in _list_custom_object_types(client, tolerate_denied=False):+ for page in client.paginate(+ path=_object_path(object_type),+ paginator=OffsetPaginator(limit=LIGHTFIELD_PAGE_SIZE, total_path="totalCount"),+ data_selector="data",+ ):+ yield [{**record, "objectType": object_type} for record in page]+++def _definition_rows(client: RESTClient, definitions_key: str) -> Iterator[list[dict[str, Any]]]:+ resources = list(STANDARD_DEFINITION_RESOURCES) + [+ LightfieldDefinitionResource(object_type=object_type, path=f"{_object_path(object_type)}/definitions")+ for object_type in _list_custom_object_types(client, tolerate_denied=True)+ ]+ # Each type needs its own read scope, so a key without one skips that type.+ hooks = create_response_hooks([{"status_code": 403, "action": "ignore"}])+ for resource in resources:+ bodies = [+ body+ for page in client.paginate(path=resource.path, paginator=SinglePagePaginator(), hooks=hooks)+ for body in page+ ]+ # Yield one item per request, even an empty one: the pipeline checks for a worker shutdown on each item.+ yield [+ {**definition, "ownerObjectType": resource.object_type, "key": key}+ for body in bodies+ for key, definition in (body.get(definitions_key) or {}).items()+ ]+++def _source_response(endpoint_config: LightfieldEndpointConfig, items: Callable[[], Iterable[Any]]) -> SourceResponse:+ partition_key = endpoint_config.partition_key+ return SourceResponse(+ name=endpoint_config.name,+ items=items,+ primary_keys=list(endpoint_config.primary_keys),+ partition_count=1 if partition_key else None,+ partition_size=1 if partition_key else None,+ partition_mode="datetime" if partition_key else None,+ partition_format="month" if partition_key else None,+ partition_keys=[partition_key] if partition_key else None,+ )++def lightfield_source(api_key: str,endpoint: str,@@ -35,6 +123,15 @@ def lightfield_source() -> SourceResponse:endpoint_config = LIGHTFIELD_ENDPOINTS[endpoint]+ if endpoint == CUSTOM_OBJECTS_ENDPOINT:+ client = _client(api_key, api_version)+ return _source_response(endpoint_config, lambda: _custom_object_records(client))++ if endpoint in DEFINITION_ENDPOINTS:+ client = _client(api_key, api_version)+ definitions_key = DEFINITION_ENDPOINTS[endpoint]+ return _source_response(endpoint_config, lambda: _definition_rows(client, definitions_key))+config: RESTAPIConfig = {"client": {"base_url": LIGHTFIELD_BASE_URL,@@ -66,16 +163,7 @@ def lightfield_source(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],- )+ return _source_response(endpoint_config, lambda: resource)def check_token(api_key: str, api_version: str) -> tuple[bool, list[str] | None, str | 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.pyindex 58e1fa18899a..30b08d277291 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/lightfield/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lightfield/settings.py@@ -6,23 +6,21 @@ from products.warehouse_sources.backend.types import IncrementalFieldLIGHTFIELD_PAGE_SIZE = 25-@dataclass+@dataclass(frozen=True)class LightfieldEndpointConfig:name: strpath: str- scope: str- primary_key: str = "id"+ # None when no single read scope covers the endpoint.+ scope: str | None+ primary_keys: tuple[str, ...] = ("id",)# `createdAt` is stable per record; `updatedAt` changes on every write and would# rewrite partitions each sync.- partition_key: str = "createdAt"+ partition_key: str | None = "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"),@@ -35,8 +33,58 @@ LIGHTFIELD_ENDPOINTS: dict[str, LightfieldEndpointConfig] = {"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"),+ # Custom object types are discovered at sync time, so every type lands in one table keyed by+ # its `objectType` slug. Record ids are only documented as unique per type.+ "custom_objects": LightfieldEndpointConfig(+ name="custom_objects",+ path="/v1/objects",+ scope=None,+ primary_keys=("objectType", "id"),+ ),+ # One row per field or relationship definition, across the standard and custom object types.+ # Relationship definitions already use `objectType` for the related type, so the owning type is+ # `ownerObjectType`.+ "field_definitions": LightfieldEndpointConfig(+ name="field_definitions",+ path="/v1/{resource}/definitions",+ scope=None,+ primary_keys=("ownerObjectType", "key"),+ partition_key=None,+ ),+ "relationship_definitions": LightfieldEndpointConfig(+ name="relationship_definitions",+ path="/v1/{resource}/definitions",+ scope=None,+ primary_keys=("ownerObjectType", "key"),+ partition_key=None,+ ),+}++CUSTOM_OBJECTS_ENDPOINT = "custom_objects"++# Definitions table name -> the map in the `/definitions` response it flattens.+DEFINITION_ENDPOINTS: dict[str, str] = {+ "field_definitions": "fieldDefinitions",+ "relationship_definitions": "relationshipDefinitions",}++@dataclass(frozen=True)+class LightfieldDefinitionResource:+ object_type: str+ path: str+++# Standard object types with a `/definitions` endpoint. Lists, members, and emails have none.+STANDARD_DEFINITION_RESOURCES: tuple[LightfieldDefinitionResource, ...] = (+ LightfieldDefinitionResource(object_type="account", path="/v1/accounts/definitions"),+ LightfieldDefinitionResource(object_type="contact", path="/v1/contacts/definitions"),+ LightfieldDefinitionResource(object_type="opportunity", path="/v1/opportunities/definitions"),+ LightfieldDefinitionResource(object_type="meeting", path="/v1/meetings/definitions"),+ LightfieldDefinitionResource(object_type="task", path="/v1/tasks/definitions"),+ LightfieldDefinitionResource(object_type="note", path="/v1/notes/definitions"),+)+ENDPOINTS = tuple(LIGHTFIELD_ENDPOINTS.keys())# No endpoint exposes a server-side timestamp filter (see the note above), so nothing isdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lightfield/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lightfield/source.pyindex 8411358a1ab6..94b91b3dd08a 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@@ -82,7 +82,7 @@ class LightfieldSource(SimpleSource[LightfieldSourceConfig]):# 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:+ if endpoint is not None and endpoint.scope 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}.",@@ -107,7 +107,7 @@ class LightfieldSource(SimpleSource[LightfieldSourceConfig]):permissions: dict[str, str | None] = {}for name in endpoints:endpoint = LIGHTFIELD_ENDPOINTS.get(name)- if endpoint is None or endpoint.scope in granted:+ if endpoint is None or endpoint.scope is None or endpoint.scope in granted:permissions[name] = Noneelse:permissions[name] = f"API key is missing the `{endpoint.scope}` scope"@@ -141,6 +141,8 @@ You can create an API key in your Lightfield settings (admin access required). G- `lists:read` - lists- `members:read` - members- `emails:read` - emails++Custom objects need no extra scope. The field and relationship definitions tables include each object type the key can read.""",docsUrl="https://posthog.com/docs/cdp/sources/lightfield",iconPath="/static/services/lightfield.png",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.pyindex 3c7b53a4658e..8d8fe5d0a624 100644--- 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@@ -1,16 +1,23 @@import jsonfrom typing import Any+from urllib.parse import parse_qs, urlparse+import pytestfrom unittest.mock import MagicMock, patch+import responsesfrom parameterized import parameterized-from requests import Response+from requests import HTTPError, Responsefrom 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+from products.warehouse_sources.backend.temporal.data_imports.sources.lightfield.settings import (+ STANDARD_DEFINITION_RESOURCES,+)++BASE = "https://api.lightfield.app"def _make_http_response(body: Any, status_code: int = 200) -> Response:@@ -21,21 +28,130 @@ def _make_http_response(body: Any, status_code: int = 200) -> Response:return resp+def _source(endpoint: str):+ return lightfield_source(+ api_key="sk_lf_test",+ endpoint=endpoint,+ team_id=123,+ job_id="test_job",+ api_version="2026-03-01",+ )+++def _rows(endpoint: str) -> list[dict[str, Any]]:+ return [row for page in _source(endpoint).items() for row in page]++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",- )+ @parameterized.expand(+ [+ ("accounts", ["id"], ["createdAt"], "datetime"),+ ("custom_objects", ["objectType", "id"], ["createdAt"], "datetime"),+ ("field_definitions", ["ownerObjectType", "key"], None, None),+ ("relationship_definitions", ["ownerObjectType", "key"], None, None),+ ]+ )+ def test_source_response_shape(+ self,+ endpoint: str,+ primary_keys: list[str],+ partition_keys: list[str] | None,+ partition_mode: str | None,+ ) -> None:+ source_response = _source(endpoint)assert source_response.name == endpoint- assert source_response.primary_keys == ["id"]- assert source_response.partition_keys == ["createdAt"]- assert source_response.partition_mode == "datetime"+ assert source_response.primary_keys == primary_keys+ assert source_response.partition_keys == partition_keys+ assert source_response.partition_mode == partition_mode+++class TestCustomObjects:+ @responses.activate+ def test_walks_every_type_to_its_terminal_page_and_tags_rows(self) -> None:+ responses.get(+ f"{BASE}/v1/objects",+ json={"data": [{"objectType": "project", "label": "Project"}, {"objectType": "vendor", "label": "Vendor"}]},+ )+ first_page = [{"id": f"p{i}", "createdAt": "2026-01-01T00:00:00Z"} for i in range(25)]+ responses.get(f"{BASE}/v1/objects/project", json={"data": first_page, "totalCount": 26})+ responses.get(f"{BASE}/v1/objects/project", json={"data": [{"id": "p25"}], "totalCount": 26})+ responses.get(f"{BASE}/v1/objects/vendor", json={"data": [{"id": "p0"}], "totalCount": 1})++ rows = _rows("custom_objects")++ assert [(row["objectType"], row["id"]) for row in rows] == [+ *[("project", f"p{i}") for i in range(26)],+ ("vendor", "p0"),+ ]+ record_calls = [call for call in responses.calls if urlparse(call.request.url).path != "/v1/objects"]+ assert [+ (urlparse(call.request.url).path, parse_qs(urlparse(call.request.url).query)["offset"])+ for call in record_calls+ ] == [("/v1/objects/project", ["0"]), ("/v1/objects/project", ["25"]), ("/v1/objects/vendor", ["0"])]+ assert all(call.request.headers["Lightfield-Version"] == "2026-03-01" for call in responses.calls)++ @responses.activate+ def test_unavailable_custom_objects_fail_the_table(self) -> None:+ responses.get(f"{BASE}/v1/objects", json={"error": "forbidden"}, status=403)++ with pytest.raises(HTTPError):+ _rows("custom_objects")+++class TestDefinitions:+ @parameterized.expand(+ [+ ("custom_objects_listed", 200, ["account", "contact", "project"]),+ ("custom_objects_unavailable", 404, ["account", "contact"]),+ ]+ )+ @responses.activate+ def test_flattens_each_readable_type(self, _name: str, objects_status: int, expected_owners: list[str]) -> None:+ responses.get(+ f"{BASE}/v1/objects",+ json={"data": [{"objectType": "project", "label": "Project"}]},+ status=objects_status,+ )+ readable = {"account", "contact"}+ for resource in STANDARD_DEFINITION_RESOURCES:+ if resource.object_type in readable:+ responses.get(+ f"{BASE}{resource.path}",+ json={+ "objectType": resource.object_type,+ "fieldDefinitions": {"$name": {"label": "Name", "valueType": "TEXT"}},+ "relationshipDefinitions": {+ "$owner": {"label": "Owner", "cardinality": "HAS_ONE", "objectType": "member"}+ },+ },+ )+ else:+ responses.get(f"{BASE}{resource.path}", json={"error": "missing scope"}, status=403)+ responses.get(+ f"{BASE}/v1/objects/project/definitions",+ json={+ "objectType": "project",+ "fieldDefinitions": {"budget": {"label": "Budget", "valueType": "CURRENCY"}},+ "relationshipDefinitions": {},+ },+ )++ field_rows = _rows("field_definitions")+ relationship_rows = _rows("relationship_definitions")++ assert [row["ownerObjectType"] for row in field_rows] == expected_owners+ assert {(row["ownerObjectType"], row["key"]) for row in field_rows} >= {("account", "$name")}+ assert relationship_rows == [+ {+ "label": "Owner",+ "cardinality": "HAS_ONE",+ "objectType": "member",+ "ownerObjectType": owner,+ "key": "$owner",+ }+ for owner in ["account", "contact"]+ ]class TestCheckToken: