:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): add 38 tables to the GitHub source (#73856)
Tom Owersadb0b5d3d6d8
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/canonical_descriptions.pyindex 202ad279bdd3..d2289e8393e8 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/github/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/canonical_descriptions.py@@ -230,4 +230,518 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"html_url": "Web URL for the member's GitHub profile.",},},+ "repository": {+ "description": "The repository itself — one row carrying its metadata, counts, and settings.",+ "docs_url": "https://docs.github.com/en/rest/repos/repos",+ "columns": {+ "id": "Unique identifier for the repository.",+ "name": "The repository's name.",+ "full_name": "The repository's owner and name, as owner/repo.",+ "owner": "The user or organization that owns the repository.",+ "description": "The repository's description.",+ "private": "Whether the repository is private.",+ "visibility": "The repository's visibility (public, private, or internal).",+ "fork": "Whether the repository is a fork of another repository.",+ "archived": "Whether the repository is archived and read-only.",+ "language": "The repository's primary language.",+ "default_branch": "Name of the repository's default branch.",+ "topics": "Topics applied to the repository.",+ "license": "The repository's license, if one is detected.",+ "size": "Approximate size of the repository in kilobytes.",+ "stargazers_count": "Number of users who have starred the repository.",+ "watchers_count": "Number of users watching the repository.",+ "forks_count": "Number of forks of the repository.",+ "subscribers_count": "Number of users subscribed to the repository's notifications.",+ "open_issues_count": "Number of open issues and pull requests.",+ "created_at": "Time at which the repository was created.",+ "updated_at": "Time at which the repository was last updated.",+ "pushed_at": "Time of the most recent push to the repository.",+ },+ },+ "topics": {+ "description": "A topic applied to the repository. One row per topic, with the repository attached.",+ "docs_url": "https://docs.github.com/en/rest/repos/repos#get-all-repository-topics",+ "columns": {+ "repository": "The repository the topic is applied to, as owner/repo.",+ "name": "The topic name.",+ },+ },+ "languages": {+ "description": "A language detected in the repository and how many bytes of code use it. One row per language.",+ "docs_url": "https://docs.github.com/en/rest/repos/repos#list-repository-languages",+ "columns": {+ "repository": "The repository the language was detected in, as owner/repo.",+ "language": "The language name.",+ "bytes": "Number of bytes of code written in this language.",+ },+ },+ "community_profile": {+ "description": "The repository's community health metrics — one row scoring the presence of a readme, license, contributing guide, and templates.",+ "docs_url": "https://docs.github.com/en/rest/metrics/community",+ "columns": {+ "repository": "The repository the metrics describe, as owner/repo.",+ "health_percentage": "Community health score, from 0 to 100.",+ "description": "The repository's description.",+ "documentation": "URL of the repository's documentation, if set.",+ "files": "The community health files that were found (readme, license, contributing, code of conduct, templates).",+ "content_reports_enabled": "Whether content reporting is enabled on the repository.",+ "updated_at": "Time at which the community profile was last updated.",+ },+ },+ "issue_comments": {+ "description": "A comment on an issue or pull request conversation, across the whole repository.",+ "docs_url": "https://docs.github.com/en/rest/issues/comments",+ "columns": {+ "id": "Unique identifier for the comment.",+ "issue_url": "API URL for the issue or pull request the comment was posted on.",+ "user": "The user who wrote the comment.",+ "body": "The comment's text in markdown.",+ "author_association": "The commenter's relationship to the repository (e.g. MEMBER, COLLABORATOR, CONTRIBUTOR).",+ "reactions": "Reaction counts on the comment.",+ "html_url": "Web URL for the comment on GitHub.",+ "created_at": "Time at which the comment was created.",+ "updated_at": "Time at which the comment was last edited.",+ },+ },+ "pull_request_comments": {+ "description": "A review comment on a pull request — a comment anchored to a line of the diff — across the whole repository.",+ "docs_url": "https://docs.github.com/en/rest/pulls/comments",+ "columns": {+ "id": "Unique identifier for the review comment.",+ "pull_request_url": "API URL for the pull request the comment was posted on.",+ "pull_request_review_id": "Identifier of the review this comment was submitted as part of, if any.",+ "in_reply_to_id": "Identifier of the comment this one replies to, if any.",+ "user": "The user who wrote the comment.",+ "body": "The comment's text in markdown.",+ "path": "Path of the file the comment is anchored to.",+ "line": "Line of the file the comment is anchored to in the latest diff.",+ "side": "Side of the diff the comment is on (LEFT or RIGHT).",+ "diff_hunk": "The portion of the diff the comment is anchored to.",+ "commit_id": "SHA of the commit the comment applies to.",+ "author_association": "The commenter's relationship to the repository.",+ "created_at": "Time at which the comment was created.",+ "updated_at": "Time at which the comment was last edited.",+ },+ },+ "issue_events": {+ "description": "A state transition on an issue or pull request — labeled, assigned, closed, reopened, and similar — used for time-in-state analysis.",+ "docs_url": "https://docs.github.com/en/rest/issues/events",+ "columns": {+ "id": "Unique identifier for the event.",+ "event": "The kind of transition (e.g. labeled, assigned, closed, reopened, merged).",+ "actor": "The user who performed the action.",+ "issue": "The issue or pull request the event happened on.",+ "label": "The label added or removed, for label events.",+ "assignee": "The user assigned or unassigned, for assignment events.",+ "milestone": "The milestone added or removed, for milestone events.",+ "rename": "The previous and new titles, for rename events.",+ "commit_id": "SHA of the commit referenced by the event, if any.",+ "created_at": "Time at which the event happened.",+ },+ },+ "labels": {+ "description": "A label defined in the repository and available to apply to issues and pull requests.",+ "docs_url": "https://docs.github.com/en/rest/issues/labels",+ "columns": {+ "id": "Unique identifier for the label.",+ "name": "The label's name.",+ "description": "The label's description.",+ "color": "Hex color code for the label, without the leading #.",+ "default": "Whether the label is one of GitHub's defaults.",+ },+ },+ "milestones": {+ "description": "A milestone grouping issues and pull requests toward a target date.",+ "docs_url": "https://docs.github.com/en/rest/issues/milestones",+ "columns": {+ "id": "Unique identifier for the milestone.",+ "number": "Number uniquely identifying the milestone within its repository.",+ "title": "The milestone's title.",+ "description": "The milestone's description.",+ "state": "Whether the milestone is open or closed.",+ "creator": "The user who created the milestone.",+ "open_issues": "Number of open issues assigned to the milestone.",+ "closed_issues": "Number of closed issues assigned to the milestone.",+ "due_on": "Date the milestone is due, if set.",+ "created_at": "Time at which the milestone was created.",+ "updated_at": "Time at which the milestone was last updated.",+ "closed_at": "Time at which the milestone was closed, if applicable.",+ },+ },+ "branches": {+ "description": "A branch in the repository. Keyed by name, since branches carry no identifier.",+ "docs_url": "https://docs.github.com/en/rest/branches/branches",+ "columns": {+ "name": "The branch's name, unique within the repository.",+ "commit": "The commit the branch currently points at.",+ "protected": "Whether branch protection rules apply to the branch.",+ "protection": "The branch protection settings, when protected.",+ },+ },+ "tags": {+ "description": "A git tag in the repository. Keyed by name, since tags carry no identifier.",+ "docs_url": "https://docs.github.com/en/rest/repos/repos#list-repository-tags",+ "columns": {+ "name": "The tag's name, unique within the repository.",+ "commit": "The commit the tag points at.",+ "node_id": "Global node ID for the tag.",+ "zipball_url": "URL to download a zip archive of the tagged source code.",+ "tarball_url": "URL to download a tar archive of the tagged source code.",+ },+ },+ "contributors": {+ "description": "A user who has contributed commits to the repository, with their commit count.",+ "docs_url": "https://docs.github.com/en/rest/repos/repos#list-repository-contributors",+ "columns": {+ "id": "Unique identifier for the contributor.",+ "login": "Username of the contributor.",+ "contributions": "Number of commits the user has contributed to the repository.",+ "type": "Type of account (User, Bot, or Anonymous).",+ "site_admin": "Whether the contributor is a GitHub site administrator.",+ "avatar_url": "URL of the contributor's avatar image.",+ "html_url": "Web URL for the contributor's GitHub profile.",+ },+ },+ "collaborators": {+ "description": "A user with access to the repository, and the permission level they hold.",+ "docs_url": "https://docs.github.com/en/rest/collaborators/collaborators",+ "columns": {+ "id": "Unique identifier for the collaborator.",+ "login": "Username of the collaborator.",+ "role_name": "Name of the role granted to the collaborator (e.g. read, write, admin).",+ "permissions": "The individual permissions the collaborator holds on the repository.",+ "type": "Type of account (User or Bot).",+ "site_admin": "Whether the collaborator is a GitHub site administrator.",+ "html_url": "Web URL for the collaborator's GitHub profile.",+ },+ },+ "subscribers": {+ "description": "A user watching the repository for notifications.",+ "docs_url": "https://docs.github.com/en/rest/activity/watching",+ "columns": {+ "id": "Unique identifier for the watcher.",+ "login": "Username of the watcher.",+ "type": "Type of account (User or Bot).",+ "site_admin": "Whether the watcher is a GitHub site administrator.",+ "html_url": "Web URL for the watcher's GitHub profile.",+ },+ },+ "forks": {+ "description": "A repository forked from this one.",+ "docs_url": "https://docs.github.com/en/rest/repos/forks",+ "columns": {+ "id": "Unique identifier for the forked repository.",+ "full_name": "The fork's owner and name, as owner/repo.",+ "owner": "The user or organization that owns the fork.",+ "private": "Whether the fork is private.",+ "stargazers_count": "Number of users who have starred the fork.",+ "forks_count": "Number of forks of the fork.",+ "default_branch": "Name of the fork's default branch.",+ "created_at": "Time at which the fork was created.",+ "updated_at": "Time at which the fork was last updated.",+ "pushed_at": "Time of the most recent push to the fork.",+ },+ },+ "environments": {+ "description": "A deployment environment configured on the repository.",+ "docs_url": "https://docs.github.com/en/rest/deployments/environments",+ "columns": {+ "id": "Unique identifier for the environment.",+ "name": "The environment's name.",+ "protection_rules": "Protection rules gating deployments to the environment (reviewers, wait timer, branch policy).",+ "deployment_branch_policy": "Which branches and tags may deploy to the environment.",+ "html_url": "Web URL for the environment on GitHub.",+ "created_at": "Time at which the environment was created.",+ "updated_at": "Time at which the environment was last updated.",+ },+ },+ "workflows": {+ "description": "A GitHub Actions workflow defined in the repository.",+ "docs_url": "https://docs.github.com/en/rest/actions/workflows",+ "columns": {+ "id": "Unique identifier for the workflow.",+ "name": "The workflow's name.",+ "path": "Path to the workflow file in the repository.",+ "state": "Whether the workflow is active, disabled, or deleted.",+ "badge_url": "URL of the workflow's status badge.",+ "html_url": "Web URL for the workflow on GitHub.",+ "created_at": "Time at which the workflow was created.",+ "updated_at": "Time at which the workflow was last updated.",+ "deleted_at": "Time at which the workflow was deleted, if applicable.",+ },+ },+ "artifacts": {+ "description": "An artifact uploaded by a GitHub Actions workflow run.",+ "docs_url": "https://docs.github.com/en/rest/actions/artifacts",+ "columns": {+ "id": "Unique identifier for the artifact.",+ "name": "The artifact's name.",+ "size_in_bytes": "Size of the artifact in bytes.",+ "expired": "Whether the artifact has passed its retention period and been deleted.",+ "expires_at": "Time at which the artifact expires.",+ "digest": "Digest of the artifact's contents, if available.",+ "workflow_run": "The workflow run that produced the artifact.",+ "archive_download_url": "API URL to download the artifact archive.",+ "created_at": "Time at which the artifact was created.",+ "updated_at": "Time at which the artifact was last updated.",+ },+ },+ "runners": {+ "description": "A self-hosted GitHub Actions runner registered to the repository.",+ "docs_url": "https://docs.github.com/en/rest/actions/self-hosted-runners",+ "columns": {+ "id": "Unique identifier for the runner.",+ "name": "The runner's name.",+ "os": "Operating system the runner runs on.",+ "status": "Whether the runner is online or offline.",+ "busy": "Whether the runner is currently executing a job.",+ "ephemeral": "Whether the runner is ephemeral and retired after one job.",+ "labels": "Labels assigned to the runner, used to route jobs to it.",+ "runner_group_id": "Identifier of the runner group the runner belongs to.",+ },+ },+ "actions_caches": {+ "description": "A GitHub Actions cache entry stored for the repository.",+ "docs_url": "https://docs.github.com/en/rest/actions/cache",+ "columns": {+ "id": "Unique identifier for the cache entry.",+ "key": "The cache key the entry was saved under.",+ "ref": "The git ref the cache entry is scoped to.",+ "version": "Version hash distinguishing entries that share a key.",+ "size_in_bytes": "Size of the cache entry in bytes.",+ "created_at": "Time at which the cache entry was created.",+ "last_accessed_at": "Time at which the cache entry was last read.",+ },+ },+ "check_runs": {+ "description": "A check run reported against a commit — the per-commit CI signal that complements workflow runs. Assembled by fanning out over commits, since GitHub has no repository-wide check runs list.",+ "docs_url": "https://docs.github.com/en/rest/checks/runs",+ "columns": {+ "id": "Unique identifier for the check run.",+ "name": "The check run's name.",+ "head_sha": "SHA of the commit the check run reports on.",+ "status": "Current execution status (queued, in_progress, or completed).",+ "conclusion": "Final result of the check run (e.g. success, failure, neutral, skipped).",+ "check_suite": "The check suite the run belongs to.",+ "app": "The GitHub App that created the check run.",+ "output": "The check run's title, summary, and annotation counts.",+ "pull_requests": "Pull requests the check run is associated with.",+ "details_url": "URL of the integrator's page with full details for the run.",+ "started_at": "Time at which the check run started.",+ "completed_at": "Time at which the check run completed, if applicable.",+ },+ },+ "commit_statuses": {+ "description": "A commit status posted against a commit by an external service, with the commit's SHA attached for attribution.",+ "docs_url": "https://docs.github.com/en/rest/commits/statuses",+ "columns": {+ "id": "Identifier for the status, unique within its commit.",+ "commit_sha": "SHA of the commit the status was posted against (injected from the parent commit).",+ "state": "The status state (error, failure, pending, or success).",+ "context": "Label identifying which service posted the status.",+ "description": "Short human-readable description of the status.",+ "target_url": "URL with more detail about the status.",+ "creator": "The user or app that posted the status.",+ "created_at": "Time at which the status was posted.",+ "updated_at": "Time at which the status was last updated.",+ },+ },+ "code_scanning_alerts": {+ "description": "A code scanning alert raised on the repository by CodeQL or another analysis tool.",+ "docs_url": "https://docs.github.com/en/rest/code-scanning/code-scanning",+ "columns": {+ "number": "Number uniquely identifying the alert within its repository.",+ "state": "The alert's state (open, dismissed, or fixed).",+ "rule": "The analysis rule that raised the alert, including its severity and description.",+ "tool": "The analysis tool that raised the alert.",+ "most_recent_instance": "The most recent occurrence of the alert, including its location.",+ "instances_url": "API URL listing every occurrence of the alert.",+ "dismissed_reason": "Why the alert was dismissed, if applicable.",+ "dismissed_by": "The user who dismissed the alert, if applicable.",+ "dismissed_at": "Time at which the alert was dismissed, if applicable.",+ "fixed_at": "Time at which the alert was fixed, if applicable.",+ "created_at": "Time at which the alert was first raised.",+ "updated_at": "Time at which the alert was last updated.",+ },+ },+ "dependabot_alerts": {+ "description": "A Dependabot alert for a vulnerable dependency of the repository.",+ "docs_url": "https://docs.github.com/en/rest/dependabot/alerts",+ "columns": {+ "number": "Number uniquely identifying the alert within its repository.",+ "state": "The alert's state (auto_dismissed, dismissed, fixed, or open).",+ "dependency": "The vulnerable dependency, its ecosystem, and the manifest it came from.",+ "security_advisory": "The advisory describing the vulnerability.",+ "security_vulnerability": "The specific vulnerable version range and its first patched version.",+ "dismissed_reason": "Why the alert was dismissed, if applicable.",+ "dismissed_by": "The user who dismissed the alert, if applicable.",+ "dismissed_at": "Time at which the alert was dismissed, if applicable.",+ "auto_dismissed_at": "Time at which the alert was auto-dismissed, if applicable.",+ "fixed_at": "Time at which the alert was fixed, if applicable.",+ "created_at": "Time at which the alert was raised.",+ "updated_at": "Time at which the alert was last updated.",+ },+ },+ "secret_scanning_alerts": {+ "description": "A secret scanning alert for a credential detected in the repository. The detected secret value itself is never synced — only the metadata about it.",+ "docs_url": "https://docs.github.com/en/rest/secret-scanning/secret-scanning",+ "columns": {+ "number": "Number uniquely identifying the alert within its repository.",+ "state": "The alert's state (open or resolved).",+ "secret_type": "Identifier of the kind of secret that was detected.",+ "secret_type_display_name": "Human-readable name of the kind of secret that was detected.",+ "validity": "Whether the detected secret is still active (active, inactive, or unknown).",+ "publicly_leaked": "Whether the secret was also found in a public repository.",+ "resolution": "How the alert was resolved, if applicable.",+ "resolved_by": "The user who resolved the alert, if applicable.",+ "resolved_at": "Time at which the alert was resolved, if applicable.",+ "push_protection_bypassed": "Whether push protection was bypassed to commit the secret.",+ "locations_url": "API URL listing where the secret was detected.",+ "created_at": "Time at which the alert was raised.",+ "updated_at": "Time at which the alert was last updated.",+ },+ },+ "security_advisories": {+ "description": "A security advisory published or drafted on the repository.",+ "docs_url": "https://docs.github.com/en/rest/security-advisories/repository-advisories",+ "columns": {+ "ghsa_id": "GitHub Security Advisory identifier, unique across GitHub.",+ "cve_id": "The advisory's CVE identifier, if one was assigned.",+ "summary": "Short summary of the advisory.",+ "description": "Full description of the advisory.",+ "severity": "Severity of the advisory (low, medium, high, or critical).",+ "state": "The advisory's state (triage, draft, published, or closed).",+ "cvss": "CVSS score and vector string for the advisory.",+ "cwes": "Common Weakness Enumeration entries the advisory maps to.",+ "vulnerabilities": "The affected packages and version ranges.",+ "credits": "Users credited for reporting or fixing the advisory.",+ "author": "The user who opened the advisory.",+ "publisher": "The user who published the advisory, if applicable.",+ "published_at": "Time at which the advisory was published, if applicable.",+ "withdrawn_at": "Time at which the advisory was withdrawn, if applicable.",+ "closed_at": "Time at which the advisory was closed, if applicable.",+ "created_at": "Time at which the advisory was created.",+ "updated_at": "Time at which the advisory was last updated.",+ },+ },+ "dependency_sbom": {+ "description": "A package in the repository's software bill of materials. One row per SPDX package in the dependency graph export.",+ "docs_url": "https://docs.github.com/en/rest/dependency-graph/sboms",+ "columns": {+ "repository": "The repository the SBOM was exported for, as owner/repo.",+ "document_name": "Name of the SPDX document the package came from.",+ "spdx_id": "SPDX identifier for the package, unique within the document.",+ "name": "The package's name.",+ "versionInfo": "The package's version, or a version range when no exact version is resolved.",+ "licenseConcluded": "License concluded for the package by the analysis.",+ "licenseDeclared": "License declared by the package itself.",+ "supplier": "The package's supplier.",+ "externalRefs": "External references for the package, including its package URL.",+ },+ },+ "rulesets": {+ "description": "A ruleset defining branch, tag, or push rules for the repository.",+ "docs_url": "https://docs.github.com/en/rest/repos/rules",+ "columns": {+ "id": "Unique identifier for the ruleset.",+ "name": "The ruleset's name.",+ "target": "What the ruleset applies to (branch, tag, or push).",+ "enforcement": "Whether the ruleset is disabled, active, or in evaluate mode.",+ "source": "The repository or organization the ruleset is defined on.",+ "source_type": "Whether the ruleset comes from the repository or its organization.",+ "rules": "The individual rules the ruleset enforces.",+ "bypass_actors": "Actors allowed to bypass the ruleset.",+ "created_at": "Time at which the ruleset was created.",+ "updated_at": "Time at which the ruleset was last updated.",+ },+ },+ "hooks": {+ "description": "A webhook configured on the repository. GitHub never returns the signing secret, so it is not synced.",+ "docs_url": "https://docs.github.com/en/rest/repos/webhooks",+ "columns": {+ "id": "Unique identifier for the webhook.",+ "name": "The webhook's type name (always web for repository webhooks).",+ "active": "Whether the webhook is enabled.",+ "events": "The events the webhook is subscribed to.",+ "config": "The webhook's delivery configuration (URL, content type, SSL verification).",+ "last_response": "Result of the most recent delivery attempt.",+ "created_at": "Time at which the webhook was created.",+ "updated_at": "Time at which the webhook was last updated.",+ },+ },+ "traffic_views": {+ "description": "Daily page views of the repository. GitHub only retains the last 14 days, so each sync refreshes that window.",+ "docs_url": "https://docs.github.com/en/rest/metrics/traffic",+ "columns": {+ "timestamp": "Start of the day the views were counted in.",+ "count": "Total page views in that day.",+ "uniques": "Number of unique visitors in that day.",+ },+ },+ "traffic_clones": {+ "description": "Daily clones of the repository. GitHub only retains the last 14 days, so each sync refreshes that window.",+ "docs_url": "https://docs.github.com/en/rest/metrics/traffic",+ "columns": {+ "timestamp": "Start of the day the clones were counted in.",+ "count": "Total clones in that day.",+ "uniques": "Number of unique cloners in that day.",+ },+ },+ "traffic_referrers": {+ "description": "A top referring site sending traffic to the repository over the last 14 days.",+ "docs_url": "https://docs.github.com/en/rest/metrics/traffic",+ "columns": {+ "referrer": "Domain of the referring site.",+ "count": "Total views referred by the site.",+ "uniques": "Number of unique visitors referred by the site.",+ },+ },+ "traffic_paths": {+ "description": "A top-visited path within the repository over the last 14 days.",+ "docs_url": "https://docs.github.com/en/rest/metrics/traffic",+ "columns": {+ "path": "The visited path, relative to github.com.",+ "title": "Page title shown for the path.",+ "count": "Total views of the path.",+ "uniques": "Number of unique visitors to the path.",+ },+ },+ "contributor_stats": {+ "description": "Per-contributor commit totals with a weekly additions, deletions, and commits breakdown. GitHub computes these asynchronously, so a sync started before the computation finishes returns no rows and the next sync picks them up.",+ "docs_url": "https://docs.github.com/en/rest/metrics/statistics",+ "columns": {+ "author_id": "Unique identifier for the contributor (flattened from author.id).",+ "author_login": "Username of the contributor (flattened from author.login).",+ "author": "The contributing user.",+ "total": "Total number of commits the contributor has authored.",+ "weeks": "Per-week breakdown, each entry holding the week start (w), additions (a), deletions (d), and commits (c).",+ },+ },+ "commit_activity_stats": {+ "description": "Weekly commit counts for the last year, broken down by day of week.",+ "docs_url": "https://docs.github.com/en/rest/metrics/statistics",+ "columns": {+ "week": "Unix timestamp of the start of the week.",+ "total": "Total commits in the week.",+ "days": "Commits per day of the week, starting with Sunday.",+ },+ },+ "participation_stats": {+ "description": "Weekly commit counts for the last 52 weeks, split between everyone and the repository owner. One row per repository, since the 52-week window rolls forward on every sync.",+ "docs_url": "https://docs.github.com/en/rest/metrics/statistics",+ "columns": {+ "repository": "The repository the counts describe, as owner/repo.",+ "all": "Commits per week from all contributors, oldest week first.",+ "owner": "Commits per week from the repository owner, oldest week first.",+ },+ },+ "code_frequency_stats": {+ "description": "Weekly additions and deletions across the repository's history. GitHub returns these as positional arrays, so the columns are named on the way in.",+ "docs_url": "https://docs.github.com/en/rest/metrics/statistics",+ "columns": {+ "week": "Unix timestamp of the start of the week.",+ "additions": "Lines added in the week.",+ "deletions": "Lines deleted in the week, as a negative number.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/github.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/github.pyindex caa5bfe2e6b6..757208eae30a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/github/github.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/github.py@@ -126,14 +126,19 @@ def _build_initial_params(if endpoint in _ALWAYS_NEWEST_FIRST_ENDPOINTS:return {"per_page": config.page_size}- params: dict[str, Any] = {- "per_page": config.page_size,- "state": "all",- # Default to created asc — created is immutable, so new items append- # to the end and don't shift already-fetched pages.- "sort": "created",- "direction": "asc",- }+ # Endpoints that take no sort at all (or a sort enum of their own, like milestones'+ # due_on/completeness) get a bare paged read plus whatever static params they declare.+ if config.param_style == "plain":+ return {"per_page": config.page_size, **(config.extra_params or {})}++ params: dict[str, Any] = {"per_page": config.page_size, **(config.extra_params or {})}+ if config.param_style == "issue_list":+ # The alert endpoints ("sorted") define their own state enum and reject `all`.+ params["state"] = "all"+ # Default to created asc — created is immutable, so new items append+ # to the end and don't shift already-fetched pages.+ params["sort"] = "created"+ params["direction"] = "asc"if should_use_incremental_field and db_incremental_field_last_value:formatted_value = _format_incremental_value(db_incremental_field_last_value)@@ -148,7 +153,7 @@ def _build_initial_params()params["sort"] = sort_field_mapping[incremental]params["direction"] = config.sort_mode- if endpoint in ("issues", "commits"):+ if endpoint in ("issues", "commits") or config.supports_since_param:params["since"] = formatted_valuereturn params@@ -183,13 +188,15 @@ def _resolve_sort_mode(configured sort once a cutoff exists. The _ALWAYS_NEWEST_FIRST_ENDPOINTS(workflow_runs, deployments) are different: they ignore sort/direction andalways return newest-first, so they emit desc on every sync, including the- first. Fan-out children inherit the parent walk's order on every sync too,- first incremental sync included: the initial_lookback_days floor gives that- sync a cutoff, which makes the parent walk descend. Reporting asc for any of- these would let the pipeline persist the cursor per batch and, on an- interrupted backfill, strand every row older than the batches that flushed.+ first; the ``always_desc`` config flag says the same for the plain-read+ endpoints added since (issue_events, forks). Fan-out children inherit the+ parent walk's order on every sync too, first incremental sync included: the+ initial_lookback_days floor gives that sync a cutoff, which makes the parent+ walk descend. Reporting asc for any of these would let the pipeline persist+ the cursor per batch and, on an interrupted backfill, strand every row older+ than the batches that flushed."""- if endpoint in _ALWAYS_NEWEST_FIRST_ENDPOINTS or config.fan_out_parent is not None:+ if endpoint in _ALWAYS_NEWEST_FIRST_ENDPOINTS or config.always_desc or config.fan_out_parent is not None:return config.sort_modeif should_use_incremental_field and db_incremental_field_last_value:return config.sort_mode@@ -436,11 +443,61 @@ def _make_parent_field_injector(return inject+def _flatten_contributor_stats(item: dict[str, Any]) -> dict[str, Any]:+ """Lift the contributor's id and login out of the nested author object so the row has a usable+ primary key and joins against `contributors` without unpacking JSON."""+ author = item.get("author")+ if isinstance(author, dict):+ item["author_id"] = author.get("id")+ item["author_login"] = author.get("login")+ return item+++def _redact_secret_scanning_alert(item: dict[str, Any]) -> dict[str, Any]:+ """Never land the leaked credential itself in a customer's warehouse — only the metadata about+ it. The request already asks GitHub for `hide_secret=true`, but strip the field here too so the+ guarantee doesn't depend on the pinned API version honoring that parameter."""+ item.pop("secret", None)+ return item+++# Repository objects that GitHub nests inside a repository object: a fork's parent and source, and a+# template-created repo's template_repository. Each is a full repository object, so it can carry the+# same clone credential and has to be sanitized too.+_NESTED_REPOSITORY_KEYS = ("parent", "source", "template_repository")+++def _redact_repository_secrets(item: dict[str, Any]) -> dict[str, Any]:+ """A repository object can carry `temp_clone_token`, a short-lived credential that clones the+ private repo. It must never reach the warehouse, where a user without GitHub access could read it+ and use it before it expires. Strip it here (the `repository` and `forks` tables are default-on)+ and recurse into the nested repository objects GitHub embeds."""+ item.pop("temp_clone_token", None)+ for key in _NESTED_REPOSITORY_KEYS:+ nested = item.get(key)+ if isinstance(nested, dict):+ _redact_repository_secrets(nested)+ return item+++def _has_contributor_author(item: dict[str, Any]) -> bool:+ """Drop anonymous contributor rows: the stats endpoint returns a null author for commits it+ can't attribute to an account, and author_id is this table's primary key."""+ author = item.get("author")+ return isinstance(author, dict) and author.get("id") is not None++def _get_item_mapper(endpoint: str) -> Callable[[dict[str, Any]], dict[str, Any]] | None:if endpoint == "commits":return _flatten_commitif endpoint == "stargazers":return _flatten_stargazer+ if endpoint == "contributor_stats":+ return _flatten_contributor_stats+ if endpoint == "secret_scanning_alerts":+ return _redact_secret_scanning_alert+ if endpoint == "forks":+ return _redact_repository_secretsreturn None@@ -449,9 +506,87 @@ def _get_item_filter(endpoint: str) -> Callable[[dict[str, Any]], bool] | None:return _is_issue_not_prif endpoint == "reviews":return _is_submitted_review+ if endpoint == "contributor_stats":+ return _has_contributor_authorreturn None+def _rows_from_repository(body: Any, repository: str) -> list[dict[str, Any]]:+ """/repos/{repo} answers with the repository object itself, not a list."""+ return [_redact_repository_secrets(body)] if isinstance(body, dict) and body else []+++def _rows_from_topics(body: Any, repository: str) -> list[dict[str, Any]]:+ """/topics answers {"names": [...]}; one row per topic keeps the table joinable."""+ names = body.get("names") if isinstance(body, dict) else None+ return [{"repository": repository, "name": name} for name in (names or []) if isinstance(name, str)]+++def _rows_from_languages(body: Any, repository: str) -> list[dict[str, Any]]:+ """/languages answers a {language: bytes} map, which has no fixed column set — one row per+ language instead, so a new language doesn't change the schema."""+ if not isinstance(body, dict):+ return []+ return [{"repository": repository, "language": language, "bytes": size} for language, size in body.items()]+++def _rows_from_community_profile(body: Any, repository: str) -> list[dict[str, Any]]:+ return [{"repository": repository, **body}] if isinstance(body, dict) and body else []+++def _rows_from_participation_stats(body: Any, repository: str) -> list[dict[str, Any]]:+ if not isinstance(body, dict) or not body:+ return []+ return [{"repository": repository, "all": body.get("all"), "owner": body.get("owner")}]+++def _rows_from_code_frequency(body: Any, repository: str) -> list[dict[str, Any]]:+ """/stats/code_frequency answers positional arrays ([week, additions, deletions]) rather than+ objects, so the columns are named here."""+ if not isinstance(body, list):+ return []+ return [+ {"week": entry[0], "additions": entry[1], "deletions": entry[2]}+ for entry in body+ if isinstance(entry, list | tuple) and len(entry) >= 3+ ]+++def _rows_from_dependency_sbom(body: Any, repository: str) -> list[dict[str, Any]]:+ """/dependency-graph/sbom answers one SPDX document; its packages are the grain a dependency+ inventory is queried at. SPDXID is renamed so the column follows the rest of the source."""+ sbom = body.get("sbom") if isinstance(body, dict) else None+ if not isinstance(sbom, dict):+ return []+ return [+ {+ "repository": repository,+ "document_name": sbom.get("name"),+ "spdx_id": package.get("SPDXID"),+ **{key: value for key, value in package.items() if key != "SPDXID"},+ }+ for package in (sbom.get("packages") or [])+ if isinstance(package, dict)+ ]+++# Endpoints whose response body is not a list of rows. The transform runs on the raw body and+# returns the rows for that page, replacing the `response_data_path` unwrap.+_BODY_TRANSFORMS: dict[str, Callable[[Any, str], list[dict[str, Any]]]] = {+ "repository": _rows_from_repository,+ "topics": _rows_from_topics,+ "languages": _rows_from_languages,+ "community_profile": _rows_from_community_profile,+ "participation_stats": _rows_from_participation_stats,+ "code_frequency_stats": _rows_from_code_frequency,+ "dependency_sbom": _rows_from_dependency_sbom,+}+++def _get_body_transform(endpoint: str) -> Callable[[Any, str], list[dict[str, Any]]] | None:+ return _BODY_TRANSFORMS.get(endpoint)++# Upper bound on how long we'll honor GitHub's rate-limit reset before retrying,# so a misreported reset header can't stall a worker indefinitely. The source# iterator runs in a thread pool while the activity's liveness heartbeat fires@@ -742,7 +877,13 @@ def _fan_out_get_rows(# _build_initial_params belong to list endpoints that define those params.parent_url = _build_initial_url(parent_config, repository, {"per_page": parent_config.page_size})- for parents, page_url in _iter_pages(+ # The parent walk bounds on the parent's own cursor column, which for commits only exists after+ # the mapper flattens commit.author.date onto the row — without it every sync would re-crawl the+ # repo's whole history. A no-op for the parents that have no mapper (pull_requests, teams,+ # workflow_runs).+ parent_mapper = _get_item_mapper(parent_config.name)++ for raw_parents, page_url in _iter_pages(parent_url,headers,parent_config.response_data_path,@@ -750,6 +891,7 @@ def _fan_out_get_rows(egress_identity=egress_identity,skip_on_not_found=parent_org_scoped,):+ parents = [parent_mapper(parent) for parent in raw_parents] if parent_mapper else raw_parentsstop_after_this_page = _should_stop_desc(parents, "desc", parent_cursor_field, parent_cutoff)for parent in parents:@@ -831,6 +973,7 @@ def get_rows(item_filter = _get_item_filter(endpoint)item_mapper = _get_item_mapper(endpoint)+ body_transform = _get_body_transform(endpoint)initial_params = _build_initial_params(config, endpoint, should_use_incremental_field, db_incremental_field_last_value, incremental_field@@ -854,10 +997,19 @@ def get_rows(logger.debug(f"Github: no accessible org teams for {endpoint}, syncing zero rows: url={url}")break+ # The /stats/* aggregates are computed asynchronously: GitHub answers 202 with no body+ # while a fresh computation runs. Nothing to sync this time; the next sync picks it up.+ if response.status_code == 202:+ logger.debug(f"Github: statistics not ready yet, syncing zero rows: url={url}")+ break+data = response.json()# Most GitHub list endpoints return a JSON array at the top level,- # but some (e.g. /actions/runs) wrap results in {"<resource>": [...]}.- if config.response_data_path and isinstance(data, dict):+ # but some (e.g. /actions/runs) wrap results in {"<resource>": [...]}, and a few+ # (/languages, /topics, the single-object reads) aren't row-shaped at all.+ if body_transform is not None:+ data = body_transform(data, repository)+ elif config.response_data_path and isinstance(data, dict):data = data.get(config.response_data_path, [])if not isinstance(data, list) or not data:breakdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/settings.pyindex 7ff5a35baace..3e3b18567b63 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/github/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/settings.py@@ -63,6 +63,31 @@ class GithubEndpointConfig:# an incremental fan-out skips parents whose value predates the child watermark — they can# hold no unseen children — keeping the reconciliation window cheap to re-walk every sync.fan_out_parent_recency_field: Optional[str] = None+ # Query-param shape for the list request.+ # "issue_list" — the original shape: per_page + state=all + a created/updated sort pair.+ # "sorted" — same minus `state`, whose enum differs per endpoint (the alert endpoints+ # reject `state=all`) while `sort`/`direction` are accepted as usual.+ # "plain" — per_page plus `extra_params` only, for endpoints that accept no sort at all+ # (or accept a different sort enum, e.g. milestones' due_on/completeness).+ param_style: Literal["issue_list", "sorted", "plain"] = "issue_list"+ # Endpoint honors GitHub's `since` filter, so an incremental sync is bounded server-side rather+ # than by walking pages until the watermark. (issues and commits predate this flag and are+ # matched by name in github.py.)+ supports_since_param: bool = False+ # Endpoint returns newest-first whatever params we send, so rows are emitted desc on every sync+ # — the first one included — and SourceResponse.sort_mode has to say so or the pipeline+ # checkpoints the watermark assuming ascending order. workflow_runs and deployments are the+ # original cases and are matched by name via _ALWAYS_NEWEST_FIRST_ENDPOINTS in github.py.+ always_desc: bool = False+++def _datetime_field(field: str) -> IncrementalField:+ return {+ "label": field,+ "type": IncrementalFieldType.DateTime,+ "field": field,+ "field_type": IncrementalFieldType.DateTime,+ }GITHUB_ENDPOINTS: dict[str, GithubEndpointConfig] = {@@ -366,6 +391,373 @@ GITHUB_ENDPOINTS: dict[str, GithubEndpointConfig] = {# memberships per team while clearing any plausible real team; the cap still logs.max_pages_per_parent=400,),+ # --- Repository metadata --------------------------------------------------------------+ "repository": GithubEndpointConfig(+ name="repository",+ # Returns the repository object itself rather than a list; a body transform in github.py+ # wraps it as the single row of a one-row-per-repo table.+ path="/repos/{repository}",+ incremental_fields=[],+ param_style="plain",+ ),+ "topics": GithubEndpointConfig(+ name="topics",+ # {"names": [...]} — the body transform emits one row per topic.+ path="/repos/{repository}/topics",+ incremental_fields=[],+ primary_key="name",+ param_style="plain",+ ),+ "languages": GithubEndpointConfig(+ name="languages",+ # A {language: bytes} map — the body transform emits one row per language.+ path="/repos/{repository}/languages",+ incremental_fields=[],+ primary_key="language",+ param_style="plain",+ ),+ "community_profile": GithubEndpointConfig(+ name="community_profile",+ path="/repos/{repository}/community/profile",+ incremental_fields=[],+ # One row per repository, so the injected repository column is the only stable key.+ primary_key="repository",+ param_style="plain",+ ),+ # --- Issue and review discussion ------------------------------------------------------+ "issue_comments": GithubEndpointConfig(+ name="issue_comments",+ path="/repos/{repository}/issues/comments",+ partition_key="created_at",+ incremental_fields=[_datetime_field("updated_at"), _datetime_field("created_at")],+ default_incremental_field="updated_at",+ param_style="sorted",+ supports_since_param=True,+ ),+ "pull_request_comments": GithubEndpointConfig(+ name="pull_request_comments",+ # Repo-wide review comments (the inline code comments on pull requests), so unlike reviews+ # this needs no fan-out over pull requests.+ path="/repos/{repository}/pulls/comments",+ partition_key="created_at",+ incremental_fields=[_datetime_field("updated_at"), _datetime_field("created_at")],+ default_incremental_field="updated_at",+ param_style="sorted",+ supports_since_param=True,+ ),+ "issue_events": GithubEndpointConfig(+ name="issue_events",+ # Labeled / assigned / closed / reopened transitions, repo-wide. The endpoint takes no time+ # filter and always answers newest-first, so incremental syncs paginate down and stop at the+ # watermark, the same way workflow_runs does.+ path="/repos/{repository}/issues/events",+ partition_key="created_at",+ incremental_fields=[_datetime_field("created_at")],+ default_incremental_field="created_at",+ param_style="plain",+ sort_mode="desc",+ always_desc=True,+ ),+ "labels": GithubEndpointConfig(+ name="labels",+ path="/repos/{repository}/labels",+ incremental_fields=[],+ param_style="plain",+ ),+ "milestones": GithubEndpointConfig(+ name="milestones",+ # Its sort enum is due_on/completeness, so the generic created/updated sort would be+ # rejected — send only state and paginate in the API's default order.+ path="/repos/{repository}/milestones",+ partition_key="created_at",+ incremental_fields=[],+ param_style="plain",+ extra_params={"state": "all"},+ ),+ # --- Git refs and people ---------------------------------------------------------------+ "branches": GithubEndpointConfig(+ name="branches",+ path="/repos/{repository}/branches",+ incremental_fields=[],+ primary_key="name", # Branches carry no id; the name is unique within the repository.+ param_style="plain",+ ),+ "tags": GithubEndpointConfig(+ name="tags",+ path="/repos/{repository}/tags",+ incremental_fields=[],+ primary_key="name", # Tags carry no id either.+ param_style="plain",+ ),+ "contributors": GithubEndpointConfig(+ name="contributors",+ path="/repos/{repository}/contributors",+ incremental_fields=[],+ param_style="plain",+ ),+ "collaborators": GithubEndpointConfig(+ name="collaborators",+ path="/repos/{repository}/collaborators",+ incremental_fields=[],+ param_style="plain",+ # Needs push access to the repository, which a read-only connection lacks; leave it+ # deselected so a default connection doesn't enable a table whose first sync would 403.+ should_sync_default=False,+ ),+ "subscribers": GithubEndpointConfig(+ name="subscribers",+ path="/repos/{repository}/subscribers",+ incremental_fields=[],+ param_style="plain",+ ),+ "forks": GithubEndpointConfig(+ name="forks",+ # Defaults to sort=newest, so rows arrive newest-first on every sync and incremental+ # pagination can stop at the watermark.+ path="/repos/{repository}/forks",+ partition_key="created_at",+ incremental_fields=[_datetime_field("created_at")],+ default_incremental_field="created_at",+ param_style="plain",+ extra_params={"sort": "newest"},+ sort_mode="desc",+ always_desc=True,+ ),+ # --- Deploys and CI --------------------------------------------------------------------+ # deployments and deployment_statuses are defined above with full webhook-fed incremental sync.+ "environments": GithubEndpointConfig(+ name="environments",+ path="/repos/{repository}/environments",+ partition_key="created_at",+ incremental_fields=[],+ param_style="plain",+ response_data_path="environments",+ ),+ "workflows": GithubEndpointConfig(+ name="workflows",+ path="/repos/{repository}/actions/workflows",+ partition_key="created_at",+ incremental_fields=[],+ param_style="plain",+ response_data_path="workflows",+ ),+ "artifacts": GithubEndpointConfig(+ name="artifacts",+ path="/repos/{repository}/actions/artifacts",+ partition_key="created_at",+ incremental_fields=[],+ param_style="plain",+ response_data_path="artifacts",+ ),+ "runners": GithubEndpointConfig(+ name="runners",+ path="/repos/{repository}/actions/runners",+ incremental_fields=[],+ param_style="plain",+ response_data_path="runners",+ # Self-hosted runners need the repository administration permission.+ should_sync_default=False,+ ),+ "actions_caches": GithubEndpointConfig(+ name="actions_caches",+ path="/repos/{repository}/actions/caches",+ partition_key="created_at",+ incremental_fields=[],+ param_style="plain",+ response_data_path="actions_caches",+ ),+ "check_runs": GithubEndpointConfig(+ name="check_runs",+ # Child of commits: {ref} is filled per parent commit during fan-out. GitHub exposes no+ # repo-wide check-runs list, so per-commit CI signal can only be assembled one commit at a+ # time, the same way reviews are assembled per pull request.+ path="/repos/{repository}/commits/{ref}/check-runs",+ # started_at is nullable while a run is queued, so it works as a cursor but not as a+ # partition key — this table stays unpartitioned.+ incremental_fields=[_datetime_field("started_at"), _datetime_field("completed_at")],+ default_incremental_field="started_at",+ # Check run ids are globally unique (GitHub exposes /repos/{repo}/check-runs/{id}), so no+ # composite key is needed even though this is a fan-out child.+ primary_key="id",+ sort_mode="desc", # Rows land parent-newest-first, like workflow_jobs and reviews.+ response_data_path="check_runs",+ fan_out_parent="commits",+ fan_out_path_param="ref",+ fan_out_parent_field="sha",+ # filter=all returns every check run for the ref, not just the latest per check name —+ # required for re-run and flake analysis.+ extra_params={"filter": "all"},+ # One call per commit, so a first incremental sync would otherwise crawl the repo's entire+ # commit history against a shared, rate-limited budget. Floor it at a recent window; later+ # syncs advance from the watermark. A deliberate full refresh still pulls everything.+ initial_lookback_days=7,+ # A commit-grained fan-out is far more expensive than the repo-wide tables, so leave it+ # deselected and let users opt in rather than paying for it on every default connection.+ should_sync_default=False,+ ),+ "commit_statuses": GithubEndpointConfig(+ name="commit_statuses",+ # Child of commits, like check_runs: the statuses API is per-ref only.+ path="/repos/{repository}/commits/{ref}/statuses",+ partition_key="created_at",+ incremental_fields=[_datetime_field("created_at"), _datetime_field("updated_at")],+ default_incremental_field="created_at",+ # GitHub documents no single-status lookup, so treat the id as unique only within its+ # commit and key on the injected sha as well — a fan-out child's key must be unique+ # table-wide or every later merge multi-matches.+ primary_key=["commit_sha", "id"],+ sort_mode="desc",+ fan_out_parent="commits",+ fan_out_path_param="ref",+ fan_out_parent_field="sha",+ # A status carries no sha of its own, so inject the commit it was posted against.+ fan_out_include_parent_fields={"sha": "commit_sha"},+ initial_lookback_days=7,+ should_sync_default=False, # Same commit-grained fan-out cost as check_runs.+ ),+ # --- Security posture ------------------------------------------------------------------+ "code_scanning_alerts": GithubEndpointConfig(+ name="code_scanning_alerts",+ path="/repos/{repository}/code-scanning/alerts",+ partition_key="created_at",+ incremental_fields=[_datetime_field("updated_at"), _datetime_field("created_at")],+ default_incremental_field="updated_at",+ # Alerts are numbered within the repository and carry no id.+ primary_key="number",+ param_style="sorted",+ # Needs the code scanning alerts read grant, which a plain repo connection lacks.+ should_sync_default=False,+ ),+ "dependabot_alerts": GithubEndpointConfig(+ name="dependabot_alerts",+ path="/repos/{repository}/dependabot/alerts",+ partition_key="created_at",+ incremental_fields=[_datetime_field("updated_at"), _datetime_field("created_at")],+ default_incremental_field="updated_at",+ primary_key="number",+ param_style="sorted",+ should_sync_default=False,+ ),+ "secret_scanning_alerts": GithubEndpointConfig(+ name="secret_scanning_alerts",+ path="/repos/{repository}/secret-scanning/alerts",+ partition_key="created_at",+ incremental_fields=[_datetime_field("updated_at"), _datetime_field("created_at")],+ default_incremental_field="updated_at",+ primary_key="number",+ param_style="sorted",+ # Ask GitHub to leave the leaked credential out of the response. github.py also strips it+ # from every row, so the guarantee doesn't rest on the pinned API version honoring this.+ extra_params={"hide_secret": "true"},+ should_sync_default=False,+ ),+ "security_advisories": GithubEndpointConfig(+ name="security_advisories",+ path="/repos/{repository}/security-advisories",+ partition_key="created_at",+ incremental_fields=[_datetime_field("updated_at"), _datetime_field("created_at")],+ default_incremental_field="updated_at",+ primary_key="ghsa_id", # Repository advisories are keyed by GHSA id, not a numeric id.+ param_style="sorted",+ should_sync_default=False,+ ),+ "dependency_sbom": GithubEndpointConfig(+ name="dependency_sbom",+ # One SPDX document per repository; the body transform emits one row per package, which is+ # the grain a dependency inventory is actually queried at.+ path="/repos/{repository}/dependency-graph/sbom",+ incremental_fields=[],+ primary_key="spdx_id",+ param_style="plain",+ ),+ "rulesets": GithubEndpointConfig(+ name="rulesets",+ path="/repos/{repository}/rulesets",+ partition_key="created_at",+ incremental_fields=[],+ param_style="plain",+ ),+ "hooks": GithubEndpointConfig(+ name="hooks",+ path="/repos/{repository}/hooks",+ partition_key="created_at",+ incremental_fields=[],+ param_style="plain",+ # Reading webhooks needs admin:repo_hook (or the repository webhooks read permission).+ should_sync_default=False,+ ),+ # --- Traffic and statistics ------------------------------------------------------------+ # GitHub only retains traffic for the last 14 days and recomputes the stats aggregates+ # asynchronously, so these are full-refresh tables that upsert on each sync.+ "traffic_views": GithubEndpointConfig(+ name="traffic_views",+ path="/repos/{repository}/traffic/views",+ partition_key="timestamp",+ incremental_fields=[],+ primary_key="timestamp",+ param_style="plain",+ response_data_path="views",+ should_sync_default=False, # Traffic needs push access to the repository.+ ),+ "traffic_clones": GithubEndpointConfig(+ name="traffic_clones",+ path="/repos/{repository}/traffic/clones",+ partition_key="timestamp",+ incremental_fields=[],+ primary_key="timestamp",+ param_style="plain",+ response_data_path="clones",+ should_sync_default=False,+ ),+ "traffic_referrers": GithubEndpointConfig(+ name="traffic_referrers",+ path="/repos/{repository}/traffic/popular/referrers",+ incremental_fields=[],+ primary_key="referrer",+ param_style="plain",+ should_sync_default=False,+ ),+ "traffic_paths": GithubEndpointConfig(+ name="traffic_paths",+ path="/repos/{repository}/traffic/popular/paths",+ incremental_fields=[],+ primary_key="path",+ param_style="plain",+ should_sync_default=False,+ ),+ "contributor_stats": GithubEndpointConfig(+ name="contributor_stats",+ path="/repos/{repository}/stats/contributors",+ incremental_fields=[],+ # The author is nested; github.py flattens the id and login onto the row.+ primary_key="author_id",+ param_style="plain",+ ),+ "commit_activity_stats": GithubEndpointConfig(+ name="commit_activity_stats",+ path="/repos/{repository}/stats/commit_activity",+ incremental_fields=[],+ # week is the unix timestamp of the week start, so it identifies the bucket.+ primary_key="week",+ param_style="plain",+ ),+ "participation_stats": GithubEndpointConfig(+ name="participation_stats",+ # {"all": [...], "owner": [...]} — a rolling 52-week window, so it is one row per repo+ # rather than one per week (the week offsets shift on every sync).+ path="/repos/{repository}/stats/participation",+ incremental_fields=[],+ primary_key="repository",+ param_style="plain",+ ),+ "code_frequency_stats": GithubEndpointConfig(+ name="code_frequency_stats",+ # Returns positional arrays ([week, additions, deletions]); the body transform names them.+ path="/repos/{repository}/stats/code_frequency",+ incremental_fields=[],+ primary_key="week",+ param_style="plain",+ ),}ENDPOINTS = tuple(GITHUB_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/source.pyindex 20cf76a691c2..eae9a6b206fb 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/github/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/source.py@@ -80,8 +80,19 @@ GITHUB_WEBHOOK_RESOURCE_MAP: dict[str, str] = {"reviews": "pull_request_review","deployments": "deployment","deployment_statuses": "deployment_status",+ # Like reviews, a fan-out child with no repo-wide list endpoint, so polling costs one call per+ # commit and the table ships deselected. The event nests the run under `check_run` and the poll+ # path injects no parent column (check run ids are globally unique), so the webhook row already+ # matches the poll row and needs no reshaping.+ "check_runs": "check_run",}+# Everything else stays poll-only. GitHub does emit events for several of the other tables, but the+# template lands `body[eventType]` as the row and these nest the object under a different key —+# `alert` for the code-scanning/Dependabot/secret-scanning alerts, `comment` for issue and review+# comments, `forkee` for forks, `commit` for statuses — so each needs its own reshaping branch+# before its webhook rows would match what the poll path writes.+@SourceRegistry.registerclass GithubSource(diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_repository_endpoints.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_repository_endpoints.pynew file mode 100644index 000000000000..a7052d1806b1--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_repository_endpoints.py@@ -0,0 +1,333 @@+import json+from datetime import UTC, datetime+from typing import Any++from unittest import mock++import pyarrow as pa+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.github import github+from products.warehouse_sources.backend.temporal.data_imports.sources.github.settings import GITHUB_ENDPOINTS++_CUTOFF = datetime(2026, 1, 15, 10, 0, 0, tzinfo=UTC)+++def _response(body: Any, next_url: str | None = None, status_code: int = 200) -> mock.Mock:+ response = mock.Mock()+ response.status_code = status_code+ response.json.return_value = body+ response.headers = {"Link": f'<{next_url}>; rel="next"'} if next_url else {}+ return response+++def _no_resume() -> mock.Mock:+ manager = mock.Mock()+ manager.can_resume.return_value = False+ return manager+++def _run(+ endpoint: str, responses_by_url: dict[str, mock.Mock], **incremental: Any+) -> tuple[list[dict[str, Any]], list[str]]:+ calls: list[str] = []++ def fetch_page(url: str, *_args: Any, **_kwargs: Any) -> mock.Mock:+ calls.append(url)+ for needle in sorted(responses_by_url, key=len, reverse=True):+ if needle in url:+ return responses_by_url[needle]+ raise AssertionError(f"Unexpected URL requested: {url}")++ with mock.patch.object(github, "_fetch_page", side_effect=fetch_page):+ tables = list(+ github.get_rows(+ personal_access_token="tok",+ repository="acme/widgets",+ endpoint=endpoint,+ logger=mock.Mock(),+ resumable_source_manager=_no_resume(),+ **incremental,+ )+ )++ rows: list[dict[str, Any]] = []+ for table in tables:+ assert isinstance(table, pa.Table)+ rows.extend(table.to_pylist())+ return rows, calls+++class TestListParams:+ @parameterized.expand(+ [+ # A "plain" endpoint that receives the generic state/sort trio would be rejected by+ # GitHub: milestones only accepts sort=due_on|completeness, and the alert endpoints+ # define their own state enum with no "all" member.+ ("milestones", {"per_page", "state"}),+ ("branches", {"per_page"}),+ ("traffic_views", {"per_page"}),+ ("issue_events", {"per_page"}),+ ("forks", {"per_page", "sort"}),+ # "sorted" endpoints keep sort/direction but must not send state.+ ("code_scanning_alerts", {"per_page", "sort", "direction"}),+ ("security_advisories", {"per_page", "sort", "direction"}),+ ("secret_scanning_alerts", {"per_page", "sort", "direction", "hide_secret"}),+ ("issue_comments", {"per_page", "sort", "direction"}),+ # The endpoints that shipped first keep the original shape.+ ("issues", {"per_page", "state", "sort", "direction"}),+ ("releases", {"per_page", "state", "sort", "direction"}),+ ]+ )+ def test_full_refresh_param_keys(self, endpoint: str, expected_keys: set[str]) -> None:+ params = github._build_initial_params(+ GITHUB_ENDPOINTS[endpoint],+ endpoint,+ should_use_incremental_field=False,+ db_incremental_field_last_value=None,+ incremental_field=None,+ )++ assert set(params) == expected_keys++ @parameterized.expand(+ [+ # `since` bounds the incremental read server-side, so losing it turns every sync back+ # into a full history walk.+ ("issue_comments", "updated_at", True),+ ("pull_request_comments", "updated_at", True),+ # These endpoints have no `since` filter; sending one would be silently ignored and is+ # not what bounds them.+ ("code_scanning_alerts", "updated_at", False),+ ("security_advisories", "created_at", False),+ ]+ )+ def test_incremental_since(self, endpoint: str, incremental_field: str, expects_since: bool) -> None:+ params = github._build_initial_params(+ GITHUB_ENDPOINTS[endpoint],+ endpoint,+ should_use_incremental_field=True,+ db_incremental_field_last_value=_CUTOFF,+ incremental_field=incremental_field,+ )++ assert ("since" in params) is expects_since+ assert params["sort"] == incremental_field.removesuffix("_at")+ assert params["direction"] == GITHUB_ENDPOINTS[endpoint].sort_mode+ assert "state" not in params++ @parameterized.expand(+ [+ # issue_events and forks answer newest-first whatever we ask for, so reporting "asc" on+ # a first sync would make the pipeline checkpoint the watermark at ~now and strand the+ # rest of the history.+ ("issue_events", "desc"),+ ("forks", "desc"),+ # Endpoints without the flag still start ascending and only flip once a cutoff exists.+ ("issue_comments", "asc"),+ ("milestones", "asc"),+ ]+ )+ def test_first_sync_sort_mode(self, endpoint: str, expected: str) -> None:+ assert (+ github._resolve_sort_mode(+ GITHUB_ENDPOINTS[endpoint],+ endpoint,+ should_use_incremental_field=True,+ db_incremental_field_last_value=None,+ )+ == expected+ )+++class TestBodyTransforms:+ @parameterized.expand(+ [+ (+ "languages",+ {"Python": 1200, "TypeScript": 340},+ [+ {"repository": "acme/widgets", "language": "Python", "bytes": 1200},+ {"repository": "acme/widgets", "language": "TypeScript", "bytes": 340},+ ],+ ),+ (+ "topics",+ {"names": ["analytics", "hogql"]},+ [+ {"repository": "acme/widgets", "name": "analytics"},+ {"repository": "acme/widgets", "name": "hogql"},+ ],+ ),+ (+ "code_frequency_stats",+ [[1336280400, 120, -40], [1336885200, 3, 0]],+ [+ {"week": 1336280400, "additions": 120, "deletions": -40},+ {"week": 1336885200, "additions": 3, "deletions": 0},+ ],+ ),+ (+ # The weekly counts arrive as arrays; the batcher lands them as their JSON encoding.+ "participation_stats",+ {"all": [1, 2], "owner": [1, 0]},+ [{"repository": "acme/widgets", "all": "[1,2]", "owner": "[1,0]"}],+ ),+ (+ "dependency_sbom",+ {"sbom": {"name": "acme/widgets", "packages": [{"SPDXID": "SPDXRef-pip-flask", "name": "flask"}]}},+ [+ {+ "repository": "acme/widgets",+ "document_name": "acme/widgets",+ "spdx_id": "SPDXRef-pip-flask",+ "name": "flask",+ }+ ],+ ),+ ("repository", {"id": 7, "full_name": "acme/widgets"}, [{"id": 7, "full_name": "acme/widgets"}]),+ ]+ )+ def test_non_row_shaped_bodies_become_rows(self, endpoint: str, body: Any, expected: list[dict[str, Any]]) -> None:+ # These endpoints answer with a map, a positional array, or a bare object. Without the+ # transform the pipeline would either write nothing or try to batch non-dict values.+ rows, _calls = _run(endpoint, {"api.github.com": _response(body)})++ assert rows == expected++ def test_statistics_not_ready_syncs_zero_rows(self) -> None:+ # GitHub answers 202 with no usable body while it recomputes a /stats aggregate. That must+ # sync nothing and end cleanly, not raise and retry the activity forever.+ rows, _calls = _run("contributor_stats", {"api.github.com": _response(None, status_code=202)})++ assert rows == []++ def test_envelope_endpoint_unwraps_named_key(self) -> None:+ rows, _calls = _run(+ "environments",+ {"api.github.com": _response({"total_count": 1, "environments": [{"id": 3, "name": "production"}]})},+ )++ assert rows == [{"id": 3, "name": "production"}]+++class TestRowMappers:+ def test_secret_scanning_alert_never_carries_the_secret(self) -> None:+ # The leaked credential itself must never land in a customer's warehouse, whichever API+ # version the source is pinned to (hide_secret is a newer parameter).+ rows, _calls = _run(+ "secret_scanning_alerts",+ {+ "api.github.com": _response(+ [{"number": 4, "secret": "ghp_realtokenvalue", "secret_type": "github_personal_access_token"}]+ )+ },+ )++ assert rows == [{"number": 4, "secret_type": "github_personal_access_token"}]++ def test_contributor_stats_flattens_author_and_drops_anonymous(self) -> None:+ # author_id is this table's primary key, so an unattributed row would seed a null key and+ # make every later merge multi-match.+ rows, _calls = _run(+ "contributor_stats",+ {+ "api.github.com": _response(+ [+ {"author": {"id": 11, "login": "ada"}, "total": 9, "weeks": []},+ {"author": None, "total": 2, "weeks": []},+ ]+ )+ },+ )++ assert [(row["author_id"], row["author_login"]) for row in rows] == [(11, "ada")]++ @parameterized.expand(+ [+ # /repos/{repo} answers with a single repository object; a fork's parent/source are+ # nested repository objects that can each carry their own clone token.+ (+ "repository",+ {+ "id": 7,+ "temp_clone_token": "v1_realclonetoken",+ "parent": {"id": 3, "temp_clone_token": "v1_parenttoken"},+ "source": {"id": 3, "temp_clone_token": "v1_sourcetoken"},+ "template_repository": {"id": 1, "temp_clone_token": "v1_templatetoken"},+ },+ ),+ # /forks answers with a list of repository objects, batched via the item mapper.+ (+ "forks",+ [+ {+ "id": 9,+ "temp_clone_token": "v1_forktoken",+ "parent": {"id": 7, "temp_clone_token": "v1_parenttoken"},+ }+ ],+ ),+ ]+ )+ def test_repository_clone_token_never_reaches_the_warehouse(self, endpoint: str, body: Any) -> None:+ # temp_clone_token is a live credential to clone the private repo. The repository and forks+ # tables are default-on, so a warehouse user without GitHub access could otherwise read it.+ # Nested repository objects land as JSON strings, so assert over the serialized row to catch+ # the token wherever it ends up.+ rows, _calls = _run(endpoint, {"api.github.com": _response(body)})++ assert rows, "expected at least one row"+ for row in rows:+ serialized = json.dumps(row, default=str)+ assert "temp_clone_token" not in serialized+++class TestCommitFanOut:+ def test_commit_statuses_inject_sha_and_stop_at_the_watermark(self) -> None:+ # The commit cursor only exists after the parent mapper flattens commit.author.date onto the+ # row. Without it the walk never recognizes an old commit, so every incremental sync+ # re-fans-out the repository's entire history — one request per commit.+ responses = {+ "/commits/new-sha/statuses": _response(+ [{"id": 900, "state": "success", "created_at": "2026-01-20T10:00:00Z"}]+ ),+ "/commits/old-sha/statuses": _response(+ [{"id": 800, "state": "failure", "created_at": "2025-12-01T10:00:00Z"}]+ ),+ "/commits": _response(+ [+ {"sha": "new-sha", "commit": {"author": {"date": "2026-01-20T09:00:00Z"}}},+ {"sha": "old-sha", "commit": {"author": {"date": "2025-12-01T09:00:00Z"}}},+ ]+ ),+ }++ rows, calls = _run(+ "commit_statuses",+ responses,+ should_use_incremental_field=True,+ db_incremental_field_last_value=_CUTOFF,+ )++ assert rows == [{"id": 900, "state": "success", "created_at": "2026-01-20T10:00:00Z", "commit_sha": "new-sha"}]+ assert not any("old-sha" in call for call in calls)++ def test_check_runs_fan_out_unwraps_envelope(self) -> None:+ responses = {+ "/commits/new-sha/check-runs": _response(+ {"total_count": 1, "check_runs": [{"id": 21, "name": "lint", "started_at": "2026-01-20T10:00:00Z"}]}+ ),+ "/commits": _response([{"sha": "new-sha", "commit": {"author": {"date": "2026-01-20T09:00:00Z"}}}]),+ }++ rows, calls = _run(+ "check_runs",+ responses,+ should_use_incremental_field=True,+ db_incremental_field_last_value=_CUTOFF,+ )++ assert rows == [{"id": 21, "name": "lint", "started_at": "2026-01-20T10:00:00Z"}]+ # filter=all is what surfaces re-runs rather than only the latest run per check name.+ assert any("filter=all" in call for call in calls)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_source_class.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_source_class.pyindex 274ca4b1e3c8..9d5ddfd0b2df 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_source_class.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_source_class.py@@ -196,7 +196,22 @@ class TestGithubSource:assert schemas["workflow_runs"].supports_webhooks is Trueassert schemas["workflow_jobs"].supports_webhooks is True- assert all(s.should_sync_default for s in schemas.values() if s.name not in ("teams", "team_members"))+ # The originally shipped repo-scoped tables must stay selected by default. Tables added+ # since may legitimately default off (they need grants beyond the repo scope validated at+ # source-create, or they fan out per commit).+ assert all(+ schemas[endpoint].should_sync_default+ for endpoint in (+ "issues",+ "pull_requests",+ "reviews",+ "commits",+ "stargazers",+ "releases",+ "workflow_runs",+ "workflow_jobs",+ )+ )def test_reviews_schema_is_webhook_only_and_default_on(self):# reviews does no poll backfill (zero lookback floor), so it must be offered webhook-only;diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_webhook_template.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_webhook_template.pyindex ccd50440279f..0dbf9ace2d73 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_webhook_template.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_webhook_template.py@@ -95,19 +95,27 @@ class TestGithubWarehouseWebhookTemplate(BaseHogFunctionTemplateTest):assert res.result["httpResponse"]["status"] == 200self.mock_produce_to_warehouse_webhooks.assert_not_called()- def test_workflow_job_row_lands_unchanged(self):- job = {"id": 1, "status": "completed", "conclusion": "success"}- self._run("workflow_job", {"action": "completed", "workflow_job": job}, {"workflow_job": "schema_jobs"})-- self.mock_produce_to_warehouse_webhooks.assert_called_once_with(job, "schema_jobs")-- def test_deployment_row_lands_unchanged(self):- # The deployment event nests the object under body.deployment, matching the polled REST- # shape, so it lands as-is like workflow_job / workflow_run.- deployment = {"id": 7, "environment": "production", "sha": "abc123"}- self._run("deployment", {"action": "created", "deployment": deployment}, {"deployment": "schema_deploys"})-- self.mock_produce_to_warehouse_webhooks.assert_called_once_with(deployment, "schema_deploys")+ @parameterized.expand(+ [+ ("workflow_job", "completed", {"id": 1, "status": "completed", "conclusion": "success"}),+ ("deployment", "created", {"id": 7, "environment": "production", "sha": "abc123"}),+ (+ "check_run",+ "completed",+ {"id": 42, "head_sha": "abc123", "status": "completed", "conclusion": "success"},+ ),+ ]+ )+ def test_row_lands_unchanged_when_event_nests_under_its_own_key(+ self, event_type: str, action: str, obj: dict[str, Any]+ ):+ # These events nest the object under body.<event_type>, matching the polled REST shape, so+ # the row lands as-is. check_run is the one that could regress silently: it is a per-commit+ # fan-out child, and if it ever started injecting a parent column the way reviews and+ # deployment_statuses do, webhook rows would drift from poll rows without erroring.+ self._run(event_type, {"action": action, event_type: obj}, {event_type: "schema_x"})++ self.mock_produce_to_warehouse_webhooks.assert_called_once_with(obj, "schema_x")def test_deployment_status_row_is_reshaped_to_poll_shape(self):# The deployment_status event nests the status under body.deployment_status and itsdiff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/github/test_github_source.py b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/github/test_github_source.pyindex e5ca065ed8f0..ad6c05fd4c96 100644--- a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/github/test_github_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/github/test_github_source.py@@ -1438,6 +1438,7 @@ class TestGithubWebhookSource:"reviews": "pull_request_review","deployments": "deployment","deployment_statuses": "deployment_status",+ "check_runs": "check_run",}def test_webhook_template_identity(self) -> None:@@ -1455,6 +1456,7 @@ class TestGithubWebhookSource:"reviews","deployments","deployment_statuses",+ "check_runs",}def test_workflow_runs_and_jobs_are_webhook_only(self) -> None:@@ -1643,6 +1645,7 @@ class TestGithubWebhookSource:assert repo == "owner/repo"assert url == "https://app.posthog.com/webhook"assert sorted(events) == [+ "check_run","deployment","deployment_status","pull_request_review",