: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(data-warehouse): add lattice reviews, reviewees, goal updates and tags tables (#113903)
Tom Owers67cb65677246
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.mdindex e66b8fc7ebb2..81a729f8e279 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@@ -5006,15 +5006,15 @@ Note: The spec has 365 paths. PostHog's `projects` table maps to /api/v1/session## Lattice — gaps-Today (6): `departments`, `feedbacks`, `goals`, `review_cycles`, `updates`, `users`+Today (10): `departments`, `feedbacks`, `goal_updates`, `goals`, `review_cycles`, `reviewees`, `reviews`, `tags`, `updates`, `users`Diffed against: <https://developers.lattice.com/reference>-- [ ] `GET /v1/reviewCycle/{id}/reviews (also /v1/reviewee/{id}/reviews)` — the actual performance reviews - the core analytical object of the review cycles already synced (high)-- [ ] `GET /v1/reviewCycle/{id}/reviewees` — membership table mapping users to review cycles, needed for participation and completion analysis (high)-- [ ] `GET /v1/goals/updates (and /v1/goals/{id}/updates)` — goal progress history - the state/transition trail behind the goals table; distinct from the synced 'updates' resource (high)+- [x] `GET /v1/reviewCycle/{id}/reviews (also /v1/reviewee/{id}/reviews)` — the actual performance reviews - the core analytical object of the review cycles already synced (high)+- [x] `GET /v1/reviewCycle/{id}/reviewees` — membership table mapping users to review cycles, needed for participation and completion analysis (high)+- [x] `GET /v1/goals/updates (and /v1/goals/{id}/updates)` — goal progress history - the state/transition trail behind the goals table; distinct from the synced 'updates' resource (high)- [ ] `GET /v1/user/{id}/tasks` — task records tied to goals and users, commonly wanted for follow-through analysis (medium)-- [ ] `GET /v1/tags` — lookup resolving tag ids that appear on goals, users and feedback (medium)+- [x] `GET /v1/tags` — lookup resolving tag ids that appear on goals, users and feedback (medium)- [ ] `GET /v1/user/{id}/customAttributes (+ /v1/customAttribute/{id}, /v1/customAttributeValue/{id})` — custom HR attributes per user plus the lookup that decodes their ids - the main segmentation dimension (medium)- [ ] `GET /v1/question/{id} and /v1/questionRevision/{id}` — lookup resolving question ids carried on reviews and feedback (fetch-by-id only, no list endpoint) (low)- [ ] `GET /v1/competency/{id}` — competency lookup referenced by review questions and ratings (low)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lattice/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lattice/canonical_descriptions.pyindex 275f6c163230..d27ca2076994 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/lattice/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lattice/canonical_descriptions.py@@ -78,6 +78,63 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {endDate="End date of the review cycle.",),},+ "goal_updates": {+ "description": "A progress update on a goal, recording its status and any change in progress at that point.",+ "docs_url": "https://developers.lattice.com/reference/api_getallgoalupdates",+ "columns": {+ "entityId": "Unique identifier (UUID) for the goal update.",+ "id": "Numeric ID of the goal update.",+ "goalId": "ID of the goal the update belongs to.",+ "comment": "Comment about the goal progress.",+ "status": "Status of the goal at the time of the update (green, amber, or red).",+ "increment": "Change in the goal's progress value recorded by this update.",+ },+ },+ "reviewees": {+ "description": "A user taking part in a review cycle as the person being reviewed.",+ "docs_url": "https://developers.lattice.com/reference/api_reviewcycle_reviewees",+ "columns": _columns(+ review_cycle_id="ID of the review cycle this row was fetched for.",+ externalUserId="The external user ID of the reviewee user.",+ reviewCycle="The review cycle this reviewee is a part of.",+ user="The user associated with this reviewee.",+ reviews="The list of reviews for this reviewee.",+ revieweeFacingPDFUrl="URL of the PDF shared with the reviewee. Null until the reviewee is closed.",+ managerFacingPDFUrl="URL of the PDF shared with the reviewee's manager. Null until the reviewee is closed.",+ closedAt="Time the reviewee was closed, after which reviews can no longer be submitted.",+ esignatureGivenAt="Time the reviewee gave their e-signature to confirm they received their review packet.",+ responsesReleasedAt="Time the review responses were released to the reviewee.",+ weightedScore="The reviewee's weighted score for the cycle.",+ ),+ },+ "reviews": {+ "description": "A review request in a review cycle: one reviewer answering one question about one reviewee.",+ "docs_url": "https://developers.lattice.com/reference/api_reviewcycle_reviews",+ "columns": {+ "id": "The API ID of the review request.",+ "review_cycle_id": "ID of the review cycle the review belongs to.",+ "reviewee": "The reviewee this request is about.",+ "reviewer": "The user writing this review.",+ "question": "The base question asked to the reviewer.",+ "questionRevision": "The revision of the question asked to the reviewer.",+ "competency": "The competency the question refers to, if any.",+ "goal": "The goal the question refers to, if any.",+ "reviewType": "The type or direction of the review: Self, Peer, Upward, Downward, or ScoredAttribute.",+ "response": "The reviewer's response, including rating and comment. Null if not yet written or not visible to the API key.",+ "calibratedResponse": "The response after calibration, if the review was calibrated.",+ "submittedAt": "Time the reviewer finalized the review request.",+ "calibrationEnded": "Whether the calibration phase has ended.",+ "parentReviewId": "ID of the parent review.",+ "questionIndex": "Zero-based position of the question within the review template.",+ "declinedAt": "Time the reviewer declined the review.",+ "isMostRecentDownwardReview": "Whether this is the most recent downward review for the reviewee in this cycle.",+ },+ },+ "tags": {+ "description": "A tag that can be applied to goals, users and feedback in Lattice.",+ "docs_url": "https://developers.lattice.com/reference/api_tags",+ "columns": _columns(name="The name of the tag."),+ },"updates": {"description": "A status update posted by a user in Lattice, often tied to goals or check-ins.","docs_url": "https://developers.lattice.com/reference/get-updates",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lattice/lattice.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lattice/lattice.pyindex 05cd24029c29..6640e9c5bbdb 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/lattice/lattice.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lattice/lattice.py@@ -9,32 +9,43 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resRESTAPIConfig,rest_api_resource,)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ build_dependent_resource,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import BasePaginator+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import ClientConfigfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse-from products.warehouse_sources.backend.temporal.data_imports.sources.lattice.settings import LATTICE_ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.lattice.settings import (+ LATTICE_ENDPOINTS,+ PAGE_SIZE,+)LATTICE_HOSTS = {"us": "https://api.latticehq.com","emea": "https://api.emea.latticehq.com",}-# Lattice's default page size is only 10; always request the max of 100.-PAGE_SIZE = 100[email protected](frozen=False)class LatticeResumeConfig:# Lattice cursor pagination: pass the previous page's endingCursor as# startingAfter; static params are rebuilt deterministically on resume.- starting_after: str+ starting_after: Optional[str] = None+ # Per-review-cycle endpoints checkpoint the shape `build_dependent_resource` emits:+ # which cycles finished and where the current one stopped.+ fanout_state: Optional[dict[str, Any]] = Noneclass LatticeCursorPaginator(BasePaginator):"""Lattice cursor pagination: the next page's ``startingAfter`` is the previouspage's ``endingCursor``. Pagination stops as soon as ``hasMore`` is false, thebody carries no ``endingCursor``, or the page returned no rows — the last of- which guards against a server that keeps advertising more with an empty page."""+ which guards against a server that keeps advertising more with an empty page.++ ``/v1/goals/updates`` reports the same cursor as ``pageInfo.endCursor`` and+ ``pageInfo.hasNextPage`` instead."""def __init__(self, cursor_param: str = "startingAfter") -> None:super().__init__()@@ -56,8 +67,13 @@ class LatticeCursorPaginator(BasePaginator):body = response.json()except Exception:body = None- ending_cursor = body.get("endingCursor") if isinstance(body, dict) else None- has_more = body.get("hasMore") if isinstance(body, dict) else None+ if not isinstance(body, dict):+ body = {}+ page_info = body.get("pageInfo")+ if not isinstance(page_info, dict):+ page_info = {}+ ending_cursor = body.get("endingCursor") or page_info.get("endCursor")+ has_more = body["hasMore"] if "hasMore" in body else page_info.get("hasNextPage")if data and has_more and ending_cursor:self._cursor_value = ending_cursorself._has_next_page = True@@ -119,15 +135,48 @@ def lattice_source(db_incremental_field_last_value: Optional[Any] = None,) -> SourceResponse:config = LATTICE_ENDPOINTS[endpoint]- base_url = _base_url(region)+ client_config: ClientConfig = {+ "base_url": _base_url(region),+ # Auth is supplied via the framework auth config so its value is redacted from logs.+ "auth": {"type": "bearer", "token": api_key},+ "paginator": LatticeCursorPaginator(),+ }++ resume: Optional[LatticeResumeConfig] = None+ if resumable_source_manager.can_resume():+ resume = resumable_source_manager.load_state()++ if config.fanout is not None:++ def save_fanout_checkpoint(state: Optional[dict[str, Any]]) -> None:+ if state:+ resumable_source_manager.save_state(LatticeResumeConfig(fanout_state=state))++ child = build_dependent_resource(+ endpoint_configs=LATTICE_ENDPOINTS,+ child_endpoint=endpoint,+ fanout=config.fanout,+ client_config=client_config,+ parent_endpoint_extra={"data_selector": "data"},+ child_endpoint_extra={"data_selector": "data"},+ path_format_values={},+ team_id=team_id,+ job_id=job_id,+ db_incremental_field_last_value=db_incremental_field_last_value,+ resume_hook=save_fanout_checkpoint,+ initial_paginator_state=resume.fanout_state if resume else None,+ )+ return SourceResponse(+ name=endpoint,+ items=lambda: child,+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ sort_mode="asc",+ )rest_config: RESTAPIConfig = {- "client": {- "base_url": base_url,- # Auth is supplied via the framework auth config so its value is redacted from logs.- "auth": {"type": "bearer", "token": api_key},- "paginator": LatticeCursorPaginator(),- },+ "client": client_config,"resource_defaults": {},"resources": [{@@ -142,10 +191,8 @@ def lattice_source(}initial_paginator_state: Optional[dict[str, Any]] = None- if resumable_source_manager.can_resume():- resume = resumable_source_manager.load_state()- if resume is not None:- initial_paginator_state = {"cursor": resume.starting_after}+ if resume is not None and resume.starting_after is not None:+ initial_paginator_state = {"cursor": resume.starting_after}def save_checkpoint(state: Optional[dict[str, Any]]) -> None:# Persist only when a next page remains; save AFTER a page is yielded so a crash re-yields@@ -165,7 +212,7 @@ def lattice_source(return SourceResponse(name=endpoint,items=lambda: resource,- primary_keys=[config.primary_key],+ primary_keys=config.primary_keys,partition_count=1,partition_size=1,sort_mode="asc",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lattice/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lattice/settings.pyindex 550e643d2c75..bd7af5e8c8ec 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/lattice/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lattice/settings.py@@ -1,17 +1,37 @@-from dataclasses import dataclass+from dataclasses import dataclass, field+from typing import Any+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ DependentEndpointConfig,+)-@dataclass+# Lattice's default page size is only 10; always request the max of 100.+PAGE_SIZE = 100++# Reviews and reviewees only exist per review cycle, so they fan out over `/v1/reviewCycles`.+REVIEW_CYCLE_FANOUT = DependentEndpointConfig(+ parent_name="review_cycles",+ resolve_param="review_cycle_id",+ resolve_field="id",+ include_from_parent=["id"],+ parent_field_renames={"id": "review_cycle_id"},+)+++@dataclass(frozen=False)class LatticeEndpointConfig:name: strpath: str- primary_key: str = "id"+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ fanout: DependentEndpointConfig | None = None+ page_size: int = PAGE_SIZE+ incremental_fields: list[Any] = field(default_factory=list)+ default_incremental_field: str | None = None# The Lattice Talent API v1 has no server-side incremental filters on any list# endpoint (Fivetran's connector re-imports every table each sync for the same-# reason), so every stream is an honest full refresh. Per-cycle fan-out streams-# (reviews/reviewees) are a possible follow-up.+# reason), so every stream is an honest full refresh.LATTICE_ENDPOINTS: dict[str, LatticeEndpointConfig] = {"users": LatticeEndpointConfig(name="users",@@ -25,6 +45,12 @@ LATTICE_ENDPOINTS: dict[str, LatticeEndpointConfig] = {name="goals",path="/v1/goals",),+ "goal_updates": LatticeEndpointConfig(+ name="goal_updates",+ path="/v1/goals/updates",+ # The numeric `id` is not documented as unique; `entityId` is the update's UUID.+ primary_keys=["entityId"],+ ),"feedbacks": LatticeEndpointConfig(name="feedbacks",path="/v1/feedbacks",@@ -33,6 +59,23 @@ LATTICE_ENDPOINTS: dict[str, LatticeEndpointConfig] = {name="review_cycles",path="/v1/reviewCycles",),+ "reviewees": LatticeEndpointConfig(+ name="reviewees",+ path="/v1/reviewCycle/{review_cycle_id}/reviewees",+ fanout=REVIEW_CYCLE_FANOUT,+ ),+ "reviews": LatticeEndpointConfig(+ name="reviews",+ path="/v1/reviewCycle/{review_cycle_id}/reviews",+ # Unlike reviewees, reviews have no fetch-by-id endpoint, so the id is only known+ # to be unique within its cycle.+ primary_keys=["review_cycle_id", "id"],+ fanout=REVIEW_CYCLE_FANOUT,+ ),+ "tags": LatticeEndpointConfig(+ name="tags",+ path="/v1/tags",+ ),"updates": LatticeEndpointConfig(name="updates",path="/v1/updates",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lattice/tests/test_lattice.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lattice/tests/test_lattice.pyindex 711a41ea77af..ea3fdb72eb00 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/lattice/tests/test_lattice.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lattice/tests/test_lattice.py@@ -23,9 +23,17 @@ LATTICE_SESSION_PATCH = (def _response(- items: list[dict[str, Any]] | None, *, has_more: bool = False, ending_cursor: str | None = None+ items: list[dict[str, Any]] | None,+ *,+ has_more: bool = False,+ ending_cursor: str | None = None,+ page_info: bool = False,) -> Response:- body: dict[str, Any] = {"data": items or [], "hasMore": has_more, "endingCursor": ending_cursor}+ body: dict[str, Any] = (+ {"data": items or [], "pageInfo": {"endCursor": ending_cursor, "hasNextPage": has_more}}+ if page_info+ else {"data": items or [], "hasMore": has_more, "endingCursor": ending_cursor}+ )resp = Response()resp.status_code = 200resp._content = json.dumps(body).encode()@@ -116,19 +124,27 @@ class TestValidateCredentials:class TestPagination:+ @pytest.mark.parametrize(+ "endpoint, page_info",+ [+ ("users", False),+ # /v1/goals/updates nests the cursor under pageInfo instead of the top level.+ ("goal_updates", True),+ ],+ )@mock.patch(CLIENT_SESSION_PATCH)- def test_paginates_via_ending_cursor(self, MockSession):+ def test_paginates_via_ending_cursor(self, MockSession, endpoint, page_info):session = MockSession.return_valuesnaps = _wire(session,[- _response([{"id": "1"}], has_more=True, ending_cursor="cur_abc"),- _response([{"id": "2"}], has_more=False),+ _response([{"id": "1"}], has_more=True, ending_cursor="cur_abc", page_info=page_info),+ _response([{"id": "2"}], has_more=False, page_info=page_info),],)manager = _make_manager()- rows = _rows(_source("us", "users", manager))+ rows = _rows(_source("us", endpoint, manager))assert [r["id"] for r in rows] == ["1", "2"]# Checkpoint saved after the first page (points at the next cursor); the second page ends it.@@ -145,3 +161,53 @@ class TestPagination:list(_source("us", "users", manager).items())assert snaps[0]["params"]["startingAfter"] == "cur_resume"+++class TestReviewCycleFanout:+ @pytest.mark.parametrize(+ "endpoint, resume_state, expected_child_urls",+ [+ (+ "reviews",+ None,+ [+ "https://api.latticehq.com/v1/reviewCycle/c1/reviews",+ "https://api.latticehq.com/v1/reviewCycle/c2/reviews",+ ],+ ),+ (+ "reviewees",+ None,+ [+ "https://api.latticehq.com/v1/reviewCycle/c1/reviewees",+ "https://api.latticehq.com/v1/reviewCycle/c2/reviewees",+ ],+ ),+ (+ "reviews",+ LatticeResumeConfig(+ fanout_state={"completed": ["/v1/reviewCycle/c1/reviews"], "current": None, "child_state": None}+ ),+ ["https://api.latticehq.com/v1/reviewCycle/c2/reviews"],+ ),+ ],+ )+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_fans_out_over_review_cycles(self, MockSession, endpoint, resume_state, expected_child_urls):+ session = MockSession.return_value+ child_responses = {+ "https://api.latticehq.com/v1/reviewCycle/c1/" + endpoint: _response([{"id": "r1"}]),+ "https://api.latticehq.com/v1/reviewCycle/c2/" + endpoint: _response([{"id": "r1"}]),+ }+ snaps = _wire(session, [])+ session.send.side_effect = lambda *_args, **_kwargs: (+ _response([{"id": "c1"}, {"id": "c2"}]) if len(snaps) == 1 else child_responses[snaps[-1]["url"]]+ )++ rows = _rows(_source("us", endpoint, _make_manager(resume_state)))++ assert snaps[0]["url"] == "https://api.latticehq.com/v1/reviewCycles"+ assert [s["url"] for s in snaps[1:]] == expected_child_urls+ # Review ids repeat across cycles, so each row must carry its cycle for the composite key.+ expected_cycles = [url.split("/")[-2] for url in expected_child_urls]+ assert [(r["review_cycle_id"], r["id"]) for r in rows] == [(c, "r1") for c in expected_cycles]