: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(warehouse-sources): add jira worklogs, boards, sprints and sprint issues tables (#115316)
Tom Owers7fdf37a578d8
diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txtindex a10226531ee7..f6bb0509b94c 100644--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt@@ -700,8 +700,6 @@1 products/warehouse_sources/backend/temporal/data_imports/sources/jenkins/jenkins.py1 products/warehouse_sources/backend/temporal/data_imports/sources/jenkins/settings.py1 products/warehouse_sources/backend/temporal/data_imports/sources/jfrog_artifactory/jfrog_artifactory.py-1 products/warehouse_sources/backend/temporal/data_imports/sources/jira/jira.py-1 products/warehouse_sources/backend/temporal/data_imports/sources/jira/settings.py1 products/warehouse_sources/backend/temporal/data_imports/sources/jobnimbus/jobnimbus.py1 products/warehouse_sources/backend/temporal/data_imports/sources/jobnimbus/settings.py1 products/warehouse_sources/backend/temporal/data_imports/sources/jotform/jotform.pydiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.mdindex 0ced75e4c345..d060c9c0a258 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md@@ -4585,16 +4585,16 @@ Note: AQL is the connector's main mechanism and it already uses the items and bu## Jira — gaps-Today (10): `dashboards`, `fields`, `filters`, `issue_types`, `issues`, `priorities`, `projects`, `resolutions`, `statuses`, `users`+Today (14): `boards`, `dashboards`, `fields`, `filters`, `issue_types`, `issues`, `priorities`, `projects`, `resolutions`, `sprint_issues`, `sprints`, `statuses`, `users`, `worklogs`Diffed against: <https://developer.atlassian.com/cloud/jira/platform/swagger-v3.v3.json>- [ ] `/rest/api/3/issue/{id}/changelog (and /changelog/bulkfetch)` — issue field transition history - the only source for cycle time, time-in-status and reopen rate (high)-- [ ] `/rest/agile/1.0/board/{boardId}/sprint` — sprints, the unit every agile velocity and commitment metric is built on (high)-- [ ] `/rest/agile/1.0/board` — boards lookup that scopes sprints and backlogs to teams (high)-- [ ] `/rest/agile/1.0/sprint/{sprintId}/issue` — sprint-to-issue membership edges needed for velocity and scope-change analysis (high)+- [x] `/rest/agile/1.0/board/{boardId}/sprint` — sprints, the unit every agile velocity and commitment metric is built on (high)+- [x] `/rest/agile/1.0/board` — boards lookup that scopes sprints and backlogs to teams (high)+- [x] `/rest/agile/1.0/sprint/{sprintId}/issue` — sprint-to-issue membership edges needed for velocity and scope-change analysis (high). Added as `sprint_issues` from the Sprint field via `/rest/api/3/search/jql`, because the spec marks this endpoint and the other agile issue listings deprecated.- [ ] `/rest/api/3/issue/{id}/comment (or /rest/api/3/comment/list)` — comment volume and response latency, the main collaboration signal on an issue (high)-- [ ] `/rest/api/3/issue/{id}/worklog (with /worklog/updated for incrementals)` — logged time per issue and user, the basis for effort and cost reporting (high)+- [x] `/rest/api/3/issue/{id}/worklog (with /worklog/updated for incrementals)` — logged time per issue and user, the basis for effort and cost reporting (high). Added as `worklogs` via `/worklog/updated` plus `POST /worklog/list`, which avoids one request per issue.- [ ] `/rest/api/3/project/{projectIdOrKey}/versions` — lookup resolving the fixVersions/affectedVersions IDs carried on synced issues (medium)- [ ] `/rest/api/3/project/{projectIdOrKey}/components` — lookup resolving the component IDs carried on synced issues (medium)- [ ] `/rest/api/3/statuscategory` — lookup rolling the already-synced statuses into To Do / In Progress / Done buckets (medium)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/jira/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/jira/canonical_descriptions.pyindex 940caa8adc1b..b5bc0d78b9dc 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/jira/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/jira/canonical_descriptions.py@@ -138,4 +138,58 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"self": "URL of the filter's REST resource.",},},+ "worklogs": {+ "description": "Time logged against a Jira issue by a user.",+ "docs_url": "https://developer.atlassian.com/cloud/jira/platform/rest/v3/api-group-issue-worklogs/#api-rest-api-3-worklog-list-post",+ "columns": {+ "id": "Unique identifier for the worklog.",+ "issueId": "ID of the issue the worklog is logged against.",+ "author": "The user who created the worklog.",+ "updateAuthor": "The user who last updated the worklog.",+ "comment": "Comment about the logged work, in Atlassian Document Format.",+ "created": "When the worklog was created.",+ "updated": "When the worklog was last updated.",+ "started": "When the logged work started.",+ "timeSpent": "Time spent, as a duration string (e.g. 3h 20m).",+ "timeSpentSeconds": "Time spent, in seconds.",+ "visibility": "Restriction on who can view the worklog, if any.",+ "self": "URL of the worklog's REST resource.",+ },+ },+ "boards": {+ "description": "A Jira Software board that shows issues from a saved filter as a scrum or kanban board.",+ "docs_url": "https://developer.atlassian.com/cloud/jira/software/rest/api-group-board/#api-rest-agile-1-0-board-get",+ "columns": {+ "id": "Unique identifier for the board.",+ "name": "The board's name.",+ "type": "The board type: scrum, kanban, or simple.",+ "location": "The project or user the board belongs to.",+ "self": "URL of the board's REST resource.",+ },+ },+ "sprints": {+ "description": "A Jira Software sprint, a time-boxed iteration on a scrum board.",+ "docs_url": "https://developer.atlassian.com/cloud/jira/software/rest/api-group-board/#api-rest-agile-1-0-board-boardid-sprint-get",+ "columns": {+ "id": "Unique identifier for the sprint.",+ "name": "The sprint's name.",+ "state": "The sprint state: future, active, or closed.",+ "startDate": "When the sprint started or is planned to start.",+ "endDate": "When the sprint ended or is planned to end.",+ "completeDate": "When the sprint was completed.",+ "createdDate": "When the sprint was created.",+ "originBoardId": "ID of the board the sprint was created on.",+ "goal": "The sprint goal.",+ "self": "URL of the sprint's REST resource.",+ },+ },+ "sprint_issues": {+ "description": "Membership of an issue in a sprint, one row per sprint an issue is or was part of.",+ "docs_url": "https://developer.atlassian.com/cloud/jira/platform/rest/v3/api-group-issue-search/#api-rest-api-3-search-jql-get",+ "columns": {+ "sprint_id": "ID of the sprint.",+ "issue_id": "ID of the issue.",+ "issue_key": "Human-readable key of the issue (e.g. PROJ-123).",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/jira/jira.py b/products/warehouse_sources/backend/temporal/data_imports/sources/jira/jira.pyindex e73b4bcb530e..25b956b3ebe0 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/jira/jira.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/jira/jira.py@@ -1,8 +1,9 @@import reimport base64import dataclasses-from datetime import date, datetime, timedelta-from typing import Any, Optional+from collections.abc import Iterator+from datetime import UTC, date, datetime, timedelta+from typing import Any, Optional, castfrom requests import Responsefrom structlog.types import FilteringBoundLogger@@ -12,15 +13,25 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resRESTAPIConfig,rest_api_resource,)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import HttpBasicAuth+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ build_dependent_resource,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (JSONResponseCursorPaginator,OffsetPaginator,SinglePagePaginator,)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.resource import Resource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import RESTClient+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import ClientConfigfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse-from products.warehouse_sources.backend.temporal.data_imports.sources.jira.settings import JIRA_ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.jira.settings import (+ JIRA_ENDPOINTS,+ JiraEndpointConfig,+)# JQL only understands minute precision in this exact layout — it rejects ISO 8601 with seconds or a Z suffix.JQL_DATETIME_FORMAT = "%Y-%m-%d %H:%M"@@ -34,15 +45,24 @@ INCREMENTAL_LOOKBACK = timedelta(days=1)# while still scanning every issue.JQL_FLOOR_DATETIME = "1970-01-01 00:00"+# ``/worklog/updated`` returns worklogs updated strictly after ``since``. Re-read a minute so a worklog+# that shares the watermark's timestamp is not skipped; merge dedupes the overlap.+WORKLOG_SINCE_OVERLAP = timedelta(minutes=1)++SPRINT_FIELD_SCHEMA = "com.pyxis.greenhopper.jira:gh-sprint"+SPRINT_ISSUES_JQL = f'sprint is not EMPTY AND created >= "{JQL_FLOOR_DATETIME}" ORDER BY created ASC'+_VALID_SUBDOMAIN = re.compile(r"^[a-zA-Z0-9][a-zA-Z0-9-]*$")[email protected](frozen=False)class JiraResumeConfig:next_page_token: Optional[str] = Nonestart_at: Optional[int] = None# The JQL the token was minted for — a token replayed against a different JQL is a 400.jql: Optional[str] = None+ # The ``since`` (epoch milliseconds) of the next ``/worklog/updated`` page.+ worklog_since: Optional[int] = Nonedef is_valid_subdomain(subdomain: str) -> bool:@@ -120,6 +140,255 @@ class JiraOffsetPaginator(OffsetPaginator):self._has_next_page = False+class JiraWorklogPaginator(JSONResponseCursorPaginator):+ """``/worklog/updated`` paging: the next page starts ``since`` the current page's ``until``, and+ ``lastPage`` ends the walk."""++ def __init__(self) -> None:+ super().__init__(cursor_path="until", cursor_param="since", raise_on_repeated_cursor=True)++ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:+ # Check ``lastPage`` first: a final page can repeat the previous ``until``, which the+ # repeated-cursor guard would reject.+ try:+ body = response.json()+ except Exception:+ body = None+ if isinstance(body, dict) and body.get("lastPage"):+ self._has_next_page = False+ return+ super().update_state(response, data)+++def _to_epoch_millis(value: Any) -> int:+ if isinstance(value, datetime):+ dt = value+ elif isinstance(value, date):+ dt = datetime.combine(value, datetime.min.time())+ else:+ dt = datetime.fromisoformat(str(value).replace("Z", "+00:00"))+ if dt.tzinfo is None:+ dt = dt.replace(tzinfo=UTC)+ return int(dt.timestamp() * 1000)+++def _worklog_since(last_value: Any) -> int:+ if not last_value:+ return 0+ return max(_to_epoch_millis(last_value) - int(WORKLOG_SINCE_OVERLAP.total_seconds() * 1000), 0)+++def _sprint_issue_rows(issue: dict[str, Any], sprint_field: str) -> list[dict[str, Any]]:+ sprints = (issue.get("fields") or {}).get(sprint_field) or []+ return [+ {"sprint_id": sprint["id"], "issue_id": issue["id"], "issue_key": issue.get("key")}+ for sprint in sprints+ if isinstance(sprint, dict) and sprint.get("id") is not None+ ]+++def _find_sprint_field(fields: list[Any]) -> Optional[str]:+ for field in fields:+ if isinstance(field, dict) and (field.get("schema") or {}).get("custom") == SPRINT_FIELD_SCHEMA:+ return field.get("id")+ return None+++def _rest_client(subdomain: str, email: str, api_token: str) -> RESTClient:+ return RESTClient(+ base_url=base_url(subdomain),+ headers={"Accept": "application/json"},+ auth=HttpBasicAuth(email, api_token),+ )+++def _client_config(subdomain: str, email: str, api_token: str) -> ClientConfig:+ return {+ "base_url": base_url(subdomain),+ # Auth (Basic) is supplied via the framework auth config so the api_token is redacted from+ # logs and raised error messages; only the non-secret Accept header is set here.+ "headers": {"Accept": "application/json"},+ "auth": {"type": "http_basic", "username": email, "password": api_token},+ }+++def _offset_paginator(config: JiraEndpointConfig) -> JiraOffsetPaginator:+ return JiraOffsetPaginator(+ limit=config.page_size,+ offset_param="startAt",+ limit_param="maxResults",+ total_path=None,+ )+++def _worklogs_source(+ subdomain: str,+ email: str,+ api_token: str,+ resumable_source_manager: ResumableSourceManager[JiraResumeConfig],+ db_incremental_field_last_value: Optional[Any],+) -> SourceResponse:+ config = JIRA_ENDPOINTS["worklogs"]+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ since = (+ resume.worklog_since+ if resume and resume.worklog_since is not None+ else _worklog_since(db_incremental_field_last_value)+ )++ def items() -> Iterator[list[dict[str, Any]]]:+ client = _rest_client(subdomain, email, api_token)+ next_page: dict[str, Any] = {}++ def stage_next_page(state: Optional[dict[str, Any]], has_next: bool) -> None:+ next_page["since"] = state.get("cursor") if state and has_next else None++ for changed in client.paginate(+ config.path,+ params={"since": since},+ paginator=JiraWorklogPaginator(),+ data_selector="values",+ page_state_hook=stage_next_page,+ ):+ ids = [entry["worklogId"] for entry in changed if entry.get("worklogId") is not None]+ worklogs: list[dict[str, Any]] = []+ if ids:+ for page in client.paginate(+ "/rest/api/3/worklog/list",+ method="post",+ json={"ids": ids},+ paginator=SinglePagePaginator(),+ ):+ worklogs.extend(page)+ # ``/worklog/list`` does not promise the request order; keep the feed's oldest-first order+ # so the ``updated`` watermark only moves forward.+ position = {str(worklog_id): index for index, worklog_id in enumerate(ids)}+ worklogs.sort(key=lambda worklog: position.get(str(worklog.get("id")), len(position)))++ if next_page.get("since") is not None:+ resumable_source_manager.save_state(JiraResumeConfig(worklog_since=int(next_page["since"])))+ if worklogs:+ yield worklogs+ else:+ resumable_source_manager.safe_point()++ return SourceResponse(+ name="worklogs",+ items=items,+ primary_keys=config.primary_key,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime",+ partition_format="month",+ partition_keys=[config.partition_key] if config.partition_key else None,+ sort_mode="asc",+ )+++def _sprint_issues_source(+ subdomain: str,+ email: str,+ api_token: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[JiraResumeConfig],+) -> SourceResponse:+ config = JIRA_ENDPOINTS["sprint_issues"]+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ initial_paginator_state = (+ {"cursor": resume.next_page_token}+ if resume and resume.next_page_token and resume.jql == SPRINT_ISSUES_JQL+ else None+ )++ def items() -> Iterator[list[dict[str, Any]]]:+ client = _rest_client(subdomain, email, api_token)+ fields = [+ field for page in client.paginate("/rest/api/3/field", paginator=SinglePagePaginator()) for field in page+ ]+ sprint_field = _find_sprint_field(fields)+ if sprint_field is None:+ # Sites without Jira Software have no Sprint field, so there is no membership to sync.+ logger.info("Jira site has no Sprint field, skipping sprint_issues")+ return++ next_page: dict[str, Any] = {}++ def stage_next_page(state: Optional[dict[str, Any]], has_next: bool) -> None:+ next_page["cursor"] = state.get("cursor") if state and has_next else None++ for issues in client.paginate(+ config.path,+ params={"jql": SPRINT_ISSUES_JQL, "maxResults": config.page_size, "fields": sprint_field},+ paginator=JiraTokenPaginator(),+ data_selector=config.data_key,+ initial_paginator_state=initial_paginator_state,+ page_state_hook=stage_next_page,+ ):+ rows = [row for issue in issues for row in _sprint_issue_rows(issue, sprint_field)]+ if next_page.get("cursor") is not None:+ resumable_source_manager.save_state(+ JiraResumeConfig(next_page_token=next_page["cursor"], jql=SPRINT_ISSUES_JQL)+ )+ if rows:+ yield rows+ else:+ resumable_source_manager.safe_point()++ return SourceResponse(+ name="sprint_issues",+ items=items,+ primary_keys=config.primary_key,+ partition_count=1,+ partition_size=1,+ sort_mode="asc",+ )+++def _sprints_source(subdomain: str, email: str, api_token: str, team_id: int, job_id: str) -> SourceResponse:+ config = JIRA_ENDPOINTS["sprints"]+ assert config.fanout is not None+ parent_config = JIRA_ENDPOINTS[config.fanout.parent_name]++ resource = cast(+ Resource,+ build_dependent_resource(+ endpoint_configs=JIRA_ENDPOINTS,+ child_endpoint="sprints",+ fanout=config.fanout,+ client_config=_client_config(subdomain, email, api_token),+ path_format_values={},+ team_id=team_id,+ job_id=job_id,+ db_incremental_field_last_value=None,+ parent_endpoint_extra={+ "data_selector": parent_config.data_key,+ "paginator": _offset_paginator(parent_config),+ },+ child_endpoint_extra={"data_selector": config.data_key, "paginator": _offset_paginator(config)},+ page_size_param=None,+ ),+ )++ seen: set[Any] = set()++ def first_listing(sprint: dict[str, Any]) -> bool:+ if sprint.get("id") in seen:+ return False+ seen.add(sprint.get("id"))+ return True++ resource.add_filter(first_listing)++ return SourceResponse(+ name="sprints",+ items=lambda: resource,+ primary_keys=config.primary_key,+ partition_count=1,+ partition_size=1,+ sort_mode="asc",+ )++def validate_credentials(subdomain: str, email: str, api_token: str) -> tuple[bool, int | None]:"""Probe ``/myself`` to confirm the token is genuine. Returns ``(ok, status_code)``."""if not is_valid_subdomain(subdomain):@@ -147,6 +416,19 @@ def jira_source() -> SourceResponse:config = JIRA_ENDPOINTS[endpoint]+ if endpoint == "worklogs":+ return _worklogs_source(+ subdomain,+ email,+ api_token,+ resumable_source_manager,+ db_incremental_field_last_value if should_use_incremental_field else None,+ )+ if endpoint == "sprint_issues":+ return _sprint_issues_source(subdomain, email, api_token, logger, resumable_source_manager)+ if endpoint == "sprints":+ return _sprints_source(subdomain, email, api_token, team_id, job_id)+resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else Noneinitial_paginator_state: Optional[dict[str, Any]] = None@@ -173,23 +455,12 @@ def jira_source(f"Discarding Jira resume token minted for a different JQL: saved={resume.jql!r}, current={issues_jql!r}")else: # offset- paginator = JiraOffsetPaginator(- limit=config.page_size,- offset_param="startAt",- limit_param="maxResults",- total_path=None,- )+ paginator = _offset_paginator(config)if resume and resume.start_at is not None:initial_paginator_state = {"offset": resume.start_at}rest_config: RESTAPIConfig = {- "client": {- "base_url": base_url(subdomain),- # Auth (Basic) is supplied via the framework auth config so the api_token is redacted from- # logs and raised error messages; only the non-secret Accept header is set here.- "headers": {"Accept": "application/json"},- "auth": {"type": "http_basic", "username": email, "password": api_token},- },+ "client": _client_config(subdomain, email, api_token),"resource_defaults": {},"resources": [{diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/jira/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/jira/settings.pyindex 095657a1de6c..2acef111cecb 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/jira/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/jira/settings.py@@ -1,18 +1,26 @@from dataclasses import dataclass, fieldfrom typing import Literal, Optional+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ DependentEndpointConfig,+)from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType# How an endpoint advances through pages:# - "token": Jira's enhanced search returns an opaque ``nextPageToken`` (issues only).# - "offset": classic ``startAt`` / ``maxResults`` paging used by the ``*/search`` endpoints.# - "none": the endpoint returns the full collection in a single (un-paginated) response.-PaginationMode = Literal["token", "offset", "none"]+# - "custom": the endpoint has its own iterator in ``jira.py``.+PaginationMode = Literal["token", "offset", "none", "custom"]DEFAULT_PAGE_SIZE = 100+# The Jira Software (agile) API caps ``maxResults`` at 50.+AGILE_PAGE_SIZE = 50+# Both ``/worklog/updated`` and ``/worklog/list`` cap a page at 1000 worklogs.+WORKLOG_PAGE_SIZE = 1000-@dataclass+@dataclass(frozen=True)class JiraEndpointConfig:name: strpath: str@@ -28,6 +36,8 @@ class JiraEndpointConfig:# Only ``issues`` exposes a genuine server-side timestamp filter (JQL ``updated >= ...``).supports_incremental: bool = Falsepage_size: int = DEFAULT_PAGE_SIZE+ default_incremental_field: Optional[str] = None+ fanout: Optional[DependentEndpointConfig] = Nonedef _datetime_field(name: str) -> IncrementalField:@@ -40,9 +50,10 @@ def _datetime_field(name: str) -> IncrementalField:# Endpoint catalog. Jira Cloud REST API v3 (https://developer.atlassian.com/cloud/jira/platform/rest/v3/).-# We deliberately exclude the per-issue fan-out streams (comments, worklogs, votes, watchers,-# remote links, properties, transitions) — each requires one HTTP request per issue and degrades-# badly on large instances. Issues carry the bulk of the useful data and sync incrementally.+# We deliberately exclude the per-issue fan-out streams (comments, votes, watchers, remote links,+# properties, transitions) — each requires one HTTP request per issue and degrades badly on large+# instances. Worklogs avoid that through the instance-wide ``/worklog/updated`` feed. Issues carry the+# bulk of the useful data and sync incrementally.JIRA_ENDPOINTS: dict[str, JiraEndpointConfig] = {"issues": JiraEndpointConfig(name="issues",@@ -114,6 +125,58 @@ JIRA_ENDPOINTS: dict[str, JiraEndpointConfig] = {pagination="offset",data_key="values",),+ "worklogs": JiraEndpointConfig(+ name="worklogs",+ # Paged through ``/worklog/updated`` (ids, oldest update first), then hydrated in bulk with+ # ``POST /worklog/list``.+ path="/rest/api/3/worklog/updated",+ primary_key=["id"],+ pagination="custom",+ supports_incremental=True,+ partition_key="created",+ incremental_fields=[_datetime_field("updated")],+ default_incremental_field="updated",+ page_size=WORKLOG_PAGE_SIZE,+ ),+ "boards": JiraEndpointConfig(+ name="boards",+ path="/rest/agile/1.0/board",+ primary_key=["id"],+ pagination="offset",+ data_key="values",+ page_size=AGILE_PAGE_SIZE,+ ),+ "sprints": JiraEndpointConfig(+ name="sprints",+ path="/rest/agile/1.0/board/{boardId}/sprint",+ # A sprint is listed on every board whose filter matches its issues, so rows are deduplicated+ # by id across boards. ``originBoardId`` names the board that owns the sprint.+ primary_key=["id"],+ pagination="offset",+ data_key="values",+ page_size=AGILE_PAGE_SIZE,+ fanout=DependentEndpointConfig(+ parent_name="boards",+ resolve_param="boardId",+ resolve_field="id",+ include_from_parent=[],+ # Kanban boards answer 400 because they have no sprints. A board deleted after the+ # listing answers 404.+ child_response_actions=[+ {"status_code": 400, "action": "ignore"},+ {"status_code": 404, "action": "ignore"},+ ],+ ),+ ),+ "sprint_issues": JiraEndpointConfig(+ name="sprint_issues",+ # The agile ``/sprint/{sprintId}/issue`` listing is deprecated, so membership comes from the+ # Sprint field of each issue, read through the enhanced JQL search.+ path="/rest/api/3/search/jql",+ primary_key=["sprint_id", "issue_id"],+ pagination="custom",+ data_key="issues",+ ),}ENDPOINTS = tuple(JIRA_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/jira/tests/test_jira.py b/products/warehouse_sources/backend/temporal/data_imports/sources/jira/tests/test_jira.pyindex f84afdf16ca9..d6f042a4a755 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/jira/tests/test_jira.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/jira/tests/test_jira.py@@ -1,6 +1,6 @@import jsonfrom collections.abc import Iterable-from datetime import date, datetime+from datetime import UTC, date, datetimefrom typing import Any, castimport pytest@@ -9,7 +9,14 @@ from unittest import mockfrom parameterized import parameterizedfrom requests import Response+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (+ ScriptedResponse,+ SourceDriver,+ route,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.jira import JiraSourceConfigfrom products.warehouse_sources.backend.temporal.data_imports.sources.jira.jira import (+ SPRINT_ISSUES_JQL,JiraResumeConfig,_format_jql_datetime,_normalize_issue,@@ -17,6 +24,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.jira.jirajira_source,validate_credentials,)+from products.warehouse_sources.backend.temporal.data_imports.sources.jira.source import JiraSource# RESTClient builds its session via make_tracked_session in the rest_client module.CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"@@ -250,3 +258,172 @@ class TestValidateCredentials:ok, status = validate_credentials("acme", "[email protected]", "token")assert ok is expected_okassert status == status_code+++def _driver() -> SourceDriver:+ return SourceDriver(JiraSource(), JiraSourceConfig(subdomain="acme", email="[email protected]", api_token="token"))+++def _worklog(worklog_id: int, updated: str) -> dict[str, Any]:+ return {"id": str(worklog_id), "issueId": "10", "created": "2026-01-01T00:00:00.000+0000", "updated": updated}+++class TestWorklogs:+ def test_walks_updated_feed_and_hydrates_each_page_in_feed_order(self) -> None:+ result = _driver().run(+ "worklogs",+ route(+ {+ "/rest/api/3/worklog/updated": [+ ScriptedResponse(+ json={+ "values": [{"worklogId": 1, "updatedTime": 100}, {"worklogId": 2, "updatedTime": 200}],+ "since": 0,+ "until": 200,+ "lastPage": False,+ }+ ),+ # An exact multiple of the page size ends on an empty page that repeats `until`.+ ScriptedResponse(json={"values": [], "since": 200, "until": 200, "lastPage": True}),+ ],+ "/rest/api/3/worklog/list": [+ ScriptedResponse(+ json=[+ _worklog(2, "2026-01-01T00:00:00.200+0000"),+ _worklog(1, "2026-01-01T00:00:00.100+0000"),+ ]+ )+ ],+ }+ ),+ )++ assert result.raised is None+ assert result.paths == [+ "/rest/api/3/worklog/updated",+ "/rest/api/3/worklog/list",+ "/rest/api/3/worklog/updated",+ ]+ assert result.params("since") == ["0", None, "200"]+ assert result.requests[1].method == "POST"+ assert result.requests[1].json() == {"ids": [1, 2]}+ assert [row["id"] for row in result.rows] == ["1", "2"]+ assert result.committed_states == [JiraResumeConfig(worklog_since=200)]++ @parameterized.expand(+ [+ ("full_refresh", {}, "0"),+ # The watermark minus a one minute overlap, in epoch milliseconds.+ (+ "incremental",+ {+ "incremental_field": "updated",+ "db_incremental_field_last_value": datetime(2026, 1, 1, 0, 1, tzinfo=UTC),+ },+ "1767225600000",+ ),+ ("resume", {"resume_state": JiraResumeConfig(worklog_since=1234)}, "1234"),+ ]+ )+ def test_first_request_since(self, _name: str, run_kwargs: dict[str, Any], expected_since: str) -> None:+ result = _driver().run(+ "worklogs",+ [ScriptedResponse(json={"values": [], "since": 0, "until": 0, "lastPage": True})],+ **run_kwargs,+ )++ assert result.raised is None+ assert result.params("since") == [expected_since]+++class TestSprints:+ def test_skips_boards_without_sprints_and_dedupes_sprints_shared_by_boards(self) -> None:+ result = _driver().run(+ "sprints",+ route(+ {+ "/rest/agile/1.0/board": [+ ScriptedResponse(+ json={"values": [{"id": 1}, {"id": 2}, {"id": 3}], "isLast": True, "startAt": 0}+ )+ ],+ "/rest/agile/1.0/board/1/sprint": [+ ScriptedResponse(json={"values": [{"id": 10}, {"id": 11}], "isLast": True})+ ],+ "/rest/agile/1.0/board/2/sprint": [+ ScriptedResponse(+ status=400, json={"errorMessages": ["The board does not support sprints"], "errors": {}}+ )+ ],+ "/rest/agile/1.0/board/3/sprint": [+ ScriptedResponse(json={"values": [{"id": 11}, {"id": 12}], "isLast": True})+ ],+ }+ ),+ )++ assert result.raised is None+ assert [row["id"] for row in result.rows] == [10, 11, 12]+ assert result.params("maxResults") == ["50", "50", "50", "50"]+++SPRINT_FIELDS_RESPONSE = ScriptedResponse(+ json=[+ {"id": "summary", "schema": {"type": "string", "system": "summary"}},+ {"id": "customfield_10020", "schema": {"type": "array", "custom": "com.pyxis.greenhopper.jira:gh-sprint"}},+ ]+)+++class TestSprintIssues:+ def test_explodes_sprint_field_into_membership_rows(self) -> None:+ result = _driver().run(+ "sprint_issues",+ route(+ {+ "/rest/api/3/field": [SPRINT_FIELDS_RESPONSE],+ "/rest/api/3/search/jql": [+ ScriptedResponse(+ json={+ "issues": [+ {+ "id": "100",+ "key": "P-1",+ "fields": {"customfield_10020": [{"id": 10}, {"id": 11}]},+ }+ ],+ "nextPageToken": "tok2",+ }+ ),+ ScriptedResponse(+ json={+ "issues": [+ {"id": "101", "key": "P-2", "fields": {"customfield_10020": None}},+ {"id": "102", "key": "P-3", "fields": {"customfield_10020": [{"id": 11}]}},+ ],+ "isLast": True,+ }+ ),+ ],+ }+ ),+ )++ assert result.raised is None+ assert result.params("fields") == [None, "customfield_10020", "customfield_10020"]+ assert result.params("nextPageToken") == [None, None, "tok2"]+ assert result.rows == [+ {"sprint_id": 10, "issue_id": "100", "issue_key": "P-1"},+ {"sprint_id": 11, "issue_id": "100", "issue_key": "P-1"},+ {"sprint_id": 11, "issue_id": "102", "issue_key": "P-3"},+ ]+ assert result.committed_states == [JiraResumeConfig(next_page_token="tok2", jql=SPRINT_ISSUES_JQL)]++ def test_site_without_sprint_field_syncs_nothing(self) -> None:+ result = _driver().run(+ "sprint_issues", [ScriptedResponse(json=[{"id": "summary", "schema": {"type": "string"}}])]+ )++ assert result.raised is None+ assert result.rows == []+ assert result.paths == ["/rest/api/3/field"]