Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(error-tracking): sync issue status from linear tickets (#125338)

Aleksander Błaszkiewicza2d32bc101df
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 85078624d37a..acdd395c237d 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -15475,9 +15475,9 @@ snapshots:
scenes-app-settings-environment--settings-environment-details--light:
hash: v1.k794b7964.6090a4ecd87046135d251b886324ecbe152effc733dce0bb2a8411a3b876ea59.jNzRUhHU4PRNOr0acvK8qpdkaGbLkdNUfbnlileSQ6I
scenes-app-settings-environment--settings-environment-error-tracking--dark:
- hash: v1.k794b7964.a2ad11c04e832b42672c961240cbaa37a55d3257fd66fde9e186f8094eb78949.34qLdPvBNJzB4YLQbLNvcn4UCRm5k95ytw4qNXQJsYU
+ hash: v1.k794b7964.de7da6a21bcac2a07929851a598ec3bb2a579b88e974dc7fcb1dad6fa26ce0dc.vJwPYHgMmxfVZZdEDXw3d7PuT811HvxOnjDW0CDUdj8
scenes-app-settings-environment--settings-environment-error-tracking--light:
- hash: v1.k794b7964.adb6fd411ffdc03ea8e1b9a29f01536d41a5af4b6224c37881d7ad6b06630f84.WGucFxYafyt1RqQ5e0M6MzvBxP4nGZseNtgVciGxRWc
+ hash: v1.k794b7964.776ea55161274342194e9c67d46ed71176c367a7251c5d9d6d995706dea85c3d.mEZkNhmBmunU6WKhqV6-tHTy-7H2j-wPf3akfik5D70
scenes-app-settings-environment--settings-environment-error-tracking-configuration--dark:
hash: v1.k794b7964.fefec3bbacd088c88914a8fcb41ecb8cb2ab327cca2d73788d27450e592c35f9.S75BhNkh_Gx5uOCqbImr0kf0CYnsY3BDW_EnFvIuZ8k
scenes-app-settings-environment--settings-environment-error-tracking-configuration--light:
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 89705131059a..1bfd52bad4d3 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -318,6 +318,7 @@ export const FEATURE_FLAGS = {
ERROR_TRACKING_BUILT_IN_FILTERS: 'error-tracking-built-in-filters', // owner: @ablaszkiewicz #team-error-tracking
ERROR_TRACKING_ISSUE_CORRELATION: 'error-tracking-issue-correlation', // owner: @david #team-error-tracking
ERROR_TRACKING_ISSUE_SPLITTING: 'error-tracking-issue-splitting', // owner: @david #team-error-tracking
+ ERROR_TRACKING_LINEAR_STATUS_SYNC: 'error-tracking-linear-status-sync', // owner: @ablaszkiewicz #team-error-tracking
ERROR_TRACKING_NEW_WIZARD: 'error-tracking-new-wizard', // owner: @ablaszkiewicz #team-error-tracking
ERROR_TRACKING_RATE_LIMITING: 'error-tracking-rate-limiting', // owner: @ablaszkiewicz #team-error-tracking
ERROR_TRACKING_RATE_LIMITING_BYPASS: 'error-tracking-rate-limiting-bypass', // owner: @ablaszkiewicz #team-error-tracking
diff --git a/frontend/src/scenes/settings/environment/ErrorTrackingIntegrations.tsx b/frontend/src/scenes/settings/environment/ErrorTrackingIntegrations.tsx
index b058f756f4e8..24a4c329b2f6 100644
--- a/frontend/src/scenes/settings/environment/ErrorTrackingIntegrations.tsx
+++ b/frontend/src/scenes/settings/environment/ErrorTrackingIntegrations.tsx
@@ -1,3 +1,4 @@
+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import {
GitLabIntegration,
GithubIntegration,
@@ -11,9 +12,13 @@ import IconGitLab from 'public/services/gitlab.png'
import IconJira from 'public/services/jira.svg'
import IconLinear from 'public/services/linear.png'
+import { LinearStatusSyncSetting } from 'products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/linear_status_sync/LinearStatusSyncSetting'
+
const NEXT_URL = urls.settings('environment-error-tracking', 'error-tracking-integrations')
export function ErrorTrackingIntegrations(): JSX.Element {
+ const showLinearStatusSync = useFeatureFlag('ERROR_TRACKING_LINEAR_STATUS_SYNC')
+
return (
<div className="flex flex-col gap-y-6">
<div>
@@ -21,7 +26,10 @@ export function ErrorTrackingIntegrations(): JSX.Element {
<img src={IconLinear} alt="" className="w-5 h-5" />
Linear
</h3>
- <LinearIntegration next={NEXT_URL} />
+ <div className="flex flex-col gap-y-4">
+ <LinearIntegration next={NEXT_URL} />
+ {showLinearStatusSync && <LinearStatusSyncSetting />}
+ </div>
</div>
<div>
<h3 className="flex items-center gap-2">
diff --git a/frontend/src/scenes/settings/stories/SettingsEnvironment.stories.tsx b/frontend/src/scenes/settings/stories/SettingsEnvironment.stories.tsx
index 5f7dc36c37f2..3c7674627af8 100644
--- a/frontend/src/scenes/settings/stories/SettingsEnvironment.stories.tsx
+++ b/frontend/src/scenes/settings/stories/SettingsEnvironment.stories.tsx
@@ -188,7 +188,23 @@ export const SettingsEnvironmentSurveys: Story = { args: { sectionId: 'environme
export const SettingsEnvironmentFeatureFlags: Story = { args: { sectionId: 'environment-feature-flags' } }
-export const SettingsEnvironmentErrorTracking: Story = { args: { sectionId: 'environment-error-tracking' } }
+export const SettingsEnvironmentErrorTracking: Story = {
+ args: { sectionId: 'environment-error-tracking' },
+ decorators: [
+ mswDecorator({
+ get: {
+ '/api/projects/:id/error_tracking/settings/retrieve_settings/': {
+ project_rate_limit_value: null,
+ project_rate_limit_bucket_size_minutes: null,
+ per_issue_rate_limit_value: null,
+ per_issue_rate_limit_bucket_size_minutes: null,
+ ingestion_enabled: true,
+ linear_status_sync_enabled: false,
+ },
+ },
+ }),
+ ],
+}
export const SettingsEnvironmentErrorTrackingConfiguration: Story = {
args: { sectionId: 'environment-error-tracking-configuration' },
diff --git a/posthog/ingress/README.md b/posthog/ingress/README.md
index 7caabbdaedbe..3ee42961e66c 100644
--- a/posthog/ingress/README.md
+++ b/posthog/ingress/README.md
@@ -79,7 +79,7 @@ Three duties fall on the incarnation rather than on `BearerJwt`, and none is enf
| `sns` | `/webhooks/workflows/ses-events` | `default` | `workflows_ses_events` | `products/workflows/backend/webhook_consumers.py` |
| `customerio` | `/api/projects/<team_id>/messaging/customerio/webhook/` | none | none, it is the DRF adapter path | `products/messaging/backend/api/customerio_webhook.py` |
| `vercel` | `/webhooks/vercel` | `marketplace` | `vercel_marketplace` | `ee/api/vercel/webhook_consumers.py` |
-| `linear` | `/webhooks/linear` | `posthog` | none | none |
+| `linear` | `/webhooks/linear` | `posthog` | `error_tracking_linear_status_sync` | `products/error_tracking/backend/webhook_consumers.py` |
The owner of the third-party App registration owns the route.
The customer-facing GitHub App is shared across products, so its two endpoints are declared in `posthog/urls.py`.
diff --git a/posthog/ingress/linear/README.md b/posthog/ingress/linear/README.md
index 20f265bc146c..fb9acd45c437 100644
--- a/posthog/ingress/linear/README.md
+++ b/posthog/ingress/linear/README.md
@@ -41,16 +41,25 @@ Linear creates the webhook for a workspace when the workspace authorizes the App
One Linear App serves both regions.
Its webhook URL names the primary region, `https://eu.posthog.com/webhooks/linear`, so every delivery arrives there first.
+Both regions hold the same `LINEAR_APP_WEBHOOK_SECRET`, because the primary region forwards the signed body and the secondary region verifies it again.
## Quirks
Success answers 200, not the default 202, because Linear counts any other status as a failed delivery.
Linear retries a failed delivery after 1 minute, 1 hour and 6 hours, and it can disable a webhook that keeps failing.
`retry_status` is 500, so a consumer that raised or that the request budget skipped asks for that retry.
+A failed ownership lookup and a failed forward to the secondary region ask for it too.
A missing secret answers 403 rather than 500, because a self-hosted deployment may never set up the Linear App.
Rejections carry an empty body, so a caller cannot tell a missing secret from a bad signature.
+A workspace that teams in both regions connect gets its deliveries in the primary region only, because the ownership lookup there answers `LOCAL` and nothing is forwarded.
+
## Consumers
-None. The endpoint verifies each delivery and answers 200, and nothing acts on it.
+`error_tracking_linear_status_sync`, declared in `products/error_tracking/backend/webhook_consumers.py`.
+It handles `Issue` updates that change the workflow state, and queues one task per change.
+Its `ownership` lookup reads `organization_id` against the `linear` integration rows, see [Regional forwarding](../README.md#regional-forwarding).
+A state change from a workspace that no team here connects is `ELSEWHERE`, so the primary region forwards it.
+Every other delivery is `UNDECIDED`, so a ticket edit that no region acts on stays in the region it arrived in.
+The task reads the current state of every linked Linear ticket from Linear, so a delivery that arrives late or out of order cannot apply a state the ticket no longer has.
See the [Endpoints table](../README.md#endpoints).
diff --git a/posthog/models/integration/__init__.py b/posthog/models/integration/__init__.py
index efa63c38c926..67d96a8046ce 100644
--- a/posthog/models/integration/__init__.py
+++ b/posthog/models/integration/__init__.py
@@ -77,7 +77,7 @@ from .google_cloud import (
is_unique_service_account_by_organization_id,
)
from .jira import JiraIntegration
-from .linear import LinearIntegration
+from .linear import LinearIntegration, LinearIntegrationError, LinearRateLimitedError
from .linkedin_ads import LinkedInAdsIntegration
from .meta import InstagramIntegration, MetaAdsIntegration, MetaGraphIntegration
from .model import (
@@ -238,6 +238,8 @@ __all__ = [
"EmailIntegration",
"cleanup_ses_identity_on_integration_delete",
"LinearIntegration",
+ "LinearIntegrationError",
+ "LinearRateLimitedError",
"SUPPORTED_EXTERNAL_ISSUE_PROVIDERS",
"external_issue_url",
"is_supported_external_issue_provider",
diff --git a/posthog/models/integration/linear.py b/posthog/models/integration/linear.py
index 73c3c5840a9b..192683808976 100644
--- a/posthog/models/integration/linear.py
+++ b/posthog/models/integration/linear.py
@@ -1,5 +1,9 @@
"""Linear integration."""
+import re
+import math
+import time
+from collections.abc import Sequence
from typing import Any
import requests
@@ -13,6 +17,33 @@ from .assignees import MAX_ASSIGNEES, Assignee, AssigneeLookupFailed
logger = structlog.get_logger(__name__)
+_ISSUE_IDENTIFIER = re.compile(r"([A-Za-z0-9]+)-([0-9]+)")
+
+# Linear counts requests over a one-hour window, so its reset time is never further away than that.
+_RATE_LIMIT_WINDOW_SECONDS = 3600
+_RATE_LIMIT_DEFAULT_WAIT_SECONDS = 60
+
+
+class LinearIntegrationError(Exception):
+ """A Linear read that failed, so the caller retries instead of acting on a guessed answer."""
+
+
+class LinearRateLimitedError(LinearIntegrationError):
+ """Linear refused a read because the token spent its hourly budget. Retry after `retry_after_seconds`."""
+
+ def __init__(self, retry_after_seconds: int) -> None:
+ super().__init__(f"Linear rate limit exceeded, retry in {retry_after_seconds}s")
+ self.retry_after_seconds = retry_after_seconds
+
+
+def _rate_limit_wait_seconds(response: requests.Response) -> int:
+ reset_ms = response.headers.get("X-RateLimit-Requests-Reset")
+ try:
+ wait = math.ceil(int(reset_ms) / 1000 - time.time()) if reset_ms else _RATE_LIMIT_DEFAULT_WAIT_SECONDS
+ except ValueError:
+ wait = _RATE_LIMIT_DEFAULT_WAIT_SECONDS
+ return min(max(wait, 1), _RATE_LIMIT_WINDOW_SECONDS)
+
class LinearIntegration:
integration: model.Integration
@@ -142,6 +173,68 @@ class LinearIntegration:
if body.get("errors") or not common.dot_get(body, "data.issueUpdate.success"):
raise ValidationError(f"Failed to move the Linear issue to a {state_type} state")
+ def issue_state_types(self, identifiers: Sequence[str]) -> dict[str, str]:
+ """The workflow state category of each issue, keyed by identifier.
+
+ An identifier that Linear does not return is absent from the result: the issue was
+ deleted, the token cannot read it, or it moved to another team and has a new identifier.
+ The issues connection answers those cases with no node, where `issue(id:)` answers with
+ an error, so a failed request is always a failed request. Raises LinearIntegrationError.
+ """
+ filters: list[dict[str, Any]] = []
+ for identifier in identifiers:
+ match = _ISSUE_IDENTIFIER.fullmatch(identifier)
+ if match is not None:
+ filters.append({"team": {"key": {"eq": match.group(1)}}, "number": {"eq": int(match.group(2))}})
+ if not filters:
+ return {}
+
+ states_query = """
+ query IssueStates($filter: IssueFilter!, $first: Int!) {
+ issues(filter: $filter, first: $first, includeArchived: true) {
+ nodes { identifier state { type } }
+ }
+ }
+ """
+ body = self._read(states_query, variables={"filter": {"or": filters}, "first": len(filters)})
+ nodes = common.dot_get(body, "data.issues.nodes")
+ if body.get("errors") or not isinstance(nodes, list):
+ raise LinearIntegrationError("Failed to read the Linear issue states")
+ return {
+ node["identifier"]: node["state"]["type"]
+ for node in nodes
+ if isinstance(node.get("identifier"), str) and isinstance((node.get("state") or {}).get("type"), str)
+ }
+
+ def workflow_state_type(self, state_id: str) -> str | None:
+ state_query = """
+ query WorkflowStateType($id: ID!) {
+ workflowStates(filter: { id: { eq: $id } }, first: 1, includeArchived: true) { nodes { type } }
+ }
+ """
+ body = self._read(state_query, variables={"id": state_id})
+ nodes = common.dot_get(body, "data.workflowStates.nodes")
+ if body.get("errors") or not isinstance(nodes, list):
+ raise LinearIntegrationError("Failed to read the Linear workflow state")
+ state_type = nodes[0].get("type") if nodes else None
+ return state_type if isinstance(state_type, str) else None
+
+ def _read(self, query: str, variables: dict[str, Any]) -> dict[str, Any]:
+ """`query`, but a rate-limited answer raises LinearRateLimitedError with the time until Linear resets."""
+ response = requests.post(
+ "https://api.linear.app/graphql",
+ headers={"Authorization": f"Bearer {self.integration.sensitive_config['access_token']}"},
+ json={"query": query, "variables": variables},
+ timeout=10,
+ )
+ body = response.json()
+ error_codes = {
+ (error.get("extensions") or {}).get("code") for error in body.get("errors") or [] if isinstance(error, dict)
+ }
+ if response.status_code == 429 or "RATELIMITED" in error_codes:
+ raise LinearRateLimitedError(_rate_limit_wait_seconds(response))
+ return body
+
def search_issues(self, query: str, *, limit: int = 25) -> list[dict[str, Any]]:
"""Search existing Linear issues by title / identifier for the link-existing flow.
diff --git a/products/error_tracking/backend/facade/api.py b/products/error_tracking/backend/facade/api.py
index 14c12b9eba43..2ec7d6387259 100644
--- a/products/error_tracking/backend/facade/api.py
+++ b/products/error_tracking/backend/facade/api.py
@@ -208,6 +208,7 @@ def _to_settings(settings, ingestion_enabled: bool) -> contracts.ErrorTrackingSe
per_issue_rate_limit_value=settings.per_issue_rate_limit_value,
per_issue_rate_limit_bucket_size_minutes=settings.per_issue_rate_limit_bucket_size_minutes,
ingestion_enabled=ingestion_enabled,
+ linear_status_sync_enabled=settings.linear_status_sync_enabled,
)
diff --git a/products/error_tracking/backend/facade/contracts.py b/products/error_tracking/backend/facade/contracts.py
index f7e54c308cbe..34da46522463 100644
--- a/products/error_tracking/backend/facade/contracts.py
+++ b/products/error_tracking/backend/facade/contracts.py
@@ -105,6 +105,21 @@ class GitHubExternalReferenceJob:
raise ValueError("Provide exactly one PostHog issue identifier.")
+@dataclass(frozen=True)
+class LinearStatusSyncJob:
+ # The Linear workspace id, which is the `integration_id` of the team's `linear` integration.
+ organization_id: str
+ # The ticket's identifier first, then any identifiers it had before it moved between Linear teams.
+ identifiers: tuple[str, ...]
+ # The workflow state the ticket left. The task reads its category to tell a reopen from a move
+ # between two open states.
+ previous_state_id: str
+
+ def __post_init__(self) -> None:
+ if not self.identifiers:
+ raise ValueError("Provide at least one Linear issue identifier.")
+
+
@dataclass(frozen=True)
class ErrorTrackingFingerprint:
id: UUID
@@ -177,6 +192,7 @@ class ErrorTrackingSettings:
per_issue_rate_limit_value: int | None
per_issue_rate_limit_bucket_size_minutes: int | None
ingestion_enabled: bool
+ linear_status_sync_enabled: bool
@dataclass(frozen=True)
diff --git a/products/error_tracking/backend/facade/issues.py b/products/error_tracking/backend/facade/issues.py
index 285c34855ec6..3ee877c9ce48 100644
--- a/products/error_tracking/backend/facade/issues.py
+++ b/products/error_tracking/backend/facade/issues.py
@@ -8,9 +8,13 @@ django.setup() path of the read-oriented main facade.
from typing import Any
from uuid import UUID
+from posthog.ingress.contracts import DeliveryOwnership
from posthog.models.user import User
-from ..logic import issue_mutations as _mutations
+from ..logic import (
+ issue_mutations as _mutations,
+ linear_status_sync as _linear_status_sync,
+)
from . import api, contracts
CohortNotFoundError = _mutations.CohortNotFoundError
@@ -69,3 +73,15 @@ def bulk_update_issues(
user=user,
was_impersonated=was_impersonated,
)
+
+
+def prepare_linear_status_sync_job(payload: dict[str, Any]) -> contracts.LinearStatusSyncJob | None:
+ return _linear_status_sync.prepare_job(payload)
+
+
+def sync_linear_status(job: contracts.LinearStatusSyncJob) -> None:
+ _linear_status_sync.sync_status(job)
+
+
+def linear_delivery_ownership(payload: dict[str, Any]) -> DeliveryOwnership:
+ return _linear_status_sync.delivery_ownership(payload)
diff --git a/products/error_tracking/backend/facade/linear.py b/products/error_tracking/backend/facade/linear.py
new file mode 100644
index 000000000000..5d21ccf80f66
--- /dev/null
+++ b/products/error_tracking/backend/facade/linear.py
@@ -0,0 +1,3 @@
+from products.error_tracking.backend.tasks.linear import enqueue_linear_status_sync
+
+__all__ = ["enqueue_linear_status_sync"]
diff --git a/products/error_tracking/backend/logic/__init__.py b/products/error_tracking/backend/logic/__init__.py
index 9e3b9a03bcfc..71a105424f44 100644
--- a/products/error_tracking/backend/logic/__init__.py
+++ b/products/error_tracking/backend/logic/__init__.py
@@ -40,6 +40,7 @@ SETTINGS_FIELDS = (
"project_rate_limit_bucket_size_minutes",
"per_issue_rate_limit_value",
"per_issue_rate_limit_bucket_size_minutes",
+ "linear_status_sync_enabled",
)
SPIKE_DETECTION_CONFIG_FIELDS = (
diff --git a/products/error_tracking/backend/logic/issue_changes.py b/products/error_tracking/backend/logic/issue_changes.py
index 5fade146142a..0675ec614f2b 100644
--- a/products/error_tracking/backend/logic/issue_changes.py
+++ b/products/error_tracking/backend/logic/issue_changes.py
@@ -256,6 +256,19 @@ class ChangeOperation:
bulk=bulk,
)
+ @classmethod
+ def for_automation(cls, team_id: int) -> "ChangeOperation | None":
+ """Start an operation that no person made, or return None when the change log is off for the team."""
+ if not issue_change_log_enabled(team_id):
+ return None
+ return cls(
+ id=uuid7(),
+ team_id=team_id,
+ actor_type=ErrorTrackingIssueChange.ActorType.AUTOMATION,
+ actor_user_id=None,
+ bulk=False,
+ )
+
@frozen
class IssueChange:
diff --git a/products/error_tracking/backend/logic/issue_mutations.py b/products/error_tracking/backend/logic/issue_mutations.py
index ef45554f4e0a..0542db4baa48 100644
--- a/products/error_tracking/backend/logic/issue_mutations.py
+++ b/products/error_tracking/backend/logic/issue_mutations.py
@@ -12,7 +12,7 @@ from django.db import transaction
from django.utils import timezone
from posthog.dataclasses import frozen
-from posthog.models.activity_logging.activity_log import Change, Detail, log_activity
+from posthog.models.activity_logging.activity_log import Change, Detail, Trigger, log_activity
from posthog.models.organization import OrganizationMembership
from posthog.models.user import User
from posthog.tasks.email import send_error_tracking_issue_assigned
@@ -246,6 +246,57 @@ def update_issue(
return IssueUpdateOutcome(issue=issue, changed_fields=tuple(key for key, changed in updated.items() if changed))
+def transition_issue_status_by_automation(
+ team_id: int,
+ issue_id: UUID,
+ *,
+ expected: "ErrorTrackingIssue.Status",
+ status: "ErrorTrackingIssue.Status",
+ trigger: Trigger,
+) -> bool:
+ """Move an issue from `expected` to `status` for a change no person made.
+
+ The check runs under the issue row lock, and the function returns False without a change
+ when the issue is no longer in `expected`. So a person or ingestion that changed the status
+ after the automation decided is never overwritten.
+ """
+ operation = ChangeOperation.for_automation(team_id)
+ with transaction.atomic():
+ locked = _lock_issues(team_id, [issue_id], select_related=("team",))
+ if not locked or locked[0].status != expected:
+ return False
+ issue = locked[0]
+ issue.status = status
+ issue.state_updated_at = timezone.now()
+ issue.save(update_fields=["status", "state_updated_at"])
+ record_issue_changes(operation, [IssueChange(issue=issue, data=StatusChanged(previous=Status(expected)))])
+ log_activity(
+ organization_id=issue.team.organization_id,
+ team_id=team_id,
+ user=None,
+ was_impersonated=False,
+ item_id=str(issue.id),
+ scope="ErrorTrackingIssue",
+ activity="updated",
+ detail=Detail(
+ name=issue.name,
+ changes=[
+ Change(type="ErrorTrackingIssue", field="status", before=expected, after=status, action="changed")
+ ],
+ trigger=trigger,
+ ),
+ )
+ produce_issue_lifecycle_event_on_commit(
+ event=STATUS_CHANGE_EVENTS[status],
+ issue=issue,
+ user=None,
+ extra_properties={"previous_status": status_label(expected)},
+ )
+
+ sync_issues_to_clickhouse(issue_ids=[issue_id], team_id=team_id)
+ return True
+
+
def merge_issues(
team_id: int, issue_id: UUID, source_ids: list[str], *, user: User, was_impersonated: bool
) -> IssueMergeOutcome:
diff --git a/products/error_tracking/backend/logic/linear_status_sync.py b/products/error_tracking/backend/logic/linear_status_sync.py
new file mode 100644
index 000000000000..d6b96755c5fd
--- /dev/null
+++ b/products/error_tracking/backend/logic/linear_status_sync.py
@@ -0,0 +1,362 @@
+"""Issue status from the workflow state of linked Linear tickets.
+
+An issue resolves when every linked Linear ticket is closed and at least one of them is done. A
+canceled ticket alone never resolves an issue, because it means nobody fixed anything. A linked ticket
+that Linear does not return has no known state, so it keeps the issue open. A resolved
+issue becomes active again when a linked ticket moves from a closed state back to an open one.
+Only projects that turn on `linear_status_sync_enabled` in their error tracking settings take part.
+
+A delivery only says that one ticket changed state. The task reads the current state of every
+linked ticket from Linear before it decides, so a late or reordered delivery cannot apply a state
+that the tickets no longer have.
+"""
+
+from collections.abc import Callable, Iterator, Mapping
+from contextlib import contextmanager, suppress
+from typing import Any
+from uuid import UUID
+
+import structlog
+from redis.exceptions import LockError, LockNotOwnedError
+
+from posthog.event_usage import groups
+from posthog.ingress.contracts import DeliveryOwnership
+from posthog.ingress.dispatch.database import bounded_statement_timeout
+from posthog.integrations import IntegrationManager, IntegrationRecord
+from posthog.models.activity_logging.activity_log import Trigger
+
+# `bounded_statement_timeout` gets the database alias of a read from the router, and the router needs
+# the model class. So `Integration` is imported only to cap the ownership lookup, and every read of a
+# row goes through the SDK.
+from posthog.models.integration import ( # nosemgrep: semgrep.rules.devex.integration-model-through-sdk
+ Integration,
+ LinearIntegration,
+ LinearRateLimitedError,
+)
+from posthog.ph_client import ph_scoped_capture
+from posthog.redis import get_client
+
+from products.error_tracking.backend.facade import contracts
+from products.error_tracking.backend.logic.issue_mutations import transition_issue_status_by_automation
+from products.error_tracking.backend.models import (
+ ErrorTrackingExternalReference,
+ ErrorTrackingIssue,
+ ErrorTrackingSettings,
+)
+
+# Linear groups every workflow state into one of these categories. A team can rename its states
+# and add more of them, but it cannot add a category, so the category is what the sync reads.
+_DONE_STATE_TYPE = "completed"
+_CLOSED_STATE_TYPES = frozenset({_DONE_STATE_TYPE, "canceled"})
+_OPEN_STATE_TYPES = frozenset({"triage", "backlog", "unstarted", "started"})
+
+_TRIGGER_JOB_TYPE = "linear_status_sync"
+
+_WORKSPACE_LOOKUP_TIMEOUT_MS = 800
+
+# Long enough to read every linked ticket of one issue. A job that dies holding the lock frees it then.
+_ISSUE_LOCK_TIMEOUT_SECONDS = 120
+_ISSUE_LOCK_WAIT_SECONDS = 10
+
+logger = structlog.get_logger(__name__)
+
+
+def prepare_job(payload: Mapping[str, Any]) -> contracts.LinearStatusSyncJob | None:
+ if payload.get("type") != "Issue" or payload.get("action") != "update":
+ return None
+ organization_id = payload.get("organizationId")
+ data = payload.get("data")
+ updated_from = payload.get("updatedFrom")
+ if not isinstance(organization_id, str) or not isinstance(data, Mapping) or not isinstance(updated_from, Mapping):
+ return None
+ identifier = data.get("identifier")
+ # Linear lists only the fields an update changed in `updatedFrom`, so `stateId` is there
+ # exactly when the ticket moved to another workflow state.
+ previous_state_id = updated_from.get("stateId")
+ if not organization_id or not isinstance(identifier, str) or not identifier:
+ return None
+ if not isinstance(previous_state_id, str) or not previous_state_id:
+ return None
+
+ # A reference stores the identifier the ticket had when it was linked, and a ticket that
+ # moved to another Linear team has a new one.
+ previous_identifiers = data.get("previousIdentifiers")
+ identifiers = [identifier]
+ if isinstance(previous_identifiers, list):
+ identifiers.extend(value for value in previous_identifiers if isinstance(value, str) and value)
+ return contracts.LinearStatusSyncJob(
+ organization_id=organization_id,
+ identifiers=tuple(dict.fromkeys(identifiers)),
+ previous_state_id=previous_state_id,
+ )
+
+
+def delivery_ownership(payload: Mapping[str, Any]) -> DeliveryOwnership:
+ """Which region holds the Linear workspace that a state change comes from.
+
+ One Linear App serves both regions, so every delivery reaches the receiving region first. A
+ workspace that no team here connects is `ELSEWHERE`, because only the other region can tell a
+ workspace it holds from one that nobody holds. A delivery that changes no workflow state is
+ `UNDECIDED`: no region acts on it, so the ticket's contents do not cross the region boundary.
+ A lookup that raises is let out, so Linear sends the delivery again instead of it going to a
+ region on a guess.
+ """
+ job = prepare_job(payload)
+ if job is None:
+ return DeliveryOwnership.UNDECIDED
+ with bounded_statement_timeout(_WORKSPACE_LOOKUP_TIMEOUT_MS, models=[Integration]):
+ held_here = IntegrationManager.linear.oauth.exists_by_external_id(job.organization_id)
+ return DeliveryOwnership.LOCAL if held_here else DeliveryOwnership.ELSEWHERE
+
+
+def sync_status(job: contracts.LinearStatusSyncJob) -> None:
+ workspace_rows = _opted_in_workspace_rows(job)
+ if not workspace_rows:
+ return
+ workspace_integration_ids = [row.id for row in workspace_rows]
+ issues = (
+ ErrorTrackingIssue.objects.filter(
+ team_id__in={row.team_id for row in workspace_rows},
+ external_issue__integration_id__in=workspace_integration_ids,
+ external_issue__external_context__id__in=job.identifiers,
+ )
+ .distinct()
+ .order_by("id")
+ .select_related("team__organization")
+ )
+
+ # Each project reads Linear with its own token, so one revoked token must not keep every other
+ # project's issue from syncing. One failure is raised after the loop so the task retries, and a
+ # retry is a no-op for the issues that already changed.
+ linear_reads = _LinearReads(job)
+ failures: list[Exception] = []
+ for issue in issues:
+ try:
+ with _issue_lock(issue.id):
+ _refresh_moved_identifiers(issue, job, workspace_integration_ids)
+ _sync_issue(issue, job, linear_reads)
+ except Exception as error:
+ logger.warning("linear_status_sync_issue_failed", issue_id=str(issue.id), team_id=issue.team_id)
+ failures.append(error)
+ if failures:
+ raise _failure_to_retry(failures)
+
+
+@contextmanager
+def _issue_lock(issue_id: UUID) -> Iterator[None]:
+ """Run one issue's Linear reads and status change while no other job does the same for it.
+
+ A job reads the ticket states before it takes the issue row lock, so two overlapping jobs
+ could act on their reads in the wrong order: a close job that read `completed` could resolve
+ the issue after a reopen job read `started` and found nothing to reopen. Raises LockError
+ while another job holds the issue, so the task retries it later.
+ """
+ lock = get_client().lock(
+ f"error_tracking:linear_status_sync:{issue_id}",
+ timeout=_ISSUE_LOCK_TIMEOUT_SECONDS,
+ blocking_timeout=_ISSUE_LOCK_WAIT_SECONDS,
+ )
+ if not lock.acquire():
+ raise LockError(f"Another Linear status sync holds issue {issue_id}")
+ try:
+ yield
+ finally:
+ # A job that outlived the lock timeout no longer owns it, and its work is already done.
+ with suppress(LockNotOwnedError):
+ lock.release()
+
+
+def _failure_to_retry(failures: list[Exception]) -> Exception:
+ """The failure that needs the longest wait, because the task picks its retry from the raised type.
+
+ A rate limit comes first, because a retry before Linear resets the limit fails again. A busy
+ issue comes next, because a job that died holding the lock keeps it for the lock timeout, and
+ the generic retry budget runs out before that.
+ """
+ rate_limited = [failure for failure in failures if isinstance(failure, LinearRateLimitedError)]
+ if rate_limited:
+ return max(rate_limited, key=lambda failure: failure.retry_after_seconds)
+ busy = [failure for failure in failures if isinstance(failure, LockError)]
+ return busy[0] if busy else failures[0]
+
+
+def _opted_in_workspace_rows(job: contracts.LinearStatusSyncJob) -> list[IntegrationRecord]:
+ """The integration rows that connect the job's Linear workspace to a project that turned the sync on."""
+ rows = IntegrationManager.linear.oauth.list_by_external_id(job.organization_id)
+ if not rows:
+ return []
+ opted_in_team_ids = set(
+ ErrorTrackingSettings.objects.filter(
+ linear_status_sync_enabled=True, team_id__in={row.team_id for row in rows}
+ ).values_list("team_id", flat=True)
+ )
+ return [row for row in rows if row.team_id in opted_in_team_ids]
+
+
+def _refresh_moved_identifiers(
+ issue: ErrorTrackingIssue, job: contracts.LinearStatusSyncJob, workspace_integration_ids: list[int]
+) -> None:
+ """Point the issue's references that hold an identifier from before a team move at the ticket's current one.
+
+ A reference stores only the identifier, and the state lookup finds a ticket by its current
+ one, so a stale identifier reads as a ticket with no known state, and the issue cannot resolve
+ until the reference is refreshed. Workflow states belong to a team, so a move between teams
+ always changes the state and reaches here. The caller holds the issue lock, so another job
+ never reads the issue's references while this job rewrites them.
+ """
+ current, *previous = job.identifiers
+ if not previous:
+ return
+ stale = ErrorTrackingExternalReference.objects.filter(
+ issue_id=issue.id,
+ integration_id__in=workspace_integration_ids,
+ external_context__id__in=previous,
+ )
+ for reference in stale:
+ reference.external_context = {**(reference.external_context or {}), "id": current}
+ reference.save(update_fields=["external_context"])
+
+
+class _LinearReads:
+ """The Linear reads of one job, kept apart per integration.
+
+ Each integration reads with the token of its own project, and Linear shows a token only the
+ teams that the token can access. So one integration's answer never stands in for another's: the
+ job reads the category of the state the ticket left at most once per integration. After Linear
+ rate limits an integration, the job sends no more reads with that integration's token, because
+ Linear refuses each of them until the limit resets. Those reads raise the first rate limit error again.
+ """
+
+ def __init__(self, job: contracts.LinearStatusSyncJob) -> None:
+ self._job = job
+ self._previous_state_types: dict[int, str | None] = {}
+ self._rate_limited: dict[int, LinearRateLimitedError] = {}
+
+ def previous_state_type(self, integration: IntegrationRecord) -> str | None:
+ if integration.id not in self._previous_state_types:
+ self._previous_state_types[integration.id] = self._read(
+ integration, lambda linear: linear.workflow_state_type(self._job.previous_state_id)
+ )
+ return self._previous_state_types[integration.id]
+
+ def issue_state_types(self, integration: IntegrationRecord, identifiers: list[str]) -> dict[str, str]:
+ return self._read(integration, lambda linear: linear.issue_state_types(identifiers))
+
+ def _read[T](self, integration: IntegrationRecord, read: Callable[[LinearIntegration], T]) -> T:
+ rate_limited = self._rate_limited.get(integration.id)
+ if rate_limited is not None:
+ raise rate_limited
+ try:
+ return read(LinearIntegration(integration))
+ except LinearRateLimitedError as error:
+ self._rate_limited[integration.id] = error
+ raise
+
+
+def _sync_issue(issue: ErrorTrackingIssue, job: contracts.LinearStatusSyncJob, linear_reads: _LinearReads) -> None:
+ references = list(ErrorTrackingExternalReference.objects.filter(issue_id=issue.id))
+ # `get_many` returns only Linear rows, so the filter below also drops references to other providers.
+ rows = IntegrationManager.linear.oauth.get_many(
+ issue.team_id, {reference.integration_id for reference in references}
+ )
+ references = [reference for reference in references if reference.integration_id in rows]
+ trigger_identifiers = set(job.identifiers)
+
+ def is_trigger(reference: ErrorTrackingExternalReference) -> bool:
+ return (
+ rows[reference.integration_id].integration_id == job.organization_id
+ and _stored_identifier(reference) in trigger_identifiers
+ )
+
+ trigger_references = [reference for reference in references if is_trigger(reference)]
+ if not trigger_references:
+ return
+
+ states = _current_state_types(
+ references, rows, linear_reads, current_trigger_identifier=job.identifiers[0], is_trigger=is_trigger
+ )
+ trigger_state = states.get(trigger_references[0].id)
+ trigger = Trigger(
+ job_type=_TRIGGER_JOB_TYPE,
+ job_id=job.identifiers[0],
+ payload={"linear_issue": job.identifiers[0], "linear_state_type": trigger_state},
+ )
+
+ if trigger_state in _CLOSED_STATE_TYPES:
+ # Linear leaves out a ticket that was deleted, a ticket the token cannot read, and a ticket
+ # that moved teams before its reference was refreshed. Only a deleted ticket is safe to ignore,
+ # and the response cannot tell the three apart, so a ticket without a state keeps the issue open.
+ linked_states = [states.get(reference.id) for reference in references]
+ if all(state in _CLOSED_STATE_TYPES for state in linked_states) and _DONE_STATE_TYPE in linked_states:
+ _transition(
+ issue,
+ expected=ErrorTrackingIssue.Status.ACTIVE,
+ status=ErrorTrackingIssue.Status.RESOLVED,
+ trigger=trigger,
+ )
+ elif trigger_state in _OPEN_STATE_TYPES:
+ # Only a move out of a closed state is a reopen. A ticket that moves from "Todo" to
+ # "In Progress" must not reactivate an issue that someone resolved in PostHog.
+ if linear_reads.previous_state_type(rows[trigger_references[0].integration_id]) in _CLOSED_STATE_TYPES:
+ _transition(
+ issue,
+ expected=ErrorTrackingIssue.Status.RESOLVED,
+ status=ErrorTrackingIssue.Status.ACTIVE,
+ trigger=trigger,
+ )
+
+
+def _transition(
+ issue: ErrorTrackingIssue,
+ *,
+ expected: ErrorTrackingIssue.Status,
+ status: ErrorTrackingIssue.Status,
+ trigger: Trigger,
+) -> None:
+ changed = transition_issue_status_by_automation(
+ issue.team_id, issue.id, expected=expected, status=status, trigger=trigger
+ )
+ if not changed:
+ return
+ with ph_scoped_capture() as capture:
+ capture(
+ distinct_id=str(issue.team.uuid),
+ # pinned: analytics event name, renaming it breaks dashboards
+ event="error_tracking_issue_status_synced_from_linear",
+ properties={"status": status.value, "previous_status": expected.value},
+ groups=groups(issue.team.organization, issue.team),
+ )
+
+
+def _stored_identifier(reference: ErrorTrackingExternalReference) -> str | None:
+ identifier = (reference.external_context or {}).get("id")
+ return identifier if isinstance(identifier, str) else None
+
+
+def _current_state_types(
+ references: list[ErrorTrackingExternalReference],
+ rows: Mapping[int, IntegrationRecord],
+ linear_reads: _LinearReads,
+ *,
+ current_trigger_identifier: str,
+ is_trigger: Callable[[ErrorTrackingExternalReference], bool],
+) -> dict[UUID, str]:
+ """The current state category of each reference's ticket, keyed by reference id.
+
+ A reference whose ticket Linear does not return is absent. The trigger ticket is read by the
+ identifier it has now, because its reference can hold one from before a move between teams.
+ """
+ lookups: dict[int, dict[UUID, str]] = {}
+ for reference in references:
+ identifier = current_trigger_identifier if is_trigger(reference) else _stored_identifier(reference)
+ if identifier is None:
+ continue
+ lookups.setdefault(reference.integration_id, {})[reference.id] = identifier
+
+ states: dict[UUID, str] = {}
+ for integration_id, by_reference in lookups.items():
+ found = linear_reads.issue_state_types(rows[integration_id], sorted(set(by_reference.values())))
+ for reference_id, identifier in by_reference.items():
+ if identifier in found:
+ states[reference_id] = found[identifier]
+ return states
diff --git a/products/error_tracking/backend/migrations/0048_errortrackingsettings_linear_status_sync_enabled.py b/products/error_tracking/backend/migrations/0048_errortrackingsettings_linear_status_sync_enabled.py
new file mode 100644
index 000000000000..53ec274ad930
--- /dev/null
+++ b/products/error_tracking/backend/migrations/0048_errortrackingsettings_linear_status_sync_enabled.py
@@ -0,0 +1,15 @@
+# Generated by Django 5.2.18 on 2026-10-28 17:58
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [("error_tracking", "0047_errortrackingsuppressionrule_built_in_key_uniq")]
+
+ operations = [
+ migrations.AddField(
+ model_name="errortrackingsettings",
+ name="linear_status_sync_enabled",
+ field=models.BooleanField(db_default=False, default=False),
+ ),
+ ]
diff --git a/products/error_tracking/backend/migrations/0049_externalreference_integration_context_id_index.py b/products/error_tracking/backend/migrations/0049_externalreference_integration_context_id_index.py
new file mode 100644
index 000000000000..20cd5058427c
--- /dev/null
+++ b/products/error_tracking/backend/migrations/0049_externalreference_integration_context_id_index.py
@@ -0,0 +1,24 @@
+import django.db.models.fields.json
+from django.db import migrations, models
+
+from posthog.migration_helpers import SafeAddIndexConcurrently
+
+
+class Migration(migrations.Migration):
+ atomic = False
+
+ dependencies = [
+ ("error_tracking", "0048_errortrackingsettings_linear_status_sync_enabled"),
+ ("posthog", "1415_organizationaiterms"),
+ ]
+
+ operations = [
+ SafeAddIndexConcurrently(
+ model_name="errortrackingexternalreference",
+ index=models.Index(
+ models.F("integration_id"),
+ django.db.models.fields.json.KeyTransform("id", "external_context"),
+ name="et_extref_integration_ctx_id",
+ ),
+ ),
+ ]
diff --git a/products/error_tracking/backend/migrations/max_migration.txt b/products/error_tracking/backend/migrations/max_migration.txt
index 9e89e8f07d18..e958734c8261 100644
--- a/products/error_tracking/backend/migrations/max_migration.txt
+++ b/products/error_tracking/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0047_errortrackingsuppressionrule_built_in_key_uniq
+0049_externalreference_integration_context_id_index
diff --git a/products/error_tracking/backend/models.py b/products/error_tracking/backend/models.py
index 93dc38586f86..d29b2555aa6e 100644
--- a/products/error_tracking/backend/models.py
+++ b/products/error_tracking/backend/models.py
@@ -9,6 +9,7 @@ from django.conf import settings
from django.contrib.postgres.fields import ArrayField
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models, transaction
+from django.db.models.fields.json import KeyTransform
from django.db.models.functions import Now
from django.utils import timezone
@@ -235,6 +236,15 @@ class ErrorTrackingExternalReference(UUIDTModel):
class Meta:
db_table = "posthog_errortrackingexternalreference"
+ indexes = [
+ # The Linear status sync looks up a workspace's references by ticket identifier on every
+ # state change in that workspace, also for tickets that no reference links.
+ models.Index(
+ models.F("integration_id"),
+ KeyTransform("id", "external_context"),
+ name="et_extref_integration_ctx_id",
+ ),
+ ]
class ErrorTrackingIssueCohort(UUIDTModel):
@@ -924,6 +934,7 @@ class ErrorTrackingSettings(models.Model):
project_rate_limit_bucket_size_minutes = models.IntegerField(null=True, blank=True)
per_issue_rate_limit_value = models.IntegerField(null=True, blank=True)
per_issue_rate_limit_bucket_size_minutes = models.IntegerField(null=True, blank=True)
+ linear_status_sync_enabled = models.BooleanField(default=False, db_default=False)
class Meta:
db_table = "posthog_errortrackingsettings"
diff --git a/products/error_tracking/backend/presentation/views/settings.py b/products/error_tracking/backend/presentation/views/settings.py
index 6b77d0ba6b9d..51fc6b48c7b1 100644
--- a/products/error_tracking/backend/presentation/views/settings.py
+++ b/products/error_tracking/backend/presentation/views/settings.py
@@ -40,6 +40,14 @@ class ErrorTrackingSettingsSerializer(serializers.Serializer):
"for this project before it is stored or billed, and the events cannot be recovered."
),
)
+ linear_status_sync_enabled = serializers.BooleanField(
+ required=False,
+ help_text=(
+ "Whether status changes on linked Linear tickets update the issue. When true, an issue resolves once "
+ "every linked Linear ticket is closed and at least one is done, and a resolved issue becomes active "
+ "again when a linked ticket reopens."
+ ),
+ )
class ErrorTrackingSettingsViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
diff --git a/products/error_tracking/backend/tasks/__init__.py b/products/error_tracking/backend/tasks/__init__.py
index 041e4a09a1b9..905d8dc658f5 100644
--- a/products/error_tracking/backend/tasks/__init__.py
+++ b/products/error_tracking/backend/tasks/__init__.py
@@ -1,4 +1,5 @@
from products.error_tracking.backend.tasks.github import process_github_external_reference # noqa: F401
+from products.error_tracking.backend.tasks.linear import process_linear_status_sync # noqa: F401
from products.error_tracking.backend.tasks.tasks import ( # noqa: F401
compute_error_tracking_recommendation,
dispatch_error_tracking_alert_deliveries,
diff --git a/products/error_tracking/backend/tasks/linear.py b/products/error_tracking/backend/tasks/linear.py
new file mode 100644
index 000000000000..9d0dd25b6a0f
--- /dev/null
+++ b/products/error_tracking/backend/tasks/linear.py
@@ -0,0 +1,80 @@
+import random
+from typing import Any, cast
+
+from django.db import DatabaseError
+
+import requests
+from celery import Task, shared_task
+from redis.exceptions import (
+ ConnectionError as RedisConnectionError,
+ LockError,
+ TimeoutError as RedisTimeoutError,
+)
+
+from posthog.models.integration import LinearIntegrationError, LinearRateLimitedError
+
+from products.error_tracking.backend.facade import contracts
+
+# Linear resets its rate limit at most an hour away, and the retry waits for the reset, so a few
+# retries cover a token that stays throttled for several windows.
+_RATE_LIMITED_MAX_RETRIES = 8
+# Another job holds the issue for a few Linear reads. Waiting a short, spread-out time lets it finish.
+_ISSUE_BUSY_MAX_RETRIES = 20
+_ISSUE_BUSY_RETRY_SECONDS = (5, 30)
+
+
+def enqueue_linear_status_sync(payload: dict[str, Any]) -> None:
+ from products.error_tracking.backend.facade import ( # noqa: PLC0415 - the write facade imports lifecycle_events, which imports temporal, which imports this package
+ issues,
+ )
+
+ job = issues.prepare_linear_status_sync_job(payload)
+ if job is None:
+ return
+ cast(Any, process_linear_status_sync).delay(
+ organization_id=job.organization_id,
+ identifiers=list(job.identifiers),
+ previous_state_id=job.previous_state_id,
+ )
+
+
+@shared_task(
+ bind=True,
+ name="products.error_tracking.backend.tasks.process_linear_status_sync",
+ ignore_result=True,
+ acks_late=True,
+ reject_on_worker_lost=True,
+ # A failed Linear read, database query or Redis lock call must retry rather than drop the
+ # delivery. Linear already holds the receipt and does not send it again.
+ autoretry_for=(
+ DatabaseError,
+ LinearIntegrationError,
+ RedisConnectionError,
+ RedisTimeoutError,
+ requests.RequestException,
+ ),
+ max_retries=5,
+ retry_backoff=True,
+ retry_backoff_max=300,
+ retry_jitter=True,
+)
+def process_linear_status_sync(
+ self: Task, *, organization_id: str, identifiers: list[str], previous_state_id: str
+) -> None:
+ from products.error_tracking.backend.facade import ( # noqa: PLC0415 - the write facade imports lifecycle_events, which imports temporal, which imports this package
+ issues,
+ )
+
+ job = contracts.LinearStatusSyncJob(
+ organization_id=organization_id,
+ identifiers=tuple(identifiers),
+ previous_state_id=previous_state_id,
+ )
+ try:
+ issues.sync_linear_status(job)
+ except LinearRateLimitedError as error:
+ raise self.retry(exc=error, countdown=error.retry_after_seconds, max_retries=_RATE_LIMITED_MAX_RETRIES)
+ except LockError as error:
+ raise self.retry(
+ exc=error, countdown=random.randint(*_ISSUE_BUSY_RETRY_SECONDS), max_retries=_ISSUE_BUSY_MAX_RETRIES
+ )
diff --git a/products/error_tracking/backend/test/test_linear_status_sync.py b/products/error_tracking/backend/test/test_linear_status_sync.py
new file mode 100644
index 000000000000..c4ffbb7fa576
--- /dev/null
+++ b/products/error_tracking/backend/test/test_linear_status_sync.py
@@ -0,0 +1,404 @@
+import hmac
+import json
+import time
+from collections import Counter
+from typing import Any
+
+from posthog.test.base import BaseTest
+from unittest.mock import Mock, patch
+
+from django.core.cache import cache
+from django.test import SimpleTestCase, override_settings
+
+import redis.exceptions as redis_exceptions
+from celery.exceptions import Retry
+from parameterized import parameterized
+
+from posthog.ingress.dispatch.loading import reset_consumer_registry
+from posthog.models import Team
+from posthog.models.activity_logging.activity_log import ActivityLog
+from posthog.models.integration import Integration, LinearIntegrationError
+
+from products.error_tracking.backend.facade import contracts, issues
+from products.error_tracking.backend.models import (
+ ErrorTrackingExternalReference,
+ ErrorTrackingIssue,
+ ErrorTrackingSettings,
+)
+from products.error_tracking.backend.tasks.linear import process_linear_status_sync
+
+ORGANIZATION_ID = "linear-org-1"
+PREVIOUS_STATE_ID = "state-previous"
+
+
+def _state_change_payload(**overrides: Any) -> dict[str, Any]:
+ return {
+ "type": "Issue",
+ "action": "update",
+ "organizationId": ORGANIZATION_ID,
+ "data": {"identifier": "ENG-1", "previousIdentifiers": ["OPS-7"]},
+ "updatedFrom": {"stateId": PREVIOUS_STATE_ID},
+ **overrides,
+ }
+
+
+class _FakeLinear:
+ """Answers the Linear GraphQL reads the sync makes, from the ticket states a test sets."""
+
+ def __init__(
+ self,
+ ticket_states: dict[str, str],
+ previous_state_type: str | None,
+ *,
+ failing_tokens: frozenset[str] = frozenset(),
+ rate_limited_tokens: dict[str, int] | None = None,
+ tokens_without_previous_state: frozenset[str] = frozenset(),
+ ) -> None:
+ self.ticket_states = ticket_states
+ self.previous_state_type = previous_state_type
+ self.failing_tokens = failing_tokens
+ self.tokens_without_previous_state = tokens_without_previous_state
+ self.rate_limited_tokens = rate_limited_tokens or {}
+ self.requests_by_token: Counter[str] = Counter()
+
+ def post(self, url: str, *, headers: dict[str, str], json: dict[str, Any], timeout: int) -> Mock:
+ query, variables = json["query"], json["variables"]
+ token = headers["Authorization"].removeprefix("Bearer ")
+ self.requests_by_token[token] += 1
+ if token in self.rate_limited_tokens:
+ reset_ms = int((time.time() + self.rate_limited_tokens[token]) * 1000)
+ return Mock(
+ status_code=429,
+ headers={"X-RateLimit-Requests-Reset": str(reset_ms)},
+ json=Mock(return_value={"errors": [{"extensions": {"code": "RATELIMITED"}}]}),
+ )
+ if token in self.failing_tokens:
+ body: dict[str, Any] = {"errors": [{"message": "Authentication required"}]}
+ elif "IssueStates" in query:
+ wanted = {(match["team"]["key"]["eq"], match["number"]["eq"]) for match in variables["filter"]["or"]}
+ nodes = [
+ {"identifier": identifier, "state": {"type": state_type}}
+ for identifier, state_type in self.ticket_states.items()
+ if (identifier.split("-")[0], int(identifier.split("-")[1])) in wanted
+ ]
+ body = {"data": {"issues": {"nodes": nodes}}}
+ elif "WorkflowStateType" in query:
+ assert variables["id"] == PREVIOUS_STATE_ID
+ visible = token not in self.tokens_without_previous_state
+ nodes = [{"type": self.previous_state_type}] if self.previous_state_type and visible else []
+ body = {"data": {"workflowStates": {"nodes": nodes}}}
+ else:
+ raise AssertionError(f"Unexpected Linear query: {query}")
+ return Mock(status_code=200, headers={}, json=Mock(return_value=body))
+
+
+class TestPrepareLinearStatusSyncJob(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("title_edit", _state_change_payload(updatedFrom={"title": "Old title"})),
+ ("created_ticket", _state_change_payload(action="create")),
+ ("comment", _state_change_payload(type="Comment")),
+ ("missing_workspace", _state_change_payload(organizationId=None)),
+ ]
+ )
+ def test_ignores_deliveries_that_do_not_change_a_ticket_state(self, _name: str, payload: dict[str, Any]) -> None:
+ assert issues.prepare_linear_status_sync_job(payload) is None
+
+ def test_carries_identifiers_from_before_a_team_move(self) -> None:
+ assert issues.prepare_linear_status_sync_job(_state_change_payload()) == contracts.LinearStatusSyncJob(
+ organization_id=ORGANIZATION_ID,
+ identifiers=("ENG-1", "OPS-7"),
+ previous_state_id=PREVIOUS_STATE_ID,
+ )
+
+
+@override_settings(LINEAR_APP_WEBHOOK_SECRET="linear-secret")
+class TestErrorTrackingLinearWebhook(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ reset_consumer_registry()
+ cache.clear()
+ self.addCleanup(reset_consumer_registry)
+ self.addCleanup(cache.clear)
+ self.addCleanup(patch.stopall)
+ # `pytest.ini` sets DEBUG, which rewrites both region domains to localhost hosts. `testserver`
+ # is the primary region here, because that is the region the Linear App's one webhook URL names.
+ patch("posthog.regions.PRIMARY_REGION_DOMAIN", "testserver").start()
+ patch("posthog.regions.SECONDARY_REGION_DOMAIN", "us.posthog.com").start()
+ self.forward = patch("posthog.ingress.dispatch.forward.requests.request").start()
+ self.forward.return_value = Mock(status_code=200, ok=True)
+ self.delay = patch("products.error_tracking.backend.tasks.linear.process_linear_status_sync.delay").start()
+
+ def _post_status(self, payload: dict[str, Any]) -> int:
+ body = json.dumps({**payload, "webhookTimestamp": int(time.time() * 1000)}).encode()
+ return self.client.post(
+ "/webhooks/linear/",
+ data=body,
+ content_type="application/json",
+ headers={
+ "Linear-Signature": hmac.digest(b"linear-secret", body, "sha256").hex(),
+ "Linear-Delivery": "delivery-1",
+ "Linear-Event": "Issue",
+ },
+ secure=True,
+ ).status_code
+
+ def test_state_change_from_a_workspace_held_here_enqueues_the_sync_without_a_forward(self) -> None:
+ Integration.objects.create(
+ team=self.team, kind=Integration.IntegrationKind.LINEAR.value, integration_id=ORGANIZATION_ID
+ )
+
+ assert self._post_status(_state_change_payload()) == 200
+ self.forward.assert_not_called()
+ self.delay.assert_called_once_with(
+ organization_id=ORGANIZATION_ID,
+ identifiers=["ENG-1", "OPS-7"],
+ previous_state_id=PREVIOUS_STATE_ID,
+ )
+
+ @parameterized.expand(
+ [
+ ("state_change_is_forwarded", _state_change_payload(), True),
+ ("title_edit_stays_here", _state_change_payload(updatedFrom={"title": "Old title"}), False),
+ ]
+ )
+ def test_delivery_from_a_workspace_held_elsewhere(
+ self, _name: str, payload: dict[str, Any], forwarded: bool
+ ) -> None:
+ assert self._post_status(payload) == 200
+ assert [call.kwargs["url"] for call in self.forward.call_args_list] == (
+ ["https://us.posthog.com/webhooks/linear/"] if forwarded else []
+ )
+
+
+class TestLinearStatusSync(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self._opt_in(self.team)
+
+ def _opt_in(self, team: Team) -> None:
+ ErrorTrackingSettings.objects.create(team=team, linear_status_sync_enabled=True)
+
+ def _linear_integration(
+ self, team: Team, organization_id: str = ORGANIZATION_ID, token: str = "linear-token"
+ ) -> Integration:
+ return Integration.objects.create(
+ team=team,
+ kind=Integration.IntegrationKind.LINEAR.value,
+ integration_id=organization_id,
+ sensitive_config={"access_token": token},
+ )
+
+ def _linked_issue(
+ self, team: Team, integration: Integration, identifiers: list[str], status: str = "active"
+ ) -> ErrorTrackingIssue:
+ issue = ErrorTrackingIssue.objects.create(team=team, name="Checkout failed", status=status)
+ for identifier in identifiers:
+ ErrorTrackingExternalReference.objects.create(
+ issue=issue, integration=integration, external_context={"id": identifier}
+ )
+ return issue
+
+ def _sync(self, linear: _FakeLinear, identifiers: tuple[str, ...] = ("ENG-1",)) -> None:
+ with patch("posthog.models.integration.linear.requests.post", side_effect=linear.post):
+ process_linear_status_sync(
+ organization_id=ORGANIZATION_ID, identifiers=list(identifiers), previous_state_id=PREVIOUS_STATE_ID
+ )
+
+ @parameterized.expand(
+ [
+ ("done_resolves", ["ENG-1"], {"ENG-1": "completed"}, "started", "active", "resolved"),
+ ("canceled_alone_does_not_resolve", ["ENG-1"], {"ENG-1": "canceled"}, "started", "active", "active"),
+ (
+ "waits_for_every_linked_ticket",
+ ["ENG-1", "ENG-2"],
+ {"ENG-1": "completed", "ENG-2": "started"},
+ "started",
+ "active",
+ "active",
+ ),
+ (
+ "done_and_canceled_resolves",
+ ["ENG-1", "ENG-2"],
+ {"ENG-1": "completed", "ENG-2": "canceled"},
+ "started",
+ "active",
+ "resolved",
+ ),
+ (
+ "unreturned_ticket_holds_the_issue_open",
+ ["ENG-1", "ENG-9"],
+ {"ENG-1": "completed"},
+ "started",
+ "active",
+ "active",
+ ),
+ ("reopened_ticket_reactivates", ["ENG-1"], {"ENG-1": "started"}, "completed", "resolved", "active"),
+ (
+ "move_between_open_states_keeps_resolved",
+ ["ENG-1"],
+ {"ENG-1": "started"},
+ "unstarted",
+ "resolved",
+ "resolved",
+ ),
+ (
+ "suppressed_issue_is_left_alone",
+ ["ENG-1"],
+ {"ENG-1": "completed"},
+ "started",
+ "suppressed",
+ "suppressed",
+ ),
+ ]
+ )
+ def test_issue_status_follows_linked_ticket_states(
+ self,
+ _name: str,
+ linked: list[str],
+ ticket_states: dict[str, str],
+ previous_state_type: str,
+ initial_status: str,
+ expected_status: str,
+ ) -> None:
+ issue = self._linked_issue(self.team, self._linear_integration(self.team), linked, status=initial_status)
+
+ self._sync(_FakeLinear(ticket_states, previous_state_type))
+
+ issue.refresh_from_db()
+ assert issue.status == expected_status
+ system_status_changes = ActivityLog.objects.filter(
+ team_id=self.team.id, scope="ErrorTrackingIssue", item_id=str(issue.id), is_system=True
+ )
+ assert system_status_changes.count() == (0 if expected_status == initial_status else 1)
+
+ def test_changes_only_opted_in_projects_linked_through_the_same_workspace(self) -> None:
+ linked_issue = self._linked_issue(self.team, self._linear_integration(self.team), ["ENG-1"])
+ other_workspace_issue = self._linked_issue(
+ self.team, self._linear_integration(self.team, organization_id="linear-org-2"), ["ENG-1"]
+ )
+ opted_in_team = Team.objects.create(organization=self.organization, name="Opted in")
+ self._opt_in(opted_in_team)
+ opted_in_issue = self._linked_issue(opted_in_team, self._linear_integration(opted_in_team), ["ENG-1"])
+ not_opted_in_team = Team.objects.create(organization=self.organization, name="Not opted in")
+ not_opted_in_issue = self._linked_issue(
+ not_opted_in_team, self._linear_integration(not_opted_in_team), ["ENG-1"]
+ )
+
+ self._sync(_FakeLinear({"ENG-1": "completed"}, "started"))
+
+ statuses = dict(
+ ErrorTrackingIssue.objects.filter(
+ id__in=[linked_issue.id, other_workspace_issue.id, opted_in_issue.id, not_opted_in_issue.id]
+ ).values_list("id", "status")
+ )
+ assert statuses == {
+ linked_issue.id: "resolved",
+ other_workspace_issue.id: "active",
+ opted_in_issue.id: "resolved",
+ not_opted_in_issue.id: "active",
+ }
+
+ @parameterized.expand([("move_job_first", True), ("completion_job_first", False)])
+ def test_a_ticket_that_moved_teams_holds_its_issue_open_until_it_closes(
+ self, _name: str, move_job_first: bool
+ ) -> None:
+ issue = self._linked_issue(self.team, self._linear_integration(self.team), ["ENG-1", "OPS-7"])
+ linear = _FakeLinear({"ENG-1": "completed", "ENG-2": "started"}, "started")
+ move_job, completion_job = ("ENG-2", "OPS-7"), ("ENG-1",)
+
+ for identifiers in (move_job, completion_job) if move_job_first else (completion_job, move_job):
+ self._sync(linear, identifiers=identifiers)
+ issue.refresh_from_db()
+ assert issue.status == "active"
+
+ linear.ticket_states["ENG-2"] = "completed"
+ self._sync(linear, identifiers=("ENG-2",))
+ issue.refresh_from_db()
+ assert issue.status == "resolved"
+
+ def test_each_project_reads_the_previous_state_with_its_own_token(self) -> None:
+ blind_team = Team.objects.create(organization=self.organization, name="Cannot see the previous team")
+ self._opt_in(blind_team)
+ blind_issue = self._linked_issue(
+ blind_team, self._linear_integration(blind_team, token="blind-token"), ["ENG-1"], status="resolved"
+ )
+ seeing_issue = self._linked_issue(self.team, self._linear_integration(self.team), ["ENG-1"], status="resolved")
+ linear = _FakeLinear(
+ {"ENG-1": "started"}, "completed", tokens_without_previous_state=frozenset({"blind-token"})
+ )
+
+ self._sync(linear)
+
+ statuses = dict(
+ ErrorTrackingIssue.objects.filter(id__in=[blind_issue.id, seeing_issue.id]).values_list("id", "status")
+ )
+ assert statuses == {blind_issue.id: "resolved", seeing_issue.id: "active"}
+
+ def test_a_project_whose_linear_read_fails_raises_without_holding_back_the_others(self) -> None:
+ revoked_team = Team.objects.create(organization=self.organization, name="Revoked token")
+ self._opt_in(revoked_team)
+ failing_issue = self._linked_issue(
+ revoked_team, self._linear_integration(revoked_team, token="revoked-token"), ["ENG-1"]
+ )
+ working_issue = self._linked_issue(self.team, self._linear_integration(self.team), ["ENG-1"])
+ linear = _FakeLinear({"ENG-1": "completed"}, "started", failing_tokens=frozenset({"revoked-token"}))
+
+ with (
+ patch("posthog.models.integration.linear.requests.post", side_effect=linear.post),
+ self.assertRaises(LinearIntegrationError),
+ ):
+ issues.sync_linear_status(
+ contracts.LinearStatusSyncJob(
+ organization_id=ORGANIZATION_ID, identifiers=("ENG-1",), previous_state_id=PREVIOUS_STATE_ID
+ )
+ )
+
+ statuses = dict(
+ ErrorTrackingIssue.objects.filter(id__in=[failing_issue.id, working_issue.id]).values_list("id", "status")
+ )
+ assert statuses == {failing_issue.id: "active", working_issue.id: "resolved"}
+
+ @parameterized.expand([("alone", False), ("behind_a_project_whose_read_fails", True)])
+ def test_a_rate_limited_read_retries_once_linear_resets_the_limit(
+ self, _name: str, failing_project_first: bool
+ ) -> None:
+ if failing_project_first:
+ revoked_team = Team.objects.create(organization=self.organization, name="Revoked token")
+ self._opt_in(revoked_team)
+ self._linked_issue(revoked_team, self._linear_integration(revoked_team, token="revoked-token"), ["ENG-1"])
+ integration = self._linear_integration(self.team)
+ self._linked_issue(self.team, integration, ["ENG-1"])
+ self._linked_issue(self.team, integration, ["ENG-1"])
+ linear = _FakeLinear(
+ {"ENG-1": "completed"},
+ "started",
+ failing_tokens=frozenset({"revoked-token"}),
+ rate_limited_tokens={"linear-token": 900},
+ )
+
+ with (
+ patch.object(process_linear_status_sync, "retry", side_effect=Retry()) as retry,
+ self.assertRaises(Retry),
+ ):
+ self._sync(linear)
+
+ assert 899 <= retry.call_args.kwargs["countdown"] <= 900
+ assert linear.requests_by_token["linear-token"] == 1
+
+ @parameterized.expand(
+ [("connection_error", redis_exceptions.ConnectionError), ("timeout", redis_exceptions.TimeoutError)]
+ )
+ def test_a_redis_failure_on_the_issue_lock_retries(self, _name: str, error: type[Exception]) -> None:
+ self._linked_issue(self.team, self._linear_integration(self.team), ["ENG-1"])
+ redis_client = Mock()
+ redis_client.lock.return_value.acquire.side_effect = error("Redis is unreachable")
+
+ with (
+ patch("products.error_tracking.backend.logic.linear_status_sync.get_client", return_value=redis_client),
+ patch.object(process_linear_status_sync, "retry", side_effect=Retry()) as retry,
+ self.assertRaises(Retry),
+ ):
+ self._sync(_FakeLinear({"ENG-1": "completed"}, "started"))
+
+ assert isinstance(retry.call_args.kwargs["exc"], error)
diff --git a/products/error_tracking/backend/tests/api/test_settings.py b/products/error_tracking/backend/tests/api/test_settings.py
index e8ae7b78fc53..61673cda77b9 100644
--- a/products/error_tracking/backend/tests/api/test_settings.py
+++ b/products/error_tracking/backend/tests/api/test_settings.py
@@ -32,15 +32,21 @@ class TestErrorTrackingSettingsAPI(APIBaseTest):
def test_update_settings_with_session_auth(self):
response = self.client.patch(
f"{self._base_url()}/update_settings/",
- {"project_rate_limit_value": 5000, "project_rate_limit_bucket_size_minutes": 60},
+ {
+ "project_rate_limit_value": 5000,
+ "project_rate_limit_bucket_size_minutes": 60,
+ "linear_status_sync_enabled": True,
+ },
format="json",
)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.json()["project_rate_limit_value"], 5000)
+ self.assertEqual(response.json()["linear_status_sync_enabled"], True)
settings = ErrorTrackingSettings.objects.get(team=self.team)
self.assertEqual(settings.project_rate_limit_value, 5000)
self.assertEqual(settings.project_rate_limit_bucket_size_minutes, 60)
+ self.assertTrue(settings.linear_status_sync_enabled)
def test_update_settings_only_changes_provided_fields(self):
setup_response = self.client.patch(
diff --git a/products/error_tracking/backend/webhook_consumers.py b/products/error_tracking/backend/webhook_consumers.py
index 88e45cc7a549..3e86a8abdb30 100644
--- a/products/error_tracking/backend/webhook_consumers.py
+++ b/products/error_tracking/backend/webhook_consumers.py
@@ -1,4 +1,4 @@
-from posthog.ingress.contracts import WebhookConsumer, WebhookDelivery
+from posthog.ingress.contracts import DeliveryOwnership, WebhookConsumer, WebhookDelivery
def _enqueue_external_references(delivery: WebhookDelivery) -> None:
@@ -9,6 +9,22 @@ def _enqueue_external_references(delivery: WebhookDelivery) -> None:
enqueue_github_external_references(delivery.event_type, dict(delivery.payload))
+def _enqueue_linear_status_sync(delivery: WebhookDelivery) -> None:
+ from products.error_tracking.backend.facade.linear import ( # noqa: PLC0415 - keeps Celery and product logic off the registry import path
+ enqueue_linear_status_sync,
+ )
+
+ enqueue_linear_status_sync(dict(delivery.payload))
+
+
+def _linear_status_sync_ownership(delivery: WebhookDelivery) -> DeliveryOwnership:
+ from products.error_tracking.backend.facade.issues import ( # noqa: PLC0415 - keeps product logic off the registry import path
+ linear_delivery_ownership,
+ )
+
+ return linear_delivery_ownership(dict(delivery.payload))
+
+
WEBHOOK_CONSUMERS = (
WebhookConsumer(
name="error_tracking_external_references",
@@ -17,4 +33,12 @@ WEBHOOK_CONSUMERS = (
event_types=frozenset({"issues", "pull_request"}),
handler=_enqueue_external_references,
),
+ WebhookConsumer(
+ name="error_tracking_linear_status_sync",
+ provider="linear",
+ app="posthog",
+ event_types=frozenset({"Issue"}),
+ handler=_enqueue_linear_status_sync,
+ ownership=_linear_status_sync_ownership,
+ ),
)
diff --git a/products/error_tracking/frontend/generated/api.schemas.ts b/products/error_tracking/frontend/generated/api.schemas.ts
index dfebb0d53e8d..bbf7ba42ab6e 100644
--- a/products/error_tracking/frontend/generated/api.schemas.ts
+++ b/products/error_tracking/frontend/generated/api.schemas.ts
@@ -2246,6 +2246,8 @@ export interface ErrorTrackingSettingsApi {
per_issue_rate_limit_bucket_size_minutes?: number | null
/** Whether the project ingests exception events. When false, ingestion drops every $exception event for this project before it is stored or billed, and the events cannot be recovered. */
ingestion_enabled?: boolean
+ /** Whether status changes on linked Linear tickets update the issue. When true, an issue resolves once every linked Linear ticket is closed and at least one is done, and a resolved issue becomes active again when a linked ticket reopens. */
+ linear_status_sync_enabled?: boolean
}
export interface PatchedErrorTrackingSettingsApi {
@@ -2275,6 +2277,8 @@ export interface PatchedErrorTrackingSettingsApi {
per_issue_rate_limit_bucket_size_minutes?: number | null
/** Whether the project ingests exception events. When false, ingestion drops every $exception event for this project before it is stored or billed, and the events cannot be recovered. */
ingestion_enabled?: boolean
+ /** Whether status changes on linked Linear tickets update the issue. When true, an issue resolves once every linked Linear ticket is closed and at least one is done, and a resolved issue becomes active again when a linked ticket reopens. */
+ linear_status_sync_enabled?: boolean
}
/**
diff --git a/products/error_tracking/frontend/generated/api.zod.ts b/products/error_tracking/frontend/generated/api.zod.ts
index 1826692d0c5b..291131ee5876 100644
--- a/products/error_tracking/frontend/generated/api.zod.ts
+++ b/products/error_tracking/frontend/generated/api.zod.ts
@@ -1124,6 +1124,12 @@ export const ErrorTrackingSettingsUpdateSettingsPartialUpdateBody = /* @__PURE__
.describe(
'Whether the project ingests exception events. When false, ingestion drops every $exception event for this project before it is stored or billed, and the events cannot be recovered.'
),
+ linear_status_sync_enabled: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'Whether status changes on linked Linear tickets update the issue. When true, an issue resolves once every linked Linear ticket is closed and at least one is done, and a resolved issue becomes active again when a linked ticket reopens.'
+ ),
})
export const errorTrackingSeverityRulesCreateBodyOrderKeyDefault = 0
diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/linear_status_sync/LinearStatusSyncSetting.tsx b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/linear_status_sync/LinearStatusSyncSetting.tsx
new file mode 100644
index 000000000000..517351c7f83d
--- /dev/null
+++ b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/linear_status_sync/LinearStatusSyncSetting.tsx
@@ -0,0 +1,45 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonBanner, LemonSkeleton, LemonSwitch } from '@posthog/lemon-ui'
+
+import { errorTrackingEditAccessDisabledReason } from '../../../utils'
+import { linearStatusSyncLogic } from './linearStatusSyncLogic'
+
+export function LinearStatusSyncSetting(): JSX.Element {
+ const { linearStatusSyncEnabled, settingsLoading, settingsLoadFailed, integrations, linearIntegrations } =
+ useValues(linearStatusSyncLogic)
+ const { setLinearStatusSyncEnabled } = useActions(linearStatusSyncLogic)
+
+ if (linearStatusSyncEnabled === null) {
+ return settingsLoadFailed ? (
+ <LemonBanner type="error">Couldn't load this setting. Refresh the page to try again.</LemonBanner>
+ ) : (
+ <LemonSkeleton className="w-60 h-10" />
+ )
+ }
+
+ // Turning the sync off stays possible after the workspace is disconnected.
+ const noWorkspaceReason =
+ integrations !== null && linearIntegrations.length === 0 && !linearStatusSyncEnabled
+ ? 'Connect a Linear workspace first'
+ : null
+
+ return (
+ <div className="flex flex-col gap-y-2">
+ <LemonSwitch
+ id="error-tracking-linear-status-sync-switch"
+ data-attr="error-tracking-linear-status-sync-switch"
+ label="Sync error tracking issue status from Linear"
+ checked={linearStatusSyncEnabled}
+ onChange={setLinearStatusSyncEnabled}
+ loading={settingsLoading || integrations === null}
+ disabledReason={errorTrackingEditAccessDisabledReason() ?? noWorkspaceReason}
+ bordered
+ />
+ <p className="m-0 text-xs text-secondary">
+ Resolves an error tracking issue when all of its linked Linear tickets are closed and at least one of
+ them is done. Reopens the issue when a linked ticket is reopened.
+ </p>
+ </div>
+ )
+}
diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/linear_status_sync/linearStatusSyncLogic.ts b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/linear_status_sync/linearStatusSyncLogic.ts
new file mode 100644
index 000000000000..360f1e3b1beb
--- /dev/null
+++ b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/linear_status_sync/linearStatusSyncLogic.ts
@@ -0,0 +1,135 @@
+import { MakeLogicType, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+import posthog from 'posthog-js'
+
+import { integrationsLogic } from 'lib/integrations/integrationsLogic'
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+import { getCurrentTeamId } from 'lib/utils/getAppContext'
+
+import { IntegrationType } from '~/types'
+
+import {
+ errorTrackingSettingsRetrieveSettingsRetrieve,
+ errorTrackingSettingsUpdateSettingsPartialUpdate,
+} from '../../../generated/api'
+import type { ErrorTrackingSettingsApi } from '../../../generated/api.schemas'
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface linearStatusSyncLogicValues {
+ integrations: IntegrationType[] | null // integrationsLogic
+ linearIntegrations: IntegrationType[] // integrationsLogic
+ linearStatusSyncEnabled: boolean | null
+ settings: ErrorTrackingSettingsApi | null
+ settingsLoadFailed: boolean
+ settingsLoading: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface linearStatusSyncLogicActions {
+ loadSettings: () => any
+ loadSettingsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadSettingsSuccess: (
+ settings: ErrorTrackingSettingsApi,
+ payload?: any
+ ) => {
+ settings: ErrorTrackingSettingsApi
+ payload?: any
+ }
+ setLinearStatusSyncEnabled: (linearStatusSyncEnabled: boolean) => boolean
+ setLinearStatusSyncEnabledFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ setLinearStatusSyncEnabledSuccess: (
+ settings: ErrorTrackingSettingsApi,
+ payload?: boolean
+ ) => {
+ settings: ErrorTrackingSettingsApi
+ payload?: boolean
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface linearStatusSyncLogicMeta {
+ __keaTypeGenInternalSelectorTypes: {
+ linearStatusSyncEnabled: (settings: ErrorTrackingSettingsApi | null) => boolean | null
+ }
+}
+
+export type linearStatusSyncLogicType = MakeLogicType<
+ linearStatusSyncLogicValues,
+ linearStatusSyncLogicActions,
+ Record<string, any>,
+ linearStatusSyncLogicMeta
+>
+
+export const linearStatusSyncLogic = kea<linearStatusSyncLogicType>([
+ path([
+ 'products',
+ 'error_tracking',
+ 'scenes',
+ 'ErrorTrackingConfigurationScene',
+ 'linear_status_sync',
+ 'linearStatusSyncLogic',
+ ]),
+
+ connect(() => ({
+ values: [integrationsLogic, ['integrations', 'linearIntegrations']],
+ })),
+
+ loaders({
+ settings: [
+ null as ErrorTrackingSettingsApi | null,
+ {
+ loadSettings: async () => {
+ return await errorTrackingSettingsRetrieveSettingsRetrieve(getCurrentTeamId().toString())
+ },
+ setLinearStatusSyncEnabled: async (linearStatusSyncEnabled: boolean) => {
+ return await errorTrackingSettingsUpdateSettingsPartialUpdate(getCurrentTeamId().toString(), {
+ linear_status_sync_enabled: linearStatusSyncEnabled,
+ })
+ },
+ },
+ ],
+ }),
+
+ reducers({
+ settingsLoadFailed: [
+ false,
+ {
+ loadSettings: () => false,
+ loadSettingsFailure: () => true,
+ },
+ ],
+ }),
+
+ selectors({
+ linearStatusSyncEnabled: [
+ (s) => [s.settings],
+ (settings: ErrorTrackingSettingsApi | null): boolean | null =>
+ settings ? settings.linear_status_sync_enabled === true : null,
+ ],
+ }),
+
+ listeners({
+ setLinearStatusSyncEnabledSuccess: ({ settings }) => {
+ const enabled = settings.linear_status_sync_enabled === true
+ // pinned: analytics event name, renaming it breaks dashboards
+ posthog.capture('error_tracking_linear_status_sync_toggled', { enabled })
+ lemonToast.success(enabled ? 'Linear status sync turned on' : 'Linear status sync turned off')
+ },
+ }),
+
+ afterMount(({ actions }) => {
+ actions.loadSettings()
+ }),
+])
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 79a6f2bad712..fe407a448b8b 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -45219,6 +45219,8 @@ export namespace Schemas {
per_issue_rate_limit_bucket_size_minutes?: number | null;
/** Whether the project ingests exception events. When false, ingestion drops every $exception event for this project before it is stored or billed, and the events cannot be recovered. */
ingestion_enabled?: boolean;
+ /** Whether status changes on linked Linear tickets update the issue. When true, an issue resolves once every linked Linear ticket is closed and at least one is done, and a resolved issue becomes active again when a linked ticket reopens. */
+ linear_status_sync_enabled?: boolean;
}
/**
@@ -88076,6 +88078,8 @@ export namespace Schemas {
per_issue_rate_limit_bucket_size_minutes?: number | null;
/** Whether the project ingests exception events. When false, ingestion drops every $exception event for this project before it is stored or billed, and the events cannot be recovered. */
ingestion_enabled?: boolean;
+ /** Whether status changes on linked Linear tickets update the issue. When true, an issue resolves once every linked Linear ticket is closed and at least one is done, and a resolved issue becomes active again when a linked ticket reopens. */
+ linear_status_sync_enabled?: boolean;
}
/**
diff --git a/services/mcp/src/generated/error_tracking/api.ts b/services/mcp/src/generated/error_tracking/api.ts
index e83fcb04043a..716c4d4c6297 100644
--- a/services/mcp/src/generated/error_tracking/api.ts
+++ b/services/mcp/src/generated/error_tracking/api.ts
@@ -8821,6 +8821,12 @@ export const ErrorTrackingSettingsUpdateSettingsPartialUpdateBody = () => zod.ob
.describe(
'Whether the project ingests exception events. When false, ingestion drops every $exception event for this project before it is stored or billed, and the events cannot be recovered.'
),
+ linear_status_sync_enabled: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'Whether status changes on linked Linear tickets update the issue. When true, an issue resolves once every linked Linear ticket is closed and at least one is done, and a resolved issue becomes active again when a linked ticket reopens.'
+ ),
})
export const ErrorTrackingSeverityRulesListParams = () => zod.object({
diff --git a/services/mcp/src/tools/generated/error_tracking.ts b/services/mcp/src/tools/generated/error_tracking.ts
index 7bc352b7c4a4..8be2a1df8756 100644
--- a/services/mcp/src/tools/generated/error_tracking.ts
+++ b/services/mcp/src/tools/generated/error_tracking.ts
@@ -464,6 +464,9 @@ const errorTrackingSettingsUpdate = (): ToolBase<
if (params.ingestion_enabled !== undefined) {
body['ingestion_enabled'] = params.ingestion_enabled
}
+ if (params.linear_status_sync_enabled !== undefined) {
+ body['linear_status_sync_enabled'] = params.linear_status_sync_enabled
+ }
const result = await context.api.request<Schemas.ErrorTrackingSettings>({
method: 'PATCH',
path: `/api/projects/${encodeURIComponent(String(projectId))}/error_tracking/settings/update_settings/`,
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/error-tracking-settings-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/error-tracking-settings-update.json
index cee30434d60c..57c781bddedc 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/error-tracking-settings-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/error-tracking-settings-update.json
@@ -5,6 +5,10 @@
"description": "Whether the project ingests exception events. When false, ingestion drops every $exception event for this project before it is stored or billed, and the events cannot be recovered.",
"type": "boolean"
},
+ "linear_status_sync_enabled": {
+ "description": "Whether status changes on linked Linear tickets update the issue. When true, an issue resolves once every linked Linear ticket is closed and at least one is done, and a resolved issue becomes active again when a linked ticket reopens.",
+ "type": "boolean"
+ },
"per_issue_rate_limit_bucket_size_minutes": {
"anyOf": [
{