: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 Stack Overflow source (#73211)
Tom Owersb5942752739b
diff --git a/frontend/public/services/stack_overflow_for_teams.png b/frontend/public/services/stack_overflow_for_teams.pngindex c5736e43b50d..6fb7cb73c865 100644Binary files a/frontend/public/services/stack_overflow_for_teams.png and b/frontend/public/services/stack_overflow_for_teams.png differdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex f434b9214398..3796f229dfd8 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -528,6 +528,7 @@ the row lists both.| squadcast | HTTP | requests | ✅ || square | HTTP | requests | ✅ || squarespace | HTTP | requests | ✅ |+| stack_overflow_for_teams | HTTP | requests + `rest_source.RESTClient` | ✅ || statuscake | HTTP | requests | ✅ || statuspage | HTTP | requests | ✅ || stigg | HTTP | requests | ✅ |@@ -1292,7 +1293,6 @@ doesn't conflict with concurrent PRs.- sprig- sprinklr- sprout_social-- stack_overflow_for_teams- statsig- stockx- stravadiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/stackoverflowforteams.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/stackoverflowforteams.pyindex 289567c93d88..a37924f59f98 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/stackoverflowforteams.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/stackoverflowforteams.py@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass StackOverflowForTeamsSourceConfig(config.Config):- pass+ team: str+ api_token: strdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/stack_overflow_for_teams/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/stack_overflow_for_teams/canonical_descriptions.pynew file mode 100644index 000000000000..96538297e728--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/stack_overflow_for_teams/canonical_descriptions.py@@ -0,0 +1,129 @@+"""Canonical, documentation-sourced descriptions for Stack Overflow for Teams v3 endpoints.++Sourced from the official v3 OpenAPI spec (https://api.stackoverflowteams.com/v3/swagger.json).+Keyed by the endpoint names in `settings.py` `STACK_OVERFLOW_FOR_TEAMS_ENDPOINTS`, which match the+`ExternalDataSchema.name` of a synced table. Columns absent here fall back to LLM enrichment.+"""++from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++_API_DOCS_URL = "https://api.stackoverflowteams.com/docs"++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "Questions": {+ "description": "A question posted to your Stack Overflow for Teams knowledge base.",+ "docs_url": _API_DOCS_URL,+ "columns": {+ "id": "The question's unique identifier.",+ "title": "The actual question, stated briefly in one sentence.",+ "body": "The main content of the question, in HTML format.",+ "tags": "Tags associated with the question.",+ "owner": "The user who posted the question.",+ "lastEditor": "The user who last edited the question, if any.",+ "creationDate": "The date and time the question was created.",+ "lastActivityDate": "The date and time the question or one of its answers last had significant activity (edit, rollback, tag change, new answer, bounty added, bump).",+ "score": "Number of upvotes minus downvotes.",+ "isAnswered": "True if the question has at least one upvoted answer.",+ "answerCount": "Number of answers to the question.",+ "commentCount": "Number of comments on the question.",+ "viewCount": "Number of times users have viewed this question.",+ "webUrl": "The question's direct URL.",+ "shareUrl": "The question's URL for sharing.",+ "isDeleted": "True if the question was deleted.",+ "isObsolete": "True if the question was marked by a moderator as obsolete.",+ "isClosed": "True if the question was closed by a moderator.",+ },+ },+ "Answers": {+ "description": "An answer posted to a question in your Stack Overflow for Teams knowledge base.",+ "docs_url": _API_DOCS_URL,+ "columns": {+ "id": "The answer's unique identifier.",+ "questionId": "The ID of the question this answer belongs to.",+ "body": "The main content of the answer, in HTML format.",+ "score": "Number of upvotes minus downvotes.",+ "isAccepted": "True if this is the accepted answer for the question.",+ "isDeleted": "True if the answer was deleted.",+ "creationDate": "The date and time the answer was created.",+ "lockedDate": "The date and time the answer was locked, if any.",+ "lastEditDate": "The date and time the answer was last edited, if any.",+ "lastActivityDate": "The date and time the answer last had activity.",+ "deletionDate": "The date and time the answer was deleted, if any.",+ "owner": "The user who posted the answer.",+ "lastEditor": "The user who last edited the answer, if any.",+ "commentCount": "Number of comments on the answer.",+ "webUrl": "The answer's direct URL.",+ "isSubjectMatterExpert": "True if the answer is from a subject matter expert.",+ },+ },+ "Articles": {+ "description": "A knowledge-base article (Business/Enterprise tier) in your Stack Overflow for Teams site.",+ "docs_url": _API_DOCS_URL,+ "columns": {+ "id": "The article's unique identifier.",+ "type": "The article's type (e.g. knowledge article, how-to guide, policy).",+ "title": "The article's title, stated briefly in one sentence.",+ "body": "The main content of the article, in HTML format.",+ "tags": "Tags associated with the article.",+ "owner": "The user who authored the article.",+ "lastEditor": "The user who last edited the article, if any.",+ "creationDate": "The date and time the article was created.",+ "lastActivityDate": "The date and time the article last had significant activity.",+ "score": "Number of upvotes minus downvotes.",+ "commentCount": "Number of comments on the article.",+ "viewCount": "Number of times users have viewed this article.",+ "webUrl": "The article's direct URL.",+ "shareUrl": "The article's URL for sharing.",+ "isDeleted": "True if the article was deleted.",+ "isObsolete": "True if the article was marked by a moderator as obsolete.",+ "isClosed": "True if the article was closed by a moderator.",+ },+ },+ "Tags": {+ "description": "A tag used to categorize questions and articles in your Stack Overflow for Teams site.",+ "docs_url": _API_DOCS_URL,+ "columns": {+ "id": "The tag's unique identifier.",+ "name": "The tag's name.",+ "description": "The tag's description.",+ "postCount": "Number of posts that have this tag.",+ "subjectMatterExpertCount": "Total number of users who are subject matter experts for this tag (individually assigned plus members of any SME groups). Null if SMEs aren't enabled for the tag.",+ "watcherCount": "Number of users watching this tag.",+ "creationDate": "The date and time the tag was created.",+ "hasSynonyms": "True if the tag has one or more synonyms.",+ "webUrl": "The tag's web URL.",+ },+ },+ "Users": {+ "description": "A user on your Stack Overflow for Teams site.",+ "docs_url": _API_DOCS_URL,+ "columns": {+ "id": "The user's unique identifier on this site.",+ "accountId": "The user's unique account identifier across all Stack Overflow sites.",+ "externalId": "Unique external ID for the user, set via SCIM or SAML.",+ "name": "The user's name.",+ "email": "The user's email address. Only visible to admins, or for the current user.",+ "department": "The user's organizational department, set via SAML.",+ "jobTitle": "The user's organizational job title, set via SAML.",+ "avatarUrl": "URL to the user's avatar (profile picture).",+ "webUrl": "URL to the user's profile.",+ "reputation": "The user's numerical reputation.",+ "role": "The user's role on the site.",+ },+ },+ "Collections": {+ "description": "A curated collection of questions and articles in your Stack Overflow for Teams site.",+ "docs_url": _API_DOCS_URL,+ "columns": {+ "id": "The collection's unique identifier.",+ "title": "A brief title to distinguish the collection and its contents.",+ "description": "A detailed description of what the collection contains. Supports Markdown.",+ "owner": "The user who created the collection.",+ "creationDate": "The date and time the collection was created.",+ "isDeleted": "True if the collection was deleted.",+ "tags": "Tags associated with the content items in the collection.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/stack_overflow_for_teams/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/stack_overflow_for_teams/settings.pynew file mode 100644index 000000000000..4c969544af1c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/stack_overflow_for_teams/settings.py@@ -0,0 +1,101 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ DependentEndpointConfig,+)+from products.warehouse_sources.backend.types import IncrementalField++# Every v3 list endpoint (except Answers, whose fan-out page size is set independently in+# fanout.py) caps `pageSize` at 100 - always request the max to minimise round trips.+PAGE_SIZE = 100+++@dataclass+class StackOverflowForTeamsEndpointConfig:+ name: str+ path: str # Path under /v3/teams/{team}, e.g. "/questions"+ # `sort`/`order` values valid for this endpoint's list action (per the v3 OpenAPI spec -+ # each resource has its own sort enum). Passed explicitly on every request so pagination+ # sees a stable order even though every endpoint here is full refresh.+ sort: Optional[str]+ order: Optional[str]+ # Stable creation-time field to partition by. None when the resource has no reliable+ # creation date (Users).+ partition_key: Optional[str] = "creationDate"+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ should_sync_default: bool = True+ page_size: int = PAGE_SIZE+ fanout: DependentEndpointConfig | None = None+ # No v3 list endpoint has a confirmed server-side timestamp filter (see INCREMENTAL_FIELDS+ # below), so every endpoint stays full refresh; these satisfy the fan-out helper's endpoint+ # protocol without advertising an incremental field.+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ default_incremental_field: str | None = None+++STACK_OVERFLOW_FOR_TEAMS_ENDPOINTS: dict[str, StackOverflowForTeamsEndpointConfig] = {+ "Questions": StackOverflowForTeamsEndpointConfig(+ name="Questions",+ path="/questions",+ sort="creation",+ order="asc",+ ),+ "Answers": StackOverflowForTeamsEndpointConfig(+ name="Answers",+ path="/questions/{questionId}/answers",+ sort="creation",+ order="asc",+ # AnswerSummaryResponseModel already carries `questionId` on every row, but the answer+ # `id` is only documented as unique within its question, and this table aggregates+ # answers fanned out across every question - keep the parent id in the key defensively.+ primary_keys=["id", "questionId"],+ fanout=DependentEndpointConfig(+ parent_name="Questions",+ resolve_param="questionId",+ resolve_field="id",+ # The answers response already includes `questionId` natively, so no parent fields+ # need to be injected.+ include_from_parent=[],+ # Keep the parent (Questions) traversal in a stable order while fanning out.+ parent_params={"sort": "creation", "order": "asc"},+ ),+ ),+ "Articles": StackOverflowForTeamsEndpointConfig(+ name="Articles",+ path="/articles",+ sort="creation",+ order="asc",+ ),+ "Tags": StackOverflowForTeamsEndpointConfig(+ name="Tags",+ path="/tags",+ # TagsSortParameter uses "creationDate", not "creation".+ sort="creationDate",+ order="asc",+ ),+ "Users": StackOverflowForTeamsEndpointConfig(+ name="Users",+ path="/users",+ # UsersSortParameter documents only "reputation" - no creation-time sort is offered, so+ # ordering isn't guaranteed stable across pages; the users table is typically small+ # enough that this doesn't matter in practice.+ sort="reputation",+ order="asc",+ partition_key=None,+ ),+ "Collections": StackOverflowForTeamsEndpointConfig(+ name="Collections",+ path="/collections",+ sort="creation",+ order="asc",+ ),+}++ENDPOINTS = tuple(STACK_OVERFLOW_FOR_TEAMS_ENDPOINTS.keys())++# The v3 API documents `from`/`to` date-time filters on Questions/Articles/Collections, but+# doesn't specify which field they filter against, and it can't be confirmed against a live+# team without a customer PAT - so every endpoint ships full refresh for now. Revisit once the+# filter semantics are verified against a real team.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {name: [] for name in ENDPOINTS}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/stack_overflow_for_teams/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/stack_overflow_for_teams/source.pyindex f76b3fc1bd32..97366dc67441 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/stack_overflow_for_teams/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/stack_overflow_for_teams/source.py@@ -1,32 +1,159 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (+ SourceSchema,+ build_endpoint_schemas,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.stackoverflowforteams import (StackOverflowForTeamsSourceConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.stack_overflow_for_teams.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.stack_overflow_for_teams.stack_overflow_for_teams import (+ StackOverflowForTeamsResumeConfig,+ stack_overflow_for_teams_source,+ validate_credentials as validate_stack_overflow_for_teams_credentials,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class StackOverflowForTeamsSource(SimpleSource[StackOverflowForTeamsSourceConfig]):+class StackOverflowForTeamsSource(+ ResumableSource[StackOverflowForTeamsSourceConfig, StackOverflowForTeamsResumeConfig]+):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs++ supported_versions = ("v3",)+ default_version = "v3"+ api_docs_url = "https://api.stackoverflowteams.com/docs"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.STACKOVERFLOWFORTEAMS+ @property+ def connection_host_fields(self) -> list[str]:+ # The PAT is sent to api.stackoverflowteams.com/v3/teams/<team>, so retargeting the+ # team must re-require it.+ return ["team"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.STACK_OVERFLOW_FOR_TEAMS,category=DataWarehouseSourceCategory.PRODUCTIVITY,label="Stack Overflow (Prosus/Stack Exchange)",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Stack Overflow for Teams team name and a Personal access token to pull your internal Q&A knowledge base — questions, answers, articles, tags, users, and collections — into the PostHog Data warehouse.++Create a token under **Account Settings → Personal access tokens**, scoped to this team. Read-only (Basic) access is sufficient — you don't need to grant write access.""",iconPath="/static/services/stack_overflow_for_teams.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/stack-overflow-for-teams",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="team",+ label="Team name",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="engineering",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="api_token",+ label="Personal access token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.stack_overflow_for_teams.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized": "Your Stack Overflow for Teams personal access token is invalid or has expired. Create a new token and reconnect.",+ "403 Client Error: Forbidden": "Your Stack Overflow for Teams personal access token doesn't have access to this team or resource. Check the token's team scope, then reconnect.",+ }++ def get_schemas(+ self,+ config: StackOverflowForTeamsSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)++ def validate_credentials(+ self,+ config: StackOverflowForTeamsSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ try:+ ok, status_code = validate_stack_overflow_for_teams_credentials(config.team, config.api_token)+ except ValueError as e:+ return False, str(e)++ if ok:+ return True, None+ if status_code == 401:+ return False, "Invalid Stack Overflow for Teams personal access token"+ return (+ False,+ "Could not connect to Stack Overflow for Teams with the provided team name and personal access token",+ )++ def get_resumable_source_manager(+ self, inputs: SourceInputs+ ) -> ResumableSourceManager[StackOverflowForTeamsResumeConfig]:+ return ResumableSourceManager[StackOverflowForTeamsResumeConfig](inputs, StackOverflowForTeamsResumeConfig)++ def source_for_pipeline(+ self,+ config: StackOverflowForTeamsSourceConfig,+ resumable_source_manager: ResumableSourceManager[StackOverflowForTeamsResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return stack_overflow_for_teams_source(+ team=config.team,+ api_token=config.api_token,+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ resumable_source_manager=resumable_source_manager,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/stack_overflow_for_teams/stack_overflow_for_teams.py b/products/warehouse_sources/backend/temporal/data_imports/sources/stack_overflow_for_teams/stack_overflow_for_teams.pynew file mode 100644index 000000000000..09f6ce6be9a9--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/stack_overflow_for_teams/stack_overflow_for_teams.py@@ -0,0 +1,207 @@+import re+import dataclasses+from collections.abc import Iterable+from typing import Any, Optional, cast++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+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.fanout import (+ build_dependent_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ PageNumberPaginator,+)+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+from products.warehouse_sources.backend.temporal.data_imports.sources.stack_overflow_for_teams.settings import (+ STACK_OVERFLOW_FOR_TEAMS_ENDPOINTS,+)++BASE_API_PATH = "/v3/teams"++# Stack Overflow for Teams requires a descriptive User-Agent to avoid being throttled; the+# Bearer token is supplied through the framework auth config so it's redacted from logs.+USER_AGENT = "PostHog Data Warehouse ([email protected])"++# A single path segment: letters, digits, hyphens, underscores. Team names are only ever used+# as a URL path component (the host is always api.stackoverflowteams.com), so this rejects+# anything that would smuggle extra path segments or query parameters into the request.+_TEAM_RE = re.compile(r"^[A-Za-z0-9_-]+$")+++def normalize_team(team: str) -> str:+ """Validate and return a bare team name for use in the API path.++ Raises ``ValueError`` on anything that isn't a single path segment.+ """+ cleaned = team.strip()+ if not _TEAM_RE.match(cleaned):+ raise ValueError(+ f"Invalid Stack Overflow for Teams team name: {team!r}. Enter just your team's slug, e.g. 'engineering'."+ )+ return cleaned+++def _base_url(team: str) -> str:+ return f"https://api.stackoverflowteams.com{BASE_API_PATH}/{normalize_team(team)}"+++class StackOverflowForTeamsResumeConfig:+ # Next 1-indexed page to fetch. Only populated for top-level (non fan-out) endpoints -+ # dependent-resource fan-out (Answers) doesn't expose a resume hook in the rest_source+ # framework, so it always restarts from page 1 of its parent (Questions).+ next_page: int | None = None+++def _client_config(team: str, api_token: str) -> ClientConfig:+ return {+ "base_url": _base_url(team),+ "headers": {"Accept": "application/json", "User-Agent": USER_AGENT},+ "auth": {"type": "bearer", "token": api_token},+ # `totalPages` is returned on every paginated list response and lets us stop cleanly on+ # the last page instead of paying for one extra empty-page request.+ "paginator": PageNumberPaginator(base_page=1, page_param="page", total_path="totalPages"),+ }+++def _non_fanout_source(+ team: str,+ api_token: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[StackOverflowForTeamsResumeConfig],+) -> SourceResponse:+ config = STACK_OVERFLOW_FOR_TEAMS_ENDPOINTS[endpoint]++ params: dict[str, Any] = {"pageSize": config.page_size}+ if config.sort:+ params["sort"] = config.sort+ if config.order:+ params["order"] = config.order++ rest_config: RESTAPIConfig = {+ "client": _client_config(team, api_token),+ "resource_defaults": {},+ "resources": [+ {+ "name": endpoint,+ "endpoint": {+ "path": config.path,+ "params": params,+ # A 200 body without an "items" key yields an empty page and ends pagination.+ "data_selector": "items",+ },+ }+ ],+ }++ 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 and resume.next_page:+ initial_paginator_state = {"page": resume.next_page}++ 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+ # the last page (merge/replace re-writes it) rather than skipping it.+ if state and state.get("page") is not None:+ resumable_source_manager.save_state(StackOverflowForTeamsResumeConfig(next_page=int(state["page"])))++ resource = rest_api_resource(+ rest_config,+ team_id,+ job_id,+ None,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )++ return SourceResponse(+ name=endpoint,+ items=lambda: resource,+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ column_hints=resource.column_hints,+ )+++def _fanout_source(+ team: str,+ api_token: str,+ endpoint: str,+ team_id: int,+ job_id: str,+) -> SourceResponse:+ config = STACK_OVERFLOW_FOR_TEAMS_ENDPOINTS[endpoint]+ assert config.fanout is not None++ dependent_resource = cast(+ Iterable[Any],+ build_dependent_resource(+ endpoint_configs=STACK_OVERFLOW_FOR_TEAMS_ENDPOINTS,+ child_endpoint=endpoint,+ fanout=config.fanout,+ client_config=_client_config(team, api_token),+ path_format_values={},+ team_id=team_id,+ job_id=job_id,+ # Answers has no server-side timestamp filter, so this fan-out is always full+ # refresh - the watermark is never consulted.+ db_incremental_field_last_value=None,+ should_use_incremental_field=False,+ page_size_param="pageSize",+ parent_endpoint_extra={"data_selector": "items"},+ child_endpoint_extra={"data_selector": "items"},+ ),+ )++ return SourceResponse(+ name=endpoint,+ items=lambda: dependent_resource,+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ )+++def stack_overflow_for_teams_source(+ team: str,+ api_token: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[StackOverflowForTeamsResumeConfig],+) -> SourceResponse:+ config = STACK_OVERFLOW_FOR_TEAMS_ENDPOINTS[endpoint]+ if config.fanout is not None:+ return _fanout_source(team, api_token, endpoint, team_id, job_id)++ return _non_fanout_source(team, api_token, endpoint, team_id, job_id, resumable_source_manager)+++def validate_credentials(team: str, api_token: str) -> tuple[bool, int | None]:+ """Probe the `/users/me` endpoint to confirm the token is genuine for this team.++ Returns ``(ok, status_code)``. ``status_code`` is ``None`` on a transport error. Raises+ ``ValueError`` if the team name is malformed so the caller can surface a precise message.+ """+ url = f"{_base_url(team)}/users/me"+ return validate_via_probe(+ lambda: make_tracked_session(redact_values=(api_token,)),+ url,+ headers={"Authorization": f"Bearer {api_token}", "Accept": "application/json", "User-Agent": USER_AGENT},+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/stack_overflow_for_teams/tests/test_stack_overflow_for_teams.py b/products/warehouse_sources/backend/temporal/data_imports/sources/stack_overflow_for_teams/tests/test_stack_overflow_for_teams.pynew file mode 100644index 000000000000..2a4512bafc5e--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/stack_overflow_for_teams/tests/test_stack_overflow_for_teams.py@@ -0,0 +1,339 @@+import json+from typing import Any, cast++import pytest+from unittest import mock++from parameterized import parameterized+from requests import Response++from products.warehouse_sources.backend.temporal.data_imports.sources.stack_overflow_for_teams.settings import (+ STACK_OVERFLOW_FOR_TEAMS_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.stack_overflow_for_teams.stack_overflow_for_teams import (+ StackOverflowForTeamsResumeConfig,+ normalize_team,+ stack_overflow_for_teams_source,+ validate_credentials,+)++# 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"+# validate_credentials builds its own tracked session in the stack_overflow_for_teams module.+SO4T_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.stack_overflow_for_teams.stack_overflow_for_teams.make_tracked_session"+# The fan-out helper builds resources via rest_api_resources in the fanout module.+FANOUT_RESOURCES_PATCH = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout.rest_api_resources"+)+++class _FakeDltResource:+ def __init__(self, name: str, rows: list[dict]) -> None:+ self.name = name+ self._rows = rows++ def add_map(self, mapper):+ self._rows = [mapper(dict(row)) for row in self._rows]+ return self++ def __iter__(self):+ return iter(self._rows)+++class TestNormalizeTeam:+ @parameterized.expand(+ [+ ("bare", "engineering", "engineering"),+ ("with_hyphen", "team-alpha", "team-alpha"),+ ("with_underscore", "team_alpha", "team_alpha"),+ ("whitespace", " engineering ", "engineering"),+ ("alnum", "team123", "team123"),+ ]+ )+ def test_valid_teams(self, _name: str, value: str, expected: str) -> None:+ assert normalize_team(value) == expected++ @parameterized.expand(+ [+ ("path_injection", "team/../evil"),+ ("host_injection", "team.evil.com"),+ ("userinfo_injection", "[email protected]"),+ ("query_injection", "team?x=1"),+ ("empty", ""),+ ("space_inside", "team one"),+ ]+ )+ def test_invalid_teams_raise(self, _name: str, value: str) -> None:+ with pytest.raises(ValueError):+ normalize_team(value)+++def _response(+ items: list[dict[str, Any]] | None,+ *,+ page: int | None = None,+ total_pages: int | None = None,+ drop_key: bool = False,+) -> Response:+ body: dict[str, Any] = {}+ if not drop_key:+ body["items"] = items or []+ if page is not None:+ body["page"] = page+ if total_pages is not None:+ body["totalPages"] = total_pages+ resp = Response()+ resp.status_code = 200+ resp._content = json.dumps(body).encode()+ return resp+++def _make_manager(resume_state: StackOverflowForTeamsResumeConfig | None = None) -> mock.MagicMock:+ manager = mock.MagicMock()+ manager.can_resume.return_value = resume_state is not None+ manager.load_state.return_value = resume_state+ return manager+++def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:+ """Wire a mock session and return a list that captures each request AT SEND TIME.++ ``request.params`` is a single dict mutated in place across pages, so inspecting it after the+ run shows only the final state - snapshot a copy when each request is prepared instead.+ """+ session.headers = {}+ snapshots: list[dict[str, Any]] = []++ def _prepare(request: Any) -> mock.MagicMock:+ snapshots.append({"url": request.url, "params": dict(request.params or {}), "auth": request.auth})+ return mock.MagicMock()++ session.prepare_request.side_effect = _prepare+ session.send.side_effect = responses+ return snapshots+++def _source(endpoint: str, manager: mock.MagicMock, **kwargs: Any):+ return stack_overflow_for_teams_source(+ team="engineering",+ api_token="tok",+ endpoint=endpoint,+ team_id=1,+ job_id="j",+ resumable_source_manager=manager,+ **kwargs,+ )+++def _rows(source_response) -> list[dict[str, Any]]:+ return [row for page in source_response.items() for row in page]+++class TestStackOverflowForTeamsSourceNonFanout:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_paginates_until_total_pages(self, MockSession) -> None:+ session = MockSession.return_value+ snapshots = _wire(+ session,+ [+ _response([{"id": "1"}, {"id": "2"}], page=1, total_pages=2),+ _response([{"id": "3"}], page=2, total_pages=2),+ ],+ )++ rows = _rows(_source("Questions", _make_manager()))++ assert [r["id"] for r in rows] == ["1", "2", "3"]+ # totalPages=2 terminates after the last page - no extra empty-page request.+ assert session.send.call_count == 2+ assert snapshots[0]["url"] == "https://api.stackoverflowteams.com/v3/teams/engineering/questions"+ assert snapshots[0]["params"] == {"pageSize": 100, "sort": "creation", "order": "asc", "page": 1}+ assert snapshots[1]["params"]["page"] == 2++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_auth_is_framework_bearer(self, MockSession) -> None:+ from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import (+ BearerTokenAuth,+ )++ session = MockSession.return_value+ snapshots = _wire(session, [_response([{"id": "1"}], total_pages=1)])++ _rows(_source("Questions", _make_manager()))++ auth = snapshots[0]["auth"]+ assert isinstance(auth, BearerTokenAuth)+ assert auth.token == "tok"++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_saves_resume_state_only_while_pages_remain(self, MockSession) -> None:+ session = MockSession.return_value+ _wire(+ session,+ [+ _response([{"id": "1"}], page=1, total_pages=2),+ _response([{"id": "2"}], page=2, total_pages=2),+ ],+ )++ manager = _make_manager()+ _rows(_source("Questions", manager))++ # State is saved only while more pages remain (page 1 -> next_page 2), never on the last page.+ manager.save_state.assert_called_once()+ assert manager.save_state.call_args.args[0] == StackOverflowForTeamsResumeConfig(next_page=2)++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_resumes_from_saved_page(self, MockSession) -> None:+ session = MockSession.return_value+ snapshots = _wire(session, [_response([{"id": "2"}], page=2, total_pages=2)])++ rows = _rows(_source("Questions", _make_manager(StackOverflowForTeamsResumeConfig(next_page=2))))++ assert [r["id"] for r in rows] == ["2"]+ assert session.send.call_count == 1+ assert snapshots[0]["params"]["page"] == 2++ @pytest.mark.parametrize(+ "endpoint, expected_path, expected_sort, expected_order",+ [+ ("Questions", "/questions", "creation", "asc"),+ ("Articles", "/articles", "creation", "asc"),+ ("Tags", "/tags", "creationDate", "asc"),+ ("Users", "/users", "reputation", "asc"),+ ("Collections", "/collections", "creation", "asc"),+ ],+ )+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_each_top_level_endpoint_requests_its_own_path_and_sort(+ self, MockSession, endpoint, expected_path, expected_sort, expected_order+ ) -> None:+ session = MockSession.return_value+ snapshots = _wire(session, [_response([{"id": "1"}], total_pages=1)])++ _rows(_source(endpoint, _make_manager()))++ assert snapshots[0]["url"] == f"https://api.stackoverflowteams.com/v3/teams/engineering{expected_path}"+ assert snapshots[0]["params"]["sort"] == expected_sort+ assert snapshots[0]["params"]["order"] == expected_order++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_stops_on_empty_page(self, MockSession) -> None:+ session = MockSession.return_value+ _wire(session, [_response([], total_pages=1)])++ manager = _make_manager()+ rows = _rows(_source("Questions", manager))++ assert rows == []+ assert session.send.call_count == 1+ manager.save_state.assert_not_called()++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_missing_items_key_stops_quietly(self, MockSession) -> None:+ # A body without the "items" key is treated as an empty page.+ session = MockSession.return_value+ _wire(session, [_response(None, drop_key=True)])++ rows = _rows(_source("Questions", _make_manager()))++ assert rows == []+ assert session.send.call_count == 1++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_no_incremental_cursor_ever_passed(self, MockSession) -> None:+ # Every endpoint is full refresh - no server-side timestamp filter is used.+ session = MockSession.return_value+ snapshots = _wire(session, [_response([{"id": "1"}], total_pages=1)])++ _rows(_source("Questions", _make_manager()))++ assert "from" not in snapshots[0]["params"]+ assert "to" not in snapshots[0]["params"]+++class TestStackOverflowForTeamsSourceFanout:+ @mock.patch(FANOUT_RESOURCES_PATCH)+ def test_answers_fanout_row_format(self, mock_rest_api_resources) -> None:+ mock_rest_api_resources.return_value = [+ _FakeDltResource("Questions", [{"id": "q1"}]),+ _FakeDltResource("Answers", [{"id": "a1", "questionId": "q1"}]),+ ]++ response = stack_overflow_for_teams_source(+ team="engineering",+ api_token="tok",+ endpoint="Answers",+ team_id=1,+ job_id="j",+ resumable_source_manager=_make_manager(),+ )++ rows = list(cast(Any, response.items()))+ assert rows == [{"id": "a1", "questionId": "q1"}]+ assert response.primary_keys == ["id", "questionId"]+ assert response.partition_mode == "datetime"+ assert response.partition_keys == ["creationDate"]++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.stack_overflow_for_teams.stack_overflow_for_teams.build_dependent_resource"+ )+ def test_answers_fanout_wires_selectors(self, mock_build_dependent_resource) -> None:+ mock_build_dependent_resource.return_value = iter([])++ stack_overflow_for_teams_source(+ team="engineering",+ api_token="tok",+ endpoint="Answers",+ team_id=1,+ job_id="j",+ resumable_source_manager=_make_manager(),+ )++ kwargs = mock_build_dependent_resource.call_args.kwargs+ assert kwargs["page_size_param"] == "pageSize"+ assert kwargs["parent_endpoint_extra"]["data_selector"] == "items"+ assert kwargs["child_endpoint_extra"]["data_selector"] == "items"+ assert kwargs["should_use_incremental_field"] is False+ assert kwargs["fanout"].parent_name == "Questions"+ assert kwargs["fanout"].resolve_param == "questionId"+ assert kwargs["fanout"].resolve_field == "id"+++class TestExpectedSchemaEndpoints:+ def test_every_endpoint_declared_in_settings_has_a_path_and_primary_key(self) -> None:+ for _name, config in STACK_OVERFLOW_FOR_TEAMS_ENDPOINTS.items():+ assert config.path+ assert config.primary_keys+++class TestValidateCredentials:+ @mock.patch(SO4T_SESSION_PATCH)+ def test_ok(self, mock_session) -> None:+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=200)+ assert validate_credentials("engineering", "tok") == (True, 200)++ @mock.patch(SO4T_SESSION_PATCH)+ def test_unauthorized(self, mock_session) -> None:+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=401)+ assert validate_credentials("engineering", "tok") == (False, 401)++ @mock.patch(SO4T_SESSION_PATCH)+ def test_swallows_transport_errors(self, mock_session) -> None:+ mock_session.return_value.get.side_effect = Exception("boom")+ assert validate_credentials("engineering", "tok") == (False, None)++ @mock.patch(SO4T_SESSION_PATCH)+ def test_probes_users_me_endpoint_with_bearer_header(self, mock_session) -> None:+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=200)+ validate_credentials("engineering", "tok")++ call = mock_session.return_value.get.call_args+ assert call.args[0] == "https://api.stackoverflowteams.com/v3/teams/engineering/users/me"+ assert call.kwargs["headers"]["Authorization"] == "Bearer tok"++ @mock.patch(SO4T_SESSION_PATCH)+ def test_bad_team_raises_before_probe(self, mock_session) -> None:+ with pytest.raises(ValueError, match="Invalid Stack Overflow for Teams team name"):+ validate_credentials("team/../evil", "tok")+ mock_session.assert_not_called()diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/stack_overflow_for_teams/tests/test_stack_overflow_for_teams_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/stack_overflow_for_teams/tests/test_stack_overflow_for_teams_source.pynew file mode 100644index 000000000000..d11ad00f9e9f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/stack_overflow_for_teams/tests/test_stack_overflow_for_teams_source.py@@ -0,0 +1,174 @@+import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.stackoverflowforteams import (+ StackOverflowForTeamsSourceConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.stack_overflow_for_teams.settings import (+ ENDPOINTS,+ STACK_OVERFLOW_FOR_TEAMS_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.stack_overflow_for_teams.source import (+ StackOverflowForTeamsSource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.stack_overflow_for_teams.stack_overflow_for_teams import (+ StackOverflowForTeamsResumeConfig,+)+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestStackOverflowForTeamsSource:+ def setup_method(self):+ self.source = StackOverflowForTeamsSource()+ self.team_id = 123+ self.config = StackOverflowForTeamsSourceConfig(team="engineering", api_token="tok")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.STACKOVERFLOWFORTEAMS++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "StackOverflowForTeams"+ assert config.label == "Stack Overflow (Prosus/Stack Exchange)"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is None+ assert config.iconPath == "/static/services/stack_overflow_for_teams.png"+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/stack-overflow-for-teams"++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["team", "api_token"]++ def test_api_token_field_is_secret_password(self):+ config = self.source.get_source_config+ api_token_field = next(+ f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_token"+ )+ assert api_token_field.type == SourceFieldInputConfigType.PASSWORD+ assert api_token_field.secret is True+ assert api_token_field.required is True++ def test_team_listed_as_connection_host_field(self):+ # The PAT is sent to api.stackoverflowteams.com/v3/teams/<team>, so retargeting the+ # team must re-require it.+ assert self.source.connection_host_fields == ["team"]++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://api.stackoverflowteams.com/v3/teams/engineering/questions",+ "403 Client Error: Forbidden for url: https://api.stackoverflowteams.com/v3/teams/engineering/articles",+ ],+ )+ def test_non_retryable_errors_match_auth_failures(self, observed_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable_errors)++ @pytest.mark.parametrize(+ "other_error",+ [+ "429 Client Error: Too Many Requests for url: https://api.stackoverflowteams.com/v3/teams/engineering/questions",+ "500 Server Error: Internal Server Error for url: https://api.stackoverflowteams.com/v3/teams/engineering/questions",+ "HTTPSConnectionPool(host='api.stackoverflowteams.com', port=443): Read timed out.",+ ],+ )+ def test_non_retryable_errors_do_not_match_transient(self, other_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable_errors)++ def test_get_schemas_match_endpoints_all_full_refresh(self):+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}++ assert set(schemas) == set(ENDPOINTS)+ for name in ENDPOINTS:+ # No verified server-side timestamp filter on any v3 list endpoint yet - every+ # table ships full refresh.+ assert schemas[name].supports_incremental is False+ assert schemas[name].supports_append is False+ assert schemas[name].incremental_fields == []++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["Questions"])+ assert len(schemas) == 1+ assert schemas[0].name == "Questions"++ def test_get_schemas_filtered_unknown_name_returns_empty(self):+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ def test_lists_tables_without_credentials_publishes_catalog(self):+ # Static endpoint catalog (no I/O) - the public docs table list should render.+ assert self.source.lists_tables_without_credentials is True+ documented = self.source.get_documented_tables()+ assert {table["name"] for table in documented} == set(ENDPOINTS)++ def test_canonical_descriptions_cover_every_endpoint(self):+ canonical = self.source.get_canonical_descriptions()+ assert set(canonical) == set(STACK_OVERFLOW_FOR_TEAMS_ENDPOINTS)++ @pytest.mark.parametrize(+ "mock_return, expected_valid, expected_message",+ [+ ((True, 200), True, None),+ ((False, 401), False, "Invalid Stack Overflow for Teams personal access token"),+ (+ (False, 403),+ False,+ "Could not connect to Stack Overflow for Teams with the provided team name and personal access token",+ ),+ (+ (False, None),+ False,+ "Could not connect to Stack Overflow for Teams with the provided team name and personal access token",+ ),+ ],+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.stack_overflow_for_teams.source.validate_stack_overflow_for_teams_credentials"+ )+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid, expected_message):+ mock_validate.return_value = mock_return++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is expected_valid+ assert error_message == expected_message+ mock_validate.assert_called_once_with("engineering", "tok")++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.stack_overflow_for_teams.source.validate_stack_overflow_for_teams_credentials"+ )+ def test_validate_credentials_surfaces_bad_team(self, mock_validate):+ mock_validate.side_effect = ValueError("Invalid Stack Overflow for Teams team name: 'a/b'.")++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is False+ assert "Invalid Stack Overflow for Teams team name" in (error_message or "")++ def test_get_resumable_source_manager_bound_to_resume_config(self):+ inputs = mock.MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)+ assert manager._data_class is StackOverflowForTeamsResumeConfig++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.stack_overflow_for_teams.source.stack_overflow_for_teams_source"+ )+ def test_source_for_pipeline_plumbs_arguments(self, mock_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "Questions"+ inputs.team_id = self.team_id+ inputs.job_id = "job-1"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_source.assert_called_once()+ kwargs = mock_source.call_args.kwargs+ assert kwargs["team"] == "engineering"+ assert kwargs["api_token"] == "tok"+ assert kwargs["endpoint"] == "Questions"+ assert kwargs["team_id"] == self.team_id+ assert kwargs["job_id"] == "job-1"+ assert kwargs["resumable_source_manager"] is manager