: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 fullstory segments, sessions and events tables (#109135)
Tom Owers28dfad268991
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 96f4acbd3048..1a74f680067f 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@@ -3465,18 +3465,18 @@ Note: Fulcrum's REST reference nav lists 182 pages. PostHog covers nearly every## FullStory — **thin**-Today (1): `users`+Today (4): `events`, `segments`, `sessions`, `users`Diffed against: <https://developer.fullstory.com/server/sessions/introduction/>-- [ ] `v1 segments/{id}/export + operations (session and event export)` — the entire session and event stream — Fullstory's headline data and the reason to sync it at all; requires the async export job pattern (high)-- [ ] `v2 sessions/{uid} (list sessions per user)` — session replay URLs and session metadata joined to the users already synced; drivable by iterating the users table (high)-- [ ] `v1 segments (list segments)` — lookup naming each segment, and the handle needed to scope any export (high)-- [ ] `v2 sessions/{id}/events (get session events)` — per-session event detail for funnel and rage-click analysis (medium)+- [x] `v1 segments/{id}/export + operations (session and event export)` — the entire session and event stream — Fullstory's headline data and the reason to sync it at all; requires the async export job pattern (high). Added as `events`: an append-only event export of the built-in `everyone` segment, one export job per day window, incremental on `EventStart`.+- [x] `v2 sessions/{uid} (list sessions per user)` — session replay URLs and session metadata joined to the users already synced; drivable by iterating the users table (high). Added as `sessions` (fan-out over identified `users`). The endpoint is unpaginated and returns each user's most recent sessions only.+- [x] `v1 segments (list segments)` — lookup naming each segment, and the handle needed to scope any export (high). Added as `segments`.+- [ ] `v2 sessions/{id}/events (get session events)` — per-session event detail for funnel and rage-click analysis (medium). Skipped: Fullstory documents the real-time Sessions API as not intended for data export, it would need a second fan-out level (one request per session), and `events` already carries the same events in bulk.- [ ] `v2 datasets (list datasets)` — lookup describing the exportable datasets available to the account (medium)- [ ] `v1 exports/get-user-events` — per-user event history, an alternative to the segment export for smaller pulls (medium)-Note: The source hard-codes ENDPOINTS = ("users",) in fullstory/fullstory.py with a comment that session/event data only exists behind Fullstory's async Data Export jobs — that is accurate for bulk pulls. Note the v2 /sessions list endpoint is per-user (requires uid, email or session_uid) and is not paginated, so it would have to be driven off the synced users table rather than listed directly. Bulk session and event data comes from the v1 segment-export / operations workflow, which is async but resumable.+Note: `events` uses the v1 segment-export / operations workflow, which is async but resumable. The v2 /sessions list endpoint is per-user (requires uid, email or session_uid) and is not paginated, so `sessions` is driven off the identified users listing rather than listed directly.## FusionAuth — gapsdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/fullstory/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fullstory/canonical_descriptions.pyindex f184dd9d696a..98548fe29075 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/fullstory/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fullstory/canonical_descriptions.py@@ -1,6 +1,6 @@"""Canonical, documentation-sourced descriptions for Fullstory endpoints and columns.-Sourced from the official Fullstory Server API v2 reference (https://developer.fullstory.com/server/v2/).+Sourced from the official Fullstory Server API reference (https://developer.fullstory.com/server/).Keyed by the endpoint names in `fullstory.py` `ENDPOINTS`, which match the `ExternalDataSchema.name`of a synced Fullstory table. Columns absent here fall back to LLM enrichment."""@@ -23,4 +23,41 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"created": "Time at which the user record was created in Fullstory.",},},+ "segments": {+ "description": "A saved Fullstory segment: a named set of filters over users and their activity.",+ "docs_url": "https://developer.fullstory.com/server/v1/segments/list-segments/",+ "columns": {+ "id": "Unique identifier for the segment.",+ "name": "Display name of the segment.",+ "creator": "Email of the Fullstory user who created the segment.",+ "created": "Time at which the segment was created. Not present for built-in segments.",+ "url": "Link to the segment in the Fullstory app.",+ },+ },+ "sessions": {+ "description": "A recorded session of an identified user, with a link to its session replay.",+ "docs_url": "https://developer.fullstory.com/server/sessions/list-sessions/",+ "columns": {+ "id": "Fullstory session identifier, formatted as <user_id>:<session_id>.",+ "app_url": "Link to the session replay in the Fullstory app.",+ "created_time": "Time at which the session was created.",+ "user_id": "Fullstory identifier of the user the session belongs to (joins to users.id).",+ "uid": "Application-specific user id of the user the session belongs to (joins to users.uid).",+ },+ },+ "events": {+ "description": "An event captured by Fullstory, from a segment export of the built-in everyone segment.",+ "docs_url": "https://developer.fullstory.com/server/v1/segments/export-fields/",+ "columns": {+ "EventStart": "Time at which the event occurred, in UTC.",+ "EventType": "Type of event that was recorded, such as click or navigate.",+ "EventSubType": "Refinement of the event type, when present.",+ "EventCustomName": "Name of the event when it is a custom analytics event.",+ "EventTargetText": "Text of the event target and its child elements, where applicable.",+ "IndvId": "Identifier of the individual, which combines all users with the same user app key.",+ "UserId": "Identifier of the Fullstory user (device cookie) that performed the event.",+ "SessionId": "Identifier of the session within the user. Combine with UserId to identify a session.",+ "PageId": "Identifier of the page load within the session. Combine with UserId and SessionId.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/fullstory/fullstory.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fullstory/fullstory.pyindex 36239562c63e..3264755385a5 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/fullstory/fullstory.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fullstory/fullstory.py@@ -1,44 +1,81 @@+import gzip+import json+import time+import tempfile+import itertoolsimport dataclasses+from collections.abc import Iterable, Iterator+from datetime import UTC, datetime, timedeltafrom typing import Any, Optional+from urllib.parse import quote, urlsplit+import requestsfrom requests import Response+from posthog.dataclasses import frozen++from products.warehouse_sources.backend.temporal.data_imports.sources.common.datetime_utils import parse_datetime_valuefrom 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.fanout import (+ DependentEndpointConfig,+ build_dependent_resource,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (JSONResponseCursorPaginator,)+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.fullstory.settings import (+ EVENTS_EXPORT_END_LAG,+ EVENTS_EXPORT_WINDOW,+ EVENTS_INITIAL_LOOKBACK,+ EXPORT_BATCH_SIZE,+ EXPORT_POLL_INTERVAL_SECONDS,+ EXPORT_POLL_MAX_ATTEMPTS,+ EXPORT_SEGMENT_ID,+ FULLSTORY_BASE_URL,+ REQUEST_TIMEOUT_SECONDS,+ SEGMENTS_PAGE_SIZE,+)-FULLSTORY_BASE_URL = "https://api.fullstory.com"-# Session/event data only exists behind Fullstory's async Data Export jobs;-# the v2 users listing is the one directly listable surface.-ENDPOINTS = ("users",)[email protected](frozen=True)+class FullStoryResumeConfig:+ # Listings paginate with an opaque next-page token.+ next_page_token: Optional[str] = None+ # Events: the export window in progress, its export operation, and how many of its rows are written.+ # A crash after a write but before its checkpoint commits replays those rows; export rows have no key to dedupe on.+ export_window_start: Optional[str] = None+ export_window_end: Optional[str] = None+ export_operation_id: Optional[str] = None+ export_rows_done: int = 0-class FullStoryResumeConfig:- # v2 listings paginate with an opaque next_page_token.- next_page_token: str+class FullStoryExportError(Exception):+ pass+++class FullStoryExportFailedError(FullStoryExportError):+ passclass FullStoryCursorPaginator(JSONResponseCursorPaginator):- """v2 cursor paginator that also halts on an empty page.+ """Body-cursor paginator that also halts on an empty page.- Fullstory carries the next cursor in the body (``next_page_token``) and the cursor in the- ``page_token`` query param. Beyond the base "no cursor => stop", this also stops when a page- returns no rows even if a cursor is present — mirroring the old ``not next_token or not items``+ v2 listings carry the cursor in ``next_page_token`` and take it back as ``page_token``; the v1+ segments listing uses ``nextPaginationToken`` and ``paginationToken``. Beyond the base "no+ cursor => stop", this also stops when a page returns no rows even if a cursor is present, as aguard against a cursor that never clears."""- def __init__(self) -> None:- super().__init__(cursor_path="next_page_token", cursor_param="page_token")+ def __init__(self, cursor_path: str = "next_page_token", cursor_param: str = "page_token") -> None:+ super().__init__(cursor_path=cursor_path, cursor_param=cursor_param)def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:super().update_state(response, data)@@ -46,11 +83,49 @@ class FullStoryCursorPaginator(JSONResponseCursorPaginator):self._has_next_page = False[email protected](frozen=True)+class _FanoutEndpoint:+ name: str+ path: str+ incremental_fields: list[Any] = dataclasses.field(default_factory=list)+ default_incremental_field: Optional[str] = None+ page_size: int = 0+++# The sessions listing is per user and unpaginated, so it fans out over identified users.+_FANOUT_ENDPOINTS: dict[str, _FanoutEndpoint] = {+ "users": _FanoutEndpoint(name="users", path="/v2/users"),+ "sessions": _FanoutEndpoint(name="sessions", path="/v2/sessions?uid={uid_param}"),+}+SESSIONS_FANOUT = DependentEndpointConfig(+ parent_name="users",+ resolve_param="uid_param",+ resolve_field="uid_param",+ include_from_parent=["id", "uid"],+ parent_field_renames={"id": "user_id", "uid": "uid"},+ # Only identified users carry the uid the sessions listing is queried by.+ parent_params={"is_identified": "true"},+)++def _auth_header(api_key: str) -> str:# Fullstory's scheme is the raw API key after "Basic" (not base64 creds).return f"Basic {api_key}"+def _client_config(api_key: str) -> ClientConfig:+ return {+ "base_url": FULLSTORY_BASE_URL,+ # The raw key rides in the Authorization header value; framework auth redacts it from+ # any raised error message. Only non-secret headers would go in client `headers`.+ "auth": {"type": "api_key", "api_key": _auth_header(api_key), "name": "Authorization"},+ }+++def _format_timestamp(value: datetime) -> str:+ return value.astimezone(UTC).isoformat(timespec="milliseconds").replace("+00:00", "Z")++def validate_credentials(api_key: str) -> bool:"""Confirm the API key is valid with a cheap one-user listing probe."""ok, _status = validate_via_probe(@@ -61,30 +136,34 @@ def validate_credentials(api_key: str) -> bool:return ok-def fullstory_source(+def _listing_resource(api_key: str,endpoint: str,team_id: int,job_id: str,resumable_source_manager: ResumableSourceManager[FullStoryResumeConfig],- db_incremental_field_last_value: Optional[Any] = None,-) -> SourceResponse:+) -> Iterable[Any]:+ if endpoint == "segments":+ path = "/segments/v1"+ params: dict[str, Any] = {"limit": SEGMENTS_PAGE_SIZE}+ data_selector = "segments"+ paginator = FullStoryCursorPaginator(cursor_path="nextPaginationToken", cursor_param="paginationToken")+ else:+ path = f"/v2/{endpoint}"+ params = {}+ data_selector = "results"+ paginator = FullStoryCursorPaginator()+rest_config: RESTAPIConfig = {- "client": {- "base_url": FULLSTORY_BASE_URL,- # The raw key rides in the Authorization header value; framework auth redacts it from- # any raised error message. Only non-secret headers would go in client `headers`.- "auth": {"type": "api_key", "api_key": _auth_header(api_key), "name": "Authorization"},- "paginator": FullStoryCursorPaginator(),- },+ "client": {**_client_config(api_key), "paginator": paginator},"resources": [{"name": endpoint,"endpoint": {- "path": f"/v2/{endpoint}",- # A missing `results` key is treated as an empty page (not an error), matching the- # old `data.get("results", []) or []`.- "data_selector": "results",+ "path": path,+ "params": params,+ # A missing list key is treated as an empty page, not an error.+ "data_selector": data_selector,},}],@@ -93,7 +172,7 @@ def fullstory_source(initial_paginator_state: Optional[dict[str, Any]] = Noneif resumable_source_manager.can_resume():resume = resumable_source_manager.load_state()- if resume is not None:+ if resume is not None and resume.next_page_token:initial_paginator_state = {"cursor": resume.next_page_token}def save_checkpoint(state: Optional[dict[str, Any]]) -> None:@@ -102,18 +181,265 @@ def fullstory_source(if state and state.get("cursor"):resumable_source_manager.save_state(FullStoryResumeConfig(next_page_token=state["cursor"]))- resource = rest_api_resource(+ return rest_api_resource(rest_config,team_id,job_id,- db_incremental_field_last_value,+ None,resume_hook=save_checkpoint,initial_paginator_state=initial_paginator_state,)++def _add_uid_param(row: dict[str, Any]) -> dict[str, Any]:+ # The fan-out binds the uid into the path with str.format, which applies no escaping.+ row["uid_param"] = quote(str(row.get("uid") or ""), safe="")+ row.setdefault("uid", None)+ return row+++def _sessions_resource(api_key: str, team_id: int, job_id: str) -> Iterable[Any]:+ # Not resumable: fan-out resume state lists every completed parent, which grows with the user count.+ return build_dependent_resource(+ endpoint_configs=_FANOUT_ENDPOINTS,+ child_endpoint="sessions",+ fanout=SESSIONS_FANOUT,+ client_config=_client_config(api_key),+ path_format_values={},+ team_id=team_id,+ job_id=job_id,+ db_incremental_field_last_value=None,+ parent_endpoint_extra={"data_selector": "results", "paginator": FullStoryCursorPaginator()},+ child_endpoint_extra={"data_selector": "results", "paginator": "single_page"},+ parent_data_map=_add_uid_param,+ page_size_param=None,+ )+++def _create_event_export(session: requests.Session, start: datetime, end: datetime) -> str:+ time_range = {"start": _format_timestamp(start), "end": _format_timestamp(end)}+ response = session.post(+ f"{FULLSTORY_BASE_URL}/segments/v1/exports",+ json={+ "segmentId": EXPORT_SEGMENT_ID,+ "type": "TYPE_EVENT",+ "format": "FORMAT_NDJSON",+ "timeRange": time_range,+ # The "everyone" segment defaults to the last 30 days; override it so only the window applies.+ "segmentTimeRange": time_range,+ },+ timeout=REQUEST_TIMEOUT_SECONDS,+ )+ response.raise_for_status()+ operation_id = response.json().get("operationId")+ if not operation_id:+ raise FullStoryExportError("Fullstory segment export returned no operationId")+ return operation_id+++def _wait_for_export(session: requests.Session, operation_id: str) -> str:+ state = None+ for _attempt in range(EXPORT_POLL_MAX_ATTEMPTS):+ response = session.get(+ f"{FULLSTORY_BASE_URL}/operations/v1/{quote(operation_id, safe='')}",+ timeout=REQUEST_TIMEOUT_SECONDS,+ )+ response.raise_for_status()+ operation = response.json()+ state = operation.get("state")+ if state == "COMPLETED":+ export_id = (operation.get("results") or {}).get("searchExportId")+ if not export_id:+ raise FullStoryExportError(f"Fullstory export operation {operation_id} completed without an export id")+ return export_id+ if state == "FAILED":+ raise FullStoryExportFailedError(+ f"Fullstory export operation {operation_id} failed: {operation.get('errorDetails')}"+ )+ time.sleep(EXPORT_POLL_INTERVAL_SECONDS)+ raise FullStoryExportError(f"Fullstory export operation {operation_id} still {state} after polling budget")+++def _iter_export_rows(session: requests.Session, export_id: str) -> Iterator[dict[str, Any]]:+ response = session.get(+ f"{FULLSTORY_BASE_URL}/search/v1/exports/{quote(export_id, safe='')}/results",+ timeout=REQUEST_TIMEOUT_SECONDS,+ )+ response.raise_for_status()+ location = response.json()["location"]+ if urlsplit(location).scheme.lower() != "https":+ raise FullStoryExportError("Fullstory export download location is not HTTPS")++ # The location is a pre-signed URL on a storage host, so it must not carry the API key.+ download_session = make_tracked_session(redact_values=(location,))+ with tempfile.TemporaryFile() as file:+ with download_session.get(location, stream=True, timeout=REQUEST_TIMEOUT_SECONDS) as download:+ download.raise_for_status()+ for chunk in download.iter_content(chunk_size=1024 * 1024):+ file.write(chunk)++ file.seek(0)+ is_gzip = file.read(2) == b"\x1f\x8b"+ file.seek(0)+ lines: Iterable[bytes] = gzip.GzipFile(fileobj=file) if is_gzip else file+ for line in lines:+ line = line.strip()+ if line:+ yield json.loads(line)+++@frozen+class _ExportWindow:+ start: datetime+ end: datetime+++def _export_windows(start: datetime, end: datetime) -> Iterator[_ExportWindow]:+ window_start = start+ while window_start < end:+ window_end = min(window_start + EVENTS_EXPORT_WINDOW, end)+ yield _ExportWindow(start=window_start, end=window_end)+ window_start = window_end+++def _export_checkpoint(+ window_start: datetime, window_end: datetime, operation_id: str, rows_done: int+) -> FullStoryResumeConfig:+ return FullStoryResumeConfig(+ export_window_start=_format_timestamp(window_start),+ export_window_end=_format_timestamp(window_end),+ export_operation_id=operation_id,+ export_rows_done=rows_done,+ )+++def _start_event_export(+ session: requests.Session,+ resumable_source_manager: ResumableSourceManager[FullStoryResumeConfig],+ window_start: datetime,+ window_end: datetime,+ commit: bool,+) -> str:+ operation_id = _create_event_export(session, window_start, window_end)+ checkpoint = _export_checkpoint(window_start, window_end, operation_id, 0)+ if commit:+ with resumable_source_manager.committing():+ resumable_source_manager.save_state(checkpoint)+ else:+ # Staged only: committing now would move the cursor past rows not yet written.+ resumable_source_manager.save_state(checkpoint)+ return operation_id+++def get_events(+ api_key: str,+ resumable_source_manager: ResumableSourceManager[FullStoryResumeConfig],+ db_incremental_field_last_value: Optional[Any] = None,+) -> Iterator[list[dict[str, Any]]]:+ session = make_tracked_session(headers={"Authorization": _auth_header(api_key)}, redact_values=(api_key,))+ end = datetime.now(UTC) - EVENTS_EXPORT_END_LAG++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ resumed_start = parse_datetime_value(resume.export_window_start) if resume else None+ resumed_end = parse_datetime_value(resume.export_window_end) if resume else None++ pending_operation_id: Optional[str] = None+ pending_rows_done = 0+ windows: Iterator[_ExportWindow]+ if resume is not None and resumed_start is not None and resumed_end is not None:+ # Finish the interrupted window exactly as it was exported before moving on.+ windows = itertools.chain(+ [_ExportWindow(start=resumed_start, end=resumed_end)], _export_windows(resumed_end, end)+ )+ pending_operation_id = resume.export_operation_id+ pending_rows_done = resume.export_rows_done+ else:+ watermark = parse_datetime_value(db_incremental_field_last_value)+ # The export's time range includes its start, so step past the last synced event.+ start = watermark + timedelta(milliseconds=1) if watermark is not None else end - EVENTS_INITIAL_LOOKBACK+ windows = _export_windows(start, end)++ yielded_any = False+ for window in windows:+ window_start, window_end = window.start, window.end+ operation_id, rows_done = pending_operation_id, pending_rows_done+ pending_operation_id, pending_rows_done = None, 0++ if operation_id is None:+ operation_id = _start_event_export(+ session, resumable_source_manager, window_start, window_end, commit=not yielded_any+ )+ export_id = _wait_for_export(session, operation_id)+ else:+ try:+ export_id = _wait_for_export(session, operation_id)+ except FullStoryExportFailedError:+ # A saved operation that failed would fail every retry, so export the window again.+ operation_id = _start_event_export(+ session, resumable_source_manager, window_start, window_end, commit=not yielded_any+ )+ rows_done = 0+ export_id = _wait_for_export(session, operation_id)++ batch: list[dict[str, Any]] = []+ written = rows_done+ for index, row in enumerate(_iter_export_rows(session, export_id)):+ if index < rows_done:+ continue+ batch.append(row)+ if len(batch) >= EXPORT_BATCH_SIZE:+ written += len(batch)+ resumable_source_manager.save_state(_export_checkpoint(window_start, window_end, operation_id, written))+ yield batch+ yielded_any = True+ batch = []+ if batch:+ written += len(batch)+ resumable_source_manager.save_state(_export_checkpoint(window_start, window_end, operation_id, written))+ yield batch+ yielded_any = True+++def fullstory_source(+ api_key: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[FullStoryResumeConfig],+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ if endpoint == "events":+ return SourceResponse(+ name=endpoint,+ items=lambda: get_events(api_key, resumable_source_manager, db_incremental_field_last_value),+ primary_keys=None,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime",+ partition_format="day",+ partition_keys=["EventStart"],+ # Rows inside an export file are unordered, so only commit the watermark once the sync completes.+ sort_mode="desc",+ )++ if endpoint == "sessions":+ resource = _sessions_resource(api_key, team_id, job_id)+ return SourceResponse(+ name=endpoint,+ items=lambda: resource,+ # Session ids are "<user_id>:<session_id>", unique across the account.+ primary_keys=["id"],+ partition_count=1,+ partition_size=1,+ partition_mode="datetime",+ partition_keys=["created_time"],+ sort_mode="asc",+ )++ listing = _listing_resource(api_key, endpoint, team_id, job_id, resumable_source_manager)return SourceResponse(name=endpoint,- items=lambda: resource,+ items=lambda: listing,primary_keys=["id"],partition_count=1,partition_size=1,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/fullstory/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fullstory/settings.pynew file mode 100644index 000000000000..fefcaeba179b--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fullstory/settings.py@@ -0,0 +1,39 @@+from datetime import timedelta++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++FULLSTORY_BASE_URL = "https://api.fullstory.com"++ENDPOINTS = ("users", "segments", "sessions", "events")++# Only the segment export takes a time range; the users, segments and sessions listings have no+# server-side filter, so they are full refresh only.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ "events": [+ {+ "label": "EventStart",+ "type": IncrementalFieldType.DateTime,+ "field": "EventStart",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+}++# Export rows carry no unique event id, so the events table can only append.+APPEND_ONLY_ENDPOINTS = ("events",)++SEGMENTS_PAGE_SIZE = 100++# The built-in segment that matches every user. Fullstory recommends it for bulk event export.+EXPORT_SEGMENT_ID = "everyone"+# The export needs a start time, and a first sync has no watermark to derive one from.+EVENTS_INITIAL_LOOKBACK = timedelta(days=90)+# One export job per window keeps each downloaded file bounded and gives resume a fine grain.+EVENTS_EXPORT_WINDOW = timedelta(days=1)+# Leave recent events out of the export until Fullstory has finished processing them.+EVENTS_EXPORT_END_LAG = timedelta(hours=1)+EXPORT_POLL_INTERVAL_SECONDS = 15+# Caps each poll loop so a stuck job fails as a retryable error instead of hanging the activity.+EXPORT_POLL_MAX_ATTEMPTS = 120+EXPORT_BATCH_SIZE = 5000+REQUEST_TIMEOUT_SECONDS = 120diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/fullstory/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fullstory/source.pyindex 9f24c307c64a..0fbe4de2c19f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/fullstory/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fullstory/source.py@@ -19,11 +19,15 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.sch)from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.fullstory.fullstory import (- ENDPOINTS,FullStoryResumeConfig,fullstory_source,validate_credentials as validate_fullstory_credentials,)+from products.warehouse_sources.backend.temporal.data_imports.sources.fullstory.settings import (+ APPEND_ONLY_ENDPOINTS,+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.fullstory import (FullStorySourceConfig,)@@ -61,9 +65,9 @@ class FullStorySource(ResumableSource[FullStorySourceConfig, FullStoryResumeConfname=ExternalDataSourceType.FULLSTORY,category=DataWarehouseSourceCategory.ANALYTICS,label="Fullstory",- caption="""Enter your Fullstory API key to pull your Fullstory user data into the PostHog Data warehouse.+ caption="""Enter your Fullstory API key to pull your Fullstory users, segments, sessions, and events into the PostHog Data warehouse.-You can create an API key in Fullstory under Settings > Integrations & API Keys > API Keys. A key with at least the Viewer permission level is sufficient for syncing.""",+You can create an API key in Fullstory under Settings > Integrations & API Keys > API Keys. A key with the Viewer permission level can sync users and segments. The sessions table needs the Admin or Architect level, and the events table needs the Segment Export add-on on your Fullstory plan.""",iconPath="/static/services/fullstory.png",docsUrl="https://posthog.com/docs/cdp/sources/fullstory",releaseStatus=ReleaseStatus.ALPHA,@@ -91,9 +95,7 @@ You can create an API key in Fullstory under Settings > Integrations & API Keysforce_refresh: bool = False,api_version: str | None = None,) -> list[SourceSchema]:- # The users listing has no updated-since filter (no incremental fields), so it is- # full-refresh only; session/event data only exists behind async Data Export jobs (a follow-up).- return build_endpoint_schemas(ENDPOINTS, {}, names)+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names, append_only=APPEND_ONLY_ENDPOINTS)def validate_credentials(self,@@ -122,4 +124,7 @@ You can create an API key in Fullstory under Settings > Integrations & API Keysteam_id=inputs.team_id,job_id=inputs.job_id,resumable_source_manager=resumable_source_manager,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/fullstory/tests/test_fullstory.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fullstory/tests/test_fullstory.pyindex 68dd5e10c434..ef74636e69f2 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/fullstory/tests/test_fullstory.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fullstory/tests/test_fullstory.py@@ -1,14 +1,19 @@+import gzipimport json+from datetime import UTC, datetimefrom typing import Anyimport pytest+import time_machinefrom unittest import mockfrom requests import Responsefrom products.warehouse_sources.backend.temporal.data_imports.sources.fullstory.fullstory import (+ FullStoryExportFailedError,FullStoryResumeConfig,fullstory_source,+ get_events,validate_credentials,)@@ -21,13 +26,18 @@ FULLSTORY_SESSION_PATCH = (def _response(- items: list[dict[str, Any]] | None, *, next_token: str | None = None, drop_results: bool = False+ items: list[dict[str, Any]] | None,+ *,+ next_token: str | None = None,+ drop_results: bool = False,+ list_key: str = "results",+ cursor_key: str = "next_page_token",) -> Response:body: dict[str, Any] = {}if not drop_results:- body["results"] = items or []+ body[list_key] = items or []if next_token:- body["next_page_token"] = next_token+ body[cursor_key] = next_tokenresp = Response()resp.status_code = 200resp._content = json.dumps(body).encode()@@ -41,7 +51,7 @@ def _make_manager(resume_state: FullStoryResumeConfig | None = None) -> mock.Magreturn manager-def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:+def _wire(session: mock.MagicMock, responses: list[Response], urls: list[str] | None = None) -> list[dict[str, Any]]:"""Wire a mock session and capture each request's params AT SEND TIME.``request.params`` is a single dict mutated in place across pages, so inspecting it after the run@@ -52,6 +62,8 @@ def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str,def _prepare(request: Any) -> mock.MagicMock:param_snapshots.append(dict(request.params or {}))+ if urls is not None:+ urls.append(request.url)return mock.MagicMock()session.prepare_request.side_effect = _prepare@@ -63,23 +75,36 @@ def _rows(source_response) -> list[dict[str, Any]]:return [row for page in source_response.items() for row in page]-def _source(manager: mock.MagicMock):- return fullstory_source("key", "users", team_id=1, job_id="j", resumable_source_manager=manager)+def _source(manager: mock.MagicMock, endpoint: str = "users"):+ return fullstory_source("key", endpoint, team_id=1, job_id="j", resumable_source_manager=manager)class TestPagination:+ @pytest.mark.parametrize(+ "endpoint, list_key, cursor_key, cursor_param",+ [+ ("users", "results", "next_page_token", "page_token"),+ ("segments", "segments", "nextPaginationToken", "paginationToken"),+ ],+ )@mock.patch(CLIENT_SESSION_PATCH)- def test_paginates_via_page_token(self, MockSession) -> None:+ def test_paginates_via_page_token(self, MockSession, endpoint, list_key, cursor_key, cursor_param) -> None:session = MockSession.return_value- params = _wire(session, [_response([{"id": "u1"}], next_token="tok1"), _response([{"id": "u2"}])])+ params = _wire(+ session,+ [+ _response([{"id": "u1"}], next_token="tok1", list_key=list_key, cursor_key=cursor_key),+ _response([{"id": "u2"}], list_key=list_key, cursor_key=cursor_key),+ ],+ )manager = _make_manager()- rows = _rows(_source(manager))+ rows = _rows(_source(manager, endpoint))assert [r["id"] for r in rows] == ["u1", "u2"]# First page has no cursor; second page carries the saved token.- assert "page_token" not in params[0]- assert params[1]["page_token"] == "tok1"+ assert cursor_param not in params[0]+ assert params[1][cursor_param] == "tok1"# Checkpoint saved once after the first page (points at the next page); the tokenless page ends it.manager.save_state.assert_called_once()assert manager.save_state.call_args.args[0] == FullStoryResumeConfig(next_page_token="tok1")@@ -143,6 +168,156 @@ class TestPagination:assert MockSession.call_args.kwargs["redact_values"] == ("Basic key",)+class TestSessionsFanout:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_queries_sessions_per_identified_user(self, MockSession) -> None:+ session = MockSession.return_value+ urls: list[str] = []+ params = _wire(+ session,+ [+ _response([{"id": "fs1", "uid": "a/b c"}]),+ _response([{"id": "1:2", "app_url": "https://app.fullstory.com/s/1:2", "created_time": "t"}]),+ ],+ urls,+ )++ rows = _rows(_source(_make_manager(), "sessions"))++ assert params[0]["is_identified"] == "true"+ assert urls[1].endswith("/v2/sessions?uid=a%2Fb%20c")+ assert rows == [+ {+ "id": "1:2",+ "app_url": "https://app.fullstory.com/s/1:2",+ "created_time": "t",+ "user_id": "fs1",+ "uid": "a/b c",+ }+ ]+++def _json_response(body: dict[str, Any]) -> mock.MagicMock:+ resp = mock.MagicMock()+ resp.json.return_value = body+ return resp+++def _export_file(rows: list[dict[str, Any]]) -> bytes:+ return gzip.compress("".join(json.dumps(row) + "\n" for row in rows).encode())+++class _FakeExportApi:+ def __init__(self, operation_states: dict[str, list[dict[str, Any]]], files: dict[str, bytes]) -> None:+ self.operation_states = operation_states+ self.files = files+ self.created: list[dict[str, Any]] = []+ self.api = mock.MagicMock()+ self.api.post.side_effect = self._post+ self.api.get.side_effect = self._get+ self.download = mock.MagicMock()+ self.download.get.side_effect = self._download++ def session_factory(self, **kwargs: Any) -> mock.MagicMock:+ return self.api if "headers" in kwargs else self.download++ def _post(self, url: str, json: dict[str, Any], **_: Any) -> mock.MagicMock:+ self.created.append(json)+ return _json_response({"operationId": f"op{len(self.created)}"})++ def _get(self, url: str, **_: Any) -> mock.MagicMock:+ if "/operations/v1/" in url:+ return _json_response(self.operation_states[url.rsplit("/", 1)[-1]].pop(0))+ export_id = url.split("/exports/")[1].split("/")[0]+ return _json_response({"location": f"https://storage.example.com/{export_id}"})++ def _download(self, url: str, **_: Any) -> mock.MagicMock:+ download = mock.MagicMock()+ download.iter_content.return_value = [self.files[url.rsplit("/", 1)[-1]]]+ response = mock.MagicMock()+ response.__enter__.return_value = download+ return response+++def _completed(export_id: str) -> dict[str, Any]:+ return {"state": "COMPLETED", "results": {"searchExportId": export_id}}+++class TestEventsExport:+ def _run(self, fake: _FakeExportApi, manager: mock.MagicMock, watermark: Any = None) -> list[dict[str, Any]]:+ with (+ time_machine.travel(datetime(2026, 3, 3, 1, 0, tzinfo=UTC), tick=False),+ mock.patch(FULLSTORY_SESSION_PATCH, side_effect=fake.session_factory),+ mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.fullstory.fullstory.time.sleep"+ ),+ ):+ return [row for batch in get_events("key", manager, watermark) for row in batch]++ def test_exports_daily_windows_after_the_watermark(self) -> None:+ fake = _FakeExportApi(+ operation_states={"op1": [{"state": "PENDING"}, _completed("e1")], "op2": [_completed("e2")]},+ files={"e1": _export_file([{"EventStart": "a"}, {"EventStart": "b"}]), "e2": _export_file([])},+ )++ rows = self._run(fake, _make_manager(), watermark="2026-03-01T12:00:00Z")++ assert rows == [{"EventStart": "a"}, {"EventStart": "b"}]+ assert [c["timeRange"] for c in fake.created] == [+ {"start": "2026-03-01T12:00:00.001Z", "end": "2026-03-02T12:00:00.001Z"},+ {"start": "2026-03-02T12:00:00.001Z", "end": "2026-03-03T00:00:00.000Z"},+ ]+ assert all(c["segmentTimeRange"] == c["timeRange"] for c in fake.created)+ assert {(c["segmentId"], c["type"], c["format"]) for c in fake.created} == {+ ("everyone", "TYPE_EVENT", "FORMAT_NDJSON")+ }++ def test_resume_reuses_the_saved_operation_and_skips_written_rows(self) -> None:+ fake = _FakeExportApi(+ operation_states={"saved": [_completed("e1")]},+ files={"e1": _export_file([{"n": 1}, {"n": 2}, {"n": 3}])},+ )+ manager = _make_manager(+ FullStoryResumeConfig(+ export_window_start="2026-03-02T00:00:00.000Z",+ export_window_end="2026-03-03T00:00:00.000Z",+ export_operation_id="saved",+ export_rows_done=2,+ )+ )++ rows = self._run(fake, manager, watermark="2026-01-01T00:00:00Z")++ assert rows == [{"n": 3}]+ assert fake.created == []+ assert manager.save_state.call_args.args[0].export_rows_done == 3++ def test_failed_saved_operation_exports_the_window_again(self) -> None:+ fake = _FakeExportApi(+ operation_states={"saved": [{"state": "FAILED", "errorDetails": "expired"}], "op1": [_completed("e1")]},+ files={"e1": _export_file([{"n": 1}, {"n": 2}])},+ )+ manager = _make_manager(+ FullStoryResumeConfig(+ export_window_start="2026-03-02T00:00:00.000Z",+ export_window_end="2026-03-03T00:00:00.000Z",+ export_operation_id="saved",+ export_rows_done=1,+ )+ )++ rows = self._run(fake, manager)++ assert rows == [{"n": 1}, {"n": 2}]+ assert [c["timeRange"]["start"] for c in fake.created] == ["2026-03-02T00:00:00.000Z"]++ def test_failed_new_operation_raises(self) -> None:+ fake = _FakeExportApi(operation_states={"op1": [{"state": "FAILED", "errorDetails": "boom"}]}, files={})++ with pytest.raises(FullStoryExportFailedError, match="boom"):+ self._run(fake, _make_manager(), watermark="2026-03-02T12:00:00Z")++class TestSourceResponse:@mock.patch(CLIENT_SESSION_PATCH)def test_response_metadata(self, MockSession) -> None: