: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(customer-analytics): sync feature requests with github issues (#101963)
Arthur Moreira de Deusde00e25fb607
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yamlindex 1505b7923fc6..b8342cfd508e 100644--- a/.semgrep/rules/security/idor-team-scoped-models.yaml+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml@@ -210,6 +210,7 @@ rules:|FeatureRequest|FeatureRequestAccountLink|FeatureRequestEvidence+ |FeatureRequestGitHubLink|FeatureRequestHistory|FeatureRequestProductArea|FeatureRequestProductAreaLink@@ -625,6 +626,7 @@ rules:|FeatureRequest|FeatureRequestAccountLink|FeatureRequestEvidence+ |FeatureRequestGitHubLink|FeatureRequestHistory|FeatureRequestProductArea|FeatureRequestProductAreaLinkdiff --git a/docs/internal/customer-analytics-feature-requests.md b/docs/internal/customer-analytics-feature-requests.mdnew file mode 100644index 000000000000..c13ea155466c--- /dev/null+++ b/docs/internal/customer-analytics-feature-requests.md@@ -0,0 +1,93 @@+# Customer Analytics feature request GitHub links++A feature request can link to one GitHub issue through a GitHub integration connected to the same project.++## Behavior++- Linking and resuming sync fetch the current issue through the selected GitHub App integration.+- The integration must be active, belong to the project, still reference the saved installation, and be visible to the person linking or resuming sync.+- Feature request responses and history include GitHub link metadata only when the person can view the integration. Other history changes remain visible.+- GitHub issue URLs use `https://github.com/<owner>/<repo>/issues/<number>`. Pull request URLs are rejected. Comment fragments do not affect the saved link.+- Closing an issue with reason `completed` marks the request Completed. Legacy closures without a reason also map to Completed.+- Closing an issue with reason `not_planned` marks the request Won't fix. Unsupported closure reasons do not change the request.+- Reopening restores the request status that existed before GitHub closed it.+- A manual request status update pauses GitHub sync and clears the saved pre-close status. Resuming a closed issue saves the current manual status as the new restore point.+- Pause sync preserves the pre-close status. If the issue reopens while paused, Resume sync restores that status.+- GitHub never overwrites the request title or description. Multiple requests can link to the same issue.+- GitHub metadata-only updates refresh the link without changing the request version, update timestamp, attribution, or history. Status and sync-control changes still update the request.+- Unlink issue preserves the request status and history. An existing link must be removed before another issue can be linked.+- Link, pause, resume, unlink, and GitHub status changes are recorded in feature request history. GitHub-sourced history uses `change_source: "github"`.+- Archived requests reject link controls. Background updates for archived requests do nothing.++## Delivery and limits++The GitHub ingress consumer queues installation ID, repository, issue number, title, state, close reason, and GitHub update time.+It also carries the GitHub delivery ID and receipt time for correlation.+It never queues issue bodies.++The worker finds all matching project-scoped links for an installation.+It ignores duplicate and older GitHub snapshots.+When conflicting state changes share a timestamp, it fetches the current issue because GitHub timestamps have second precision.+The worker checks the feature flag for the user who last enabled sync, with the same organization and project context as the API.+A deleted user, unavailable integration, archived request, paused link, or disabled flag prevents automatic updates.++The worker processes every matching link before it retries a delivery with a conflicted request. It does not periodically repair missed webhooks.+Pause sync, then select Resume sync to fetch the latest issue state.+Scheduled reconciliation and operator alerts are separate work.++## Tracing a sync++Start with the `X-GitHub-Delivery` value from GitHub's delivery page.+Find the shared `ingress_delivery_dispatch` log by `delivery_id`, then filter product logs by `github_delivery_id` with the same value.+The queue log includes `task_id`. Retries retain that task ID and increment the zero-based `sync_attempt`.++| Event | Meaning |+| ------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------- |+| `feature_request_github_delivery_queued` | Celery publication returned a task ID. This does not prove that a worker ran. |+| `feature_request_github_task_started` | An attempt began. `delivery_age_seconds` measures time since receipt, including retry delays. |+| `feature_request_github_target_applied` | The target transaction committed. `status_before`, `status_after`, and `changed` describe the request status change. |+| `feature_request_github_target_skipped` | A matched target did not apply the update. Inspect `reason`. Stale and duplicate outcomes use debug level. |+| `feature_request_github_target_conflicted` | A request version changed. Other targets can still update before the delivery retries. |+| `feature_request_github_target_failed` | A target failed. Inspect `stage` and `error_type`. |+| `feature_request_github_delivery_summary` | The attempt reports matched, applied, skipped, conflicted, and failed target counts. Earlier targets can commit even when the attempt fails. |++Target logs include `team_id`, `feature_request_id`, `github_link_id`, and `integration_id`.+The initial query excludes paused links, so `matched=0` does not distinguish a paused link from an unlinked issue.+A `paused` reason means the worker observed a link pause after selecting it.+A successful summary with `applied=0` is not proof of synchronization.++Terminal failures after the three configured retries produce a sanitized `FeatureRequestGitHubTaskFailed` exception in PostHog Error Tracking.+Search its properties by `github_delivery_id` or `task_id`, then inspect the target logs for the failing request.+The exception retains stack locations and records the original exception type, but excludes its message, chain, and local variables.+No new log includes issue titles, bodies, repository URLs, credentials, or raw payloads.++For manual actions, search `feature_request_github_manual_action_committed` by `team_id` and `feature_request_id`.+Link and resume fetch failures use `feature_request_github_issue_fetch_failed`, with the action, request ID, upstream status when available, and a bounded failure stage.+These logs preserve the user-facing validation response.++Verify log and exception delivery with an internal test before expanding the flag.+Reuse the existing Celery metrics for `customer_analytics.process_feature_request_github_issue` when configuring failure alerts.+This instrumentation does not create alerts or add missed-webhook reconciliation.+Do not infer a missed delivery from an old `last_synced_at` alone; an unchanged issue may have no new event.++## Local checks++Run:++```sh+hogli test products/customer_analytics/backend/test/test_feature_request_github.py products/customer_analytics/backend/test/test_feature_request_github_observability.py+hogli test posthog/ingress/test/+pnpm --filter=@posthog/frontend typescript:check+```++Generate OpenAPI after backend changes with `hogli build:openapi`.+The rollout remains gated by `customer-analytics-feature-requests`.++## Rollout checks++Use an internal test request and an accessible test issue.+Link it, close it as completed, reopen it, and close it as not planned.+Check request history after each transition.+Change the request status manually and confirm that later issue events do not override it until sync resumes.+Repeat a denied write as a viewer.+Do not expand the rollout until missed-webhook recovery and synchronization health checks are available.diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 5f7a1ec3944f..18e217493dce 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -2316,6 +2316,42 @@ snapshots:hash: v1.k794b7964.a1866d682eb35809e8a9bea08ec0c7af8cb77581e4667745851bd9db5f49918d.mhIpdnK7yIoTFvovSR-wJrEHGV_7_T3eTvSNRv0UbtYcustomer-analytics-custom-property-sync-runs--loading--light:hash: v1.k794b7964.b376cab90219eb5e85b659c1399b40c0d60caf7a91b006c0d168375ed365d2af.61Y57PmrNuzzIfBps59FSyMmFnBf3yzKDcPD6vs5VHI+ customer-analytics-feature-requests-github-issue--archived--dark:+ hash: v1.k794b7964.6353d8360a139bb403c1ece6b033793a0e9d71ece3e3624c40097d702b8a8393.ZF8kHNdiifHQUHTWzRM0a4tvySXtrbkKOm5fB0l2ie8+ customer-analytics-feature-requests-github-issue--archived--light:+ hash: v1.k794b7964.4b34507504c8e08e9fb4c694674ef1e3c6f3262644cb75de5ebe2062431a3afc.RswO9tihTAdZQfbNaQ-I1RucrsQx9LgmBtXeeipFTrs+ customer-analytics-feature-requests-github-issue--error--dark:+ hash: v1.k794b7964.e2bf53c41ee850848979128cda770db93dbbea69ba5436f706ec191cc72e7a18._lDW_-_atxEzNnVBCJg3v9qVPem8ovMqyqlOqtVOsa4+ customer-analytics-feature-requests-github-issue--error--light:+ hash: v1.k794b7964.0c77c184bfc5a44937186e0d61a9eff35d5e5711f5495a6035aaeac9e58e3548.XiW6Gz3x0d5fyBmXbZo4xtaaPp0yw3XicpQZTOl2Bxw+ customer-analytics-feature-requests-github-issue--linked--dark:+ hash: v1.k794b7964.873d57a505271659a6e25f9312ab71371203d70e84347ef0874d8a01656cd024.GuCbCY6Wu6nP6TrlCgA7ZMlw5uBypg3aa-ooy-sdBXc+ customer-analytics-feature-requests-github-issue--linked--light:+ hash: v1.k794b7964.e28fd921284e0bfa66037d431f28857a009cce11dc11fa2797951a0f7965d4d5.ou06lsC-0HIgUHHwGfGBIp0of29DQpJBGbYDujF9-eI+ customer-analytics-feature-requests-github-issue--linked-narrow--dark:+ hash: v1.k794b7964.a08ce4b5b92304d6be722079d4d9864dd44c75479aa14646256e2151a31537c8.cEVZ-USlmB32k3pn0FS5UG266M4PiZZLW4HHoJWs6oo+ customer-analytics-feature-requests-github-issue--linked-narrow--light:+ hash: v1.k794b7964.92920221247ae1dea6a55715c44745e5b275f3cb2845d1cee8117e889036390c._qVeZZqXJkf1o2XgPJiONIbYTBYtSV4d4dAbbT7nWrQ+ customer-analytics-feature-requests-github-issue--loading--dark:+ hash: v1.k794b7964.ae8c6c47cc537ea53b1af9fe0969c40b88e243e451240a74569c293581ae8659.2iXfUI6yL3y7gGoBWpCQjQbO69lkeiHGwGIfldLBe4w+ customer-analytics-feature-requests-github-issue--loading--light:+ hash: v1.k794b7964.316a650bdd443ec9185e6e4b10cf8b6c2ae4aefd455bc06d11b778038223b9c3.bAMZZRFWt-l9cLVIrDmwwJinwVy-ZbnAiTSXNEqwTTQ+ customer-analytics-feature-requests-github-issue--paused--dark:+ hash: v1.k794b7964.c38146948affb061a13a3e3f38d9363de5f493370121a8e438688cf5fd5bd08e.58XelnRiylPK7Ltp_oBmZ813chv65ymyaegkhoqDUDA+ customer-analytics-feature-requests-github-issue--paused--light:+ hash: v1.k794b7964.e84e1e2475720a708d4dbd52decd32a1eecfb0f89b95f461e861a18a6cc2d7c4.u7zqiuRcEhrGU7MKY5mxtvVV2kj0ero-1VRlFXo66g8+ customer-analytics-feature-requests-github-issue--read-only--dark:+ hash: v1.k794b7964.6353d8360a139bb403c1ece6b033793a0e9d71ece3e3624c40097d702b8a8393.siWLuXtJkh4_9I_phWXL3H37bbkAeshfjEtjtKecINE+ customer-analytics-feature-requests-github-issue--read-only--light:+ hash: v1.k794b7964.4b34507504c8e08e9fb4c694674ef1e3c6f3262644cb75de5ebe2062431a3afc.UKgwKIazvMczbae5lFtAm6dlNU0LNsVXKZ-l7RXGXg0+ customer-analytics-feature-requests-github-issue--unlinked--dark:+ hash: v1.k794b7964.04dd14f58cf2bed301e0699739df17660b664171e750ed19adcbb9b4b9addc1b.jLGCrdvqrTJ-YL9kmpg3SLwauJ36J73F0Zw85laaKFE+ customer-analytics-feature-requests-github-issue--unlinked--light:+ hash: v1.k794b7964.d62bbd8b11d4417475bb6d0b11eaaa3eefe1480070d703e3e64709ca357377de.CYN66qHaMOPVcVM8H2tIxAG8BcQvC6gQjJDnZ8MSETs+ customer-analytics-feature-requests-github-issue--unlinked-narrow--dark:+ hash: v1.k794b7964.5195345d37cfa03c1ed49a8d7e834c09fd84fe12254946df942a9b6da7f64749.NzqeFSnrKRRDTIE3hB8c8pqTNg3J3WJ92_HNk3iMKiA+ customer-analytics-feature-requests-github-issue--unlinked-narrow--light:+ hash: v1.k794b7964.319a777cdf92ef36e338a0d1169f6730d32eb4e2f9970e2fa57105ef2e2f4a77.T6buSnxFuJwtVO0v_coBZPCXBqg5yWRuFCxxrgpJYt0customer-analytics-google-account-backfill--default--dark:hash: v1.k794b7964.ecd19318b62cacf92b36fb61a3c0bd0972a10d144883d5abd28b75237a58a74a.2Ut9o4x8DHeuHyXBP64avfL_gVepYPHuCuJk3_himWQcustomer-analytics-google-account-backfill--default--light:@@ -7165,9 +7201,9 @@ snapshots:scenes-app-customer-analytics-dashboard--customer-tasks--light:hash: v1.k794b7964.acedcb03c7c39d27c2b9f0ed3f1b1ac44fe3fdc58f68a0ed0d0b9e475e70ca96.nKLpWDvqLrHFG2HwFEAexR8rc63-OmxYQogH_Utdg9Iscenes-app-customer-analytics-dashboard--feature-request-details--dark:- hash: v1.k794b7964.dd76e36d821568ab1a8ea103274a39792a5916586913dcc54d4b8c6022aed968.ofepc5cJ-e3ysJbDmjbn2yyefm6X7NwNtnjOfyB4WmA+ hash: v1.k794b7964.d87f1abf2d12f5814dd652ba1c760a15d00f6fa2f6927f9aaa662dacbd91a83c.8qn3xLm6N1ZugTMoofH8kEhupFhydr4UcG0Wlko4SLYscenes-app-customer-analytics-dashboard--feature-request-details--light:- hash: v1.k794b7964.8cd0d06dbe8fa12d819f9324d191d3ec9a0741b51acf19ac6490b99aecc1dda7.k0bCKYz1oUdVTINzDzlFA4ZUmefNVOBoQx7Y3KADYxI+ hash: v1.k794b7964.d680dee192e6bae4a5d9da8a0f07b536a4fc5d60e7be61c289bb9b68947f7baf.-uES35AODxvWOszJFog_2I2AoUS8zZKkPQDN4P5jcIMscenes-app-customer-analytics-dashboard--feature-requests--dark:hash: v1.k794b7964.cdb1e78cc03a73305759adfda8ec4e46998a7c9826d48596f540585080cdd9e2.uvLopYXQLlmpCnN6udMWmzalGd8gZ1YL_iGj4DT4cAcscenes-app-customer-analytics-dashboard--feature-requests--light:diff --git a/posthog/egress/github/README.md b/posthog/egress/github/README.mdindex 0bda972dada7..d39d26480905 100644--- a/posthog/egress/github/README.md+++ b/posthog/egress/github/README.md@@ -26,7 +26,7 @@ All three budgets use the default reserve ladder.Deferrable background callers construct their client on the `BATCH` lane (`GitHubIntegration(integration, source=..., priority=Priority.BATCH)`; `api_request` also takes a per-call override).A shed sweep stops for the cycle and resumes on the next scheduled run.A caller that walks pages, such as the warehouse source, paces with `github_installation_pace_seconds` instead of getting denied.-The warehouse source's page fetches run on `BATCH`, while its repository validation and webhook management run on `NORMAL`, because a person waits on them.+The warehouse source's page fetches run on `BATCH`, while its repository validation and webhook management run on `NORMAL`, because a person waits on them. Customer Analytics feature-request link and resume lookups also run on `NORMAL` because an editor waits for the current issue state.The `BATCH` floor on the `core` resource is **demand-responsive**, because a reserve is only worth holding against traffic that exists.An installation whose only consumer is a bulk one (a warehouse backfill of a repository nothing else touches) would otherwise forfeit 30% of its hourly budget to contention that never arrives, and the hourly budget is what decides whether a large backfill finishes in one run.diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.pyindex 738de27ce2eb..902615ca70c4 100644--- a/products/customer_analytics/backend/facade/api.py+++ b/products/customer_analytics/backend/facade/api.py@@ -105,6 +105,7 @@ from products.customer_analytics.backend.logic import (channel_summaries as _channel_summaries_logic,custom_property_values as _custom_property_values_logic,customer_tasks as _customer_tasks_logic,+ feature_request_github as _feature_request_github_logic,feature_requests as _feature_requests_logic,ownership as _ownership,relationships as _relationships_logic,@@ -2433,6 +2434,7 @@ def list_custom_property_sync_runs(FeatureRequestValidationError = _feature_requests_logic.FeatureRequestValidationErrorFeatureRequestProductAreaConflictError = _feature_requests_logic.FeatureRequestProductAreaConflictErrorFeatureRequestConflictError = _feature_requests_logic.FeatureRequestConflictError+GitHubLinkUnavailableError = _feature_request_github_logic.GitHubLinkUnavailableErrordef list_feature_request_product_areas(@@ -2530,6 +2532,89 @@ def update_feature_request()+def link_feature_request_github(+ *,+ team_id: int,+ feature_request_id: UUID,+ input: contracts.LinkFeatureRequestGitHubInput,+ actor_id: int,+ user_access_control: "UserAccessControl",+) -> contracts.FeatureRequestView | None:+ return _feature_request_github_logic.link_feature_request_github(+ team_id=team_id,+ feature_request_id=feature_request_id,+ input=input,+ actor_id=actor_id,+ user_access_control=user_access_control,+ )+++def set_feature_request_github_sync(+ *,+ team_id: int,+ feature_request_id: UUID,+ expected_version: int,+ enabled: bool,+ actor_id: int,+ user_access_control: "UserAccessControl",+) -> contracts.FeatureRequestView | None:+ return _feature_request_github_logic.set_feature_request_github_sync(+ team_id=team_id,+ feature_request_id=feature_request_id,+ expected_version=expected_version,+ enabled=enabled,+ actor_id=actor_id,+ user_access_control=user_access_control,+ )+++def unlink_feature_request_github(+ *,+ team_id: int,+ feature_request_id: UUID,+ expected_version: int,+ actor_id: int,+ user_access_control: "UserAccessControl",+) -> contracts.FeatureRequestView | None:+ return _feature_request_github_logic.unlink_feature_request_github(+ team_id=team_id,+ feature_request_id=feature_request_id,+ expected_version=expected_version,+ actor_id=actor_id,+ user_access_control=user_access_control,+ )+++def process_feature_request_github_delivery(+ *,+ installation_id: str,+ repository: str,+ issue_number: int,+ issue_title: str,+ issue_state: str,+ issue_state_reason: str,+ github_updated_at: datetime,+ github_delivery_id: str | None = None,+ github_received_at: str | None = None,+) -> str:+ from products.customer_analytics.backend.tasks.tasks import (+ process_feature_request_github_issue, # noqa: PLC0415 — Celery task registration must stay off the facade import path+ )++ task = process_feature_request_github_issue.delay(+ installation_id=installation_id,+ repository=repository,+ issue_number=issue_number,+ issue_title=issue_title,+ issue_state=issue_state,+ issue_state_reason=issue_state_reason,+ github_updated_at=github_updated_at.isoformat(),+ github_delivery_id=github_delivery_id,+ github_received_at=github_received_at,+ )+ return task.id++def add_feature_request_account(*,team_id: int,diff --git a/products/customer_analytics/backend/facade/contracts.py b/products/customer_analytics/backend/facade/contracts.pyindex 28261399e4a2..e06a753cec11 100644--- a/products/customer_analytics/backend/facade/contracts.py+++ b/products/customer_analytics/backend/facade/contracts.py@@ -837,6 +837,18 @@ class FeatureRequestAccountLinkView:updated_at: datetime | None = None+@stdlib_dataclass(frozen=True)+class FeatureRequestGitHubLinkView:+ id: UUID | None = None+ issue_url: str = ""+ repository: str = ""+ issue_number: int = 0+ issue_title: str = ""+ issue_state: Literal["open", "closed"] = "open"+ sync_enabled: bool = True+ last_synced_at: datetime | None = None++@stdlib_dataclass(frozen=True)class FeatureRequestView:id: UUID | None = None@@ -853,6 +865,7 @@ class FeatureRequestView:account_links: list[FeatureRequestAccountLinkView] = field(default_factory=list)evidence_count: int = 0product_areas: list[FeatureRequestProductAreaView] = field(default_factory=list)+ github_link: FeatureRequestGitHubLinkView | None = Nonecreated_by: int | None = Noneupdated_by: int | None = Nonecreated_at: datetime | None = None@@ -937,6 +950,13 @@ class UpdateFeatureRequestInput:request_priority_is_set: bool = False+@dataclass(frozen=True)+class LinkFeatureRequestGitHubInput:+ expected_version: int+ integration_id: int+ issue_url: str++@dataclass(frozen=True)class AddFeatureRequestAccountInput:expected_version: intdiff --git a/products/customer_analytics/backend/logic/feature_request_github.py b/products/customer_analytics/backend/logic/feature_request_github.pynew file mode 100644index 000000000000..5c13da3555d1--- /dev/null+++ b/products/customer_analytics/backend/logic/feature_request_github.py@@ -0,0 +1,674 @@+import re+from datetime import datetime+from functools import partial+from typing import TYPE_CHECKING, Literal+from urllib.parse import urlparse+from uuid import UUID++from django.db import transaction+from django.utils import timezone++import requests+import structlog+from structlog.contextvars import bound_contextvars, get_contextvars++from posthog.dataclasses import frozen+from posthog.egress.github.transport import GitHubEgressBudgetExhausted, GitHubRateLimitError+from posthog.egress.limiter.policies import Priority+from posthog.models import Integration+from posthog.models.github_integration_base import GitHubIntegrationError+from posthog.models.integration.github import GitHubIntegration+from posthog.permissions import posthog_feature_flag_enabled++from products.customer_analytics.backend.constants import CUSTOMER_ANALYTICS_FEATURE_REQUESTS_FLAG+from products.customer_analytics.backend.facade import contracts+from products.customer_analytics.backend.logic.feature_requests import (+ FeatureRequestConflictError,+ FeatureRequestValidationError,+ _ensure_initial_history,+ _get_accessible_feature_request_for_update,+ _refresh_feature_request,+)+from products.customer_analytics.backend.models import (+ FeatureRequest,+ FeatureRequestGitHubLink,+ FeatureRequestHistory,+ FeatureRequestHistorySource,+ FeatureRequestStatus,+)++if TYPE_CHECKING:+ from products.access_control.backend.facade.user_access_control import UserAccessControl+++class GitHubLinkUnavailableError(ValueError):+ pass+++@frozen+class GitHubIssueState:+ title: str+ state: Literal["open", "closed"]+ reason: str+ updated_at: datetime+++logger = structlog.get_logger(__name__)++_CONFLICT_MESSAGE = "This request changed since you opened it. Reload it and try again."+_REPOSITORY = re.compile(r"[A-Za-z0-9_-]+/[A-Za-z0-9_.-]+")+++def _log_manual_action_after_commit(+ *,+ action: str,+ team_id: int,+ feature_request_id: UUID,+ github_link_id: UUID | None,+ integration_id: int | None,+ changed: bool,+) -> None:+ with bound_contextvars(+ team_id=team_id,+ feature_request_id=str(feature_request_id),+ github_link_id=str(github_link_id) if github_link_id is not None else None,+ integration_id=integration_id,+ action=action,+ ):+ committed_context = get_contextvars()+ transaction.on_commit(+ partial(logger.info, "feature_request_github_manual_action_committed", changed=changed, **committed_context)+ )+++def _log_issue_fetch_failure(+ integration: Integration, *, stage: str, error_type: str, status_code: int | None = None+) -> None:+ logger.warning(+ "feature_request_github_issue_fetch_failed",+ team_id=integration.team_id,+ integration_id=integration.id,+ stage=stage,+ error_type=error_type,+ status_code=status_code,+ )+++def _parse_issue_url(issue_url: str) -> tuple[str, int]:+ try:+ parsed = urlparse(issue_url)+ port = parsed.port+ except ValueError as exc:+ raise FeatureRequestValidationError("issue_url", "Enter a GitHub issue URL.") from exc+ if (+ parsed.scheme != "https"+ or parsed.hostname != "github.com"+ or port is not None+ or parsed.username is not None+ or parsed.password is not None+ or parsed.query+ ):+ raise FeatureRequestValidationError("issue_url", "Enter a GitHub issue URL.")+ match = re.fullmatch(r"/([^/]+/[^/]+)/issues/([0-9]+)/?", parsed.path)+ if match is None or not _REPOSITORY.fullmatch(match[1]) or match[1].split("/")[1] in {".", ".."}:+ raise FeatureRequestValidationError("issue_url", "Enter a GitHub issue URL. Pull requests are not supported.")+ number = int(match[2])+ if not 0 < number <= 2147483647:+ raise FeatureRequestValidationError("issue_url", "Enter a valid GitHub issue number.")+ return match[1].lower(), number+++def _issue_snapshot(link: FeatureRequestGitHubLink) -> dict[str, object]:+ return {+ "id": str(link.id),+ "issue_url": f"https://github.com/{link.repository}/issues/{link.issue_number}",+ "repository": link.repository,+ "issue_number": link.issue_number,+ "issue_title": link.issue_title,+ "issue_state": link.issue_state,+ "sync_enabled": link.sync_enabled,+ }+++def _github_status(reason: str) -> str:+ if reason in {"completed", ""}:+ return FeatureRequestStatus.COMPLETED+ if reason == "not_planned":+ return FeatureRequestStatus.WONT_FIX+ raise GitHubLinkUnavailableError("GitHub returned an unsupported closure reason. Check the issue and try again.")+++def _parse_issue_payload(payload: dict[str, object], repository: str, issue_number: int) -> GitHubIssueState:+ html_url = payload.get("html_url")+ repository_url = payload.get("repository_url")+ if not isinstance(html_url, str) or not isinstance(repository_url, str):+ raise GitHubLinkUnavailableError("GitHub returned an invalid issue. Try again.")+ try:+ coordinates = _parse_issue_url(html_url)+ except FeatureRequestValidationError as exc:+ raise GitHubLinkUnavailableError("GitHub returned an invalid issue. Try again.") from exc+ if (+ "pull_request" in payload+ or type(payload.get("number")) is not int+ or payload["number"] != issue_number+ or coordinates != (repository, issue_number)+ or repository_url.lower() != f"https://api.github.com/repos/{repository}"+ ):+ raise GitHubLinkUnavailableError("GitHub returned a different issue. Check the URL and try again.")+ state = payload.get("state")+ title = payload.get("title")+ timestamp = payload.get("updated_at")+ reason = payload.get("state_reason") or ""+ if state not in {"open", "closed"} or not isinstance(title, str) or not isinstance(reason, str):+ raise GitHubLinkUnavailableError("GitHub returned an invalid issue state. Try again.")+ if state == "closed":+ _github_status(reason)+ try:+ updated_at = datetime.fromisoformat(timestamp.replace("Z", "+00:00")) if isinstance(timestamp, str) else None+ except ValueError as exc:+ raise GitHubLinkUnavailableError("GitHub returned an invalid issue update time. Try again.") from exc+ if updated_at is None or timezone.is_naive(updated_at):+ raise GitHubLinkUnavailableError("GitHub returned an invalid issue update time. Try again.")+ return GitHubIssueState(+ title=title, state="closed" if state == "closed" else "open", reason=reason, updated_at=updated_at+ )+++def _integration(+ team_id: int,+ integration_id: int | None,+ installation_id: str | None = None,+ user_access_control: "UserAccessControl | None" = None,+) -> Integration:+ if integration_id is None:+ raise FeatureRequestValidationError("integration_id", "Reconnect the GitHub integration before resuming sync.")+ integration = Integration.objects.filter(id=integration_id, team_id=team_id, kind="github").first()+ if (+ integration is None+ or not integration.integration_id+ or (installation_id is not None and integration.integration_id != installation_id)+ or GitHubIntegration(integration).installation_unavailable()+ ):+ raise FeatureRequestValidationError(+ "integration_id", "Select an available GitHub integration for this project."+ )+ if user_access_control is not None and not user_access_control.check_access_level_for_object(+ integration, required_level="viewer"+ ):+ raise FeatureRequestValidationError("integration_id", "Select a GitHub integration you can access.")+ return integration+++def _fetch_issue(+ integration: Integration, repository: str, issue_number: int, *, priority: Priority = Priority.NORMAL+) -> GitHubIssueState:+ try:+ response = GitHubIntegration(integration, source="customer_analytics", priority=priority).api_request(+ "GET",+ f"/repos/{repository}/issues/{issue_number}",+ endpoint="/repos/{owner}/{repo}/issues/{issue_number}",+ priority=priority,+ retry_transient=False,+ )+ except GitHubEgressBudgetExhausted as exc:+ _log_issue_fetch_failure(integration, stage="budget", error_type=type(exc).__name__)+ raise GitHubLinkUnavailableError("GitHub could not load this issue. Try again.") from exc+ except GitHubRateLimitError as exc:+ _log_issue_fetch_failure(integration, stage="rate_limit", error_type=type(exc).__name__)+ raise GitHubLinkUnavailableError("GitHub could not load this issue. Try again.") from exc+ except GitHubIntegrationError as exc:+ _log_issue_fetch_failure(integration, stage="integration", error_type=type(exc).__name__)+ raise GitHubLinkUnavailableError("GitHub could not load this issue. Try again.") from exc+ except requests.RequestException as exc:+ _log_issue_fetch_failure(integration, stage="transport", error_type=type(exc).__name__)+ raise+ if response.status_code in {401, 403, 404}:+ _log_issue_fetch_failure(+ integration, stage="status", error_type="GitHubResponseError", status_code=response.status_code+ )+ raise FeatureRequestValidationError(+ "issue_url", "GitHub cannot access this issue. Check the integration's repository access."+ )+ if response.status_code != 200:+ _log_issue_fetch_failure(+ integration, stage="status", error_type="GitHubResponseError", status_code=response.status_code+ )+ raise GitHubLinkUnavailableError("GitHub could not load this issue. Try again.")+ try:+ payload = response.json()+ except ValueError as exc:+ _log_issue_fetch_failure(integration, stage="invalid_payload", error_type=type(exc).__name__, status_code=200)+ raise GitHubLinkUnavailableError("GitHub returned an invalid issue. Try again.") from exc+ if not isinstance(payload, dict):+ _log_issue_fetch_failure(integration, stage="invalid_payload", error_type="InvalidPayload", status_code=200)+ raise GitHubLinkUnavailableError("GitHub returned an invalid issue. Try again.")+ try:+ return _parse_issue_payload(payload, repository, issue_number)+ except GitHubLinkUnavailableError as exc:+ _log_issue_fetch_failure(integration, stage="invalid_payload", error_type=type(exc).__name__, status_code=200)+ raise+++def _editable_request(+ team_id: int, request_id: UUID, expected_version: int, user_access_control: "UserAccessControl"+) -> FeatureRequest | None:+ request = _get_accessible_feature_request_for_update(+ team_id=team_id, feature_request_id=request_id, user_access_control=user_access_control+ )+ if request is not None:+ if request.archived_at is not None:+ raise FeatureRequestValidationError("feature_request", "Restore this request before changing GitHub sync.")+ if request.version != expected_version:+ raise FeatureRequestConflictError(_CONFLICT_MESSAGE)+ return request+++def _apply_state(+ request: FeatureRequest, link: FeatureRequestGitHubLink, issue: GitHubIssueState+) -> list[contracts.FeatureRequestHistoryChange]:+ before = request.status+ if issue.state == "closed":+ if link.status_before_github_close is None:+ link.status_before_github_close = before+ request.status = _github_status(issue.reason)+ elif link.status_before_github_close is not None:+ request.status = link.status_before_github_close+ link.status_before_github_close = None+ link.issue_title = issue.title+ link.issue_state = issue.state+ link.issue_state_reason = issue.reason+ link.github_updated_at = issue.updated_at+ link.last_synced_at = timezone.now()+ link.save()+ return [{"field": "status", "before": before, "after": request.status}] if request.status != before else []+++def _save_change(+ request: FeatureRequest, changes: list[contracts.FeatureRequestHistoryChange], actor_id: int | None+) -> None:+ request.version += 1+ request.updated_at = timezone.now()+ request.updated_by_id = actor_id+ request.save(update_fields=["status", "version", "updated_at", "updated_by_id"])+ if changes:+ FeatureRequestHistory.objects.for_team(request.team_id).create(+ team_id=request.team_id,+ feature_request=request,+ changes=changes,+ source=FeatureRequestHistorySource.GITHUB,+ actor_id=actor_id,+ changed_at=request.updated_at,+ )+++def link_feature_request_github(+ *,+ team_id: int,+ feature_request_id: UUID,+ input: contracts.LinkFeatureRequestGitHubInput,+ actor_id: int,+ user_access_control: "UserAccessControl",+) -> contracts.FeatureRequestView | None:+ repository, issue_number = _parse_issue_url(input.issue_url)+ with transaction.atomic():+ request = _editable_request(team_id, feature_request_id, input.expected_version, user_access_control)+ if request is None:+ return None+ if FeatureRequestGitHubLink.objects.for_team(team_id).filter(feature_request=request).exists():+ raise FeatureRequestValidationError(+ "issue_url", "This request already has a GitHub issue. Unlink it before adding another."+ )+ integration = _integration(team_id, input.integration_id, user_access_control=user_access_control)+ installation_id = integration.integration_id+ with bound_contextvars(+ team_id=team_id,+ feature_request_id=str(feature_request_id),+ integration_id=integration.id,+ action="link",+ ):+ issue = _fetch_issue(integration, repository, issue_number)+ with transaction.atomic():+ request = _editable_request(team_id, feature_request_id, input.expected_version, user_access_control)+ if request is None:+ return None+ integration = _integration(+ team_id, input.integration_id, installation_id, user_access_control=user_access_control+ )+ if FeatureRequestGitHubLink.objects.for_team(team_id).filter(feature_request=request).exists():+ raise FeatureRequestConflictError(_CONFLICT_MESSAGE)+ _ensure_initial_history(request)+ link = FeatureRequestGitHubLink.objects.for_team(team_id).create(+ team_id=team_id,+ feature_request=request,+ integration=integration,+ installation_id=installation_id,+ repository=repository,+ issue_number=issue_number,+ sync_enabled_by_id=actor_id,+ )+ changes = _apply_state(request, link, issue)+ changes.insert(0, {"field": "github_link", "before": None, "after": _issue_snapshot(link)})+ _save_change(request, changes, actor_id)+ _log_manual_action_after_commit(+ action="link",+ team_id=team_id,+ feature_request_id=feature_request_id,+ github_link_id=link.id,+ integration_id=integration.id,+ changed=True,+ )+ return _refresh_feature_request(+ team_id=team_id, feature_request_id=feature_request_id, user_access_control=user_access_control+ )+++def set_feature_request_github_sync(+ *,+ team_id: int,+ feature_request_id: UUID,+ expected_version: int,+ enabled: bool,+ actor_id: int,+ user_access_control: "UserAccessControl",+) -> contracts.FeatureRequestView | None:+ with transaction.atomic():+ request = _editable_request(team_id, feature_request_id, expected_version, user_access_control)+ if request is None:+ return None+ link = FeatureRequestGitHubLink.objects.for_team(team_id).filter(feature_request=request).first()+ if link is None:+ raise FeatureRequestValidationError("github_link", "Link a GitHub issue first.")+ if not enabled:+ changed = link.sync_enabled+ if changed:+ _ensure_initial_history(request)+ link.sync_enabled = False+ link.save(update_fields=["sync_enabled"])+ _save_change(request, [{"field": "github_sync", "before": True, "after": False}], actor_id)+ _log_manual_action_after_commit(+ action="pause",+ team_id=team_id,+ feature_request_id=feature_request_id,+ github_link_id=link.id,+ integration_id=link.integration_id,+ changed=changed,+ )+ return _refresh_feature_request(+ team_id=team_id, feature_request_id=feature_request_id, user_access_control=user_access_control+ )+ integration = _integration(+ team_id, link.integration_id, link.installation_id, user_access_control=user_access_control+ )+ with bound_contextvars(+ team_id=team_id,+ feature_request_id=str(feature_request_id),+ github_link_id=str(link.id),+ integration_id=integration.id,+ action="resume",+ ):+ issue = _fetch_issue(integration, link.repository, link.issue_number)+ with transaction.atomic():+ request = _editable_request(team_id, feature_request_id, expected_version, user_access_control)+ if request is None:+ return None+ current = FeatureRequestGitHubLink.objects.for_team(team_id).select_for_update().filter(id=link.id).first()+ if current is None or current.integration_id != link.integration_id:+ raise FeatureRequestConflictError(_CONFLICT_MESSAGE)+ _integration(team_id, current.integration_id, current.installation_id, user_access_control=user_access_control)+ if current.github_updated_at is not None and issue.updated_at < current.github_updated_at:+ raise FeatureRequestConflictError(_CONFLICT_MESSAGE)+ _ensure_initial_history(request)+ changes: list[contracts.FeatureRequestHistoryChange] = []+ if not current.sync_enabled:+ changes.append({"field": "github_sync", "before": False, "after": True})+ current.sync_enabled = True+ current.sync_enabled_by_id = actor_id+ changes.extend(_apply_state(request, current, issue))+ changed = bool(changes)+ if changed:+ _save_change(request, changes, actor_id)+ _log_manual_action_after_commit(+ action="resume",+ team_id=team_id,+ feature_request_id=feature_request_id,+ github_link_id=current.id,+ integration_id=current.integration_id,+ changed=bool(changed),+ )+ return _refresh_feature_request(+ team_id=team_id, feature_request_id=feature_request_id, user_access_control=user_access_control+ )+++def unlink_feature_request_github(+ *,+ team_id: int,+ feature_request_id: UUID,+ expected_version: int,+ actor_id: int,+ user_access_control: "UserAccessControl",+) -> contracts.FeatureRequestView | None:+ with transaction.atomic():+ request = _editable_request(team_id, feature_request_id, expected_version, user_access_control)+ if request is None:+ return None+ link = FeatureRequestGitHubLink.objects.for_team(team_id).filter(feature_request=request).first()+ if link is not None:+ _ensure_initial_history(request)+ before = _issue_snapshot(link)+ link_id = link.id+ integration_id = link.integration_id+ link.delete()+ _save_change(request, [{"field": "github_link", "before": before, "after": None}], actor_id)+ _log_manual_action_after_commit(+ action="unlink",+ team_id=team_id,+ feature_request_id=feature_request_id,+ github_link_id=link_id,+ integration_id=integration_id,+ changed=True,+ )+ return _refresh_feature_request(+ team_id=team_id, feature_request_id=feature_request_id, user_access_control=user_access_control+ )+++def _eligible_integration(link: FeatureRequestGitHubLink) -> tuple[Integration | None, str | None]:+ if not link.sync_enabled:+ return None, "paused"+ if link.feature_request.archived_at is not None:+ return None, "archived"+ if link.integration_id is None:+ return None, "unavailable"+ try:+ return _integration(link.team_id, link.integration_id, link.installation_id), None+ except FeatureRequestValidationError:+ return None, "unavailable"+++def process_github_issue_update(+ *,+ installation_id: str,+ repository: str,+ issue_number: int,+ issue_title: str,+ issue_state: str,+ issue_state_reason: str,+ github_updated_at: datetime,+) -> None:+ with bound_contextvars(installation_id=installation_id):+ matched = applied = skipped = conflicted = failed = 0+ outcome = "success"+ ignored_reason: str | None = None+ error_type: str | None = None+ try:+ if issue_state not in {"open", "closed"} or timezone.is_naive(github_updated_at):+ outcome = "ignored"+ ignored_reason = "invalid_state"+ return+ if issue_state == "closed" and issue_state_reason not in {"completed", "not_planned", ""}:+ outcome = "ignored"+ ignored_reason = "unsupported_closure_reason"+ return+ issue = GitHubIssueState(+ title=issue_title,+ state="closed" if issue_state == "closed" else "open",+ reason=issue_state_reason,+ updated_at=github_updated_at,+ )+ # One installation can serve several projects; each mutation below re-enters its team's scope.+ targets = (+ FeatureRequestGitHubLink.objects.unscoped()+ .filter(+ installation_id=installation_id,+ repository=repository.lower(),+ issue_number=issue_number,+ sync_enabled=True,+ )+ .values_list("id", "team_id", "feature_request_id", "integration_id")+ )+ for link_id, team_id, feature_request_id, integration_id in targets.iterator():+ matched += 1+ with bound_contextvars(+ team_id=team_id,+ feature_request_id=str(feature_request_id),+ github_link_id=str(link_id),+ integration_id=integration_id,+ ):+ stage = "load_target"+ try:+ link = (+ FeatureRequestGitHubLink.objects.for_team(team_id)+ .select_related("feature_request", "team", "sync_enabled_by")+ .filter(id=link_id)+ .first()+ )+ if link is None:+ skipped += 1+ logger.info("feature_request_github_target_skipped", reason="not_found")+ continue+ integration, skip_reason = _eligible_integration(link)+ if integration is None or skip_reason is not None:+ skipped += 1+ logger.info("feature_request_github_target_skipped", reason=skip_reason)+ continue+ user = link.sync_enabled_by+ if user is None:+ skipped += 1+ logger.info("feature_request_github_target_skipped", reason="user_missing")+ continue+ if not posthog_feature_flag_enabled(+ CUSTOMER_ANALYTICS_FEATURE_REQUESTS_FLAG,+ str(user.distinct_id),+ organization_id=link.team.organization_id,+ team_id=team_id,+ ):+ skipped += 1+ logger.info("feature_request_github_target_skipped", reason="flag_disabled")+ continue+ if link.github_updated_at is not None and issue.updated_at < link.github_updated_at:+ skipped += 1+ logger.debug("feature_request_github_target_skipped", reason="stale")+ continue+ current_issue = issue+ if issue.updated_at == link.github_updated_at:+ if (issue.state, issue.reason) == (link.issue_state, link.issue_state_reason):+ skipped += 1+ logger.debug("feature_request_github_target_skipped", reason="duplicate")+ continue+ # GitHub timestamps have second precision. Resolve conflicting same-second events from the API.+ stage = "same_second_fetch"+ current_issue = _fetch_issue(+ integration, link.repository, link.issue_number, priority=Priority.BATCH+ )+ expected_version = link.feature_request.version+ stage = "apply"+ with transaction.atomic():+ request = (+ FeatureRequest.objects.for_team(team_id)+ .select_for_update()+ .filter(id=link.feature_request_id)+ .first()+ )+ if request is None:+ skipped += 1+ logger.info("feature_request_github_target_skipped", reason="not_found")+ continue+ current = (+ FeatureRequestGitHubLink.objects.for_team(team_id)+ .select_for_update()+ .filter(id=link_id)+ .first()+ )+ if current is None:+ skipped += 1+ logger.info("feature_request_github_target_skipped", reason="not_found")+ continue+ _, skip_reason = _eligible_integration(current)+ if skip_reason is not None:+ skipped += 1+ logger.info("feature_request_github_target_skipped", reason=skip_reason)+ continue+ if request.version != expected_version:+ conflicted += 1+ logger.info("feature_request_github_target_conflicted", reason="version_conflict")+ continue+ if (+ current.github_updated_at is not None+ and current_issue.updated_at < current.github_updated_at+ ):+ skipped += 1+ logger.debug("feature_request_github_target_skipped", reason="stale")+ continue+ if current_issue.updated_at == current.github_updated_at and (+ current_issue.state,+ current_issue.reason,+ ) == (current.issue_state, current.issue_state_reason):+ skipped += 1+ logger.debug("feature_request_github_target_skipped", reason="duplicate")+ continue+ _ensure_initial_history(request)+ status_before = request.status+ changes = _apply_state(request, current, current_issue)+ changed = bool(changes)+ if changes:+ _save_change(request, changes, None)+ committed_context = get_contextvars()+ transaction.on_commit(+ partial(+ logger.info,+ "feature_request_github_target_applied",+ changed=changed,+ status_before=status_before,+ status_after=request.status,+ **committed_context,+ )+ )+ applied += 1+ except Exception as exc:+ failed += 1+ logger.error( # noqa: TRY400 - records the error category without exception details+ "feature_request_github_target_failed",+ error_type=type(exc).__name__,+ stage=stage,+ )+ raise+ if conflicted:+ raise FeatureRequestConflictError(_CONFLICT_MESSAGE)+ except Exception as exc:+ outcome = "failure"+ error_type = type(exc).__name__+ raise+ finally:+ log_method = logger.error if outcome == "failure" else logger.info+ log_method(+ "feature_request_github_delivery_summary",+ outcome=outcome,+ ignored_reason=ignored_reason,+ matched=matched,+ applied=applied,+ skipped=skipped,+ conflicted=conflicted,+ failed=failed,+ error_type=error_type,+ )diff --git a/products/customer_analytics/backend/logic/feature_requests.py b/products/customer_analytics/backend/logic/feature_requests.pyindex 59e389f6d793..b345430e492e 100644--- a/products/customer_analytics/backend/logic/feature_requests.py+++ b/products/customer_analytics/backend/logic/feature_requests.py@@ -2,7 +2,7 @@ from typing import TYPE_CHECKING, Protocol, castfrom urllib.parse import urlparsefrom uuid import UUID-from django.core.exceptions import PermissionDenied+from django.core.exceptions import ObjectDoesNotExist, PermissionDeniedfrom django.db import IntegrityError, transactionfrom django.db.models import (Case,@@ -31,6 +31,7 @@ from products.customer_analytics.backend.models import (FeatureRequest,FeatureRequestAccountLink,FeatureRequestEvidence,+ FeatureRequestGitHubLink,FeatureRequestHistory,FeatureRequestHistorySource,FeatureRequestPriority,@@ -124,6 +125,36 @@ def _get_feature_request_can_update(feature_request: FeatureRequest, user_access)+def _can_view_github_link(link: FeatureRequestGitHubLink | None, user_access_control: "UserAccessControl") -> bool:+ if link is None:+ return False+ try:+ integration = link.integration+ except ObjectDoesNotExist:+ return False+ return integration is not None and user_access_control.check_access_level_for_object(+ integration, required_level="viewer"+ )+++def _to_github_link_view(+ link: FeatureRequestGitHubLink | None, *, user_access_control: "UserAccessControl"+) -> contracts.FeatureRequestGitHubLinkView | None:+ if not _can_view_github_link(link, user_access_control):+ return None+ assert link is not None+ return contracts.FeatureRequestGitHubLinkView(+ id=link.id,+ issue_url=f"https://github.com/{link.repository}/issues/{link.issue_number}",+ repository=link.repository,+ issue_number=link.issue_number,+ issue_title=link.issue_title,+ issue_state="closed" if link.issue_state == "closed" else "open",+ sync_enabled=link.sync_enabled,+ last_synced_at=link.last_synced_at,+ )++def _to_feature_request_view(feature_request: FeatureRequest,*,@@ -156,6 +187,9 @@ def _to_feature_request_view(account_links=account_links,evidence_count=sum(link.evidence_count for link in account_links),product_areas=[_to_product_area_view(area) for area in feature_request.product_areas.all()],+ github_link=_to_github_link_view(+ getattr(feature_request, "github_link", None), user_access_control=user_access_control+ ),created_by=feature_request.created_by_id,updated_by=feature_request.updated_by_id,created_at=feature_request.created_at,@@ -192,6 +226,7 @@ def _feature_request_queryset(queryset = (FeatureRequest.objects.for_team(team_id).filter(account_links__account_id__in=accessible_account_ids, account_links__unlinked_at__isnull=True)+ .select_related("github_link__integration").prefetch_related("product_areas", Prefetch("account_links", queryset=visible_links)))return queryset.prefetch_related(@@ -778,6 +813,18 @@ def update_feature_request(feature_request.description = descriptionupdate_fields.add("description")if input.request_status is not None and input.request_status != feature_request.status:+ github_link = (+ FeatureRequestGitHubLink.objects.for_team(team_id)+ .select_for_update()+ .filter(feature_request=feature_request)+ .first()+ )+ if github_link is not None:+ if github_link.sync_enabled:+ history_changes.append({"field": "github_sync", "before": True, "after": False})+ github_link.sync_enabled = False+ github_link.status_before_github_close = None+ github_link.save(update_fields=["sync_enabled", "status_before_github_close"])history_changes.append({"field": "status", "before": feature_request.status, "after": input.request_status})feature_request.status = input.request_statusupdate_fields.add("status")@@ -1308,6 +1355,13 @@ def list_feature_request_history() -> list[contracts.FeatureRequestHistoryView] | None:if not _feature_request_queryset(team_id, user_access_control).filter(id=feature_request_id).exists():return None+ github_link = (+ FeatureRequestGitHubLink.objects.for_team(team_id)+ .select_related("integration")+ .filter(feature_request_id=feature_request_id)+ .first()+ )+ can_view_github_link = _can_view_github_link(github_link, user_access_control)history = list(FeatureRequestHistory.objects.for_team(team_id).filter(feature_request_id=feature_request_id)@@ -1336,7 +1390,11 @@ def list_feature_request_history(actor_names = {actor.id: actor.get_full_name().strip() or actor.email for actor in actors}visible_history: list[contracts.FeatureRequestHistoryView] = []for entry in history:- visible_changes = _redact_inaccessible_history_accounts(entry.changes, accessible_account_ids)+ visible_changes = [+ change+ for change in _redact_inaccessible_history_accounts(entry.changes, accessible_account_ids)+ if change["field"] != "github_link" or can_view_github_link+ ]if not visible_changes:continuevisible_history.append(diff --git a/products/customer_analytics/backend/migrations/0056_feature_request_github.py b/products/customer_analytics/backend/migrations/0056_feature_request_github.pynew file mode 100644index 000000000000..328677352256--- /dev/null+++ b/products/customer_analytics/backend/migrations/0056_feature_request_github.py@@ -0,0 +1,107 @@+# Generated by Django 5.2.17 on 2026-09-16 20:29++import django.db.models.deletion+from django.conf import settings+from django.db import migrations, models++import posthog.uuidt+++class Migration(migrations.Migration):+ dependencies = [+ (+ "customer_analytics",+ "0055_source_ref_unique_constraint",+ ),+ ("posthog", "1365_heatmap_screenshot_allowed_hostnames"),+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),+ ]++ operations = [+ migrations.AlterField(+ model_name="featurerequesthistory",+ name="source",+ field=models.CharField(+ choices=[("manual", "Manual"), ("github", "GitHub")],+ default="manual",+ max_length=32,+ ),+ ),+ migrations.CreateModel(+ name="FeatureRequestGitHubLink",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.uuidt.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ ("installation_id", models.CharField(max_length=255)),+ ("repository", models.CharField(max_length=255)),+ ("issue_number", models.PositiveIntegerField()),+ ("issue_title", models.TextField(blank=True, default="")),+ ("issue_state", models.CharField(default="open", max_length=16)),+ (+ "issue_state_reason",+ models.CharField(blank=True, default="", max_length=32),+ ),+ ("github_updated_at", models.DateTimeField(blank=True, null=True)),+ ("last_synced_at", models.DateTimeField(blank=True, null=True)),+ ("sync_enabled", models.BooleanField(default=True)),+ (+ "status_before_github_close",+ models.CharField(blank=True, max_length=32, null=True),+ ),+ (+ "feature_request",+ models.OneToOneField(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="github_link",+ to="customer_analytics.featurerequest",+ ),+ ),+ (+ "integration",+ models.ForeignKey(+ blank=True,+ db_constraint=False,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="+",+ to="posthog.integration",+ ),+ ),+ (+ "sync_enabled_by",+ models.ForeignKey(+ blank=True,+ db_constraint=False,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="+",+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ (+ "team",+ models.ForeignKey(+ db_constraint=False,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="+",+ to="posthog.team",+ ),+ ),+ ],+ options={+ "indexes": [+ models.Index(+ fields=["installation_id", "repository", "issue_number"],+ name="customer_an_install_7d454f_idx",+ )+ ],+ },+ ),+ ]diff --git a/products/customer_analytics/backend/migrations/max_migration.txt b/products/customer_analytics/backend/migrations/max_migration.txtindex 6fd67a338d12..b1a846365428 100644--- a/products/customer_analytics/backend/migrations/max_migration.txt+++ b/products/customer_analytics/backend/migrations/max_migration.txt@@ -1 +1 @@-0055_source_ref_unique_constraint+0056_feature_request_githubdiff --git a/products/customer_analytics/backend/models/__init__.py b/products/customer_analytics/backend/models/__init__.pyindex ff6c9fb64916..eea7e80e70da 100644--- a/products/customer_analytics/backend/models/__init__.py+++ b/products/customer_analytics/backend/models/__init__.py@@ -23,6 +23,7 @@ from .feature_request import (FeatureRequest,FeatureRequestAccountLink,FeatureRequestEvidence,+ FeatureRequestGitHubLink,FeatureRequestHistory,FeatureRequestHistorySource,FeatureRequestPriority,@@ -66,6 +67,7 @@ __all__ = ["FeatureRequest","FeatureRequestAccountLink","FeatureRequestEvidence",+ "FeatureRequestGitHubLink","FeatureRequestHistory","FeatureRequestHistorySource","FeatureRequestPriority",diff --git a/products/customer_analytics/backend/models/feature_request.py b/products/customer_analytics/backend/models/feature_request.pyindex 8a65c35ed25a..be24755bb63f 100644--- a/products/customer_analytics/backend/models/feature_request.py+++ b/products/customer_analytics/backend/models/feature_request.py@@ -22,6 +22,7 @@ class FeatureRequestPriority(models.TextChoices):class FeatureRequestHistorySource(models.TextChoices):MANUAL = "manual", "Manual"+ GITHUB = "github", "GitHub"class FeatureRequestProductArea(TeamScopedRootMixin, UUIDModel):@@ -80,6 +81,30 @@ class FeatureRequest(TeamScopedRootMixin, UUIDModel):ordering = ["-updated_at", "-created_at", "-id"]+class FeatureRequestGitHubLink(TeamScopedRootMixin, UUIDModel):+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False, related_name="+")+ feature_request = models.OneToOneField(FeatureRequest, on_delete=models.CASCADE, related_name="github_link")+ integration = models.ForeignKey(+ "posthog.Integration", on_delete=models.SET_NULL, null=True, blank=True, db_constraint=False, related_name="+"+ )+ installation_id = models.CharField(max_length=255)+ repository = models.CharField(max_length=255)+ issue_number = models.PositiveIntegerField()+ issue_title = models.TextField(blank=True, default="")+ issue_state = models.CharField(max_length=16, default="open")+ issue_state_reason = models.CharField(max_length=32, blank=True, default="")+ github_updated_at = models.DateTimeField(null=True, blank=True)+ last_synced_at = models.DateTimeField(null=True, blank=True)+ sync_enabled = models.BooleanField(default=True)+ sync_enabled_by = models.ForeignKey(+ "posthog.User", on_delete=models.SET_NULL, null=True, blank=True, db_constraint=False, related_name="+"+ )+ status_before_github_close = models.CharField(max_length=32, null=True, blank=True)++ class Meta:+ indexes = [models.Index(fields=["installation_id", "repository", "issue_number"])]++class FeatureRequestHistory(TeamScopedRootMixin, UUIDModel):team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False, related_name="+")feature_request = models.ForeignKey(diff --git a/products/customer_analytics/backend/presentation/views/serializers.py b/products/customer_analytics/backend/presentation/views/serializers.pyindex a331197bdd2e..de5d3edc0400 100644--- a/products/customer_analytics/backend/presentation/views/serializers.py+++ b/products/customer_analytics/backend/presentation/views/serializers.py@@ -71,6 +71,7 @@ from products.customer_analytics.backend.facade.contracts import (FeatureRequestAccountLinkView,FeatureRequestAccountView,FeatureRequestEvidenceView,+ FeatureRequestGitHubLinkView,FeatureRequestHistoryView,FeatureRequestProductAreaView,FeatureRequestStatusHistoryView,@@ -382,6 +383,37 @@ class FeatureRequestAccountLinkSerializer(DataclassSerializer):fields = ["id", "account", "evidence", "evidence_count", "created_at", "updated_at"]+class FeatureRequestGitHubLinkSerializer(DataclassSerializer):+ id = serializers.UUIDField(read_only=True, help_text="Stable GitHub link ID.")+ issue_url = serializers.URLField(read_only=True, help_text="Canonical GitHub issue URL.")+ repository = serializers.CharField(read_only=True, help_text="Canonical owner and repository name.")+ issue_number = serializers.IntegerField(read_only=True, min_value=1, help_text="GitHub issue number.")+ issue_title = serializers.CharField(read_only=True, help_text="Latest GitHub issue title.")+ issue_state = serializers.ChoiceField(+ read_only=True, choices=["open", "closed"], help_text="Latest GitHub issue state."+ )+ sync_enabled = serializers.BooleanField(+ read_only=True, help_text="Whether GitHub issue changes update this request."+ )+ last_synced_at = serializers.DateTimeField(+ read_only=True, allow_null=True, help_text="When GitHub last updated this link."+ )++ class Meta:+ dataclass = FeatureRequestGitHubLinkView+ ref_name = "FeatureRequestGitHubLink"+ fields = [+ "id",+ "issue_url",+ "repository",+ "issue_number",+ "issue_title",+ "issue_state",+ "sync_enabled",+ "last_synced_at",+ ]++class FeatureRequestSerializer(DataclassSerializer):id = serializers.UUIDField(read_only=True, help_text="Stable feature request ID.")title = serializers.CharField(read_only=True, help_text="Customer-facing request title.")@@ -436,6 +468,11 @@ class FeatureRequestSerializer(DataclassSerializer):read_only=True,help_text="Product areas affected by this request.",)+ github_link = FeatureRequestGitHubLinkSerializer(+ read_only=True,+ allow_null=True,+ help_text="Linked GitHub issue, or null when no issue is linked.",+ )created_by = serializers.IntegerField(read_only=True, allow_null=True, help_text="ID of the user who created the request.")@@ -463,6 +500,7 @@ class FeatureRequestSerializer(DataclassSerializer):"account_links","evidence_count","product_areas",+ "github_link","created_by","updated_by","created_at",@@ -474,6 +512,20 @@ _FEATURE_REQUEST_HISTORY_VALUE_SCHEMA = {"nullable": True,"oneOf": [{"type": "string"},+ {"type": "boolean"},+ {+ "type": "object",+ "required": ["id", "issue_url", "repository", "issue_number", "issue_title", "issue_state", "sync_enabled"],+ "properties": {+ "id": {"type": "string", "format": "uuid"},+ "issue_url": {"type": "string", "format": "uri"},+ "repository": {"type": "string"},+ "issue_number": {"type": "integer"},+ "issue_title": {"type": "string"},+ "issue_state": {"type": "string", "enum": ["open", "closed"]},+ "sync_enabled": {"type": "boolean"},+ },+ },{"type": "object","required": ["id", "name"],@@ -544,6 +596,8 @@ class FeatureRequestHistoryChangeSerializer(serializers.Serializer):("accounts", "Accounts"),("evidence", "Evidence"),("product_areas", "Product areas"),+ ("github_link", "GitHub link"),+ ("github_sync", "GitHub sync"),],help_text="Request field represented by this change.",)@@ -570,7 +624,7 @@ class FeatureRequestHistorySerializer(DataclassSerializer):)change_source = serializers.ChoiceField(read_only=True,- choices=[("manual", "Manual")],+ choices=[("manual", "Manual"), ("github", "GitHub")],help_text="System that recorded the request change.",)actor_id = serializers.IntegerField(@@ -614,7 +668,7 @@ class FeatureRequestStatusHistorySerializer(DataclassSerializer):)change_source = serializers.ChoiceField(read_only=True,- choices=[("manual", "Manual")],+ choices=[("manual", "Manual"), ("github", "GitHub")],help_text="System that recorded the status change.",)actor_id = serializers.IntegerField(@@ -847,6 +901,14 @@ class FeatureRequestEvidenceDeleteSerializer(serializers.Serializer):evidence_id = serializers.UUIDField(help_text="Evidence item to delete.")+class FeatureRequestGitHubLinkSerializerInput(serializers.Serializer):+ integration_id = serializers.IntegerField(min_value=1, help_text="GitHub integration ID connected to this project.")+ issue_url = serializers.URLField(help_text="GitHub issue URL. Pull request URLs are not supported.")+ expected_version = serializers.IntegerField(+ min_value=1, help_text="Request version loaded by the editor. Stale versions return 409 Conflict."+ )++class FeatureRequestVersionSerializer(serializers.Serializer):expected_version = serializers.IntegerField(min_value=1,diff --git a/products/customer_analytics/backend/presentation/views/views.py b/products/customer_analytics/backend/presentation/views/views.pyindex 8325baa5107c..f2450426986c 100644--- a/products/customer_analytics/backend/presentation/views/views.py+++ b/products/customer_analytics/backend/presentation/views/views.py@@ -103,6 +103,7 @@ from products.customer_analytics.backend.presentation.views.serializers import (FeatureRequestEvidenceCreateSerializer,FeatureRequestEvidenceDeleteSerializer,FeatureRequestEvidenceUpdateSerializer,+ FeatureRequestGitHubLinkSerializerInput,FeatureRequestHistorySerializer,FeatureRequestListQuerySerializer,FeatureRequestProductAreaListQuerySerializer,@@ -620,6 +621,82 @@ class FeatureRequestViewSet(def partial_update(self, request: Request, *args, **kwargs) -> Response:return self.update(request, *args, **kwargs)+ @extend_schema(request=FeatureRequestGitHubLinkSerializerInput, responses={200: FeatureRequestSerializer})+ @action(methods=["POST"], detail=True, required_scopes=["customer_analytics:write"])+ def link_github(self, request: Request, *args, **kwargs) -> Response:+ serializer = FeatureRequestGitHubLinkSerializerInput(data=request.data)+ serializer.is_valid(raise_exception=True)+ try:+ feature_request = api.link_feature_request_github(+ team_id=self.team_id,+ feature_request_id=self.kwargs["pk"],+ input=contracts.LinkFeatureRequestGitHubInput(**serializer.validated_data),+ actor_id=cast(User, request.user).id,+ user_access_control=self.user_access_control,+ )+ except api.FeatureRequestValidationError as error:+ raise ValidationError({error.field: error.message})+ except api.GitHubLinkUnavailableError as error:+ raise ValidationError({"issue_url": str(error)})+ except api.FeatureRequestConflictError as error:+ raise Conflict(str(error))+ if feature_request is None:+ return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)+ return Response(FeatureRequestSerializer(instance=feature_request).data)++ def _set_github_sync(self, request: Request, *, enabled: bool) -> Response:+ serializer = FeatureRequestVersionSerializer(data=request.data)+ serializer.is_valid(raise_exception=True)+ try:+ feature_request = api.set_feature_request_github_sync(+ team_id=self.team_id,+ feature_request_id=self.kwargs["pk"],+ expected_version=serializer.validated_data["expected_version"],+ enabled=enabled,+ actor_id=cast(User, request.user).id,+ user_access_control=self.user_access_control,+ )+ except api.FeatureRequestValidationError as error:+ raise ValidationError({error.field: error.message})+ except api.GitHubLinkUnavailableError as error:+ raise ValidationError({"github_link": str(error)})+ except api.FeatureRequestConflictError as error:+ raise Conflict(str(error))+ if feature_request is None:+ return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)+ return Response(FeatureRequestSerializer(instance=feature_request).data)++ @extend_schema(request=FeatureRequestVersionSerializer, responses={200: FeatureRequestSerializer})+ @action(methods=["POST"], detail=True, required_scopes=["customer_analytics:write"])+ def pause_github(self, request: Request, *args, **kwargs) -> Response:+ return self._set_github_sync(request, enabled=False)++ @extend_schema(request=FeatureRequestVersionSerializer, responses={200: FeatureRequestSerializer})+ @action(methods=["POST"], detail=True, required_scopes=["customer_analytics:write"])+ def resume_github(self, request: Request, *args, **kwargs) -> Response:+ return self._set_github_sync(request, enabled=True)++ @extend_schema(request=FeatureRequestVersionSerializer, responses={200: FeatureRequestSerializer})+ @action(methods=["POST"], detail=True, required_scopes=["customer_analytics:write"])+ def unlink_github(self, request: Request, *args, **kwargs) -> Response:+ serializer = FeatureRequestVersionSerializer(data=request.data)+ serializer.is_valid(raise_exception=True)+ try:+ feature_request = api.unlink_feature_request_github(+ team_id=self.team_id,+ feature_request_id=self.kwargs["pk"],+ expected_version=serializer.validated_data["expected_version"],+ actor_id=cast(User, request.user).id,+ user_access_control=self.user_access_control,+ )+ except api.FeatureRequestValidationError as error:+ raise ValidationError({error.field: error.message})+ except api.FeatureRequestConflictError as error:+ raise Conflict(str(error))+ if feature_request is None:+ return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)+ return Response(FeatureRequestSerializer(instance=feature_request).data)+@extend_schema(request=FeatureRequestAddAccountSerializer, responses={200: FeatureRequestSerializer})@action(methods=["POST"], detail=True, required_scopes=["customer_analytics:write"])def add_account(self, request: Request, *args, **kwargs) -> Response:diff --git a/products/customer_analytics/backend/tasks/__init__.py b/products/customer_analytics/backend/tasks/__init__.pyindex 115e64d9c8a0..75c6b8addf0f 100644--- a/products/customer_analytics/backend/tasks/__init__.py+++ b/products/customer_analytics/backend/tasks/__init__.py@@ -1,6 +1,7 @@# Re-exported so Celery autodiscovers the tasks when the tasks package is imported.from products.customer_analytics.backend.tasks.tasks import ( # noqa: F401process_custom_property_sync,+ process_feature_request_github_issue,recalculate_email_thread_account_links,recalculate_email_thread_account_links_for_threads,rematch_account_meetings,diff --git a/products/customer_analytics/backend/tasks/tasks.py b/products/customer_analytics/backend/tasks/tasks.pyindex 30e5beae529e..9eaac822cce0 100644--- a/products/customer_analytics/backend/tasks/tasks.py+++ b/products/customer_analytics/backend/tasks/tasks.py@@ -1,4 +1,9 @@-from celery import shared_task+from datetime import UTC, datetime++import structlog+import posthoganalytics+from celery import Task, shared_task+from structlog.contextvars import bound_contextvarsfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models.scoping import with_team_scope@@ -9,6 +14,113 @@ from products.customer_analytics.backend.facade.email_matching import ()from products.customer_analytics.backend.logic.announcements import send_pending_deliveriesfrom products.customer_analytics.backend.logic.custom_property_sync import sync_custom_property_values+from products.customer_analytics.backend.logic.feature_request_github import process_github_issue_update++logger = structlog.get_logger(__name__)+++class FeatureRequestGitHubTaskFailed(Exception):+ pass+++def _delivery_age_seconds(github_received_at: str | None) -> float | None:+ if github_received_at is None:+ return None+ try:+ received_at = datetime.fromisoformat(github_received_at)+ except ValueError:+ return None+ if received_at.tzinfo is None:+ return None+ delay_seconds = (datetime.now(UTC) - received_at).total_seconds()+ return delay_seconds if delay_seconds >= 0 else None+++def _capture_terminal_feature_request_github_failure(+ error: Exception,+ *,+ github_delivery_id: str | None,+ task_id: str | None,+ sync_attempt: int,+ installation_id: str,+ github_received_at: str | None,+) -> None:+ sanitized_error = FeatureRequestGitHubTaskFailed().with_traceback(error.__traceback__)+ try:+ with posthoganalytics.new_context(fresh=True, capture_exceptions=False):+ posthoganalytics.set_capture_exception_code_variables_context(False)+ try:+ raise sanitized_error from None+ except FeatureRequestGitHubTaskFailed as captured_error:+ capture_exception(+ captured_error,+ {+ "github_delivery_id": github_delivery_id,+ "task_id": task_id,+ "sync_attempt": sync_attempt,+ "installation_id": installation_id,+ "github_received_at": github_received_at,+ "exception_type": type(error).__name__,+ },+ )+ except Exception:+ logger.warning("feature_request_github_exception_capture_failed")+++@shared_task(+ name="customer_analytics.process_feature_request_github_issue",+ bind=True,+ ignore_result=True,+ autoretry_for=(Exception,),+ max_retries=3,+ retry_backoff=True,+ retry_jitter=True,+)+def process_feature_request_github_issue(+ self: Task,+ installation_id: str,+ repository: str,+ issue_number: int,+ issue_title: str,+ issue_state: str,+ issue_state_reason: str,+ github_updated_at: str,+ github_delivery_id: str | None = None,+ github_received_at: str | None = None,+) -> None:+ task_id = self.request.id+ sync_attempt = self.request.retries+ with bound_contextvars(+ github_delivery_id=github_delivery_id,+ task_id=task_id,+ sync_attempt=sync_attempt,+ installation_id=installation_id,+ github_received_at=github_received_at,+ ):+ logger.info(+ "feature_request_github_task_started", delivery_age_seconds=_delivery_age_seconds(github_received_at)+ )+ try:+ process_github_issue_update(+ installation_id=installation_id,+ repository=repository,+ issue_number=issue_number,+ issue_title=issue_title,+ issue_state=issue_state,+ issue_state_reason=issue_state_reason,+ github_updated_at=datetime.fromisoformat(github_updated_at),+ )+ except Exception as error:+ if self.max_retries is not None and sync_attempt >= self.max_retries:+ _capture_terminal_feature_request_github_failure(+ error,+ github_delivery_id=github_delivery_id,+ task_id=task_id,+ sync_attempt=sync_attempt,+ installation_id=installation_id,+ github_received_at=github_received_at,+ )+ raise@shared_task(name="customer_analytics.process_custom_property_sync", ignore_result=True)diff --git a/products/customer_analytics/backend/test/test_feature_request_github.py b/products/customer_analytics/backend/test/test_feature_request_github.pynew file mode 100644index 000000000000..988816a32414--- /dev/null+++ b/products/customer_analytics/backend/test/test_feature_request_github.py@@ -0,0 +1,965 @@+import hmac+import json+import hashlib+from collections.abc import Callable, Mapping, Sequence+from datetime import UTC, datetime+from typing import TYPE_CHECKING, Any++from posthog.test.base import APIBaseTest+from unittest.mock import Mock, patch++from django.core.cache import cache+from django.db import transaction+from django.test import SimpleTestCase++import structlog+from celery import current_app+from parameterized import parameterized+from rest_framework import status+from structlog.contextvars import bound_contextvars, clear_contextvars, merge_contextvars+from structlog.testing import capture_logs++from posthog.constants import AvailableFeature+from posthog.ingress.contracts import WebhookDelivery+from posthog.ingress.dispatch.loading import reset_consumer_registry+from posthog.models import Integration, OrganizationMembership, Team, User+from posthog.models.organization import Organization++from products.access_control.backend.models import AccessControl+from products.customer_analytics.backend.logic.feature_request_github import (+ FeatureRequestConflictError,+ FeatureRequestValidationError,+ _parse_issue_url,+ process_github_issue_update,+)+from products.customer_analytics.backend.models import (+ FeatureRequestGitHubLink,+ FeatureRequestHistory,+ FeatureRequestHistorySource,+ FeatureRequestStatus,+)+from products.customer_analytics.backend.test.factories import (+ create_account,+ create_feature_request,+ create_feature_request_account_link,+)+from products.customer_analytics.backend.webhook_consumers import _run_github_issue_delivery++if TYPE_CHECKING:+ from products.customer_analytics.backend.models import FeatureRequest+++class TestFeatureRequestGitHubIssueUrl(SimpleTestCase):+ def test_normalizes_issue_comment_url_and_rejects_non_issue_paths(self) -> None:+ self.assertEqual(+ _parse_issue_url("https://github.com/PostHog/PostHog/issues/42#issuecomment-1"),+ ("posthog/posthog", 42),+ )+ for url in (+ "http://github.com/posthog/posthog/issues/42",+ "https://github.com/posthog/posthog/pull/42",+ "https://github.com/posthog/posthog/issues/42?state=open",+ "https://github.com.evil.example/posthog/posthog/issues/42",+ ):+ with self.assertRaises(FeatureRequestValidationError):+ _parse_issue_url(url)++ def test_issue_delivery_queues_only_issue_metadata(self) -> None:+ clear_contextvars()+ self.addCleanup(clear_contextvars)+ task = current_app.tasks["customer_analytics.process_feature_request_github_issue"]+ with (+ patch.object(task, "delay", return_value=Mock(id="task-1")) as delay,+ patch(+ "products.customer_analytics.backend.webhook_consumers.logger",+ structlog.get_logger("test.feature_request_github.delivery"),+ ),+ capture_logs(processors=[merge_contextvars]) as logs,+ ):+ _run_github_issue_delivery(+ WebhookDelivery(+ provider="github",+ app="posthog",+ delivery_id="delivery-1",+ event_type="issues",+ payload={+ "action": "closed",+ "installation": {"id": 123},+ "repository": {"full_name": "PostHog/PostHog"},+ "issue": {+ "number": 42,+ "title": "Export CSV",+ "state": "closed",+ "state_reason": "completed",+ "updated_at": "2026-01-01T00:00:00Z",+ "body": "This must never enter the worker payload.",+ },+ },+ received_at=datetime(2026, 1, 1, tzinfo=UTC),+ context={},+ )+ )++ delay.assert_called_once_with(+ installation_id="123",+ repository="posthog/posthog",+ issue_number=42,+ issue_title="Export CSV",+ issue_state="closed",+ issue_state_reason="completed",+ github_updated_at="2026-01-01T00:00:00+00:00",+ github_delivery_id="delivery-1",+ github_received_at="2026-01-01T00:00:00+00:00",+ )+ queued = [log for log in logs if log["event"] == "feature_request_github_delivery_queued"][-1]+ self.assertEqual(+ {key: queued[key] for key in ("github_delivery_id", "task_id", "sync_attempt")},+ {"github_delivery_id": "delivery-1", "task_id": "task-1", "sync_attempt": 0},+ )+ self.assertNotIn("Export CSV", repr(queued))+ self.assertNotIn("This must never enter the worker payload.", repr(queued))+ self.assertNotIn("PostHog/PostHog", repr(queued))++ @parameterized.expand(+ (+ ("boolean_issue_number", {"number": True}),+ ("boolean_installation_id", {"installation_id": True}),+ ("naive_timestamp", {"updated_at": "2026-01-01T00:00:00"}),+ ("unknown_closed_reason", {"state_reason": "reopened"}),+ )+ )+ @patch("products.customer_analytics.backend.facade.api.process_feature_request_github_delivery")+ def test_issue_delivery_ignores_invalid_worker_metadata(+ self, _name: str, invalid_field: dict[str, object], process_delivery: Mock+ ) -> None:+ issue: dict[str, object] = {+ "number": 42,+ "title": "Export CSV",+ "state": "closed",+ "state_reason": "completed",+ "updated_at": "2026-01-01T00:00:00Z",+ }+ installation: dict[str, object] = {"id": 123}+ if "installation_id" in invalid_field:+ installation["id"] = invalid_field["installation_id"]+ else:+ issue.update(invalid_field)+ _run_github_issue_delivery(+ WebhookDelivery(+ provider="github",+ app="posthog",+ delivery_id="delivery-1",+ event_type="issues",+ payload={+ "action": "closed",+ "installation": installation,+ "repository": {"full_name": "PostHog/PostHog"},+ "issue": issue,+ },+ received_at=datetime(2026, 1, 1, tzinfo=UTC),+ context={},+ )+ )++ process_delivery.assert_not_called()+++class TestFeatureRequestGitHubIngress(SimpleTestCase):+ def setUp(self) -> None:+ reset_consumer_registry()+ cache.clear()+ self.addCleanup(reset_consumer_registry)+ self.addCleanup(cache.clear)++ @staticmethod+ def _signature(body: bytes, secret: str) -> str:+ return "sha256=" + hmac.new(secret.encode(), body, hashlib.sha256).hexdigest()++ @patch("posthog.models.integration.github.GitHubIntegration.api_request")+ @patch("products.workflows.backend.facade.api.accept_github_event")+ @patch("products.tasks.backend.facade.api.accept_github_event_for_loops")+ @patch("products.conversations.backend.facade.api.accept_github_event")+ @patch("products.customer_analytics.backend.facade.api.process_feature_request_github_delivery")+ @patch("posthog.ingress.github.provider.get_instance_setting", return_value="test-webhook-secret")+ def test_signed_issue_delivery_enqueues_only_feature_request_work(+ self,+ _get_secret: Mock,+ process_delivery: Mock,+ conversations: Mock,+ loops: Mock,+ workflows: Mock,+ api_request: Mock,+ ) -> None:+ body = json.dumps(+ {+ "action": "closed",+ "installation": {"id": 123},+ "repository": {"full_name": "PostHog/PostHog"},+ "issue": {+ "number": 42,+ "title": "Export CSV",+ "state": "closed",+ "state_reason": "completed",+ "updated_at": "2026-01-01T00:00:00Z",+ },+ }+ ).encode()++ response = self.client.post(+ "/webhooks/github/",+ data=body,+ content_type="application/json",+ headers={+ "X-Hub-Signature-256": self._signature(body, "test-webhook-secret"),+ "X-GitHub-Event": "issues",+ "X-GitHub-Delivery": "delivery-1",+ },+ )++ self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)+ process_delivery.assert_called_once_with(+ installation_id="123",+ repository="posthog/posthog",+ issue_number=42,+ issue_title="Export CSV",+ issue_state="closed",+ issue_state_reason="completed",+ github_updated_at=datetime(2026, 1, 1, tzinfo=UTC),+ github_delivery_id="delivery-1",+ github_received_at=process_delivery.call_args.kwargs["github_received_at"],+ )+ self.assertIsNotNone(datetime.fromisoformat(process_delivery.call_args.kwargs["github_received_at"]))+ conversations.assert_called_once()+ loops.assert_called_once()+ workflows.assert_called_once()+ api_request.assert_not_called()+++class TestFeatureRequestGitHubAPI(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.account = create_account(team_id=self.team.id)+ self.request = create_feature_request(team_id=self.team.id, status=FeatureRequestStatus.PLANNED)+ create_feature_request_account_link(team_id=self.team.id, feature_request=self.request, account=self.account)+ self.integration = Integration.objects.create(+ team=self.team,+ kind="github",+ integration_id="installation-1",+ config={},+ sensitive_config={},+ )+ self.url = f"/api/projects/{self.team.id}/feature_requests/{self.request.id}/"+ self.flag = patch("posthog.permissions.posthog_feature_flag_enabled", return_value=True)+ self.flag.start()+ self.addCleanup(self.flag.stop)+ self.api_request = patch(+ "products.customer_analytics.backend.logic.feature_request_github.GitHubIntegration.api_request",+ return_value=self._github_response(),+ )+ self.mock_api_request = self.api_request.start()+ self.addCleanup(self.api_request.stop)++ @staticmethod+ def _github_response(+ *,+ title: str = "Export CSV",+ state: str = "open",+ state_reason: str | None = None,+ updated_at: str = "2026-01-01T00:00:00Z",+ ) -> Mock:+ return Mock(+ status_code=200,+ json=Mock(+ return_value={+ "number": 42,+ "title": title,+ "state": state,+ "state_reason": state_reason,+ "updated_at": updated_at,+ "repository_url": "https://api.github.com/repos/PostHog/PostHog",+ "html_url": "https://github.com/PostHog/PostHog/issues/42",+ }+ ),+ )++ def _link(self, version: int | None = None) -> Any:+ return self.client.post(+ f"{self.url}link_github/",+ {+ "integration_id": self.integration.id,+ "issue_url": "https://github.com/PostHog/PostHog/issues/42",+ "expected_version": version or self.request.version,+ },+ format="json",+ )++ def test_link_pause_resume_and_unlink_preserve_the_public_link_contract(self) -> None:+ linked = self._link()++ self.assertEqual(linked.status_code, status.HTTP_200_OK)+ self.assertEqual(+ linked.json()["github_link"],+ {+ "id": linked.json()["github_link"]["id"],+ "issue_url": "https://github.com/posthog/posthog/issues/42",+ "repository": "posthog/posthog",+ "issue_number": 42,+ "issue_title": "Export CSV",+ "issue_state": "open",+ "sync_enabled": True,+ "last_synced_at": linked.json()["github_link"]["last_synced_at"],+ },+ )+ paused = self.client.post(+ f"{self.url}pause_github/", {"expected_version": linked.json()["version"]}, format="json"+ )+ resumed = self.client.post(+ f"{self.url}resume_github/", {"expected_version": paused.json()["version"]}, format="json"+ )+ unlinked = self.client.post(+ f"{self.url}unlink_github/", {"expected_version": resumed.json()["version"]}, format="json"+ )++ self.assertEqual(paused.status_code, status.HTTP_200_OK)+ self.assertFalse(paused.json()["github_link"]["sync_enabled"])+ self.assertEqual(resumed.status_code, status.HTTP_200_OK)+ self.assertTrue(resumed.json()["github_link"]["sync_enabled"])+ self.assertEqual(unlinked.status_code, status.HTTP_200_OK)+ self.assertIsNone(unlinked.json()["github_link"])+ self.assertEqual(+ FeatureRequestHistory.objects.for_team(self.team.id)+ .filter(feature_request=self.request, source=FeatureRequestHistorySource.GITHUB)+ .count(),+ 4,+ )++ def test_stale_link_version_does_not_fetch_or_modify_the_existing_link(self) -> None:+ response = self._link(version=self.request.version + 1)++ self.assertEqual(response.status_code, status.HTTP_409_CONFLICT)+ self.mock_api_request.assert_not_called()+ self.assertFalse(FeatureRequestGitHubLink.objects.for_team(self.team.id).exists())++ def test_duplicate_issue_url_does_not_fetch_or_modify_the_existing_link(self) -> None:+ linked = self._link()+ self.mock_api_request.reset_mock()++ duplicate = self._link(version=linked.json()["version"])++ self.assertEqual(duplicate.status_code, status.HTTP_400_BAD_REQUEST)+ self.mock_api_request.assert_not_called()+ link = FeatureRequestGitHubLink.objects.for_team(self.team.id).get()+ self.assertEqual(link.issue_title, "Export CSV")+ self.assertTrue(link.sync_enabled)++ def test_unknown_closed_reason_is_rejected_without_creating_a_link(self) -> None:+ self.mock_api_request.return_value = self._github_response(state="closed", state_reason="reopened")++ response = self._link()++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertFalse(FeatureRequestGitHubLink.objects.for_team(self.team.id).exists())++ @parameterized.expand((("deleted",), ("unavailable",)))+ def test_unavailable_integrations_are_rejected_without_fetching(self, state: str) -> None:+ if state == "deleted":+ self.integration.delete()+ else:+ self.integration.config = {"installation_unavailable_since": 1}+ self.integration.save(update_fields=["config"])++ response = self._link()++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.mock_api_request.assert_not_called()+ self.assertFalse(FeatureRequestGitHubLink.objects.for_team(self.team.id).exists())++ def test_failed_refetch_keeps_the_existing_link_unchanged(self) -> None:+ linked = self._link()+ paused = self.client.post(+ f"{self.url}pause_github/", {"expected_version": linked.json()["version"]}, format="json"+ )+ self.mock_api_request.return_value = Mock(+ status_code=500,+ text="private upstream error",+ title="private issue title",+ body="private issue body",+ )+ clear_contextvars()++ with (+ patch(+ "products.customer_analytics.backend.logic.feature_request_github.logger",+ structlog.get_logger("test.feature_request_github.fetch_failure"),+ ),+ capture_logs(processors=[merge_contextvars]) as logs,+ ):+ response = self.client.post(+ f"{self.url}resume_github/", {"expected_version": paused.json()["version"]}, format="json"+ )++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ link = FeatureRequestGitHubLink.objects.for_team(self.team.id).get()+ self.assertEqual(link.repository, "posthog/posthog")+ self.assertEqual(link.issue_number, 42)+ self.assertFalse(link.sync_enabled)+ failed_fetch = [log for log in logs if log["event"] == "feature_request_github_issue_fetch_failed"][-1]+ self.assertEqual(failed_fetch["feature_request_id"], str(self.request.id))+ self.assertIsInstance(failed_fetch["action"], str)+ self.assertEqual(failed_fetch["status_code"], 500)+ for private_value in ("private issue title", "private issue body", "private upstream error"):+ self.assertNotIn(private_value, repr(failed_fetch))++ def test_concurrent_request_change_while_linking_does_not_create_a_link(self) -> None:+ def change_request_during_fetch(*args: object, **kwargs: object) -> Mock:+ self.request.version += 1+ self.request.save(update_fields=["version"])+ return self._github_response()++ self.mock_api_request.side_effect = change_request_during_fetch++ response = self._link()++ self.assertEqual(response.status_code, status.HTTP_409_CONFLICT)+ self.assertFalse(FeatureRequestGitHubLink.objects.for_team(self.team.id).exists())++ def test_concurrent_request_change_while_resuming_keeps_sync_paused(self) -> None:+ linked = self._link()+ paused = self.client.post(+ f"{self.url}pause_github/", {"expected_version": linked.json()["version"]}, format="json"+ )++ def change_request_during_fetch(*args: object, **kwargs: object) -> Mock:+ self.request.refresh_from_db()+ self.request.version += 1+ self.request.save(update_fields=["version"])+ return self._github_response()++ self.mock_api_request.side_effect = change_request_during_fetch+ resumed = self.client.post(+ f"{self.url}resume_github/", {"expected_version": paused.json()["version"]}, format="json"+ )++ self.assertEqual(resumed.status_code, status.HTTP_409_CONFLICT)+ self.assertFalse(FeatureRequestGitHubLink.objects.for_team(self.team.id).get().sync_enabled)++ @parameterized.expand(+ (mode, state) for mode in ("manual", "manual_after_pause", "pause") for state in ("open", "closed")+ )+ def test_pause_and_resume_preserve_status_ownership(self, mode: str, state: str) -> None:+ self.mock_api_request.return_value = self._github_response(state="closed", state_reason="completed")+ linked = self._link()+ self.assertEqual(linked.status_code, 200)+ version = linked.json()["version"]+ if mode != "manual":+ paused = self.client.post(f"{self.url}pause_github/", {"expected_version": version}, format="json")+ self.assertEqual(paused.status_code, 200)+ version = paused.json()["version"]+ if mode.startswith("manual"):+ changed = self.client.patch(+ self.url, {"expected_version": version, "request_status": "requested"}, format="json"+ )+ self.assertEqual(changed.status_code, 200)+ self.assertFalse(changed.json()["github_link"]["sync_enabled"])+ version = changed.json()["version"]+ restored_status = "requested" if mode.startswith("manual") else "planned"+ with patch(+ "products.customer_analytics.backend.logic.feature_request_github.posthog_feature_flag_enabled",+ autospec=True,+ return_value=True,+ ):+ process_github_issue_update(+ installation_id="installation-1",+ repository="posthog/posthog",+ issue_number=42,+ issue_title="GitHub title",+ issue_state="open",+ issue_state_reason="",+ github_updated_at=datetime(2026, 1, 2, tzinfo=UTC),+ )+ self.request.refresh_from_db()+ self.assertEqual(self.request.version, version)+ self.mock_api_request.return_value = self._github_response(+ state=state,+ state_reason="not_planned" if state == "closed" else None,+ updated_at="2026-01-02T00:00:00Z",+ )+ resumed = self.client.post(f"{self.url}resume_github/", {"expected_version": version}, format="json")+ self.assertEqual(resumed.status_code, 200)+ self.assertEqual(resumed.json()["version"], version + 1)+ self.assertEqual(resumed.json()["request_status"], "wont_fix" if state == "closed" else restored_status)+ self.assertTrue(resumed.json()["github_link"]["sync_enabled"])+ self.assertEqual(resumed.json()["title"], self.request.title)+ self.assertEqual(resumed.json()["description"], self.request.description)+ if state == "closed":+ history = self.client.get(f"{self.url}history/").json()+ self.assertTrue(+ any(change["field"] == "status" and change["after"] == "wont_fix" for change in history[0]["changes"])+ )+ with patch(+ "products.customer_analytics.backend.logic.feature_request_github.posthog_feature_flag_enabled",+ autospec=True,+ return_value=True,+ ):+ process_github_issue_update(+ installation_id="installation-1",+ repository="posthog/posthog",+ issue_number=42,+ issue_title="GitHub title",+ issue_state="open",+ issue_state_reason="",+ github_updated_at=datetime(2026, 1, 3, tzinfo=UTC),+ )+ self.request.refresh_from_db()+ self.assertEqual(self.request.status, restored_status)++ @parameterized.expand(("link_github", "pause_github", "resume_github", "unlink_github"))+ def test_account_viewer_cannot_change_github_or_trigger_a_fetch(self, action: str) -> None:+ linked = self._link()+ self.assertEqual(linked.status_code, 200)+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},+ {"key": AvailableFeature.ROLE_BASED_ACCESS, "name": AvailableFeature.ROLE_BASED_ACCESS},+ ]+ self.organization.save()+ reader = User.objects.create_and_join(self.organization, "[email protected]", "testtest")+ membership = OrganizationMembership.objects.get(user=reader, organization=self.organization)+ AccessControl.objects.create(+ team=self.team, resource="customer_analytics", access_level="editor", organization_member=membership+ )+ AccessControl.objects.create(+ team=self.team,+ resource="account",+ resource_id=str(self.account.id),+ access_level="viewer",+ organization_member=membership,+ )+ self.client.force_login(reader)+ self.mock_api_request.reset_mock()+ response = self.client.post(+ f"{self.url}{action}/",+ {+ "expected_version": linked.json()["version"],+ "integration_id": self.integration.id,+ "issue_url": "https://github.com/posthog/posthog/issues/42",+ },+ format="json",+ )+ self.assertEqual(response.status_code, 403)+ self.mock_api_request.assert_not_called()++ @parameterized.expand(("link_github", "resume_github"))+ def test_denied_integration_access_rejects_link_and_resume_without_fetching(self, action: str) -> None:+ if action == "resume_github":+ linked = self._link()+ paused = self.client.post(+ f"{self.url}pause_github/", {"expected_version": linked.json()["version"]}, format="json"+ )+ expected_version = paused.json()["version"]+ else:+ expected_version = self.request.version+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},+ {"key": AvailableFeature.ROLE_BASED_ACCESS, "name": AvailableFeature.ROLE_BASED_ACCESS},+ ]+ self.organization.save()+ reader = User.objects.create_and_join(self.organization, "[email protected]", "testtest")+ membership = OrganizationMembership.objects.get(user=reader, organization=self.organization)+ AccessControl.objects.create(+ team=self.team, resource="customer_analytics", access_level="editor", organization_member=membership+ )+ AccessControl.objects.create(+ team=self.team,+ resource="account",+ resource_id=str(self.account.id),+ access_level="editor",+ organization_member=membership,+ )+ AccessControl.objects.create(+ team=self.team, resource="integration", access_level="none", organization_member=membership+ )+ self.client.force_login(reader)+ self.mock_api_request.reset_mock()++ response = self.client.post(+ f"{self.url}{action}/",+ {+ "expected_version": expected_version,+ "integration_id": self.integration.id,+ "issue_url": "https://github.com/posthog/posthog/issues/42",+ },+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.mock_api_request.assert_not_called()++ def test_another_projects_integration_cannot_be_used(self) -> None:+ other_organization = Organization.objects.create(name="Other organization")+ other_team = Team.objects.create(organization=other_organization, name="Other project")+ self.integration.team = other_team+ self.integration.save(update_fields=["team"])+ response = self._link()+ self.assertEqual(response.status_code, 400)+ self.mock_api_request.assert_not_called()+ self.assertFalse(FeatureRequestGitHubLink.objects.for_team(self.team.id).exists())+++class TestFeatureRequestGitHubWorker(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.integration = Integration.objects.create(+ team=self.team,+ kind="github",+ integration_id="installation-1",+ config={},+ sensitive_config={},+ )+ self.request = create_feature_request(team_id=self.team.id, status=FeatureRequestStatus.PLANNED)+ self.link = FeatureRequestGitHubLink.objects.for_team(self.team.id).create(+ team_id=self.team.id,+ feature_request=self.request,+ integration=self.integration,+ sync_enabled_by=self.user,+ installation_id="installation-1",+ repository="posthog/posthog",+ issue_number=42,+ issue_title="Original title",+ issue_state="open",+ )+ self.flag = patch(+ "products.customer_analytics.backend.logic.feature_request_github.posthog_feature_flag_enabled",+ return_value=True,+ )+ self.flag.start()+ self.addCleanup(self.flag.stop)++ @staticmethod+ def _log(logs: Sequence[Mapping[str, object]], event: str) -> Mapping[str, object]:+ return next(log for log in logs if log["event"] == event)++ def _deliver(+ self,+ *,+ issue_number: int = 42,+ title: str = "Updated title",+ state: str = "closed",+ reason: str = "completed",+ updated_at: datetime = datetime(2026, 1, 1, tzinfo=UTC),+ ) -> None:+ process_github_issue_update(+ installation_id="installation-1",+ repository="PostHog/PostHog",+ issue_number=issue_number,+ issue_title=title,+ issue_state=state,+ issue_state_reason=reason,+ github_updated_at=updated_at,+ )++ @parameterized.expand(+ (+ ("completed", FeatureRequestStatus.COMPLETED),+ ("not_planned", FeatureRequestStatus.WONT_FIX),+ ("", FeatureRequestStatus.COMPLETED),+ )+ )+ def test_closed_issue_maps_known_and_legacy_reasons_to_request_status(+ self, reason: str, expected_status: str+ ) -> None:+ self._deliver(reason=reason)++ self.request.refresh_from_db()+ self.link.refresh_from_db()+ self.assertEqual(self.request.status, expected_status)+ self.assertEqual(self.link.status_before_github_close, FeatureRequestStatus.PLANNED)+ history = (+ FeatureRequestHistory.objects.for_team(self.team.id)+ .filter(feature_request=self.request, source=FeatureRequestHistorySource.GITHUB)+ .get()+ )+ self.assertEqual(history.source, FeatureRequestHistorySource.GITHUB)+ self.assertEqual(history.changes, [{"field": "status", "before": "planned", "after": expected_status}])++ def test_reopen_restores_the_baseline_without_replacing_it_on_repeated_close(self) -> None:+ self._deliver(title="Closed once")+ self._deliver(title="Closed twice", updated_at=datetime(2026, 1, 2, tzinfo=UTC))+ self._deliver(state="open", reason="", updated_at=datetime(2026, 1, 3, tzinfo=UTC))++ self.request.refresh_from_db()+ self.link.refresh_from_db()+ self.assertEqual(self.request.status, FeatureRequestStatus.PLANNED)+ self.assertIsNone(self.link.status_before_github_close)+ self.assertEqual(self.link.issue_title, "Updated title")++ @parameterized.expand((("disabled", "sync_enabled"), ("archived", "archived_at"), ("disconnected", "integration")))+ def test_worker_ignores_links_that_cannot_sync(self, condition: str, field: str) -> None:+ if field == "sync_enabled":+ self.link.sync_enabled = False+ self.link.save(update_fields=[field])+ elif field == "archived_at":+ self.request.archived_at = datetime(2026, 1, 1, tzinfo=UTC)+ self.request.save(update_fields=[field])+ else:+ self.link.integration = None+ self.link.save(update_fields=[field])++ self._deliver()++ self.request.refresh_from_db()+ self.link.refresh_from_db()+ self.assertEqual(self.request.status, FeatureRequestStatus.PLANNED)+ self.assertEqual(self.link.issue_title, "Original title")++ def test_worker_logs_applied_target_after_commit_with_delivery_correlation(self) -> None:+ with capture_logs(processors=[merge_contextvars]) as logs:+ with bound_contextvars(+ github_delivery_id="delivery-1",+ task_id="task-1",+ sync_attempt=0,+ github_received_at="2026-01-01T00:00:00+00:00",+ ):+ with self.captureOnCommitCallbacks(execute=True):+ self._deliver()+ self.assertFalse(any(log["event"] == "feature_request_github_target_applied" for log in logs))++ applied = self._log(logs, "feature_request_github_target_applied")+ self.assertEqual(+ {key: applied[key] for key in ("github_delivery_id", "task_id", "sync_attempt", "installation_id")},+ {+ "github_delivery_id": "delivery-1",+ "task_id": "task-1",+ "sync_attempt": 0,+ "installation_id": "installation-1",+ },+ )+ self.assertEqual(+ {key: applied[key] for key in ("status_before", "status_after", "changed")},+ {"status_before": "planned", "status_after": "completed", "changed": True},+ )+ summary = self._log(logs, "feature_request_github_delivery_summary")+ self.assertNotIn("feature_request_id", summary)+ self.assertNotIn("github_link_id", summary)+ self.assertEqual(+ {key: summary[key] for key in ("outcome", "matched", "applied", "skipped", "conflicted", "failed")},+ {"outcome": "success", "matched": 1, "applied": 1, "skipped": 0, "conflicted": 0, "failed": 0},+ )++ @parameterized.expand(+ (+ ("flag_disabled",),+ ("user_missing",),+ ("unavailable",),+ ("stale",),+ ("duplicate",),+ ("no_matches",),+ )+ )+ def test_worker_logs_skipped_target_reasons_and_summary_counts(self, reason: str) -> None:+ if reason == "user_missing":+ self.link.sync_enabled_by = None+ self.link.save(update_fields=["sync_enabled_by"])+ elif reason == "unavailable":+ self.link.integration = None+ self.link.save(update_fields=["integration"])+ elif reason in {"stale", "duplicate"}:+ self.link.github_updated_at = datetime(2026, 1, 2, tzinfo=UTC)+ self.link.issue_state = "closed"+ self.link.issue_state_reason = "completed"+ self.link.save(update_fields=["github_updated_at", "issue_state", "issue_state_reason"])++ with capture_logs(processors=[merge_contextvars]) as logs:+ if reason == "flag_disabled":+ with patch(+ "products.customer_analytics.backend.logic.feature_request_github.posthog_feature_flag_enabled",+ return_value=False,+ ):+ self._deliver()+ else:+ self._deliver(+ issue_number=43 if reason == "no_matches" else 42,+ updated_at=datetime(2026, 1, 1, tzinfo=UTC)+ if reason == "stale"+ else datetime(2026, 1, 2, tzinfo=UTC),+ )++ summary = self._log(logs, "feature_request_github_delivery_summary")+ self.assertEqual(summary["matched"], 0 if reason == "no_matches" else 1)+ self.assertEqual(summary["applied"], 0)+ self.assertEqual(summary["skipped"], 0 if reason == "no_matches" else 1)+ if reason != "no_matches":+ skipped = self._log(logs, "feature_request_github_target_skipped")+ self.assertEqual(skipped["reason"], reason)++ def test_worker_logs_no_applied_target_when_transaction_rolls_back(self) -> None:+ original_on_commit = transaction.on_commit++ def schedule_then_fail(callback: Callable[[], None]) -> None:+ original_on_commit(callback)+ raise RuntimeError("rollback")++ with capture_logs(processors=[merge_contextvars]) as logs:+ with patch(+ "products.customer_analytics.backend.logic.feature_request_github.transaction.on_commit",+ side_effect=schedule_then_fail,+ ):+ with self.assertRaisesRegex(RuntimeError, "rollback"):+ self._deliver()++ self.assertFalse(any(log["event"] == "feature_request_github_target_applied" for log in logs))++ def test_shared_installation_fans_out_only_to_matching_issue_links(self) -> None:+ second_team = Team.objects.create(organization=self.organization, name="Second project")+ second_integration = Integration.objects.create(+ team=second_team,+ kind="github",+ integration_id="installation-1",+ config={},+ sensitive_config={},+ )+ second_request = create_feature_request(team_id=second_team.id, status=FeatureRequestStatus.REQUESTED)+ FeatureRequestGitHubLink.objects.for_team(second_team.id).create(+ team_id=second_team.id,+ feature_request=second_request,+ integration=second_integration,+ sync_enabled_by=self.user,+ installation_id="installation-1",+ repository="posthog/posthog",+ issue_number=42,+ issue_title="Original title",+ issue_state="open",+ )+ unrelated = create_feature_request(team_id=second_team.id, status=FeatureRequestStatus.PLANNED)+ FeatureRequestGitHubLink.objects.for_team(second_team.id).create(+ team_id=second_team.id,+ feature_request=unrelated,+ integration=second_integration,+ installation_id="installation-1",+ repository="posthog/posthog",+ issue_number=43,+ issue_title="Unrelated",+ issue_state="open",+ )++ self._deliver()++ self.request.refresh_from_db()+ second_request.refresh_from_db()+ unrelated.refresh_from_db()+ self.assertEqual(self.request.status, FeatureRequestStatus.COMPLETED)+ self.assertEqual(second_request.status, FeatureRequestStatus.COMPLETED)+ self.assertEqual(unrelated.status, FeatureRequestStatus.PLANNED)++ def test_conflicted_link_does_not_block_other_links_in_the_delivery(self) -> None:+ second_user = User.objects.create_and_join(self.organization, "[email protected]", "testtest")+ second_request = create_feature_request(team_id=self.team.id, status=FeatureRequestStatus.PLANNED)+ second_link = FeatureRequestGitHubLink.objects.for_team(self.team.id).create(+ team_id=self.team.id,+ feature_request=second_request,+ integration=self.integration,+ sync_enabled_by=second_user,+ installation_id="installation-1",+ repository="posthog/posthog",+ issue_number=42,+ issue_title="Original title",+ issue_state="open",+ )+ requests_by_distinct_id = {+ str(self.user.distinct_id): self.request,+ str(second_user.distinct_id): second_request,+ }+ conflicted_request: FeatureRequest | None = None++ def change_first_target_before_locking(_flag: str, distinct_id: str, **_kwargs: object) -> bool:+ nonlocal conflicted_request+ if conflicted_request is None:+ conflicted_request = requests_by_distinct_id[distinct_id]+ conflicted_request.version += 1+ conflicted_request.save(update_fields=["version"])+ return True++ with capture_logs(processors=[merge_contextvars]) as logs:+ with patch(+ "products.customer_analytics.backend.logic.feature_request_github.posthog_feature_flag_enabled",+ side_effect=change_first_target_before_locking,+ ):+ with self.captureOnCommitCallbacks(execute=True):+ with self.assertRaises(FeatureRequestConflictError):+ self._deliver()++ self.assertEqual(self._log(logs, "feature_request_github_target_conflicted")["reason"], "version_conflict")+ self.assertEqual(self._log(logs, "feature_request_github_target_applied")["changed"], True)+ summary = self._log(logs, "feature_request_github_delivery_summary")+ self.assertEqual(+ {+ key: summary[key]+ for key in ("outcome", "matched", "applied", "skipped", "conflicted", "failed", "error_type")+ },+ {+ "outcome": "failure",+ "matched": 2,+ "applied": 1,+ "skipped": 0,+ "conflicted": 1,+ "failed": 0,+ "error_type": "FeatureRequestConflictError",+ },+ )++ if conflicted_request is None:+ self.fail("Expected a target to conflict.")+ other_request = second_request if conflicted_request.id == self.request.id else self.request+ conflicted_link = self.link if conflicted_request.id == self.request.id else second_link+ other_link = second_link if conflicted_request.id == self.request.id else self.link+ conflicted_request.refresh_from_db()+ other_request.refresh_from_db()+ conflicted_link.refresh_from_db()+ other_link.refresh_from_db()+ self.assertEqual(conflicted_request.status, FeatureRequestStatus.PLANNED)+ self.assertEqual(conflicted_link.issue_title, "Original title")+ self.assertEqual(other_request.status, FeatureRequestStatus.COMPLETED)+ self.assertEqual(other_link.issue_title, "Updated title")++ def test_duplicate_or_old_delivery_creates_no_history_or_version_change(self) -> None:+ timestamp = datetime(2026, 1, 2, tzinfo=UTC)+ self._deliver(updated_at=timestamp)+ self.request.refresh_from_db()+ version = self.request.version+ history_count = FeatureRequestHistory.objects.for_team(self.team.id).count()++ self._deliver(title="Duplicate", updated_at=timestamp)+ self._deliver(title="Old", updated_at=datetime(2026, 1, 1, tzinfo=UTC))++ self.request.refresh_from_db()+ self.link.refresh_from_db()+ self.assertEqual(self.request.version, version)+ self.assertEqual(FeatureRequestHistory.objects.for_team(self.team.id).count(), history_count)+ self.assertEqual(self.link.issue_title, "Updated title")++ @patch("products.customer_analytics.backend.logic.feature_request_github.GitHubIntegration.api_request")+ def test_conflicting_delivery_at_the_same_timestamp_refetches_the_current_issue(self, api_request: Mock) -> None:+ timestamp = datetime(2026, 1, 2, tzinfo=UTC)+ self.link.github_updated_at = timestamp+ self.link.save(update_fields=["github_updated_at"])+ api_request.return_value = Mock(+ status_code=200,+ json=Mock(+ return_value={+ "number": 42,+ "title": "Current title",+ "state": "closed",+ "state_reason": "completed",+ "updated_at": "2026-01-02T00:00:00Z",+ "repository_url": "https://api.github.com/repos/PostHog/PostHog",+ "html_url": "https://github.com/PostHog/PostHog/issues/42",+ }+ ),+ )++ self._deliver(state="closed", updated_at=timestamp)++ self.request.refresh_from_db()+ self.link.refresh_from_db()+ self.assertEqual(self.request.status, FeatureRequestStatus.COMPLETED)+ self.assertEqual(self.link.issue_title, "Current title")+ api_request.assert_called_once()diff --git a/products/customer_analytics/backend/test/test_feature_request_github_access.py b/products/customer_analytics/backend/test/test_feature_request_github_access.pynew file mode 100644index 000000000000..ad78216e5ee1--- /dev/null+++ b/products/customer_analytics/backend/test/test_feature_request_github_access.py@@ -0,0 +1,130 @@+from posthog.test.base import APIBaseTest+from unittest.mock import patch++from django.utils import timezone++from rest_framework import status++from posthog.constants import AvailableFeature+from posthog.models import Integration, OrganizationMembership, User++from products.access_control.backend.models import AccessControl+from products.customer_analytics.backend.models import (+ FeatureRequestGitHubLink,+ FeatureRequestHistory,+ FeatureRequestHistorySource,+ FeatureRequestStatus,+)+from products.customer_analytics.backend.test.factories import (+ create_account,+ create_feature_request,+ create_feature_request_account_link,+)+++class TestFeatureRequestGitHubAccess(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ flag = patch("posthog.permissions.posthog_feature_flag_enabled", return_value=True)+ flag.start()+ self.addCleanup(flag.stop)++ def test_integration_access_controls_github_link_and_history_snapshots(self) -> None:+ account = create_account(team_id=self.team.id)+ request = create_feature_request(team_id=self.team.id, status=FeatureRequestStatus.COMPLETED)+ create_feature_request_account_link(team_id=self.team.id, feature_request=request, account=account)+ integration = Integration.objects.create(+ team=self.team,+ kind="github",+ integration_id="installation-1",+ config={},+ sensitive_config={},+ )+ link = FeatureRequestGitHubLink.objects.for_team(self.team.id).create(+ team_id=self.team.id,+ feature_request=request,+ integration=integration,+ installation_id="installation-1",+ repository="posthog/posthog",+ issue_number=42,+ issue_title="Export CSV",+ issue_state="closed",+ )+ FeatureRequestHistory.objects.for_team(self.team.id).create(+ team_id=self.team.id,+ feature_request=request,+ source=FeatureRequestHistorySource.GITHUB,+ actor_id=self.user.id,+ changed_at=timezone.now(),+ changes=[+ {+ "field": "github_link",+ "before": None,+ "after": {+ "id": str(link.id),+ "issue_url": "https://github.com/posthog/posthog/issues/42",+ "repository": "posthog/posthog",+ "issue_number": 42,+ "issue_title": "Export CSV",+ "issue_state": "closed",+ "sync_enabled": True,+ },+ },+ {"field": "status", "before": "planned", "after": "completed"},+ ],+ )+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},+ {"key": AvailableFeature.ROLE_BASED_ACCESS, "name": AvailableFeature.ROLE_BASED_ACCESS},+ ]+ self.organization.save()+ requests_url = f"/api/projects/{self.team.id}/feature_requests/"+ request_url = f"{requests_url}{request.id}/"++ owner_list = self.client.get(requests_url)+ owner_retrieve = self.client.get(request_url)+ owner_history = self.client.get(f"{request_url}history/")++ self.assertEqual(owner_list.json()["results"][0]["github_link"]["issue_title"], "Export CSV")+ self.assertEqual(owner_retrieve.json()["github_link"]["issue_title"], "Export CSV")+ self.assertEqual([change["field"] for change in owner_history.json()[0]["changes"]], ["github_link", "status"])++ viewer = User.objects.create_and_join(self.organization, "[email protected]", "testtest")+ membership = OrganizationMembership.objects.get(user=viewer, organization=self.organization)+ for resource, resource_id in (+ ("customer_analytics", None),+ ("account", str(account.id)),+ ("integration", None),+ ):+ AccessControl.objects.create(+ team=self.team,+ resource=resource,+ resource_id=resource_id,+ access_level="none" if resource == "integration" else "viewer",+ organization_member=membership,+ )+ self.client.force_login(viewer)++ listed = self.client.get(requests_url)+ retrieved = self.client.get(request_url)+ history = self.client.get(f"{request_url}history/")++ self.assertEqual([response.status_code for response in (listed, retrieved, history)], [status.HTTP_200_OK] * 3)+ self.assertIsNone(listed.json()["results"][0]["github_link"])+ self.assertIsNone(retrieved.json()["github_link"])+ self.assertEqual(history.json()[0]["changes"], [{"field": "status", "before": "planned", "after": "completed"}])+ self.assertNotIn("github_link", str(history.json()))+ self.assertNotIn("Export CSV", str(history.json()))+ self.assertNotIn("posthog/posthog", str(history.json()))++ link.integration = None+ link.save(update_fields=["integration"])+ self.assertEqual(+ self.client.get(f"{request_url}history/").json()[0]["changes"],+ [{"field": "status", "before": "planned", "after": "completed"}],+ )+ link.delete()+ self.assertEqual(+ self.client.get(f"{request_url}history/").json()[0]["changes"],+ [{"field": "status", "before": "planned", "after": "completed"}],+ )diff --git a/products/customer_analytics/backend/test/test_feature_request_github_metadata.py b/products/customer_analytics/backend/test/test_feature_request_github_metadata.pynew file mode 100644index 000000000000..e8c40177d7b1--- /dev/null+++ b/products/customer_analytics/backend/test/test_feature_request_github_metadata.py@@ -0,0 +1,154 @@+from datetime import UTC, datetime++from posthog.test.base import APIBaseTest+from unittest.mock import Mock, patch++from django.utils import timezone++from structlog.contextvars import merge_contextvars+from structlog.testing import capture_logs++from posthog.dataclasses import frozen+from posthog.models import Integration++from products.customer_analytics.backend.logic.feature_request_github import process_github_issue_update+from products.customer_analytics.backend.models import (+ FeatureRequestGitHubLink,+ FeatureRequestHistory,+ FeatureRequestStatus,+)+from products.customer_analytics.backend.test.factories import (+ create_account,+ create_feature_request,+ create_feature_request_account_link,+ create_feature_request_history,+)+++@frozen+class _RequestState:+ version: int+ updated_at: datetime+ updated_by_id: int | None+ history_count: int+++class TestFeatureRequestGitHubMetadataOnlySync(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.integration = Integration.objects.create(+ team=self.team,+ kind="github",+ integration_id="installation-1",+ config={},+ sensitive_config={},+ )+ self.request = create_feature_request(team_id=self.team.id, status=FeatureRequestStatus.PLANNED)+ self.request.updated_by_id = self.user.id+ self.request.save(update_fields=["updated_by_id"])+ account = create_account(team_id=self.team.id)+ create_feature_request_account_link(team_id=self.team.id, feature_request=self.request, account=account)+ create_feature_request_history(+ team_id=self.team.id,+ feature_request=self.request,+ changed_at=timezone.now(),+ is_initial=True,+ )+ self.link = FeatureRequestGitHubLink.objects.for_team(self.team.id).create(+ team_id=self.team.id,+ feature_request=self.request,+ integration=self.integration,+ sync_enabled_by=self.user,+ installation_id="installation-1",+ repository="posthog/posthog",+ issue_number=42,+ issue_title="Original title",+ issue_state="open",+ github_updated_at=datetime(2026, 1, 1, tzinfo=UTC),+ last_synced_at=datetime(2026, 1, 1, tzinfo=UTC),+ )+ self.url = f"/api/projects/{self.team.id}/feature_requests/{self.request.id}/"+ self.flag = patch("posthog.permissions.posthog_feature_flag_enabled", return_value=True)+ self.flag.start()+ self.addCleanup(self.flag.stop)++ def _request_snapshot(self) -> _RequestState:+ self.request.refresh_from_db()+ return _RequestState(+ version=self.request.version,+ updated_at=self.request.updated_at,+ updated_by_id=self.request.updated_by_id,+ history_count=FeatureRequestHistory.objects.for_team(self.team.id)+ .filter(feature_request=self.request)+ .count(),+ )++ def test_resume_refreshes_newer_title_without_changing_the_request(self) -> None:+ before = self._request_snapshot()+ synced_at = datetime(2026, 1, 3, tzinfo=UTC)+ response = Mock(+ status_code=200,+ json=Mock(+ return_value={+ "number": 42,+ "title": "Renamed export",+ "state": "open",+ "state_reason": None,+ "updated_at": "2026-01-02T00:00:00Z",+ "repository_url": "https://api.github.com/repos/PostHog/PostHog",+ "html_url": "https://github.com/PostHog/PostHog/issues/42",+ }+ ),+ )++ with (+ patch(+ "products.customer_analytics.backend.logic.feature_request_github.GitHubIntegration.api_request",+ return_value=response,+ ),+ patch(+ "products.customer_analytics.backend.logic.feature_request_github.timezone.now", return_value=synced_at+ ),+ ):+ resumed = self.client.post(f"{self.url}resume_github/", {"expected_version": before.version}, format="json")++ self.assertEqual(resumed.status_code, 200)+ self.link.refresh_from_db()+ self.assertEqual(self.link.issue_title, "Renamed export")+ self.assertEqual(self.link.github_updated_at, datetime(2026, 1, 2, tzinfo=UTC))+ self.assertEqual(self.link.last_synced_at, synced_at)+ self.assertEqual(self._request_snapshot(), before)++ def test_worker_refreshes_newer_title_without_changing_the_request(self) -> None:+ before = self._request_snapshot()+ synced_at = datetime(2026, 1, 3, tzinfo=UTC)++ with capture_logs(processors=[merge_contextvars]) as logs:+ with (+ patch(+ "products.customer_analytics.backend.logic.feature_request_github.posthog_feature_flag_enabled",+ return_value=True,+ ),+ patch(+ "products.customer_analytics.backend.logic.feature_request_github.timezone.now",+ return_value=synced_at,+ ),+ self.captureOnCommitCallbacks(execute=True),+ ):+ process_github_issue_update(+ installation_id="installation-1",+ repository="PostHog/PostHog",+ issue_number=42,+ issue_title="Renamed export",+ issue_state="open",+ issue_state_reason="",+ github_updated_at=datetime(2026, 1, 2, tzinfo=UTC),+ )++ self.link.refresh_from_db()+ self.assertEqual(self.link.issue_title, "Renamed export")+ self.assertEqual(self.link.github_updated_at, datetime(2026, 1, 2, tzinfo=UTC))+ self.assertEqual(self.link.last_synced_at, synced_at)+ self.assertEqual(self._request_snapshot(), before)+ applied = next(log for log in logs if log["event"] == "feature_request_github_target_applied")+ self.assertFalse(applied["changed"])diff --git a/products/customer_analytics/backend/test/test_feature_request_github_observability.py b/products/customer_analytics/backend/test/test_feature_request_github_observability.pynew file mode 100644index 000000000000..c958bf56cdc9--- /dev/null+++ b/products/customer_analytics/backend/test/test_feature_request_github_observability.py@@ -0,0 +1,219 @@+from typing import Any++import time_machine+from unittest.mock import patch++from django.test import SimpleTestCase++import posthoganalytics+from celery.exceptions import Retry+from posthoganalytics.contexts import get_capture_exception_code_variables_context+from structlog.contextvars import bound_contextvars, clear_contextvars, get_contextvars, merge_contextvars+from structlog.testing import capture_logs++from products.customer_analytics.backend.tasks.tasks import (+ _capture_terminal_feature_request_github_failure,+ process_feature_request_github_issue,+)+++class TestFeatureRequestGitHubTaskObservability(SimpleTestCase):+ def setUp(self) -> None:+ clear_contextvars()+ self.addCleanup(clear_contextvars)++ task_args = (+ "installation-1",+ "posthog/posthog",+ 42,+ "Issue title",+ "closed",+ "completed",+ "2026-01-01T00:00:00+00:00",+ )++ def test_task_accepts_legacy_arguments_and_restores_parent_log_context(self) -> None:+ with (+ patch("products.customer_analytics.backend.tasks.tasks.process_github_issue_update") as process_update,+ bound_contextvars(github_delivery_id="parent-delivery", parent_context="present"),+ ):+ result = process_feature_request_github_issue.apply(args=self.task_args, task_id="legacy-task")+ context_after_task = get_contextvars()++ self.assertEqual(result.state, "SUCCESS")+ process_update.assert_called_once()+ self.assertEqual(context_after_task["github_delivery_id"], "parent-delivery")+ self.assertEqual(context_after_task["parent_context"], "present")++ def test_nonterminal_retry_does_not_capture_and_keeps_attempt_context_isolated(self) -> None:+ observed_request: dict[str, str | int | None] = {}++ def fail_retryably(**_kwargs: object) -> None:+ observed_request["task_id"] = process_feature_request_github_issue.request.id+ observed_request["retries"] = process_feature_request_github_issue.request.retries+ raise RuntimeError("retryable error")++ with (+ patch(+ "products.customer_analytics.backend.tasks.tasks.process_github_issue_update",+ side_effect=fail_retryably,+ ),+ patch("products.customer_analytics.backend.tasks.tasks.capture_exception") as capture_exception,+ bound_contextvars(github_delivery_id="parent-delivery"),+ ):+ with self.assertRaises(Retry) as raised:+ process_feature_request_github_issue.apply(+ args=self.task_args,+ kwargs={"github_delivery_id": "delivery-1", "github_received_at": "2026-01-01T00:00:00+00:00"},+ task_id="retry-task",+ retries=1,+ )+ context_after_task = get_contextvars()++ self.assertIsInstance(raised.exception.exc, RuntimeError)+ self.assertEqual(observed_request, {"task_id": "retry-task", "retries": 1})+ capture_exception.assert_not_called()+ self.assertEqual(context_after_task["github_delivery_id"], "parent-delivery")++ @time_machine.travel("2026-01-01T00:01:00+00:00", tick=False)+ def test_task_started_log_includes_delivery_correlation_and_age(self) -> None:+ with (+ patch("products.customer_analytics.backend.tasks.tasks.process_github_issue_update"),+ capture_logs(processors=[merge_contextvars]) as logs,+ ):+ result = process_feature_request_github_issue.apply(+ args=self.task_args,+ kwargs={"github_delivery_id": "started-delivery", "github_received_at": "2026-01-01T00:00:00+00:00"},+ task_id="started-task",+ retries=2,+ )++ self.assertEqual(result.state, "SUCCESS")++ self.assertIn(+ {+ "github_delivery_id": "started-delivery",+ "task_id": "started-task",+ "sync_attempt": 2,+ "delivery_age_seconds": 60.0,+ },+ [+ {key: log[key] for key in ("github_delivery_id", "task_id", "sync_attempt", "delivery_age_seconds")}+ for log in logs+ if log["event"] == "feature_request_github_task_started"+ ],+ )++ def test_terminal_retry_captures_a_sanitized_exception_once_without_masking_the_failure(self) -> None:+ original = RuntimeError("original failure")+ with (+ patch(+ "products.customer_analytics.backend.tasks.tasks.process_github_issue_update",+ side_effect=original,+ ),+ patch("products.customer_analytics.backend.tasks.tasks.capture_exception") as capture_exception,+ ):+ result = process_feature_request_github_issue.apply(+ args=self.task_args,+ kwargs={"github_delivery_id": "delivery-1", "github_received_at": "2026-01-01T00:00:00+00:00"},+ task_id="terminal-task",+ retries=3,+ throw=False,+ )++ self.assertEqual(result.state, "FAILURE")+ capture_exception.assert_called_once()+ captured_error, properties = capture_exception.call_args.args+ self.assertNotEqual(captured_error, original)+ self.assertEqual(type(captured_error).__name__, "FeatureRequestGitHubTaskFailed")+ self.assertEqual(+ properties,+ {+ "github_delivery_id": "delivery-1",+ "task_id": "terminal-task",+ "sync_attempt": 3,+ "installation_id": "installation-1",+ "github_received_at": "2026-01-01T00:00:00+00:00",+ "exception_type": "RuntimeError",+ },+ )++ def test_capture_failure_does_not_mask_the_original_terminal_failure(self) -> None:+ with (+ patch(+ "products.customer_analytics.backend.tasks.tasks.process_github_issue_update",+ side_effect=RuntimeError("original failure"),+ ),+ patch(+ "products.customer_analytics.backend.tasks.tasks.capture_exception",+ side_effect=RuntimeError("capture failure"),+ ),+ ):+ result = process_feature_request_github_issue.apply(args=self.task_args, retries=3, throw=False)++ self.assertEqual(result.state, "FAILURE")+ self.assertIsInstance(result.result, RuntimeError)+ self.assertEqual(str(result.result), "original failure")++ def test_terminal_capture_serializes_only_the_sanitized_exception_without_code_variables(self) -> None:+ captured_context: list[bool | None] = []+ enqueued: list[dict[str, Any]] = []+ client = posthoganalytics.Client("test-key", capture_exception_code_variables=True)+ self.addCleanup(client.shutdown)++ def fail_with_sensitive_context(**_kwargs: object) -> None:+ issue_title = " ".join(("private", "issue", "title"))+ repository = "/".join(("private", "repository"))+ issue_body = " ".join(("private", "issue", "body"))+ if not all((issue_title, repository, issue_body)):+ raise AssertionError+ try:+ raise ValueError(" ".join(("private", "cause")))+ except ValueError as error:+ raise RuntimeError(" ".join(("private", "original", "error"))) from error++ def capture_with_pinned_sdk(error: Exception, properties: dict[str, object]) -> None:+ captured_context.append(get_capture_exception_code_variables_context())+ client.capture_exception(error, properties=properties)++ def capture_serialized_exception(event: str, *, properties: dict[str, object], **_kwargs: object) -> str:+ enqueued.append({"event": event, "properties": properties})+ return "event-1"++ with (+ patch(+ "products.customer_analytics.backend.tasks.tasks.capture_exception",+ side_effect=capture_with_pinned_sdk,+ ),+ patch.object(client, "capture", side_effect=capture_serialized_exception),+ posthoganalytics.new_context(fresh=True, capture_exceptions=False),+ bound_contextvars(parent_context="present"),+ ):+ posthoganalytics.set_capture_exception_code_variables_context(True)+ try:+ fail_with_sensitive_context()+ except Exception as error:+ _capture_terminal_feature_request_github_failure(+ error,+ github_delivery_id="delivery-1",+ task_id="terminal-task",+ sync_attempt=3,+ installation_id="installation-1",+ github_received_at="2026-01-01T00:00:00+00:00",+ )+ self.assertEqual(get_contextvars()["parent_context"], "present")+ self.assertTrue(get_capture_exception_code_variables_context())++ self.assertEqual(captured_context, [False])+ self.assertEqual(len(enqueued), 1)+ serialized = repr(enqueued[0])+ for secret in (+ "private issue title",+ "private/repository",+ "private issue body",+ "private cause",+ "private original error",+ ):+ self.assertNotIn(secret, serialized)+ exception_list = enqueued[0]["properties"]["$exception_list"]+ self.assertFalse(any("vars" in frame for value in exception_list for frame in value["stacktrace"]["frames"]))diff --git a/products/customer_analytics/backend/webhook_consumers.py b/products/customer_analytics/backend/webhook_consumers.pynew file mode 100644index 000000000000..c4237b4fafd4--- /dev/null+++ b/products/customer_analytics/backend/webhook_consumers.py@@ -0,0 +1,100 @@+from collections.abc import Mapping+from datetime import UTC, datetime++import structlog+from structlog.contextvars import bound_contextvars++from posthog.ingress.contracts import WebhookConsumer, WebhookDelivery++logger = structlog.get_logger(__name__)+++def _log_ignored_delivery(reason: str) -> None:+ logger.debug("feature_request_github_delivery_ignored", reason=reason)+++def _process_github_issue_delivery(delivery: WebhookDelivery) -> None:+ payload: object = delivery.payload+ if not isinstance(payload, Mapping):+ _log_ignored_delivery("invalid_payload")+ return+ if payload.get("action") not in {"opened", "closed", "reopened", "edited"}:+ _log_ignored_delivery("unsupported_action")+ return++ issue = payload.get("issue")+ repository = payload.get("repository")+ installation = payload.get("installation")+ if not isinstance(issue, Mapping) or not isinstance(repository, Mapping) or not isinstance(installation, Mapping):+ _log_ignored_delivery("missing_issue_context")+ return+ if issue.get("pull_request"):+ _log_ignored_delivery("pull_request")+ return+ if type(issue.get("number")) is not int or not isinstance(issue.get("updated_at"), str):+ _log_ignored_delivery("invalid_issue")+ return++ full_name = repository.get("full_name")+ installation_id = installation.get("id")+ state = issue.get("state")+ if (+ not isinstance(full_name, str)+ or type(installation_id) is not int+ or state not in {"open", "closed"}+ or (state == "closed" and issue.get("state_reason") not in {None, "", "completed", "not_planned"})+ ):+ _log_ignored_delivery("unsupported_issue_state")+ return+ try:+ updated_at = datetime.fromisoformat(issue["updated_at"].replace("Z", "+00:00"))+ except ValueError:+ _log_ignored_delivery("invalid_updated_at")+ return+ if updated_at.tzinfo is None:+ _log_ignored_delivery("invalid_updated_at")+ return++ github_received_at = delivery.received_at.astimezone(UTC).isoformat()+ from products.customer_analytics.backend.facade import (+ api, # noqa: PLC0415 - keep task registration off the ingress import path+ )++ task_id = api.process_feature_request_github_delivery(+ installation_id=str(installation_id),+ repository=full_name.lower(),+ issue_number=issue["number"],+ issue_title=issue["title"] if isinstance(issue.get("title"), str) else "",+ issue_state=state,+ issue_state_reason=issue["state_reason"] if isinstance(issue.get("state_reason"), str) else "",+ github_updated_at=updated_at,+ github_delivery_id=delivery.delivery_id,+ github_received_at=github_received_at,+ )+ with bound_contextvars(+ github_delivery_id=delivery.delivery_id,+ task_id=task_id,+ sync_attempt=0,+ installation_id=str(installation_id),+ github_received_at=github_received_at,+ ):+ logger.info("feature_request_github_delivery_queued")+++def _run_github_issue_delivery(delivery: WebhookDelivery) -> None:+ with bound_contextvars(+ github_delivery_id=delivery.delivery_id,+ github_received_at=delivery.received_at.astimezone(UTC).isoformat(),+ ):+ _process_github_issue_delivery(delivery)+++WEBHOOK_CONSUMERS = (+ WebhookConsumer(+ name="customer_analytics_feature_requests",+ provider="github",+ app="posthog",+ event_types=frozenset({"issues"}),+ handler=_run_github_issue_delivery,+ ),+)diff --git a/products/customer_analytics/frontend/components/Accounts/accountFeatureRequestsLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountFeatureRequestsLogic.test.tsindex a371f896735b..516ee40accd2 100644--- a/products/customer_analytics/frontend/components/Accounts/accountFeatureRequestsLogic.test.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountFeatureRequestsLogic.test.ts@@ -21,6 +21,7 @@ const existingRequest: FeatureRequestApi = {archived_by: null,version: 3,can_update: true,+ github_link: null,account: { id: 'account-1', name: 'Acme' },account_links: [{diff --git a/products/customer_analytics/frontend/components/FeatureRequests/FeatureRequestDetail.tsx b/products/customer_analytics/frontend/components/FeatureRequests/FeatureRequestDetail.tsxindex b4130f5fdbdf..9a86b6aab5e3 100644--- a/products/customer_analytics/frontend/components/FeatureRequests/FeatureRequestDetail.tsx+++ b/products/customer_analytics/frontend/components/FeatureRequests/FeatureRequestDetail.tsx@@ -22,6 +22,7 @@ import { FeatureRequestAccountEvidenceModal } from './FeatureRequestAccountEvideimport { FeatureRequestAccountItem } from './FeatureRequestAccountItem'import { FeatureRequestDetailSection } from './FeatureRequestDetailSection'import { FeatureRequestEditModal } from './FeatureRequestEditModal'+import { FeatureRequestGithubSection } from './FeatureRequestGithubSection'import { FeatureRequestHistorySection } from './FeatureRequestHistorySection'import { FeatureRequestImages } from './FeatureRequestImages'import { FeatureRequestPriorityBadge } from './FeatureRequestPriorityBadge'@@ -142,6 +143,8 @@ export function FeatureRequestDetail({ request }: { request: FeatureRequestApi }</div><aside className="flex flex-col min-w-0 gap-5">+ <FeatureRequestGithubSection request={request} />+<FeatureRequestDetailSection icon={<IconFolder />} title="Product areas"><div className="flex flex-wrap gap-1.5">{request.product_areas.map((area) => (diff --git a/products/customer_analytics/frontend/components/FeatureRequests/FeatureRequestEditModal.tsx b/products/customer_analytics/frontend/components/FeatureRequests/FeatureRequestEditModal.tsxindex 7b7e3f05e786..3840a2e09956 100644--- a/products/customer_analytics/frontend/components/FeatureRequests/FeatureRequestEditModal.tsx+++ b/products/customer_analytics/frontend/components/FeatureRequests/FeatureRequestEditModal.tsx@@ -18,6 +18,7 @@ import { featureRequestsLogic } from './featureRequestsLogic'export function FeatureRequestEditModal(): JSX.Element {const {editRequestOpen,+ activeRequest,editTitle,editDescription,editAccountIds,@@ -89,6 +90,9 @@ export function FeatureRequestEditModal(): JSX.Element {options={FEATURE_REQUEST_STATUS_OPTIONS}fullWidth/>+ {activeRequest?.github_link && (+ <span className="text-xs text-tertiary">Changing the status pauses GitHub sync.</span>+ )}</div><div className="flex flex-col gap-1"><LemonLabel>Priority</LemonLabel>diff --git a/products/customer_analytics/frontend/components/FeatureRequests/FeatureRequestGithubSection.stories.tsx b/products/customer_analytics/frontend/components/FeatureRequests/FeatureRequestGithubSection.stories.tsxnew file mode 100644index 000000000000..460301f55537--- /dev/null+++ b/products/customer_analytics/frontend/components/FeatureRequests/FeatureRequestGithubSection.stories.tsx@@ -0,0 +1,204 @@+import type { Meta, StoryObj } from '@storybook/react'+import { useActions, useValues } from 'kea'+import { useEffect } from 'react'++import { FEATURE_FLAGS } from 'lib/constants'+import { integrationsLogic } from 'lib/integrations/integrationsLogic'++import { useStorybookMocks } from '~/mocks/browser'+import type { Mocks } from '~/mocks/utils'++import type { FeatureRequestApi, FeatureRequestGitHubLinkApi } from '../../generated/api.schemas'+import { featureRequestGithubLogic } from './featureRequestGithubLogic'+import { FeatureRequestGithubSection } from './FeatureRequestGithubSection'+import { featureRequestsLogic } from './featureRequestsLogic'++const integration = {+ id: 12,+ kind: 'github' as const,+ display_name: 'Example GitHub',+ icon_url: '',+ config: {},+ created_at: '2024-01-01T00:00:00Z',+}++const linkedIssue: FeatureRequestGitHubLinkApi = {+ id: 'github-link-1',+ issue_url: 'https://github.com/posthog/example-repository/issues/123',+ repository: 'posthog/example-repository',+ issue_number: 123,+ issue_title: 'Show retention data in account reports',+ issue_state: 'open',+ sync_enabled: true,+ last_synced_at: '2024-01-14T10:00:00Z',+}++const unlinkedRequest: FeatureRequestApi = {+ id: 'feature-request-1',+ title: 'Show retention data in account reports',+ description: 'Example request used only for Storybook.',+ request_status: 'planned',+ request_priority: null,+ is_archived: false,+ archived_at: null,+ archived_by: null,+ version: 1,+ can_update: true,+ github_link: null,+ account: { id: 'account-1', name: 'Example account' },+ account_links: [],+ evidence_count: 0,+ product_areas: [],+ created_by: 1,+ updated_by: 1,+ created_at: '2024-01-01T00:00:00Z',+ updated_at: '2024-01-01T00:00:00Z',+}++const linkedRequest: FeatureRequestApi = { ...unlinkedRequest, github_link: linkedIssue }+const pausedRequest: FeatureRequestApi = {+ ...linkedRequest,+ github_link: { ...linkedIssue, sync_enabled: false },+}++interface SectionStoryProps {+ request: FeatureRequestApi+ integrations?: (typeof integration)[]+ post?: Mocks['post']+ mutationError?: string+ loading?: boolean+ width?: 'normal' | 'narrow'+}++function SectionStory({+ request,+ integrations = [integration],+ post = {},+ mutationError,+ loading = false,+ width = 'normal',+}: SectionStoryProps): JSX.Element {+ useStorybookMocks({+ get: {+ '/api/projects/:team_id/feature_requests/': { count: 1, next: null, previous: null, results: [request] },+ '/api/projects/:team_id/feature_requests/:id/': request,+ '/api/projects/:team_id/feature_requests/:id/history/': [],+ '/api/projects/:team_id/feature_request_product_areas/': [],+ '/api/projects/:team_id/accounts/': { count: 0, next: null, previous: null, results: [] },+ '/api/projects/:team_id/integrations/': () => {+ if (loading) {+ return new Promise<never>(() => {})+ }+ return {+ count: integrations.length,+ next: null,+ previous: null,+ results: integrations,+ }+ },+ },+ post,+ })++ const requestsLogic = featureRequestsLogic()+ const githubLogic = featureRequestGithubLogic({ requestId: request.id })+ const { activeRequest } = useValues(requestsLogic)+ const { loadActiveRequestSuccess } = useActions(requestsLogic)+ const { setMutationError } = useActions(githubLogic)++ useValues(integrationsLogic)++ useEffect(() => {+ loadActiveRequestSuccess(request)+ if (mutationError) {+ setMutationError(mutationError)+ }+ }, [loadActiveRequestSuccess, mutationError, request, setMutationError])++ return (+ <div className={width === 'narrow' ? 'w-[520px] p-4' : 'w-[900px] p-4'}>+ <FeatureRequestGithubSection request={activeRequest ?? request} />+ </div>+ )+}++const meta: Meta<typeof SectionStory> = {+ title: 'Customer analytics/Feature requests/GitHub issue',+ component: SectionStory,+ parameters: {+ layout: 'padded',+ featureFlags: [FEATURE_FLAGS.CUSTOMER_ANALYTICS],+ },+}+export default meta++type Story = StoryObj<typeof SectionStory>++export const Linked: Story = {+ args: {+ request: linkedRequest,+ post: {+ '/api/projects/:team_id/feature_requests/:id/pause_github/': pausedRequest,+ '/api/projects/:team_id/feature_requests/:id/unlink_github/': unlinkedRequest,+ },+ },+}++export const Paused: Story = {+ args: {+ request: pausedRequest,+ post: {+ '/api/projects/:team_id/feature_requests/:id/resume_github/': linkedRequest,+ '/api/projects/:team_id/feature_requests/:id/unlink_github/': unlinkedRequest,+ },+ },+}++export const Unlinked: Story = {+ args: {+ request: unlinkedRequest,+ post: {+ '/api/projects/:team_id/feature_requests/:id/link_github/': linkedRequest,+ },+ },+}++export const ReadOnly: Story = {+ args: {+ request: { ...linkedRequest, can_update: false },+ },+}++export const Archived: Story = {+ args: {+ request: { ...linkedRequest, is_archived: true },+ },+}++export const Error: Story = {+ args: {+ request: unlinkedRequest,+ mutationError: "Couldn't link this GitHub issue. Check the URL and try again.",+ },+}++export const Loading: Story = {+ args: {+ request: unlinkedRequest,+ loading: true,+ },+}++export const LinkedNarrow: Story = {+ args: {+ request: linkedRequest,+ width: 'narrow',+ },+}++export const UnlinkedNarrow: Story = {+ args: {+ request: unlinkedRequest,+ width: 'narrow',+ },+}diff --git a/products/customer_analytics/frontend/components/FeatureRequests/FeatureRequestGithubSection.tsx b/products/customer_analytics/frontend/components/FeatureRequests/FeatureRequestGithubSection.tsxnew file mode 100644index 000000000000..27b00a85b44f--- /dev/null+++ b/products/customer_analytics/frontend/components/FeatureRequests/FeatureRequestGithubSection.tsx@@ -0,0 +1,153 @@+import { useActions, useValues } from 'kea'++import { IconGithub } from '@posthog/icons'+import { LemonBanner, LemonButton, LemonInput, LemonSelect, LemonTag, Link } from '@posthog/lemon-ui'++import { urls } from 'scenes/urls'++import type { FeatureRequestApi } from '../../generated/api.schemas'+import { FeatureRequestDetailSection } from './FeatureRequestDetailSection'+import { featureRequestGithubLogic } from './featureRequestGithubLogic'++export function FeatureRequestGithubSection({ request }: { request: FeatureRequestApi }): JSX.Element {+ const logic = featureRequestGithubLogic({ requestId: request.id })+ const {+ githubIntegrations,+ integrationsLoading,+ issueUrl,+ selectedIntegrationId,+ mutationError,+ mutationIsStale,+ mutatingGithubLink,+ canUpdate,+ linkDisabledReason,+ } = useValues(logic)+ const {+ setIssueUrl,+ setIntegrationId,+ linkGithub,+ pauseGithub,+ resumeGithub,+ unlinkGithub,+ reloadLatestGithubLink,+ } = useActions(logic)+ const githubLink = request.github_link+ const disabledReason = request.is_archived+ ? 'Restore this request to update GitHub sync'+ : canUpdate+ ? undefined+ : 'You do not have permission to update this request'++ return (+ <FeatureRequestDetailSection icon={<IconGithub />} title="GitHub issue">+ <div className="flex min-w-0 flex-col gap-3">+ {mutationError && (+ <LemonBanner type="error">+ <div className="flex flex-wrap items-center gap-2">+ <span>{mutationError}</span>+ {mutationIsStale && (+ <LemonButton+ type="secondary"+ size="xsmall"+ onClick={reloadLatestGithubLink}+ data-attr="reload-feature-request-github-link"+ >+ Reload+ </LemonButton>+ )}+ </div>+ </LemonBanner>+ )}+ {githubLink ? (+ <>+ <div className="flex min-w-0 flex-wrap items-center gap-2">+ <LemonButton+ type="tertiary"+ size="small"+ to={githubLink.issue_url}+ targetBlank+ className="min-w-0 max-w-full truncate"+ >+ {`${githubLink.repository}#${githubLink.issue_number}${+ githubLink.issue_title ? `: ${githubLink.issue_title}` : ''+ }`}+ </LemonButton>+ <LemonTag type={githubLink.issue_state === 'open' ? 'success' : 'muted'}>+ {githubLink.issue_state === 'open' ? 'Open' : 'Closed'}+ </LemonTag>+ <LemonTag type={githubLink.sync_enabled ? 'primary' : 'muted'}>+ {githubLink.sync_enabled ? 'Syncing' : 'Sync paused'}+ </LemonTag>+ </div>+ <div className="flex flex-wrap gap-2">+ <LemonButton+ type="secondary"+ size="small"+ onClick={githubLink.sync_enabled ? pauseGithub : resumeGithub}+ loading={mutatingGithubLink}+ disabledReason={disabledReason}+ data-attr={+ githubLink.sync_enabled+ ? 'pause-feature-request-github-sync'+ : 'resume-feature-request-github-sync'+ }+ >+ {githubLink.sync_enabled ? 'Pause sync' : 'Resume sync'}+ </LemonButton>+ <LemonButton+ type="tertiary"+ size="small"+ onClick={unlinkGithub}+ loading={mutatingGithubLink}+ disabledReason={disabledReason}+ data-attr="unlink-feature-request-github-issue"+ >+ Unlink issue+ </LemonButton>+ </div>+ </>+ ) : integrationsLoading ? (+ <span className="text-secondary">Loading GitHub integrations.</span>+ ) : githubIntegrations.length === 0 ? (+ <LemonBanner type="info">+ Connect GitHub in <Link to={urls.integration('github')}>settings</Link> to link an issue.+ </LemonBanner>+ ) : (+ <>+ <span className="text-secondary">Link this request to a GitHub issue.</span>+ {githubIntegrations.length > 1 && (+ <LemonSelect<number>+ value={selectedIntegrationId ?? undefined}+ onChange={(integrationId) => setIntegrationId(integrationId ?? null)}+ options={githubIntegrations.map((integration) => ({+ value: integration.id,+ label: integration.display_name,+ }))}+ placeholder="Select a GitHub integration"+ fullWidth+ />+ )}+ <div className="flex flex-wrap gap-2">+ <LemonInput+ value={issueUrl}+ onChange={setIssueUrl}+ placeholder="https://github.com/owner/repo/issues/123"+ className="min-w-0 flex-1 basis-64"+ />+ <LemonButton+ type="primary"+ size="small"+ onClick={linkGithub}+ loading={mutatingGithubLink}+ disabledReason={linkDisabledReason}+ data-attr="link-feature-request-github-issue"+ >+ Link issue+ </LemonButton>+ </div>+ </>+ )}+ </div>+ </FeatureRequestDetailSection>+ )+}diff --git a/products/customer_analytics/frontend/components/FeatureRequests/FeatureRequestHistory.test.tsx b/products/customer_analytics/frontend/components/FeatureRequests/FeatureRequestHistory.test.tsxindex 6b6a77898c1b..89fef4f1e8d4 100644--- a/products/customer_analytics/frontend/components/FeatureRequests/FeatureRequestHistory.test.tsx+++ b/products/customer_analytics/frontend/components/FeatureRequests/FeatureRequestHistory.test.tsx@@ -5,6 +5,73 @@ import { cleanup, fireEvent, render, screen } from '@testing-library/react'import type { FeatureRequestHistoryApi } from '../../generated/api.schemas'import { FeatureRequestHistory } from './FeatureRequestHistory'+const githubHistory: FeatureRequestHistoryApi[] = [+ {+ id: 'history-github-link',+ changes: [+ {+ field: 'github_link',+ before: null,+ after: {+ id: 'github-link-1',+ issue_url: 'https://github.com/posthog/posthog/issues/81886',+ repository: 'posthog/posthog',+ issue_number: 81886,+ issue_title: 'Export account-level retention data',+ issue_state: 'open',+ sync_enabled: true,+ },+ },+ ],+ is_initial: false,+ change_source: 'github',+ actor_id: null,+ actor_name: null,+ changed_at: '2026-01-03T00:00:00Z',+ },+ {+ id: 'history-github-paused',+ changes: [{ field: 'github_sync', before: true, after: false }],+ is_initial: false,+ change_source: 'github',+ actor_id: null,+ actor_name: null,+ changed_at: '2026-01-03T01:00:00Z',+ },+ {+ id: 'history-github-resumed',+ changes: [{ field: 'github_sync', before: false, after: true }],+ is_initial: false,+ change_source: 'github',+ actor_id: null,+ actor_name: null,+ changed_at: '2026-01-03T02:00:00Z',+ },+ {+ id: 'history-github-unlink',+ changes: [+ {+ field: 'github_link',+ before: {+ id: 'github-link-1',+ issue_url: 'https://github.com/posthog/posthog/issues/81886',+ repository: 'posthog/posthog',+ issue_number: 81886,+ issue_title: 'Export account-level retention data',+ issue_state: 'open',+ sync_enabled: false,+ },+ after: null,+ },+ ],+ is_initial: false,+ change_source: 'github',+ actor_id: null,+ actor_name: null,+ changed_at: '2026-01-03T03:00:00Z',+ },+]+const history: FeatureRequestHistoryApi[] = [{id: 'history-evidence',@@ -29,6 +96,15 @@ const history: FeatureRequestHistoryApi[] = [actor_name: 'Test user',changed_at: '2026-01-03T00:00:00Z',},+ {+ id: 'history-github',+ changes: [{ field: 'status', before: 'planned', after: 'completed' }],+ is_initial: false,+ change_source: 'github',+ actor_id: null,+ actor_name: null,+ changed_at: '2026-01-03T01:00:00Z',+ },{id: 'history-account',changes: [@@ -72,4 +148,46 @@ describe('FeatureRequestHistory', () => {fireEvent.click(screen.getByText('Accounts:'))expect(onShowTarget).toHaveBeenLastCalledWith('account-2', undefined)})++ it('describes GitHub links and sync changes without showing raw history data', () => {+ render(+ <FeatureRequestHistory+ history={githubHistory}+ loading={false}+ error={null}+ showingAll+ onRetry={jest.fn()}+ onSetShowingAll={jest.fn()}+ onShowTarget={jest.fn()}+ />+ )++ expect(+ screen.getByText('linked posthog/posthog#81886 (Export account-level retention data)')+ ).toBeInTheDocument()+ expect(screen.getByText('paused')).toBeInTheDocument()+ expect(screen.getByText('resumed')).toBeInTheDocument()+ expect(+ screen.getByText('unlinked posthog/posthog#81886 (Export account-level retention data)')+ ).toBeInTheDocument()+ })++ it.each([+ ['a recorded actor', { actor_id: 1, actor_name: 'Test user' }, 'Test user updated this request'],+ ['an actorless GitHub entry', { actor_id: null, actor_name: null }, 'GitHub updated this request'],+ ])('identifies %s in GitHub history', (_, actor, expectedLabel) => {+ render(+ <FeatureRequestHistory+ history={[{ ...githubHistory[0], ...actor }]}+ loading={false}+ error={null}+ showingAll+ onRetry={jest.fn()}+ onSetShowingAll={jest.fn()}+ onShowTarget={jest.fn()}+ />+ )++ expect(screen.getByText(expectedLabel)).toBeInTheDocument()+ })})diff --git a/products/customer_analytics/frontend/components/FeatureRequests/FeatureRequestHistory.tsx b/products/customer_analytics/frontend/components/FeatureRequests/FeatureRequestHistory.tsxindex af367f770f88..044cd8888e10 100644--- a/products/customer_analytics/frontend/components/FeatureRequests/FeatureRequestHistory.tsx+++ b/products/customer_analytics/frontend/components/FeatureRequests/FeatureRequestHistory.tsx@@ -15,6 +15,7 @@ import { featureRequestPriorityLabel, featureRequestStatusLabel } from './featurtype RelationSnapshot = { id: string; name: string }type EvidenceSnapshot = { id: string; account: RelationSnapshot }+type GitHubIssueSnapshot = { repository: string; issueNumber: number; issueTitle: string }type ShowHistoryTarget = (accountId: string, evidenceId?: string) => voidconst FEATURE_REQUEST_STATUSES = new Set<string>(['requested', 'planned', 'completed', 'wont_fix', 'duplicate'])@@ -55,6 +56,30 @@ function relationSnapshots(value: unknown): RelationSnapshot[] {: []}+function githubIssueSnapshot(value: unknown): GitHubIssueSnapshot | null {+ if (+ typeof value !== 'object' ||+ value === null ||+ !('repository' in value) ||+ typeof value.repository !== 'string' ||+ !('issue_number' in value) ||+ typeof value.issue_number !== 'number'+ ) {+ return null+ }+ return {+ repository: value.repository,+ issueNumber: value.issue_number,+ issueTitle: 'issue_title' in value && typeof value.issue_title === 'string' ? value.issue_title : '',+ }+}++function githubIssueName(issue: GitHubIssueSnapshot): string {+ return issue.issueTitle+ ? `${issue.repository}#${issue.issueNumber} (${issue.issueTitle})`+ : `${issue.repository}#${issue.issueNumber}`+}+function statusName(value: unknown): string {return typeof value === 'string' && FEATURE_REQUEST_STATUSES.has(value)? featureRequestStatusLabel(value as FeatureRequestStatusEnumApi)@@ -207,6 +232,32 @@ function describeEvidenceChange(change: FeatureRequestHistoryChangeApi, onShowTa)}+function describeGithubLinkChange(change: FeatureRequestHistoryChangeApi): JSX.Element {+ const before = githubIssueSnapshot(change.before)+ const after = githubIssueSnapshot(change.after)+ const description =+ after && !before+ ? `linked ${githubIssueName(after)}`+ : before && !after+ ? `unlinked ${githubIssueName(before)}`+ : after+ ? `updated ${githubIssueName(after)}`+ : 'updated'+ return (+ <div>+ <span className="font-medium">GitHub issue:</span> {description}+ </div>+ )+}++function describeGithubSyncChange(change: FeatureRequestHistoryChangeApi): JSX.Element {+ return (+ <div>+ <span className="font-medium">GitHub sync:</span> {change.after === true ? 'resumed' : 'paused'}+ </div>+ )+}+function describeProductAreasChange(change: FeatureRequestHistoryChangeApi,isInitial: boolean,@@ -264,6 +315,10 @@ function describeChange(return describeEvidenceChange(change, onShowTarget)case 'product_areas':return describeProductAreasChange(change, isInitial, onShowTarget)+ case 'github_link':+ return describeGithubLinkChange(change)+ case 'github_sync':+ return describeGithubSyncChange(change)default:return null}@@ -332,7 +387,8 @@ export function FeatureRequestHistory({<div className="min-w-0 flex-1"><div className="mb-1 flex min-w-0 flex-wrap items-center gap-x-1.5 gap-y-0.5"><span className="font-medium text-sm text-default">- {entry.actor_name ?? 'Unknown user'}{' '}+ {entry.actor_name ??+ (entry.change_source === 'github' ? 'GitHub' : 'Unknown user')}{' '}{entry.is_initial ? 'created this request' : 'updated this request'}</span><span className="text-xs text-tertiary">diff --git a/products/customer_analytics/frontend/components/FeatureRequests/featureRequestGithubLogic.test.ts b/products/customer_analytics/frontend/components/FeatureRequests/featureRequestGithubLogic.test.tsnew file mode 100644index 000000000000..0377f9057170--- /dev/null+++ b/products/customer_analytics/frontend/components/FeatureRequests/featureRequestGithubLogic.test.ts@@ -0,0 +1,210 @@+import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'++import { expectLogic } from 'kea-test-utils'++import { ApiError } from 'lib/api'+import { integrationsLogic } from 'lib/integrations/integrationsLogic'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import * as generatedApi from '../../generated/api'+import type { FeatureRequestApi } from '../../generated/api.schemas'+import { featureRequestGithubLogic } from './featureRequestGithubLogic'+import { featureRequestsLogic } from './featureRequestsLogic'++const request: FeatureRequestApi = {+ id: 'request-1',+ title: 'Export account-level retention data',+ description: 'The customer needs this for reporting.',+ request_status: 'planned',+ request_priority: null,+ is_archived: false,+ archived_at: null,+ archived_by: null,+ version: 3,+ can_update: true,+ github_link: null,+ account: { id: 'account-1', name: 'Acme' },+ account_links: [],+ evidence_count: 0,+ product_areas: [],+ created_by: 1,+ updated_by: 1,+ created_at: '2026-01-01T00:00:00Z',+ updated_at: '2026-01-01T00:00:00Z',+}++function createDeferred<T>(): { promise: Promise<T>; resolve: (value: T) => void } {+ let resolve: (value: T) => void = () => undefined+ const promise = new Promise<T>((resolvePromise) => {+ resolve = resolvePromise+ })+ return { promise, resolve }+}++describe('featureRequestGithubLogic', () => {+ let featureRequests: ReturnType<typeof featureRequestsLogic.build>+ let integrations: ReturnType<typeof integrationsLogic.build>+ let github: ReturnType<typeof featureRequestGithubLogic.build>++ beforeEach(async () => {+ useMocks({+ get: {+ '/api/projects/:team_id/feature_requests/': { count: 0, next: null, previous: null, results: [] },+ '/api/projects/:team_id/feature_requests/:id/': request,+ '/api/projects/:team_id/feature_request_product_areas/': [],+ '/api/projects/:team_id/accounts/': { count: 0, next: null, previous: null, results: [] },+ '/api/projects/:team_id/integrations/': {+ count: 1,+ next: null,+ previous: null,+ results: [+ {+ id: 12,+ kind: 'github',+ display_name: 'PostHog GitHub',+ icon_url: '',+ config: {},+ created_at: '2026-01-01T00:00:00Z',+ },+ ],+ },+ },+ })+ initKeaTests(true, MOCK_DEFAULT_TEAM)+ featureRequests = featureRequestsLogic()+ integrations = integrationsLogic()+ github = featureRequestGithubLogic({ requestId: request.id })+ featureRequests.mount()+ integrations.mount()+ github.mount()+ featureRequests.actions.loadActiveRequestSuccess(request)+ await expectLogic(integrations, () => integrations.actions.loadIntegrations()).toFinishAllListeners()+ })++ afterEach(() => {+ jest.restoreAllMocks()+ github.unmount()+ integrations.unmount()+ featureRequests.unmount()+ })++ it('links an issue through the active project URL', async () => {+ const updated = { ...request, version: 4 }+ const linkSpy = jest.spyOn(generatedApi, 'featureRequestsLinkGithubCreate').mockResolvedValueOnce(updated)+ github.actions.setIssueUrl('https://github.com/posthog/posthog/issues/81886')++ await expectLogic(github, () => github.actions.linkGithub()).toFinishAllListeners()++ expect(linkSpy).toHaveBeenCalledWith(String(MOCK_DEFAULT_TEAM.id), request.id, {+ integration_id: 12,+ issue_url: 'https://github.com/posthog/posthog/issues/81886',+ expected_version: 3,+ })+ expect(featureRequests.values.activeRequest).toEqual(updated)+ expect(github.values.issueUrl).toBe('')+ })++ it('does not send a duplicate link while the first request is pending', async () => {+ const pendingLink = createDeferred<FeatureRequestApi>()+ const linkStarted = createDeferred<void>()+ const linkSpy = jest.spyOn(generatedApi, 'featureRequestsLinkGithubCreate').mockImplementationOnce(() => {+ linkStarted.resolve()+ return pendingLink.promise+ })+ github.actions.setIssueUrl('https://github.com/posthog/posthog/issues/81886')++ github.actions.linkGithub()+ await linkStarted.promise+ github.actions.linkGithub()++ expect(linkSpy).toHaveBeenCalledTimes(1)+ pendingLink.resolve(request)+ await expectLogic(github).toFinishAllListeners()+ })++ it.each([+ ['read-only request', { ...request, can_update: false }],+ ['archived request', { ...request, is_archived: true }],+ ])('does not mutate a %s', async (_, inaccessibleRequest) => {+ featureRequests.actions.loadActiveRequestSuccess(inaccessibleRequest)+ github.actions.setIssueUrl('https://github.com/posthog/posthog/issues/81886')+ const linkSpy = jest.spyOn(generatedApi, 'featureRequestsLinkGithubCreate')+ const pauseSpy = jest.spyOn(generatedApi, 'featureRequestsPauseGithubCreate')+ const resumeSpy = jest.spyOn(generatedApi, 'featureRequestsResumeGithubCreate')+ const unlinkSpy = jest.spyOn(generatedApi, 'featureRequestsUnlinkGithubCreate')++ github.actions.linkGithub()+ github.actions.pauseGithub()+ github.actions.resumeGithub()+ github.actions.unlinkGithub()+ await expectLogic(github).toFinishAllListeners()++ expect(linkSpy).not.toHaveBeenCalled()+ expect(pauseSpy).not.toHaveBeenCalled()+ expect(resumeSpy).not.toHaveBeenCalled()+ expect(unlinkSpy).not.toHaveBeenCalled()+ })++ it.each([+ [+ 'link an issue',+ () => github.actions.linkGithub(),+ () => jest.spyOn(generatedApi, 'featureRequestsLinkGithubCreate'),+ ],+ [+ 'pause GitHub sync',+ () => github.actions.pauseGithub(),+ () => jest.spyOn(generatedApi, 'featureRequestsPauseGithubCreate'),+ ],+ [+ 'resume GitHub sync',+ () => github.actions.resumeGithub(),+ () => jest.spyOn(generatedApi, 'featureRequestsResumeGithubCreate'),+ ],+ [+ 'unlink an issue',+ () => github.actions.unlinkGithub(),+ () => jest.spyOn(generatedApi, 'featureRequestsUnlinkGithubCreate'),+ ],+ ] as const)('does not %s after the active request changes', async (_, mutate, createMutationSpy) => {+ github.actions.setIssueUrl('https://github.com/posthog/posthog/issues/81886')+ featureRequests.actions.loadActiveRequestSuccess({ ...request, id: 'request-2', version: 4 })+ const mutationSpy = createMutationSpy()++ mutate()+ await expectLogic(github).toFinishAllListeners()++ expect(mutationSpy).not.toHaveBeenCalled()+ })++ it('keeps the entered issue URL when linking fails', async () => {+ jest.spyOn(generatedApi, 'featureRequestsLinkGithubCreate').mockRejectedValueOnce(new ApiError('stale', 409))+ github.actions.setIssueUrl('https://github.com/posthog/posthog/issues/81886')++ await expectLogic(github, () => github.actions.linkGithub()).toFinishAllListeners()++ expect(github.values.issueUrl).toBe('https://github.com/posthog/posthog/issues/81886')+ expect(github.values.mutationIsStale).toBe(true)+ })++ it('does not replace a newly active request when a pending link completes', async () => {+ const pendingLink = createDeferred<FeatureRequestApi>()+ const linkStarted = createDeferred<void>()+ jest.spyOn(generatedApi, 'featureRequestsLinkGithubCreate').mockImplementationOnce(() => {+ linkStarted.resolve()+ return pendingLink.promise+ })+ github.actions.setIssueUrl('https://github.com/posthog/posthog/issues/81886')++ github.actions.linkGithub()+ await linkStarted.promise+ const otherRequest = { ...request, id: 'request-2', title: 'Keep this request active' }+ featureRequests.actions.loadActiveRequestSuccess(otherRequest)+ pendingLink.resolve({ ...request, title: 'Linked request response' })+ await expectLogic(github).toFinishAllListeners()++ expect(featureRequests.values.activeRequest).toEqual(otherRequest)+ })+})diff --git a/products/customer_analytics/frontend/components/FeatureRequests/featureRequestGithubLogic.ts b/products/customer_analytics/frontend/components/FeatureRequests/featureRequestGithubLogic.tsnew file mode 100644index 000000000000..4a326660044f--- /dev/null+++ b/products/customer_analytics/frontend/components/FeatureRequests/featureRequestGithubLogic.ts@@ -0,0 +1,351 @@+import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'++import { ApiError } from 'lib/api'+import { integrationsLogic } from 'lib/integrations/integrationsLogic'+import { teamLogic } from 'scenes/teamLogic'++import type { IntegrationType } from '~/types'++import {+ featureRequestsLinkGithubCreate,+ featureRequestsPauseGithubCreate,+ featureRequestsResumeGithubCreate,+ featureRequestsUnlinkGithubCreate,+} from '../../generated/api'+import type { FeatureRequestApi } from '../../generated/api.schemas'+import { featureRequestsLogic } from './featureRequestsLogic'++export interface FeatureRequestGithubLogicProps {+ requestId: string+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface featureRequestGithubLogicValues {+ activeRequest: FeatureRequestApi | null // featureRequestsLogic+ githubIntegrations: IntegrationType[] // integrationsLogic+ integrationsLoading: boolean // integrationsLogic+ currentTeamId: number | null // teamLogic+ canUpdate: boolean+ integrationId: number | null+ issueUrl: string+ linkDisabledReason: string | undefined+ mutatingGithubLink: boolean+ mutationError: string | null+ mutationIsStale: boolean+ selectedIntegrationId: number | null+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface featureRequestGithubLogicActions {+ loadActiveRequest: (requestId: string) => string // featureRequestsLogic+ loadActiveRequestSuccess: (+ activeRequest: FeatureRequestApi,+ payload?: string | undefined+ ) => {+ activeRequest: FeatureRequestApi+ payload?: string+ } // featureRequestsLogic+ loadFeatureRequests: () => any // featureRequestsLogic+ loadRequestHistory: (requestId: string) => string // featureRequestsLogic+ linkGithub: () => {+ value: true+ }+ pauseGithub: () => {+ value: true+ }+ reloadLatestGithubLink: () => {+ value: true+ }+ resumeGithub: () => {+ value: true+ }+ setIntegrationId: (integrationId: number | null) => {+ integrationId: number | null+ }+ setIssueUrl: (issueUrl: string) => {+ issueUrl: string+ }+ setMutatingGithubLink: (mutatingGithubLink: boolean) => {+ mutatingGithubLink: boolean+ }+ setMutationError: (mutationError: string | null) => {+ mutationError: string | null+ }+ setMutationIsStale: (mutationIsStale: boolean) => {+ mutationIsStale: boolean+ }+ unlinkGithub: () => {+ value: true+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface featureRequestGithubLogicMeta {+ key: string+ __keaTypeGenInternalSelectorTypes: {+ selectedIntegrationId: (integrationId: number | null, githubIntegrations: IntegrationType[]) => number | null+ canUpdate: (activeRequest: FeatureRequestApi | null) => boolean+ linkDisabledReason: (+ canUpdate: boolean,+ githubIntegrations: IntegrationType[],+ integrationsLoading: boolean,+ selectedIntegrationId: number | null,+ issueUrl: string+ ) => string | undefined+ }+}++export type featureRequestGithubLogicType = MakeLogicType<+ featureRequestGithubLogicValues,+ featureRequestGithubLogicActions,+ FeatureRequestGithubLogicProps,+ featureRequestGithubLogicMeta+>++function apiErrorMessage(error: unknown, fallback: string): string {+ if (!(error instanceof ApiError)) {+ return fallback+ }+ const detail = error.data?.detail ?? error.data?.error+ return typeof detail === 'string' ? detail : fallback+}++function isActiveRequest(+ activeRequest: FeatureRequestApi | null,+ requestId: string+): activeRequest is FeatureRequestApi {+ return activeRequest?.id === requestId+}++export const featureRequestGithubLogic = kea<featureRequestGithubLogicType>([+ props({} as FeatureRequestGithubLogicProps),+ key((props) => props.requestId),+ path((key) => ['products', 'customer_analytics', 'featureRequestGithubLogic', key]),+ connect(() => ({+ values: [+ teamLogic,+ ['currentTeamId'],+ featureRequestsLogic,+ ['activeRequest'],+ integrationsLogic,+ ['githubIntegrations', 'integrationsLoading'],+ ],+ actions: [+ featureRequestsLogic,+ ['loadActiveRequestSuccess', 'loadActiveRequest', 'loadFeatureRequests', 'loadRequestHistory'],+ ],+ })),+ actions({+ setIssueUrl: (issueUrl: string) => ({ issueUrl }),+ setIntegrationId: (integrationId: number | null) => ({ integrationId }),+ setMutationError: (mutationError: string | null) => ({ mutationError }),+ setMutationIsStale: (mutationIsStale: boolean) => ({ mutationIsStale }),+ setMutatingGithubLink: (mutatingGithubLink: boolean) => ({ mutatingGithubLink }),+ linkGithub: true,+ pauseGithub: true,+ resumeGithub: true,+ unlinkGithub: true,+ reloadLatestGithubLink: true,+ }),+ reducers({+ issueUrl: ['', { setIssueUrl: (_, { issueUrl }) => issueUrl }],+ integrationId: [null as number | null, { setIntegrationId: (_, { integrationId }) => integrationId }],+ mutationError: [+ null as string | null,+ {+ setMutationError: (_, { mutationError }) => mutationError,+ linkGithub: () => null,+ pauseGithub: () => null,+ resumeGithub: () => null,+ unlinkGithub: () => null,+ reloadLatestGithubLink: () => null,+ },+ ],+ mutationIsStale: [+ false,+ {+ setMutationIsStale: (_, { mutationIsStale }) => mutationIsStale,+ linkGithub: () => false,+ pauseGithub: () => false,+ resumeGithub: () => false,+ unlinkGithub: () => false,+ reloadLatestGithubLink: () => false,+ },+ ],+ mutatingGithubLink: [false, { setMutatingGithubLink: (_, { mutatingGithubLink }) => mutatingGithubLink }],+ }),+ selectors({+ selectedIntegrationId: [+ (s) => [s.integrationId, s.githubIntegrations],+ (integrationId: number | null, integrations: IntegrationType[]): number | null =>+ integrationId ?? (integrations.length === 1 ? integrations[0].id : null),+ ],+ canUpdate: [+ (s) => [s.activeRequest],+ (activeRequest: FeatureRequestApi | null): boolean =>+ Boolean(activeRequest && !activeRequest.is_archived && activeRequest.can_update),+ ],+ linkDisabledReason: [+ (s) => [s.canUpdate, s.githubIntegrations, s.integrationsLoading, s.selectedIntegrationId, s.issueUrl],+ (+ canUpdate: boolean,+ integrations: IntegrationType[],+ integrationsLoading: boolean,+ selectedIntegrationId: number | null,+ issueUrl: string+ ): string | undefined => {+ if (!canUpdate) {+ return 'You do not have permission to update this request'+ }+ if (integrationsLoading) {+ return 'GitHub integrations are still loading'+ }+ if (!integrations.length) {+ return 'Connect a GitHub integration first'+ }+ if (!selectedIntegrationId) {+ return 'Select a GitHub integration'+ }+ if (!issueUrl.trim()) {+ return 'Enter a GitHub issue URL'+ }+ return undefined+ },+ ],+ }),+ listeners(({ actions, props, values }) => ({+ linkGithub: async () => {+ if (+ values.mutatingGithubLink ||+ values.linkDisabledReason ||+ values.currentTeamId === null ||+ !values.selectedIntegrationId ||+ !isActiveRequest(values.activeRequest, props.requestId)+ ) {+ return+ }+ actions.setMutatingGithubLink(true)+ try {+ const updated = await featureRequestsLinkGithubCreate(String(values.currentTeamId), props.requestId, {+ integration_id: values.selectedIntegrationId,+ issue_url: values.issueUrl.trim(),+ expected_version: values.activeRequest.version,+ })+ if (isActiveRequest(values.activeRequest, props.requestId)) {+ actions.loadActiveRequestSuccess(updated)+ actions.setIssueUrl('')+ }+ actions.loadFeatureRequests()+ actions.loadRequestHistory(props.requestId)+ } catch (error) {+ if (error instanceof ApiError && error.status === 409) {+ actions.setMutationError('This request changed. Reload it and try again.')+ actions.setMutationIsStale(true)+ actions.loadActiveRequest(props.requestId)+ } else {+ actions.setMutationError(+ apiErrorMessage(error, "Couldn't link this GitHub issue. Check the URL and try again.")+ )+ }+ } finally {+ actions.setMutatingGithubLink(false)+ }+ },+ pauseGithub: async () => {+ if (+ !values.canUpdate ||+ values.mutatingGithubLink ||+ values.currentTeamId === null ||+ !isActiveRequest(values.activeRequest, props.requestId)+ ) {+ return+ }+ actions.setMutatingGithubLink(true)+ try {+ const updated = await featureRequestsPauseGithubCreate(String(values.currentTeamId), props.requestId, {+ expected_version: values.activeRequest.version,+ })+ if (isActiveRequest(values.activeRequest, props.requestId)) {+ actions.loadActiveRequestSuccess(updated)+ }+ actions.loadFeatureRequests()+ actions.loadRequestHistory(props.requestId)+ } catch (error) {+ if (error instanceof ApiError && error.status === 409) {+ actions.setMutationError('This request changed. Reload it and try again.')+ actions.setMutationIsStale(true)+ actions.loadActiveRequest(props.requestId)+ } else {+ actions.setMutationError(apiErrorMessage(error, "Couldn't pause GitHub sync. Try again."))+ }+ } finally {+ actions.setMutatingGithubLink(false)+ }+ },+ resumeGithub: async () => {+ if (+ !values.canUpdate ||+ values.mutatingGithubLink ||+ values.currentTeamId === null ||+ !isActiveRequest(values.activeRequest, props.requestId)+ ) {+ return+ }+ actions.setMutatingGithubLink(true)+ try {+ const updated = await featureRequestsResumeGithubCreate(String(values.currentTeamId), props.requestId, {+ expected_version: values.activeRequest.version,+ })+ if (isActiveRequest(values.activeRequest, props.requestId)) {+ actions.loadActiveRequestSuccess(updated)+ }+ actions.loadFeatureRequests()+ actions.loadRequestHistory(props.requestId)+ } catch (error) {+ if (error instanceof ApiError && error.status === 409) {+ actions.setMutationError('This request changed. Reload it and try again.')+ actions.setMutationIsStale(true)+ actions.loadActiveRequest(props.requestId)+ } else {+ actions.setMutationError(apiErrorMessage(error, "Couldn't resume GitHub sync. Try again."))+ }+ } finally {+ actions.setMutatingGithubLink(false)+ }+ },+ reloadLatestGithubLink: () => {+ actions.loadActiveRequest(props.requestId)+ },+ unlinkGithub: async () => {+ if (+ !values.canUpdate ||+ values.mutatingGithubLink ||+ values.currentTeamId === null ||+ !isActiveRequest(values.activeRequest, props.requestId)+ ) {+ return+ }+ actions.setMutatingGithubLink(true)+ try {+ const updated = await featureRequestsUnlinkGithubCreate(String(values.currentTeamId), props.requestId, {+ expected_version: values.activeRequest.version,+ })+ if (isActiveRequest(values.activeRequest, props.requestId)) {+ actions.loadActiveRequestSuccess(updated)+ }+ actions.loadFeatureRequests()+ actions.loadRequestHistory(props.requestId)+ } catch (error) {+ if (error instanceof ApiError && error.status === 409) {+ actions.setMutationError('This request changed. Reload it and try again.')+ actions.setMutationIsStale(true)+ actions.loadActiveRequest(props.requestId)+ } else {+ actions.setMutationError(apiErrorMessage(error, "Couldn't unlink this GitHub issue. Try again."))+ }+ } finally {+ actions.setMutatingGithubLink(false)+ }+ },+ })),+])diff --git a/products/customer_analytics/frontend/components/FeatureRequests/featureRequestsLogic.test.ts b/products/customer_analytics/frontend/components/FeatureRequests/featureRequestsLogic.test.tsindex c00748c51346..55da88bc1ff3 100644--- a/products/customer_analytics/frontend/components/FeatureRequests/featureRequestsLogic.test.ts+++ b/products/customer_analytics/frontend/components/FeatureRequests/featureRequestsLogic.test.ts@@ -42,6 +42,7 @@ const createdRequest: FeatureRequestApi = {archived_by: null,version: 1,can_update: true,+ github_link: null,account: { id: 'account-1', name: 'Acme' },account_links: [{diff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.tsindex d522116e958f..cc6ca788c34b 100644--- a/products/customer_analytics/frontend/generated/api.schemas.ts+++ b/products/customer_analytics/frontend/generated/api.schemas.ts@@ -3641,6 +3641,45 @@ export interface FeatureRequestAccountLinkApi {readonly updated_at: string | null}+/**+ * * `open` - open+ * * `closed` - closed+ */+export type IssueStateEnumApi = (typeof IssueStateEnumApi)[keyof typeof IssueStateEnumApi]++export const IssueStateEnumApi = {+ Open: 'open',+ Closed: 'closed',+} as const++export interface FeatureRequestGitHubLinkApi {+ /** Stable GitHub link ID. */+ readonly id: string+ /** Canonical GitHub issue URL. */+ readonly issue_url: string+ /** Canonical owner and repository name. */+ readonly repository: string+ /**+ * GitHub issue number.+ * @minimum 1+ */+ readonly issue_number: number+ /** Latest GitHub issue title. */+ readonly issue_title: string+ /** Latest GitHub issue state.+ *+ * * `open` - open+ * * `closed` - closed */+ readonly issue_state: IssueStateEnumApi+ /** Whether GitHub issue changes update this request. */+ readonly sync_enabled: boolean+ /**+ * When GitHub last updated this link.+ * @nullable+ */+ readonly last_synced_at: string | null+}+export interface FeatureRequestApi {/** Stable feature request ID. */readonly id: string@@ -3692,6 +3731,8 @@ export interface FeatureRequestApi {readonly evidence_count: number/** Product areas affected by this request. */readonly product_areas: readonly FeatureRequestProductAreaApi[]+ /** Linked GitHub issue, or null when no issue is linked. */+ readonly github_link: FeatureRequestGitHubLinkApi | null/*** ID of the user who created the request.* @nullable@@ -3881,6 +3922,8 @@ export interface FeatureRequestVersionApi {* * `accounts` - Accounts* * `evidence` - Evidence* * `product_areas` - Product areas+ * * `github_link` - GitHub link+ * * `github_sync` - GitHub sync*/export type FeatureRequestHistoryChangeFieldEnumApi =(typeof FeatureRequestHistoryChangeFieldEnumApi)[keyof typeof FeatureRequestHistoryChangeFieldEnumApi]@@ -3892,6 +3935,8 @@ export const FeatureRequestHistoryChangeFieldEnumApi = {Accounts: 'accounts',Evidence: 'evidence',ProductAreas: 'product_areas',+ GithubLink: 'github_link',+ GithubSync: 'github_sync',} as const/**@@ -3899,6 +3944,16 @@ export const FeatureRequestHistoryChangeFieldEnumApi = {*/export type FeatureRequestHistoryChangeApiBefore =| string+ | boolean+ | {+ id: string+ issue_url: string+ repository: string+ issue_number: number+ issue_title: string+ issue_state: 'open' | 'closed'+ sync_enabled: boolean+ }| {/** @nullable */id: string | null@@ -3929,6 +3984,16 @@ export type FeatureRequestHistoryChangeApiBefore =*/export type FeatureRequestHistoryChangeApiAfter =| string+ | boolean+ | {+ id: string+ issue_url: string+ repository: string+ issue_number: number+ issue_title: string+ issue_state: 'open' | 'closed'+ sync_enabled: boolean+ }| {/** @nullable */id: string | null@@ -3962,7 +4027,9 @@ export interface FeatureRequestHistoryChangeApi {* * `account` - Account* * `accounts` - Accounts* * `evidence` - Evidence- * * `product_areas` - Product areas */+ * * `product_areas` - Product areas+ * * `github_link` - GitHub link+ * * `github_sync` - GitHub sync */readonly field: FeatureRequestHistoryChangeFieldEnumApi/** Value before the update, including relation snapshots. */readonly before: FeatureRequestHistoryChangeApiBefore@@ -3972,12 +4039,14 @@ export interface FeatureRequestHistoryChangeApi {/*** * `manual` - Manual+ * * `github` - GitHub*/export type FeatureRequestHistorySourceEnumApi =(typeof FeatureRequestHistorySourceEnumApi)[keyof typeof FeatureRequestHistorySourceEnumApi]export const FeatureRequestHistorySourceEnumApi = {Manual: 'manual',+ Github: 'github',} as constexport interface FeatureRequestHistoryApi {@@ -3989,7 +4058,8 @@ export interface FeatureRequestHistoryApi {readonly is_initial: boolean/** System that recorded the request change.*- * * `manual` - Manual */+ * * `manual` - Manual+ * * `github` - GitHub */readonly change_source: FeatureRequestHistorySourceEnumApi/*** ID of the user who changed the request, if known.@@ -4005,6 +4075,21 @@ export interface FeatureRequestHistoryApi {readonly changed_at: string}+export interface FeatureRequestGitHubLinkSerializerInputApi {+ /**+ * GitHub integration ID connected to this project.+ * @minimum 1+ */+ integration_id: number+ /** GitHub issue URL. Pull request URLs are not supported. */+ issue_url: string+ /**+ * Request version loaded by the editor. Stale versions return 409 Conflict.+ * @minimum 1+ */+ expected_version: number+}+export interface FeatureRequestEvidenceDeleteApi {/*** Request version loaded by the editor. Stale versions return 409 Conflict.@@ -4036,7 +4121,8 @@ export interface FeatureRequestStatusHistoryApi {readonly request_status: FeatureRequestStatusEnumApi/** System that recorded the status change.*- * * `manual` - Manual */+ * * `manual` - Manual+ * * `github` - GitHub */readonly change_source: FeatureRequestHistorySourceEnumApi/*** ID of the user who changed the status, if known.diff --git a/products/customer_analytics/frontend/generated/api.ts b/products/customer_analytics/frontend/generated/api.tsindex 2efb069ef542..6da9d0a29b2a 100644--- a/products/customer_analytics/frontend/generated/api.ts+++ b/products/customer_analytics/frontend/generated/api.ts@@ -75,6 +75,7 @@ import type {FeatureRequestEvidenceCreateApi,FeatureRequestEvidenceDeleteApi,FeatureRequestEvidenceUpdateApi,+ FeatureRequestGitHubLinkSerializerInputApi,FeatureRequestHistoryApi,FeatureRequestProductAreaApi,FeatureRequestProductAreasListParams,@@ -2252,6 +2253,42 @@ export const featureRequestsHistoryList = async (})}+export const getFeatureRequestsLinkGithubCreateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/feature_requests/${id}/link_github/`+}++export const featureRequestsLinkGithubCreate = async (+ projectId: string,+ id: string,+ featureRequestGitHubLinkSerializerInputApi: FeatureRequestGitHubLinkSerializerInputApi,+ options?: RequestInit+): Promise<FeatureRequestApi> => {+ return apiMutator<FeatureRequestApi>(getFeatureRequestsLinkGithubCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(featureRequestGitHubLinkSerializerInputApi),+ })+}++export const getFeatureRequestsPauseGithubCreateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/feature_requests/${id}/pause_github/`+}++export const featureRequestsPauseGithubCreate = async (+ projectId: string,+ id: string,+ featureRequestVersionApi: FeatureRequestVersionApi,+ options?: RequestInit+): Promise<FeatureRequestApi> => {+ return apiMutator<FeatureRequestApi>(getFeatureRequestsPauseGithubCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(featureRequestVersionApi),+ })+}+export const getFeatureRequestsRemoveEvidenceCreateUrl = (projectId: string, id: string) => {return `/api/projects/${projectId}/feature_requests/${id}/remove_evidence/`}@@ -2288,6 +2325,24 @@ export const featureRequestsRestoreCreate = async (})}+export const getFeatureRequestsResumeGithubCreateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/feature_requests/${id}/resume_github/`+}++export const featureRequestsResumeGithubCreate = async (+ projectId: string,+ id: string,+ featureRequestVersionApi: FeatureRequestVersionApi,+ options?: RequestInit+): Promise<FeatureRequestApi> => {+ return apiMutator<FeatureRequestApi>(getFeatureRequestsResumeGithubCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(featureRequestVersionApi),+ })+}+export const getFeatureRequestsStatusHistoryListUrl = (projectId: string, id: string) => {return `/api/projects/${projectId}/feature_requests/${id}/status_history/`}@@ -2303,6 +2358,24 @@ export const featureRequestsStatusHistoryList = async (})}+export const getFeatureRequestsUnlinkGithubCreateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/feature_requests/${id}/unlink_github/`+}++export const featureRequestsUnlinkGithubCreate = async (+ projectId: string,+ id: string,+ featureRequestVersionApi: FeatureRequestVersionApi,+ options?: RequestInit+): Promise<FeatureRequestApi> => {+ return apiMutator<FeatureRequestApi>(getFeatureRequestsUnlinkGithubCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(featureRequestVersionApi),+ })+}+export const getFeatureRequestsUpdateEvidenceCreateUrl = (projectId: string, id: string) => {return `/api/projects/${projectId}/feature_requests/${id}/update_evidence/`}diff --git a/products/customer_analytics/frontend/generated/api.zod.ts b/products/customer_analytics/frontend/generated/api.zod.tsindex d6eb38c84612..1584336a21c4 100644--- a/products/customer_analytics/frontend/generated/api.zod.ts+++ b/products/customer_analytics/frontend/generated/api.zod.ts@@ -1430,6 +1430,22 @@ export const FeatureRequestsArchiveCreateBody = /* @__PURE__ */ zod.object({.describe('Request version loaded by the editor. Stale versions return 409 Conflict.'),})+export const FeatureRequestsLinkGithubCreateBody = /* @__PURE__ */ zod.object({+ integration_id: zod.number().min(1).describe('GitHub integration ID connected to this project.'),+ issue_url: zod.url().describe('GitHub issue URL. Pull request URLs are not supported.'),+ expected_version: zod+ .number()+ .min(1)+ .describe('Request version loaded by the editor. Stale versions return 409 Conflict.'),+})++export const FeatureRequestsPauseGithubCreateBody = /* @__PURE__ */ zod.object({+ expected_version: zod+ .number()+ .min(1)+ .describe('Request version loaded by the editor. Stale versions return 409 Conflict.'),+})+export const FeatureRequestsRemoveEvidenceCreateBody = /* @__PURE__ */ zod.object({expected_version: zod.number()@@ -1445,6 +1461,20 @@ export const FeatureRequestsRestoreCreateBody = /* @__PURE__ */ zod.object({.describe('Request version loaded by the editor. Stale versions return 409 Conflict.'),})+export const FeatureRequestsResumeGithubCreateBody = /* @__PURE__ */ zod.object({+ expected_version: zod+ .number()+ .min(1)+ .describe('Request version loaded by the editor. Stale versions return 409 Conflict.'),+})++export const FeatureRequestsUnlinkGithubCreateBody = /* @__PURE__ */ zod.object({+ expected_version: zod+ .number()+ .min(1)+ .describe('Request version loaded by the editor. Stale versions return 409 Conflict.'),+})+export const featureRequestsUpdateEvidenceCreateBodySummaryDefault = ``export const featureRequestsUpdateEvidenceCreateBodyCustomerQuoteDefault = ``export const featureRequestsUpdateEvidenceCreateBodyEvidenceSourceMax = 200diff --git a/products/customer_analytics/mcp/tools.yaml b/products/customer_analytics/mcp/tools.yamlindex 5917bfa27f54..8581d8640c31 100644--- a/products/customer_analytics/mcp/tools.yaml+++ b/products/customer_analytics/mcp/tools.yaml@@ -1183,6 +1183,9 @@ tools:the caller cannot access are removed or redacted. HogQL `system.feature_request_history` exposes entrymetadata and changed field names, but not before and after values.feature_flag: customer-analytics-feature-requests+ feature-requests-link-github-create:+ operation: feature_requests_link_github_create+ enabled: falsefeature-requests-list:operation: feature_requests_listenabled: true@@ -1221,6 +1224,9 @@ tools:expected_version:required: truefeature_flag: customer-analytics-feature-requests+ feature-requests-pause-github-create:+ operation: feature_requests_pause_github_create+ enabled: falsefeature-requests-remove-evidence-create:operation: feature_requests_remove_evidence_createenabled: true@@ -1252,6 +1258,9 @@ tools:Restore an archived Customer analytics feature request so editors can change it again. Pass the request `id`and its current `expected_version`. Account links, evidence, product areas, and history remain attached.feature_flag: customer-analytics-feature-requests+ feature-requests-resume-github-create:+ operation: feature_requests_resume_github_create+ enabled: falsefeature-requests-retrieve:operation: feature_requests_retrieveenabled: true@@ -1284,6 +1293,9 @@ tools:previous status, resulting status, actor, source, and change time. HogQL `system.feature_request_history`exposes when changes occurred and which fields changed, but not status values.feature_flag: customer-analytics-feature-requests+ feature-requests-unlink-github-create:+ operation: feature_requests_unlink_github_create+ enabled: falsefeature-requests-update:operation: feature_requests_updateenabled: falsediff --git a/products/customer_analytics/turbo.json b/products/customer_analytics/turbo.jsonindex e1ee10eb4dba..e9f285d53d98 100644--- a/products/customer_analytics/turbo.json+++ b/products/customer_analytics/turbo.json@@ -6,6 +6,7 @@"backend/facade/**","backend/presentation/**","backend/routes.py",+ "backend/webhook_consumers.py","backend/hogql_queries/**","backend/max_tools.py","backend/tasks/**",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex e0016b023ec6..b81c379aabb5 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -42904,6 +42904,46 @@ export namespace Schemas {readonly updated_at: string;}+ /**+ * * `open` - open+ * * `closed` - closed+ */+ export type IssueStateEnum = typeof IssueStateEnum[keyof typeof IssueStateEnum];+++ export const IssueStateEnum = {+ Open: 'open',+ Closed: 'closed',+ } as const;++ export interface FeatureRequestGitHubLink {+ /** Stable GitHub link ID. */+ readonly id: string;+ /** Canonical GitHub issue URL. */+ readonly issue_url: string;+ /** Canonical owner and repository name. */+ readonly repository: string;+ /**+ * GitHub issue number.+ * @minimum 1+ */+ readonly issue_number: number;+ /** Latest GitHub issue title. */+ readonly issue_title: string;+ /** Latest GitHub issue state.+ *+ * * `open` - open+ * * `closed` - closed */+ readonly issue_state: IssueStateEnum;+ /** Whether GitHub issue changes update this request. */+ readonly sync_enabled: boolean;+ /**+ * When GitHub last updated this link.+ * @nullable+ */+ readonly last_synced_at: string | null;+ }+export interface FeatureRequest {/** Stable feature request ID. */readonly id: string;@@ -42955,6 +42995,8 @@ export namespace Schemas {readonly evidence_count: number;/** Product areas affected by this request. */readonly product_areas: readonly FeatureRequestProductArea[];+ /** Linked GitHub issue, or null when no issue is linked. */+ readonly github_link: FeatureRequestGitHubLink | null;/*** ID of the user who created the request.* @nullable@@ -43088,6 +43130,21 @@ export namespace Schemas {evidence_id: string;}+ export interface FeatureRequestGitHubLinkSerializerInput {+ /**+ * GitHub integration ID connected to this project.+ * @minimum 1+ */+ integration_id: number;+ /** GitHub issue URL. Pull request URLs are not supported. */+ issue_url: string;+ /**+ * Request version loaded by the editor. Stale versions return 409 Conflict.+ * @minimum 1+ */+ expected_version: number;+ }+/*** * `status` - Status* * `priority` - Priority@@ -43095,6 +43152,8 @@ export namespace Schemas {* * `accounts` - Accounts* * `evidence` - Evidence* * `product_areas` - Product areas+ * * `github_link` - GitHub link+ * * `github_sync` - GitHub sync*/export type FeatureRequestHistoryChangeFieldEnum = typeof FeatureRequestHistoryChangeFieldEnum[keyof typeof FeatureRequestHistoryChangeFieldEnum];@@ -43106,12 +43165,22 @@ export namespace Schemas {Accounts: 'accounts',Evidence: 'evidence',ProductAreas: 'product_areas',+ GithubLink: 'github_link',+ GithubSync: 'github_sync',} as const;/*** Value before the update, including relation snapshots.*/- export type FeatureRequestHistoryChangeBefore = string | {+ export type FeatureRequestHistoryChangeBefore = string | boolean | {+ id: string;+ issue_url: string;+ repository: string;+ issue_number: number;+ issue_title: string;+ issue_state: 'open' | 'closed';+ sync_enabled: boolean;+ } | {/** @nullable */id: string | null;name: string;@@ -43136,7 +43205,15 @@ export namespace Schemas {/*** Value after the update, including relation snapshots.*/- export type FeatureRequestHistoryChangeAfter = string | {+ export type FeatureRequestHistoryChangeAfter = string | boolean | {+ id: string;+ issue_url: string;+ repository: string;+ issue_number: number;+ issue_title: string;+ issue_state: 'open' | 'closed';+ sync_enabled: boolean;+ } | {/** @nullable */id: string | null;name: string;@@ -43166,7 +43243,9 @@ export namespace Schemas {* * `account` - Account* * `accounts` - Accounts* * `evidence` - Evidence- * * `product_areas` - Product areas */+ * * `product_areas` - Product areas+ * * `github_link` - GitHub link+ * * `github_sync` - GitHub sync */readonly field: FeatureRequestHistoryChangeFieldEnum;/** Value before the update, including relation snapshots. */readonly before: FeatureRequestHistoryChangeBefore;@@ -43176,12 +43255,14 @@ export namespace Schemas {/*** * `manual` - Manual+ * * `github` - GitHub*/export type FeatureRequestHistorySourceEnum = typeof FeatureRequestHistorySourceEnum[keyof typeof FeatureRequestHistorySourceEnum];export const FeatureRequestHistorySourceEnum = {Manual: 'manual',+ Github: 'github',} as const;export interface FeatureRequestHistory {@@ -43193,7 +43274,8 @@ export namespace Schemas {readonly is_initial: boolean;/** System that recorded the request change.*- * * `manual` - Manual */+ * * `manual` - Manual+ * * `github` - GitHub */readonly change_source: FeatureRequestHistorySourceEnum;/*** ID of the user who changed the request, if known.@@ -43230,7 +43312,8 @@ export namespace Schemas {readonly request_status: FeatureRequestStatusEnum;/** System that recorded the status change.*- * * `manual` - Manual */+ * * `manual` - Manual+ * * `github` - GitHub */readonly change_source: FeatureRequestHistorySourceEnum;/*** ID of the user who changed the status, if known.