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(warehouse-sources): add four codescene analysis tables (#103349)

Tom Owersbacd7a51a1e8
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index 15008c84b93a..aa7bec3c3ccf 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
@@ -1797,14 +1797,14 @@ Note: The whole public REST API is four doc pages (applications, artifacts, buil
## Codescene — **thin**
-Today (3): `Components`, `Files`, `Projects`
+Today (7): `Analyses`, `AuthorStatistics`, `Components`, `Files`, `Issues`, `Projects`, `TechnicalDebt`
Diffed against: <https://docs.enterprise.codescene.io/latest/integrations/rest-api.html>
-- [ ] `projects/{project-id}/analyses` — the analysis-run history; without it every synced table is a single 'latest' snapshot with no trend and no way to pin an analysis id (high)
-- [ ] `projects/{project-id}/analyses/latest/issues` — code health issues (hotspots, brain classes) - the product's core finding table (high)
-- [ ] `projects/{project-id}/analyses/latest/technical-debt` — technical debt and refactoring targets, CodeScene's headline metric (high)
-- [ ] `projects/{project-id}/analyses/latest/author-statistics` — per-author contribution stats; the only way to join code health to people (high)
+- [x] `projects/{project-id}/analyses` — the analysis-run history; without it every synced table is a single 'latest' snapshot with no trend and no way to pin an analysis id (high)
+- [x] `projects/{project-id}/analyses/latest/issues` — issues from the project management integration, with status, cycle time and the commits and files changed while each was open (high)
+- [x] `projects/{project-id}/analyses/latest/technical-debt` — technical debt and refactoring targets, CodeScene's headline metric (high)
+- [x] `projects/{project-id}/analyses/latest/author-statistics` — per-author contribution stats; the only way to join code health to people (high)
- [ ] `projects/{project-id}/analyses/latest/commits` — commit-level rows underpinning every aggregate CodeScene reports (medium)
- [ ] `projects/{project-id}/analyses/latest/commit-activity` — commit activity time series for delivery-rate dashboards (medium)
- [ ] `projects/{project-id}/analyses/latest/branch-statistics` — per-branch stats for branching-strategy and lead-time analysis (medium)
@@ -1814,7 +1814,7 @@ Diffed against: <https://docs.enterprise.codescene.io/latest/integrations/rest-a
- [ ] `active-authors` — authoritative author roster; a lookup table for the author ids appearing in analyses (medium)
- [ ] `projects/{project-id}/analyses/latest/experience/languages` — author language experience, used for knowledge-risk and bus-factor reporting (low)
-Note: Static endpoint list; no dynamic table discovery in products/warehouse_sources/backend/temporal/data_imports/sources/codescene/settings.py (three hardcoded CODESCENE_ENDPOINTS). The v2 API exposes ~100 paths; PostHog covers 3, and notably syncs only the 'latest' analysis with no analysis history.
+Note: Static endpoint list; no dynamic table discovery in products/warehouse_sources/backend/temporal/data_imports/sources/codescene/settings.py (hardcoded CODESCENE_ENDPOINTS). The v2 API exposes ~100 paths; PostHog covers 7. The per-analysis tables still read the 'latest' analysis only, but `Analyses` now carries the run history so an analysis id can be pinned.
## Cody — adequate
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/codescene/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/codescene/canonical_descriptions.py
index fe0482d6c255..c343e887de3e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/codescene/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/codescene/canonical_descriptions.py
@@ -35,4 +35,63 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"lines_of_code": "Number of lines of code in the component.",
},
},
+ "Analyses": {
+ "description": "The analysis runs recorded for a CodeScene project, newest first.",
+ "docs_url": "https://docs.enterprise.codescene.io/latest/integrations/rest-api.html",
+ "columns": {
+ "project_id": "Identifier of the CodeScene project this analysis ran for.",
+ "id": "Unique identifier of the analysis run, usable in place of `latest` on the analysis endpoints.",
+ "name": "Display name of the analysis run.",
+ "ref": "API path of the analysis resource.",
+ },
+ },
+ "Issues": {
+ "description": "Issues from a project's latest analysis, linking ticket data to the code changed while the issue was open.",
+ "docs_url": "https://docs.enterprise.codescene.io/latest/integrations/rest-api.html",
+ "columns": {
+ "project_id": "Identifier of the CodeScene project this issue belongs to.",
+ "id": "Issue identifier taken from the commit messages, for example a ticket key.",
+ "status": "Status of the issue as reported by the project management integration.",
+ "date": "Date the issue was first seen in the commit history.",
+ "closed_at": "Date the issue was closed.",
+ "cycle_time_hours": "Hours between the first and last commit that reference the issue.",
+ "first_commit": "Hash of the first commit that references the issue.",
+ "last_commit": "Hash of the last commit that references the issue.",
+ "authors": "Number of authors who committed against the issue.",
+ "files": "Number of files changed while the issue was open.",
+ "loc_added": "Lines of code added across the issue's commits.",
+ "loc_deleted": "Lines of code deleted across the issue's commits.",
+ "file_changes": "Per-file breakdown of the lines added and deleted for the issue.",
+ "href": "Link to the issue in the project management tool.",
+ },
+ },
+ "TechnicalDebt": {
+ "description": "Refactoring targets from a project's latest analysis: the hotspots CodeScene recommends paying down first.",
+ "docs_url": "https://docs.enterprise.codescene.io/latest/integrations/rest-api.html",
+ "columns": {
+ "project_id": "Identifier of the CodeScene project this refactoring target belongs to.",
+ "file_name": "Repository-relative path of the file recommended for refactoring.",
+ "score": "Code Health score of the file (1-10, 10 being the healthiest).",
+ "revisions": "Number of times the file changed over the analysis period.",
+ },
+ },
+ "AuthorStatistics": {
+ "description": "Per-author contribution statistics from a project's latest analysis.",
+ "docs_url": "https://docs.enterprise.codescene.io/latest/integrations/rest-api.html",
+ "columns": {
+ "project_id": "Identifier of the CodeScene project these statistics cover.",
+ "author": "Name of the author, as recorded in the commit history.",
+ "commits": "Number of commits the author made over the analysis period.",
+ "lines_of_code_added": "Lines of code the author added.",
+ "lines_of_code_removed": "Lines of code the author removed.",
+ "lines_of_code_net": "Lines added minus lines removed.",
+ "first_contribution": "Date of the author's first commit.",
+ "last_contribution": "Date of the author's most recent commit.",
+ "months_contributing": "Number of months between the author's first and last commit.",
+ "primary_file_owner": "Number of files where the author contributed most of the code.",
+ "primary_component_owner": "Number of architectural components where the author contributed most of the code.",
+ "commit_pattern": "Description of when the author commits, for example working hours or weekends.",
+ "former_contributor": "Whether the author is marked as a former contributor in CodeScene.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/codescene/codescene.py b/products/warehouse_sources/backend/temporal/data_imports/sources/codescene/codescene.py
index 6414dad38088..814e53333a31 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/codescene/codescene.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/codescene/codescene.py
@@ -8,7 +8,10 @@ from requests.exceptions import RequestException
from posthog.cloud_utils import is_cloud
-from products.warehouse_sources.backend.temporal.data_imports.sources.codescene.settings import CODESCENE_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.codescene.settings import (
+ CODESCENE_ENDPOINTS,
+ CodesceneEndpointConfig,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import _is_host_safe
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (
@@ -19,7 +22,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
build_dependent_resource,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ BasePaginator,
PageNumberPaginator,
+ SinglePagePaginator,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
ClientConfig,
@@ -118,7 +123,9 @@ def _client_config(base_url: str | None, api_token: str) -> ClientConfig:
}
-def _page_paginator() -> PageNumberPaginator:
+def _paginator(config: CodesceneEndpointConfig) -> BasePaginator:
+ if not config.paginated:
+ return SinglePagePaginator()
# CodeScene's paginated list endpoints default to page 1 and report `max_pages` in the
# response body so the last page can be detected without an extra empty-page request.
return PageNumberPaginator(base_page=1, page=1, page_param="page", total_path="max_pages")
@@ -157,12 +164,13 @@ def _get_resource(endpoint: str) -> EndpointResource:
"write_disposition": "replace",
"endpoint": {
"path": config.path,
- "params": {"page_size": config.page_size},
+ "params": {config.page_size_param: config.page_size} if config.page_size_param else {},
"data_selector": config.data_selector,
- # The wrapper key is documented, so a response without it means the API shape
- # changed — fail loud rather than silently syncing 0 rows.
+ # The response shape is documented, so a body without the wrapper key (or, for an
+ # envelope-free endpoint, a body that isn't a list) means the API changed — fail
+ # loud rather than silently syncing 0 rows.
"data_selector_required": True,
- "paginator": _page_paginator(),
+ "paginator": _paginator(config),
},
"table_format": "delta",
}
@@ -207,16 +215,18 @@ def codescene_source(
team_id=team_id,
job_id=job_id,
db_incremental_field_last_value=None,
- page_size_param="page_size",
+ # One setting covers parent and child, so a child endpoint that takes no
+ # page-size param also leaves the projects listing on the server default.
+ page_size_param=endpoint_config.page_size_param,
parent_endpoint_extra={
"data_selector": parent_config.data_selector,
"data_selector_required": True,
- "paginator": _page_paginator(),
+ "paginator": _paginator(parent_config),
},
child_endpoint_extra={
"data_selector": endpoint_config.data_selector,
"data_selector_required": True,
- "paginator": _page_paginator(),
+ "paginator": _paginator(endpoint_config),
},
),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/codescene/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/codescene/settings.py
index a37aa52bc554..ad95d202a09d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/codescene/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/codescene/settings.py
@@ -1,23 +1,31 @@
-from dataclasses import dataclass, field
+from dataclasses import field
+
+from posthog.dataclasses import frozen
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
DependentEndpointConfig,
)
from products.warehouse_sources.backend.types import IncrementalField
-# CodeScene has no documented server-side timestamp filter for these endpoints (the `analyses`
-# list/detail shape isn't publicly documented), so every endpoint here is full refresh only.
+# CodeScene's list endpoints take a generic `filter` expression but no server-side timestamp
+# filter, so every endpoint here is full refresh only.
INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}
-@dataclass
+@frozen
class CodesceneEndpointConfig:
name: str
path: str
# Key holding the row array in the response body (e.g. `{"projects": [...], "max_pages": 3}`).
- data_selector: str
+ # `None` for an endpoint that returns a bare array with no envelope.
+ data_selector: str | None
primary_key: str | list[str] = "id"
page_size: int = 100
+ # The endpoints differ in what they page on: most take `page` + `page_size` and report
+ # `max_pages`, `analyses` pages on `page` alone, and `author-statistics` returns the whole
+ # collection in a single unpaginated response.
+ paginated: bool = True
+ page_size_param: str | None = "page_size"
fanout: DependentEndpointConfig | None = None
# No endpoint here has a documented server-side timestamp filter, so every stream is full
# refresh; these stay empty but satisfy the fan-out helper's endpoint protocol.
@@ -58,6 +66,66 @@ CODESCENE_ENDPOINTS: dict[str, CodesceneEndpointConfig] = {
parent_field_renames={"id": "project_id"},
),
),
+ "Analyses": CodesceneEndpointConfig(
+ name="Analyses",
+ path="/projects/{project_id}/analyses",
+ data_selector="analyses",
+ primary_key=["project_id", "id"],
+ page_size_param=None,
+ fanout=DependentEndpointConfig(
+ parent_name="Projects",
+ resolve_param="project_id",
+ resolve_field="id",
+ include_from_parent=["id"],
+ parent_field_renames={"id": "project_id"},
+ ),
+ ),
+ "Issues": CodesceneEndpointConfig(
+ name="Issues",
+ path="/projects/{project_id}/analyses/latest/issues",
+ data_selector="issues",
+ primary_key=["project_id", "id"],
+ page_size=200,
+ fanout=DependentEndpointConfig(
+ parent_name="Projects",
+ resolve_param="project_id",
+ resolve_field="id",
+ include_from_parent=["id"],
+ parent_field_renames={"id": "project_id"},
+ ),
+ ),
+ "TechnicalDebt": CodesceneEndpointConfig(
+ name="TechnicalDebt",
+ path="/projects/{project_id}/analyses/latest/technical-debt",
+ data_selector="result",
+ primary_key=["project_id", "file_name"],
+ page_size=200,
+ fanout=DependentEndpointConfig(
+ parent_name="Projects",
+ resolve_param="project_id",
+ resolve_field="id",
+ include_from_parent=["id"],
+ parent_field_renames={"id": "project_id"},
+ # Without this the endpoint returns the friction summary rather than the
+ # per-file refactoring targets.
+ child_params={"refactoring_targets": "true"},
+ ),
+ ),
+ "AuthorStatistics": CodesceneEndpointConfig(
+ name="AuthorStatistics",
+ path="/projects/{project_id}/analyses/latest/author-statistics",
+ data_selector=None,
+ primary_key=["project_id", "author"],
+ paginated=False,
+ page_size_param=None,
+ fanout=DependentEndpointConfig(
+ parent_name="Projects",
+ resolve_param="project_id",
+ resolve_field="id",
+ include_from_parent=["id"],
+ parent_field_renames={"id": "project_id"},
+ ),
+ ),
}
ENDPOINTS = tuple(CODESCENE_ENDPOINTS)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/codescene/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/codescene/source.py
index 7132db77b3c2..c00b600eede9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/codescene/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/codescene/source.py
@@ -56,7 +56,7 @@ class CodesceneSource(ResumableSource[CodesceneSourceConfig, CodesceneResumeConf
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="CodeScene",
releaseStatus=ReleaseStatus.ALPHA,
- caption="""Sync projects, per-file Code Health metrics, and architectural components from CodeScene.
+ caption="""Sync projects, analysis runs, per-file Code Health metrics, architectural components, code health issues, technical debt refactoring targets, and author statistics from CodeScene.
Create a Personal Access Token from the CodeScene API tokens page with an Admin, Architect, or RestApi role. Leave the API base URL blank to use CodeScene Cloud, or enter your on-prem CodeScene server's API URL (for example `https://codescene.yourcompany.com:3003/api/v2`).""",
iconPath="/static/services/codescene.png",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/codescene/tests/test_codescene.py b/products/warehouse_sources/backend/temporal/data_imports/sources/codescene/tests/test_codescene.py
index 21d4c24b7aee..193a73fdb0e6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/codescene/tests/test_codescene.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/codescene/tests/test_codescene.py
@@ -14,6 +14,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.codescene.
validate_credentials,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.codescene.settings import CODESCENE_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ PageNumberPaginator,
+ SinglePagePaginator,
+)
class _FakeDltResource:
@@ -248,44 +252,72 @@ class TestCodesceneSourceFanout:
# part of the key.
assert response.primary_keys == ["project_id", "name"]
+ @parameterized.expand(
+ [
+ ("files", "Files", "files", "page_size", PageNumberPaginator),
+ ("components", "Components", "components", "page_size", PageNumberPaginator),
+ # The analyses list pages on `page` alone, so no page-size param goes out.
+ ("analyses", "Analyses", "analyses", None, PageNumberPaginator),
+ ("issues", "Issues", "issues", "page_size", PageNumberPaginator),
+ ("technical_debt", "TechnicalDebt", "result", "page_size", PageNumberPaginator),
+ # Author statistics comes back as a bare array with no envelope and no pagination.
+ ("author_statistics", "AuthorStatistics", None, None, SinglePagePaginator),
+ ]
+ )
@patch(
"products.warehouse_sources.backend.temporal.data_imports.sources.codescene.codescene.build_dependent_resource"
)
- def test_files_fanout_wiring(self, mock_build_dependent_resource: MagicMock) -> None:
+ def test_fanout_wiring(
+ self,
+ _name: str,
+ endpoint: str,
+ data_selector: str | None,
+ page_size_param: str | None,
+ paginator_type: type,
+ mock_build_dependent_resource: MagicMock,
+ ) -> None:
mock_build_dependent_resource.return_value = iter([])
codescene_source(
api_token="token",
base_url=None,
- endpoint="Files",
+ endpoint=endpoint,
team_id=1,
job_id="job-1",
resumable_source_manager=_make_fake_manager(),
)
kwargs = mock_build_dependent_resource.call_args.kwargs
- assert kwargs["page_size_param"] == "page_size"
+ assert kwargs["page_size_param"] == page_size_param
assert kwargs["parent_endpoint_extra"]["data_selector"] == "projects"
- assert kwargs["child_endpoint_extra"]["data_selector"] == "files"
- assert kwargs["fanout"] is CODESCENE_ENDPOINTS["Files"].fanout
+ assert kwargs["child_endpoint_extra"]["data_selector"] == data_selector
+ assert isinstance(kwargs["child_endpoint_extra"]["paginator"], paginator_type)
+ assert kwargs["fanout"] is CODESCENE_ENDPOINTS[endpoint].fanout
@patch(
- "products.warehouse_sources.backend.temporal.data_imports.sources.codescene.codescene.build_dependent_resource"
+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout.rest_api_resources"
)
- def test_components_fanout_wiring(self, mock_build_dependent_resource: MagicMock) -> None:
- mock_build_dependent_resource.return_value = iter([])
+ def test_technical_debt_asks_for_refactoring_targets(self, mock_rest_api_resources: MagicMock) -> None:
+ # Without the flag the endpoint answers with the friction summary under the same
+ # `result` key, so dropping it would sync the wrong rows without failing.
+ mock_rest_api_resources.return_value = [
+ _FakeDltResource("Projects", []),
+ _FakeDltResource("TechnicalDebt", []),
+ ]
codescene_source(
api_token="token",
base_url=None,
- endpoint="Components",
+ endpoint="TechnicalDebt",
team_id=1,
job_id="job-1",
resumable_source_manager=_make_fake_manager(),
)
- kwargs = mock_build_dependent_resource.call_args.kwargs
- assert kwargs["child_endpoint_extra"]["data_selector"] == "components"
+ config = mock_rest_api_resources.call_args.args[0]
+ child = next(resource for resource in config["resources"] if resource["name"] == "TechnicalDebt")
+ assert child["endpoint"]["params"]["refactoring_targets"] == "true"
+ assert child["endpoint"]["params"]["project_id"]["type"] == "resolve"
class TestCodesceneEndpointCatalog:
@@ -295,7 +327,10 @@ class TestCodesceneEndpointCatalog:
assert primary_key
def test_fanout_endpoints_key_on_parent_id(self) -> None:
- for endpoint in ("Files", "Components"):
- config = CODESCENE_ENDPOINTS[endpoint]
- assert isinstance(config.primary_key, list)
- assert "project_id" in config.primary_key
+ # Every fan-out table aggregates rows from all projects, so a key that is only
+ # unique within a project seeds duplicates the merge then multi-matches.
+ for endpoint, config in CODESCENE_ENDPOINTS.items():
+ if config.fanout is None:
+ continue
+ assert isinstance(config.primary_key, list), endpoint
+ assert "project_id" in config.primary_key, endpoint