: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 huntr activity categories, tags and action metrics (#111524)
Tom Owersa0608dc1db2b
diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txtindex 50900d38c8e2..909b1d6aa310 100644--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt@@ -676,7 +676,6 @@1 products/warehouse_sources/backend/temporal/data_imports/sources/humanitix/humanitix.py1 products/warehouse_sources/backend/temporal/data_imports/sources/humanitix/settings.py1 products/warehouse_sources/backend/temporal/data_imports/sources/huntr/huntr.py-1 products/warehouse_sources/backend/temporal/data_imports/sources/huntr/settings.py1 products/warehouse_sources/backend/temporal/data_imports/sources/hyperspell/hyperspell.py1 products/warehouse_sources/backend/temporal/data_imports/sources/hyperspell/settings.py1 products/warehouse_sources/backend/temporal/data_imports/sources/imagga/settings.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 8a0899f077e1..a5a72f9df27d 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@@ -4188,10 +4188,10 @@ Today (8): `actions`, `activities`, `advisors`, `candidates`, `employers`, `job_Diffed against: <https://docs.huntr.co>-- [ ] `/org/events` — the job state transition log (JOB_CREATED, JOB_MOVED, JOB_OFFER_DATE_SET, interview dates) - the pipeline history behind jobs we already sync (high)-- [ ] `/org/activity-categories` — lookup resolving the category ID on every activity row we already sync (high)-- [ ] `/org/tags` — lookup resolving tag IDs applied across members, jobs and candidates (high)-- [ ] `/org/candidates/{id}/action-metrics` — per-candidate activity metrics - the engagement measure for candidates we already sync (high)+- [ ] `/org/events` — the job state transition log (JOB_CREATED, JOB_MOVED, JOB_OFFER_DATE_SET, interview dates) - the pipeline history behind jobs we already sync (high) — skipped: deprecated by Huntr in favor of `/org/actions` and `/org/activities`, which we already sync+- [x] `/org/activity-categories` — lookup resolving the category ID on every activity row we already sync (high). Added as `activity_categories`.+- [x] `/org/tags` — lookup resolving tag IDs applied across members, jobs and candidates (high). Added as `tags`.+- [x] `/org/candidates/{id}/action-metrics` — per-candidate activity metrics - the engagement measure for candidates we already sync (high). Added as `candidate_action_metrics` (fan-out over `candidates`, one row per candidate and action type).- [ ] `/org/goals` — goal definitions and targets that member progress is measured against (medium)- [ ] `/org/member-groups` — cohort/group membership for the members table, the main breakdown dimension (medium)- [ ] `/org/member-fields (and /org/members/{id}/member-fields)` — custom field definitions plus per-member values, the org's own segmentation attributes (medium)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/huntr/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/huntr/canonical_descriptions.pyindex be72cff2b64b..8981818fc0e2 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/huntr/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/huntr/canonical_descriptions.py@@ -80,4 +80,34 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"createdAt": "When the action was created (Unix seconds).",},},+ "activity_categories": {+ "description": "A category that classifies an activity, such as Apply, Phone Interview, or Offer Received.",+ "docs_url": "https://docs.huntr.co",+ "columns": {+ "id": "The unique ID of the activity category.",+ "name": "The name of the activity category.",+ },+ },+ "tags": {+ "description": "A tag the organization created to label records such as job posts.",+ "docs_url": "https://docs.huntr.co",+ "columns": {+ "id": "The unique ID of the tag.",+ "name": "The display name of the tag.",+ "description": "An internal description of what the tag means.",+ "color": "The hex color used to display the tag.",+ "targetObjects": "The types of record the tag can be applied to (for example JOB_POST).",+ },+ },+ "candidate_action_metrics": {+ "description": "Per-candidate counts of an action type that employers performed, such as viewing the candidate profile.",+ "docs_url": "https://docs.huntr.co",+ "columns": {+ "candidate_id": "The ID of the candidate the metrics belong to.",+ "action_type": "The action the metrics count (for example CANDIDATE_PROFILE_VIEWED).",+ "uniqueEmployersCt": "The number of unique employers that performed the action.",+ "totalCt": "The total number of times the action was performed.",+ "employers": "The employers that performed the action, each with its own count.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/huntr/huntr.py b/products/warehouse_sources/backend/temporal/data_imports/sources/huntr/huntr.pyindex 91141876cbbc..451a84119fea 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/huntr/huntr.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/huntr/huntr.py@@ -1,5 +1,5 @@import dataclasses-from typing import Any, Optional+from typing import Any, Optional, castfrom requests import Response@@ -8,18 +8,31 @@ 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 (+ DependentEndpointConfig,+ build_dependent_resource,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (JSONResponseCursorPaginator,+ SinglePagePaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.resource import Resource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (+ ClientConfig,+ Endpoint,)from 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.huntr.settings import HUNTR_ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.huntr.settings import (+ HUNTR_ENDPOINTS,+ HuntrEndpointConfig,+)HUNTR_BASE_URL = "https://api.huntr.co/org"-# The list endpoints accept a `limit`; the docs don't state a hard maximum, so 100 keeps each page-# reasonably sized while minimising round trips.-PAGE_SIZE = 100+# Bounds each request so a stalled connection cannot hold the worker, which matters most for the+# one-request-per-candidate fan-out.+REQUEST_TIMEOUT_SECONDS = 60# Cheap endpoint used to confirm an access token is genuine. The org access token is account-wide, so# one probe validates access to every list endpoint.DEFAULT_PROBE_PATH = "/members"@@ -49,6 +62,69 @@ def _headers(access_token: str) -> dict[str, str]:return {"Authorization": f"Bearer {access_token}", "Accept": "application/json"}+def _client_config(access_token: str, paginator: JSONResponseCursorPaginator | SinglePagePaginator) -> ClientConfig:+ return {+ "base_url": HUNTR_BASE_URL,+ # Only the non-secret Accept header goes here; auth (Bearer) is supplied via the framework+ # auth config so its value is redacted from logs and error messages.+ "headers": {"Accept": "application/json"},+ "auth": {"type": "bearer", "token": access_token},+ "paginator": paginator,+ "request_timeout": REQUEST_TIMEOUT_SECONDS,+ }+++def _cursor_paginator() -> HuntrCursorPaginator:+ return HuntrCursorPaginator(cursor_path="next", cursor_param="next")+++def _explode_action_metrics(row: dict[str, Any]) -> list[dict[str, Any]]:+ """Turn ``{"candidate_id": ..., "<ACTION_TYPE>": {...metrics}}`` into one row per action type."""+ candidate_id = row.get("candidate_id")+ return [+ {"candidate_id": candidate_id, "action_type": action_type, **metrics}+ for action_type, metrics in row.items()+ if action_type != "candidate_id" and isinstance(metrics, dict)+ ]+++def _fanout_source(+ access_token: str, config: HuntrEndpointConfig, fanout: DependentEndpointConfig, team_id: int, job_id: str+) -> SourceResponse:+ # Not resumable: the dependent-resource resume state lists every completed parent, which would+ # grow with the candidate count and be rewritten after each candidate.+ resource = cast(+ Resource,+ build_dependent_resource(+ endpoint_configs=HUNTR_ENDPOINTS,+ child_endpoint=config.name,+ fanout=fanout,+ client_config=_client_config(access_token, SinglePagePaginator()),+ path_format_values={},+ team_id=team_id,+ job_id=job_id,+ db_incremental_field_last_value=None,+ # The parent page size goes through `parent_params`; the per-candidate endpoint takes no `limit`.+ page_size_param=None,+ parent_endpoint_extra={+ "paginator": _cursor_paginator(),+ "data_selector": "data",+ "data_selector_malformed_retryable": True,+ },+ child_endpoint_extra={"paginator": SinglePagePaginator(), "data_selector": "$"},+ ),+ ).add_map(_explode_action_metrics)++ return SourceResponse(+ name=config.name,+ items=lambda: resource,+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ supports_resume=False,+ )++def huntr_source(access_token: str,endpoint: str,@@ -58,30 +134,24 @@ def huntr_source(db_incremental_field_last_value: Optional[Any] = None,) -> SourceResponse:config = HUNTR_ENDPOINTS[endpoint]+ if config.fanout is not None:+ return _fanout_source(access_token, config, config.fanout, team_id, job_id)++ endpoint_config: Endpoint = {+ "path": config.path,+ "params": {"limit": config.page_size},+ "data_selector": "data",+ # An unexpected 200-body shape (non-dict body, or `data` not a list) is treated as+ # transient and reissued rather than failing the import.+ "data_selector_malformed_retryable": True,+ }+ if not config.paginated:+ endpoint_config.update({"params": {}, "paginator": SinglePagePaginator(), "data_selector": "$"})rest_config: RESTAPIConfig = {- "client": {- "base_url": HUNTR_BASE_URL,- # Only the non-secret Accept header goes here; auth (Bearer) is supplied via the framework- # auth config so its value is redacted from logs and error messages.- "headers": {"Accept": "application/json"},- "auth": {"type": "bearer", "token": access_token},- "paginator": HuntrCursorPaginator(cursor_path="next", cursor_param="next"),- },+ "client": _client_config(access_token, _cursor_paginator()),"resource_defaults": {},- "resources": [- {- "name": endpoint,- "endpoint": {- "path": config.path,- "params": {"limit": PAGE_SIZE},- "data_selector": "data",- # An unexpected 200-body shape (non-dict body, or `data` not a list) is treated as- # transient and reissued rather than failing the import.- "data_selector_malformed_retryable": True,- },- }- ],+ "resources": [{"name": endpoint, "endpoint": endpoint_config}],}initial_paginator_state: Optional[dict[str, Any]] = Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/huntr/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/huntr/settings.pyindex 3d1a802d0d7e..e6772a9a0376 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/huntr/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/huntr/settings.py@@ -1,14 +1,27 @@from dataclasses import dataclass, field+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ DependentEndpointConfig,+)from products.warehouse_sources.backend.types import IncrementalField+# The list endpoints accept a `limit`; the docs don't state a hard maximum, so 100 keeps each page+# reasonably sized while minimising round trips.+PAGE_SIZE = 100-@dataclass++@dataclass(frozen=True)class HuntrEndpointConfig:name: strpath: str# Huntr object IDs are globally unique within an organization, so `id` is a safe primary key.primary_keys: list[str] = field(default_factory=lambda: ["id"])+ # False for endpoints that return a bare JSON array with no `next` cursor and take no `limit`.+ paginated: bool = True+ fanout: DependentEndpointConfig | None = None+ page_size: int = PAGE_SIZE+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ default_incremental_field: str | None = None# Huntr Organization API list endpoints (https://docs.huntr.co). All are full-refresh only: only the@@ -24,6 +37,25 @@ HUNTR_ENDPOINTS: dict[str, HuntrEndpointConfig] = {"employers": HuntrEndpointConfig(name="employers", path="/employers"),"activities": HuntrEndpointConfig(name="activities", path="/activities"),"actions": HuntrEndpointConfig(name="actions", path="/actions"),+ "activity_categories": HuntrEndpointConfig(name="activity_categories", path="/activity-categories"),+ "tags": HuntrEndpointConfig(name="tags", path="/tags", paginated=False),+ # One request per candidate. The response is an object keyed by action type, which huntr.py+ # explodes into one row per (candidate, action type).+ "candidate_action_metrics": HuntrEndpointConfig(+ name="candidate_action_metrics",+ path="/candidates/{candidate_id}/action-metrics",+ primary_keys=["candidate_id", "action_type"],+ fanout=DependentEndpointConfig(+ parent_name="candidates",+ resolve_param="candidate_id",+ resolve_field="id",+ include_from_parent=["id"],+ parent_field_renames={"id": "candidate_id"},+ parent_params={"limit": PAGE_SIZE},+ # A candidate deleted between the candidates listing and its metrics fetch must not fail the sync.+ child_response_actions=[{"status_code": 404, "action": "ignore"}],+ ),+ ),}ENDPOINTS = tuple(HUNTR_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/huntr/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/huntr/source.pyindex cf4a37a9500e..4b7ef5cc9ec3 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/huntr/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/huntr/source.py@@ -51,7 +51,7 @@ class HuntrSource(ResumableSource[HuntrSourceConfig, HuntrResumeConfig]):releaseStatus=ReleaseStatus.ALPHA,caption="""Enter your Huntr organization access token to pull your Organization API data into the PostHog Data warehouse.-You can generate an access token in your Huntr organization admin dashboard. The token grants read access to your members, advisors, candidates, jobs, job posts, employers, activities, and actions.+You can generate an access token in your Huntr organization admin dashboard. The token grants read access to your members, advisors, candidates, jobs, job posts, employers, activities, actions, activity categories, tags, and candidate action metrics.""",iconPath="/static/services/huntr.png",docsUrl="https://posthog.com/docs/cdp/sources/huntr",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/huntr/tests/test_huntr.py b/products/warehouse_sources/backend/temporal/data_imports/sources/huntr/tests/test_huntr.pyindex f980221663bc..968a5bc90ca2 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/huntr/tests/test_huntr.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/huntr/tests/test_huntr.py@@ -8,12 +8,15 @@ from parameterized import parameterizedfrom requests import HTTPError, Responsefrom products.warehouse_sources.backend.temporal.data_imports.sources.huntr.huntr import (- PAGE_SIZE,HuntrResumeConfig,huntr_source,validate_credentials,)-from products.warehouse_sources.backend.temporal.data_imports.sources.huntr.settings import ENDPOINTS, HUNTR_ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.huntr.settings import (+ ENDPOINTS,+ HUNTR_ENDPOINTS,+ PAGE_SIZE,+)# RESTClient builds its session via make_tracked_session in the rest_client module.CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"@@ -145,6 +148,46 @@ class TestPagination:assert session.send.call_count == 1manager.save_state.assert_not_called()+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_unpaginated_endpoint_reads_bare_array_in_one_request(self, MockSession) -> None:+ session = MockSession.return_value+ params = _wire(session, [_response([{"id": "t1", "name": "Hot Jobs"}, {"id": "t2", "name": "Exclusive"}])])++ rows = _rows(_source(_make_manager(), "tags"))++ assert rows == [{"id": "t1", "name": "Hot Jobs"}, {"id": "t2", "name": "Exclusive"}]+ assert session.send.call_count == 1+ assert params == [{}]+++class TestCandidateActionMetrics:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_fans_out_over_candidates_and_explodes_action_types(self, MockSession) -> None:+ session = MockSession.return_value+ metrics = {"uniqueEmployersCt": 1, "totalCt": 2, "employers": [{"id": "e1", "name": "Acme", "totalCt": 2}]}+ params = _wire(+ session,+ [+ _page([{"id": "c1"}, {"id": "c2"}], next_cursor="c2"),+ _response({"CANDIDATE_PROFILE_VIEWED": metrics, "OTHER_ACTION": {"totalCt": 5}}),+ # Candidate deleted between the listing and the metrics fetch.+ _response({"error": "not found"}, status=404),+ _page([{"id": "c3"}]),+ _response({}),+ ],+ )++ rows = _rows(_source(_make_manager(), "candidate_action_metrics"))++ assert rows == [+ {"candidate_id": "c1", "action_type": "CANDIDATE_PROFILE_VIEWED", **metrics},+ {"candidate_id": "c1", "action_type": "OTHER_ACTION", "totalCt": 5},+ ]+ assert session.send.call_count == 5+ assert params[0] == {"limit": PAGE_SIZE}+ assert params[3] == {"limit": PAGE_SIZE, "next": "c2"}+ assert "limit" not in params[1]+class TestErrorHandling:@parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])@@ -230,10 +273,6 @@ class TestHuntrSourceResponse:def test_source_response_shape(self, endpoint: str, MockSession) -> None:response = _source(_make_manager(), endpoint)assert response.name == endpoint- assert response.primary_keys == ["id"]+ assert response.primary_keys == HUNTR_ENDPOINTS[endpoint].primary_keys# No stable creation timestamp is guaranteed across every object, so we don't partition.assert response.partition_mode is None-- def test_every_endpoint_uses_id_primary_key(self) -> None:- assert all(config.primary_keys == ["id"] for config in HUNTR_ENDPOINTS.values())- assert set(HUNTR_ENDPOINTS) == set(ENDPOINTS)