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): add 1 missing table to the Humanitix source (#125394)

Tom Owersbd23154434cc
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index 06f9ad42a0c4..609d3af7bc8e 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
@@ -6133,7 +6133,7 @@ Diffed against: <https://api.humanitix.com/v1/documentation/json>
- [x] `/v1/events/{eventId}/orders` — ticket orders with buyer and revenue data - the core transaction table for any ticketing analysis (high). Added as `orders` (fan-out over `events`).
- [x] `/v1/events/{eventId}/tickets` — individual issued tickets including attendee and check-in state, the line-item table under orders (high). Added as `tickets` (fan-out over `events`).
-- [ ] `/v1/events/{eventId}/check-in-count` — attendance vs sold counts per event, the headline event-day metric (medium). Skipped: the API marks it beta and subject to change, it needs a second fan-out over every event date, and it returns one aggregate object per date that a query over `tickets.checkIn` already reproduces.
+- [x] `/v1/events/{eventId}/check-in-count` — attendance vs sold counts per event, the headline event-day metric (medium). Added as `check_in_counts` (one request per non-deleted date in each event's `dates`). The API marks it beta.
- [ ] `/v1/global/event-dates` — occurrence/date rows for recurring events, needed to attribute orders to a specific date (medium). Skipped: it lists event dates from across the whole Humanitix platform rather than the account's own, and needs a permission Humanitix grants by hand. Orders and tickets already carry `eventDateId`, and `events.dates` lists each event's dates.
Note: Fetched the OpenAPI 3.0 spec directly. Orders and tickets are nested under /v1/events/{eventId}, so PostHog syncs them with a per-event fan-out over `events`.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/humanitix/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/humanitix/canonical_descriptions.py
index e02f9d1257fd..f77d27717200 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/humanitix/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/humanitix/canonical_descriptions.py
@@ -104,4 +104,14 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"updatedAt": "The date and time the ticket was last modified.",
},
},
+ "check_in_counts": {
+ "description": "The check-in count for one date of a Humanitix event, in total and by ticket type, for tickets that have had sales. The API marks this endpoint as beta.",
+ "docs_url": "https://api.humanitix.com/v1/documentation",
+ "columns": {
+ "eventId": "The ID of the event.",
+ "eventDateId": "The ID of the event date the counts are for.",
+ "checkedIn": "The number of check-ins across all ticket types.",
+ "ticketTypes": "The check-in count for each ticket type with sales, with the ticket type ID and name, sorted by check-ins in descending order.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/humanitix/humanitix.py b/products/warehouse_sources/backend/temporal/data_imports/sources/humanitix/humanitix.py
index 2ecb3d7b8b5b..ed1671647ea0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/humanitix/humanitix.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/humanitix/humanitix.py
@@ -1,18 +1,28 @@
import dataclasses
-from collections.abc import Iterable
+from collections.abc import Iterable, Iterator
from typing import Any, Optional, cast
from requests import Request, Response
+from posthog.dataclasses import frozen
+
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.auth import APIKeyAuth
+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.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.paginators import (
+ BasePaginator,
+ SinglePagePaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import RESTClient
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import ClientConfig
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe
@@ -37,6 +47,8 @@ class HumanitixResumeConfig:
# Fan-out endpoints (orders, tickets) resume by parent event: the child paths already fully
# synced, the one in progress, and its paginator state — see
# `common.rest_source.__init__._make_paginate_dependent_resource`.
+ # Check-in counts reuse `next_page` for the events page and `completed` for the
+ # `<eventId>:<eventDateId>` keys already fetched on it.
completed: Optional[list[str]] = None
current: Optional[str] = None
child_state: Optional[dict[str, Any]] = None
@@ -117,6 +129,90 @@ def _client_config(api_key: str) -> ClientConfig:
}
+# An event or event date can be deleted between the events listing and the check-in request.
+_IGNORE_NOT_FOUND = create_response_hooks([{"status_code": 404, "action": "ignore"}], resource_name="humanitix")
+
+
+def _rest_client(api_key: str) -> RESTClient:
+ return RESTClient(
+ base_url=HUMANITIX_BASE_URL,
+ headers=_headers(),
+ auth=APIKeyAuth(api_key=api_key, name="x-api-key", location="header"),
+ allowed_hosts=[],
+ allow_redirects=False,
+ capture=False,
+ )
+
+
+@frozen
+class _EventDateKey:
+ event_id: str
+ date_id: str
+
+ @property
+ def marker(self) -> str:
+ return f"{self.event_id}:{self.date_id}"
+
+
+def _event_date_keys(events: list[Any]) -> list[_EventDateKey]:
+ keys: list[_EventDateKey] = []
+ for event in events:
+ for date in event.get("dates") or []:
+ if date.get("_id") and not date.get("deleted"):
+ keys.append(_EventDateKey(event_id=event["_id"], date_id=date["_id"]))
+ return keys
+
+
+def _check_in_count_rows(
+ config: HumanitixEndpointConfig,
+ api_key: str,
+ resumable_source_manager: ResumableSourceManager[HumanitixResumeConfig],
+) -> Iterator[dict[str, Any]]:
+ client = _rest_client(api_key)
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ page = resume.next_page if resume else 1
+ # Full refresh appends without dedupe, so skip exactly the dates already fetched, even if the page changed.
+ done = list(resume.completed or []) if resume else []
+
+ for events in client.paginate(
+ path="/events",
+ params={"pageSize": PAGE_SIZE},
+ paginator=HumanitixPaginator(page_size=PAGE_SIZE, page=page),
+ data_selector="events",
+ data_selector_required=True,
+ ):
+ completed = done
+ skip = set(done)
+ for key in _event_date_keys(events):
+ event_id, date_id, marker = key.event_id, key.date_id, key.marker
+ if marker in skip:
+ continue
+ body: Optional[dict[str, Any]] = None
+ responded = False
+ for result in client.paginate(
+ path=config.path.format(eventId=event_id),
+ params={"eventDateId": date_id},
+ paginator=SinglePagePaginator(),
+ hooks=_IGNORE_NOT_FOUND,
+ ):
+ responded = True
+ if result and isinstance(result[0], dict):
+ body = result[0]
+ # Only a 404 (no response) means the date is gone; any other non-object body is a shape change.
+ if responded and body is None:
+ raise ValueError(f"Humanitix check-in count for {marker} returned a non-object body")
+ completed.append(marker)
+ resumable_source_manager.save_state(HumanitixResumeConfig(next_page=page, completed=list(completed)))
+ if body is None:
+ resumable_source_manager.safe_point()
+ continue
+ yield {**body, "eventId": event_id, "eventDateId": date_id}
+
+ done = []
+ page += 1
+ resumable_source_manager.safe_point()
+
+
def _make_source_response(
config: HumanitixEndpointConfig, items: Any, column_hints: Optional[dict[str, Any]] = None
) -> SourceResponse:
@@ -195,6 +291,9 @@ def humanitix_source(
) -> SourceResponse:
config = HUMANITIX_ENDPOINTS[endpoint]
+ if config.per_event_date:
+ return _make_source_response(config, lambda: _check_in_count_rows(config, api_key, resumable_source_manager))
+
if config.fanout is not None:
return _fanout_source(config, api_key, team_id, job_id, resumable_source_manager)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/humanitix/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/humanitix/settings.py
index 97a8ea1820d1..d7c2ee60ab42 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/humanitix/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/humanitix/settings.py
@@ -15,7 +15,8 @@ class HumanitixEndpointConfig:
path: str
# Key of the row array in the paginated response envelope; it differs per endpoint
# (e.g. `events` for /events, `tags` for /tags) even though the envelope shape is identical.
- list_key: str
+ # None for an endpoint that returns a single object instead of a list.
+ list_key: Optional[str] = None
# Humanitix objects are Mongo documents, so `_id` is a stable, globally unique primary key.
primary_keys: list[str] = field(default_factory=lambda: ["_id"])
# A stable (never-rewritten) datetime field to partition by.
@@ -26,6 +27,9 @@ class HumanitixEndpointConfig:
incremental_fields: list[Any] = field(default_factory=list)
default_incremental_field: Optional[str] = None
page_size: int = PAGE_SIZE
+ # Set for endpoints fetched once per event date. The dates come from each event's `dates` array,
+ # so the shared single-hop fan-out builder can't express this.
+ per_event_date: bool = False
# Orders and tickets are only listed per event. Fan out over `/events` and stamp the parent event id
@@ -40,8 +44,9 @@ _EVENT_FANOUT = DependentEndpointConfig(
# Humanitix Public API list endpoints. `/events` and `/tags` are account-scoped top-level lists;
-# orders and tickets fan out per event. The `/global/*` endpoints return the public marketplace
-# catalog rather than the account's own data, so they are not exposed here.
+# orders and tickets fan out per event, and check-in counts per event date. The `/global/*`
+# endpoints return the public marketplace catalog rather than the account's own data, so they are
+# not exposed here.
# All are full refresh only. Orders and tickets accept a `since` filter, but the API does not say
# which timestamp it compares, so a cursor on `updatedAt` could silently miss refunds and cancellations.
HUMANITIX_ENDPOINTS: dict[str, HumanitixEndpointConfig] = {
@@ -63,6 +68,13 @@ HUMANITIX_ENDPOINTS: dict[str, HumanitixEndpointConfig] = {
partition_key="createdAt",
fanout=_EVENT_FANOUT,
),
+ # Beta endpoint that returns one check-in summary object per event date, so it has no list key.
+ "check_in_counts": HumanitixEndpointConfig(
+ name="check_in_counts",
+ path="/events/{eventId}/check-in-count",
+ primary_keys=["eventId", "eventDateId"],
+ per_event_date=True,
+ ),
}
ENDPOINTS = tuple(HUMANITIX_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/humanitix/tests/test_humanitix.py b/products/warehouse_sources/backend/temporal/data_imports/sources/humanitix/tests/test_humanitix.py
index 71528c658390..f1821289d3a6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/humanitix/tests/test_humanitix.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/humanitix/tests/test_humanitix.py
@@ -123,6 +123,81 @@ class TestEventFanout:
)
+def _count(checked_in: int) -> ScriptedResponse:
+ return ScriptedResponse(
+ json={"checkedIn": checked_in, "ticketTypes": [{"ticketTypeId": "tt1", "checkedIn": checked_in}]}
+ )
+
+
+class TestCheckInCounts:
+ def test_fetches_one_count_per_live_event_date(self) -> None:
+ events: list[dict[str, Any]] = [
+ {"_id": "e1", "dates": [{"_id": "d1"}, {"_id": "d2", "deleted": True}]},
+ {"_id": "e2"},
+ {"_id": "e3", "dates": [{"_id": "d3"}, {"_id": "d4"}]},
+ ]
+ result = _driver().run(
+ "check_in_counts",
+ [
+ _page(events, total=3),
+ _count(5),
+ ScriptedResponse(status=404, json={"code": "event_not_found"}),
+ _count(0),
+ ],
+ )
+
+ assert result.raised is None
+ assert result.paths == [
+ "/v1/events",
+ "/v1/events/e1/check-in-count",
+ "/v1/events/e3/check-in-count",
+ "/v1/events/e3/check-in-count",
+ ]
+ assert result.params("eventDateId")[1:] == ["d1", "d3", "d4"]
+ assert [(row["eventId"], row["eventDateId"], row["checkedIn"]) for row in result.rows] == [
+ ("e1", "d1", 5),
+ ("e3", "d4", 0),
+ ]
+ assert result.response is not None
+ assert result.response.primary_keys == ["eventId", "eventDateId"]
+ assert result.saved_states[-1] == HumanitixResumeConfig(next_page=1, completed=["e1:d1", "e3:d3", "e3:d4"])
+
+ @parameterized.expand(
+ [
+ ("skips_completed_dates", HumanitixResumeConfig(next_page=2, completed=["e1:d1"]), ["d2", "d3"]),
+ (
+ "skips_completed_dates_after_one_is_removed",
+ HumanitixResumeConfig(next_page=2, completed=["e9:d9", "e1:d2"]),
+ ["d1", "d3"],
+ ),
+ ]
+ )
+ def test_resume(self, _name: str, resume_state: HumanitixResumeConfig, expected_dates: list[str]) -> None:
+ events = [{"_id": "e1", "dates": [{"_id": "d1"}, {"_id": "d2"}, {"_id": "d3"}]}]
+ result = _driver().run(
+ "check_in_counts",
+ [_page(events, total=PAGE_SIZE + 1)] + [_count(1) for _ in expected_dates],
+ resume_state=resume_state,
+ )
+
+ assert result.raised is None
+ assert result.params("page")[0] == "2"
+ assert result.params("eventDateId")[1:] == expected_dates
+ assert [row["eventDateId"] for row in result.rows] == expected_dates
+ # Every checkpoint keeps the dates finished before the restart, so a second restart skips them too.
+ for state in result.saved_states:
+ assert set(resume_state.completed or []) <= set(state.completed or [])
+
+ @parameterized.expand([("null", b"null"), ("empty_list", b"[]"), ("scalar", b"5")])
+ def test_non_object_count_body_fails_without_checkpoint(self, _name: str, body: bytes) -> None:
+ events = [{"_id": "e1", "dates": [{"_id": "d1"}]}]
+ result = _driver().run("check_in_counts", [_page(events, total=1), ScriptedResponse(body=body)])
+
+ assert isinstance(result.raised, ValueError)
+ assert result.rows == []
+ assert result.saved_states == []
+
+
class TestRetryAndErrors:
@parameterized.expand([("unauthorized", 401), ("forbidden", 403)])
def test_auth_errors_raise_without_retry(self, _name: str, status: int) -> None: