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(data-warehouse): add 1 missing table to the CratesIO source (#118829)

Tom Owersc91a07861e88
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 a91729f7574a..b6d64a05bd40 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
@@ -3354,8 +3354,8 @@ Diffed against: <https://crates.io/api/openapi.json>
- [x] `/api/v1/crates/{name}/reverse_dependencies` — who depends on your crate; the headline adoption metric for a crate owner (high)
- [x] `/api/v1/categories (and /api/v1/category_slugs)` — lookup table resolving the category slugs carried on every crate record (medium). `/api/v1/category_slugs` returns a strict subset of the `/api/v1/categories` fields (id, slug, description), so only `categories` is synced.
- [x] `/api/v1/keywords` — lookup table resolving the keyword IDs on crates, plus per-keyword crate counts (medium)
-- [ ] `/api/v1/users/{user} and /api/v1/teams/{team}` — lookup resolving the user/team IDs returned by the owners endpoints (low)
-- [ ] `/api/v1/crates/{name}/{version}/downloads` — per-version download series, finer grain than the crate-level downloads table (low)
+- [ ] `/api/v1/users/{user} and /api/v1/teams/{team}` — lookup resolving the user/team IDs returned by the owners endpoints (low). Not synced: the owners endpoint already returns the full user and team records (id, login, name, avatar, url, kind), and these endpoints look up by login, so a lookup table would only add the user `created_at`.
+- [x] `/api/v1/crates/{name}/{version}/downloads` — per-version download series, finer grain than the crate-level downloads table (low). Synced as `version_downloads` for the 25 most recently published versions of each crate.
Note: Verified against the live OpenAPI document at https://crates.io/api/openapi.json (returns 403 without a descriptive User-Agent - crates.io requires one). The payload's https://crates.io/data-access page now 404s. Source is static: the user supplies a crate list and PostHog fans out per crate.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/crates_io/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/crates_io/canonical_descriptions.py
index 31970546b78d..36d6435218a0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/crates_io/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/crates_io/canonical_descriptions.py
@@ -79,6 +79,19 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"downloads": "Number of downloads on that day.",
},
},
+ "version_downloads": {
+ "description": "Daily download counts for each of the most recent versions of each configured crate, "
+ "over the trailing ~90-day window the crates.io API exposes.",
+ "docs_url": _API_DOCS,
+ "columns": {
+ "crate": "Canonical crate name (injected by the connector; not returned by the endpoint).",
+ "version_num": "Version number the downloads are for (injected by the connector; not returned by "
+ "the endpoint).",
+ "version": "Registry-wide numeric id of the version the downloads are for.",
+ "date": "Day the downloads were counted (UTC); used as the partition key.",
+ "downloads": "Number of downloads of this version on that day.",
+ },
+ },
"dependencies": {
"description": "Dependencies declared by the most recent versions of each configured crate, one row "
"per dependency edge.",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/crates_io/crates_io.py b/products/warehouse_sources/backend/temporal/data_imports/sources/crates_io/crates_io.py
index a7e51e961602..89e740b1af37 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/crates_io/crates_io.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/crates_io/crates_io.py
@@ -39,11 +39,14 @@ VERSIONS_PER_PAGE = 100
LIST_PER_PAGE = 100
# Dependencies are only exposed per version, so a crate with a long release history would cost one
-# request per version on every sync. Only the most recently published versions are walked. The walk
-# sorts by publish date rather than semver, so a backport released onto an older line is included
-# and a stale high version number does not hold a slot.
+# request per version on every sync. Only the most recently published versions are walked.
MAX_VERSIONS_PER_CRATE_FOR_DEPENDENCIES = 25
+# The per-version download series costs one request per version too. The crate-level downloads
+# table already breaks down the latest 5 versions, and an old version with no downloads in the
+# trailing window returns an empty series, so only the most recently published versions are walked.
+MAX_VERSIONS_PER_CRATE_FOR_VERSION_DOWNLOADS = 25
+
# A widely used crate has tens of thousands of reverse dependencies, which at the crawler-policy
# request rate would let one crate consume the whole sync. Cap the walk instead.
MAX_REVERSE_DEPENDENCY_PAGES = 100
@@ -311,21 +314,23 @@ def _iter_list_pages(
logger.warning(f"crates.io: page cap reached, results may be truncated: url={url}, max_pages={max_pages}")
-def _dependency_rows(
+def _recent_versions(
session: requests.Session,
throttle: _RequestThrottle,
crate: str,
logger: FilteringBoundLogger,
-) -> Iterator[dict[str, Any]]:
- """One row per dependency declared by the crate's most recent versions.
+ limit: int,
+ stream: str,
+) -> list[dict[str, Any]]:
+ """The crate's most recently published versions, newest first, for streams that fan out per version.
- Rows are stamped with the parent crate and version number: the endpoint's own `crate_id` names
- the crate being depended on, not the crate that declares the dependency.
+ The walk sorts by publish date rather than semver, so a backport released onto an older line is
+ included and a stale high version number does not hold a slot.
"""
- query = urlencode({"per_page": MAX_VERSIONS_PER_CRATE_FOR_DEPENDENCIES, "sort": "date"})
+ query = urlencode({"per_page": limit, "sort": "date"})
document = _fetch_json(session, throttle, f"{_crate_url(crate)}/versions?{query}", logger)
if document is None:
- return
+ return []
versions = [
version for version in (document.get("versions") or []) if isinstance(version, dict) and version.get("num")
@@ -333,10 +338,26 @@ def _dependency_rows(
total = (document.get("meta") or {}).get("total")
if isinstance(total, int) and total > len(versions):
logger.warning(
- f"crates.io: version cap reached for dependencies, older versions skipped: "
+ f"crates.io: version cap reached for {stream}, older versions skipped: "
f"crate={crate}, synced={len(versions)}, total={total}"
)
+ return versions
+
+
+def _dependency_rows(
+ session: requests.Session,
+ throttle: _RequestThrottle,
+ crate: str,
+ logger: FilteringBoundLogger,
+) -> Iterator[dict[str, Any]]:
+ """One row per dependency declared by the crate's most recent versions.
+ Rows are stamped with the parent crate and version number: the endpoint's own `crate_id` names
+ the crate being depended on, not the crate that declares the dependency.
+ """
+ versions = _recent_versions(
+ session, throttle, crate, logger, limit=MAX_VERSIONS_PER_CRATE_FOR_DEPENDENCIES, stream="dependencies"
+ )
for version in versions:
num = str(version["num"])
dependencies = _fetch_json(session, throttle, f"{_crate_url(crate)}/{quote(num, safe='')}/dependencies", logger)
@@ -352,6 +373,36 @@ def _dependency_rows(
yield row
+def _version_download_rows(
+ session: requests.Session,
+ throttle: _RequestThrottle,
+ crate: str,
+ logger: FilteringBoundLogger,
+) -> Iterator[dict[str, Any]]:
+ """One row per (version id, date) from the ~90-day daily download series of each recent version.
+
+ Rows are stamped with the crate and version number, because the endpoint only returns the numeric
+ version id.
+ """
+ versions = _recent_versions(
+ session, throttle, crate, logger, limit=MAX_VERSIONS_PER_CRATE_FOR_VERSION_DOWNLOADS, stream="version_downloads"
+ )
+ for version in versions:
+ num = str(version["num"])
+ document = _fetch_json(session, throttle, f"{_crate_url(crate)}/{quote(num, safe='')}/downloads", logger)
+ if document is None:
+ continue
+ for entry in document.get("version_downloads") or []:
+ # `version` and `date` form the primary key; a row missing either can't upsert cleanly.
+ if not isinstance(entry, dict) or not entry.get("date") or entry.get("version") is None:
+ continue
+ row = dict(entry)
+ # The version record carries the canonical crate name, so no extra lookup is needed.
+ row["crate"] = version.get("crate") or crate
+ row["version_num"] = num
+ yield row
+
+
def _reverse_dependency_rows(
session: requests.Session,
throttle: _RequestThrottle,
@@ -436,6 +487,7 @@ _ROW_BUILDERS: dict[
"owners": _owner_rows,
"dependencies": _dependency_rows,
"reverse_dependencies": _reverse_dependency_rows,
+ "version_downloads": _version_download_rows,
}
# Registry-wide lookup tables: one pass per sync rather than one pass per configured crate.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/crates_io/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/crates_io/settings.py
index 2684578e54b4..36c9c2a150db 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/crates_io/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/crates_io/settings.py
@@ -63,6 +63,15 @@ CRATES_IO_ENDPOINTS: dict[str, CratesIOEndpointConfig] = {
description="Daily download counts per version of each configured crate, over the trailing "
"~90-day window the crates.io API exposes.",
),
+ "version_downloads": CratesIOEndpointConfig(
+ name="version_downloads",
+ # Version ids are unique across the whole registry, so the version and day identify a row.
+ primary_keys=["version", "date"],
+ incremental_fields=list(_DATE_INCREMENTAL_FIELDS),
+ partition_key="date",
+ description="Daily download counts for each of the most recent versions of each configured crate, "
+ "over the trailing ~90-day window the crates.io API exposes.",
+ ),
"owners": CratesIOEndpointConfig(
name="owners",
# Owner (user/team) ids are global on crates.io; rows aggregate across crates.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/crates_io/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/crates_io/source.py
index 1aac1c0a0932..454b16d63ce1 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/crates_io/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/crates_io/source.py
@@ -61,7 +61,7 @@ tokio
posthog-rs
```
-Each sync fetches the current data for every configured crate. The dependency table covers the 25 most recent versions of each crate. The category and keyword tables cover the whole registry, so they do not depend on the crates you list. crates.io has no server-side "changed since" filter, and daily download counts only cover the trailing ~90 days, so all tables sync as a full refresh.""",
+Each sync fetches the current data for every configured crate. The dependency and version download tables cover the 25 most recent versions of each crate. The category and keyword tables cover the whole registry, so they do not depend on the crates you list. crates.io has no server-side "changed since" filter, and daily download counts only cover the trailing ~90 days, so all tables sync as a full refresh.""",
iconPath="/static/services/crates_io.png",
docsUrl="https://posthog.com/docs/cdp/sources/crates-io",
fields=cast(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/crates_io/tests/test_crates_io.py b/products/warehouse_sources/backend/temporal/data_imports/sources/crates_io/tests/test_crates_io.py
index 92d542f18fe0..1f1385238c04 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/crates_io/tests/test_crates_io.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/crates_io/tests/test_crates_io.py
@@ -18,6 +18,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.crates_io.
EXTRA_DOWNLOADS_VERSION_ID,
MAX_CRATES,
MAX_VERSIONS_PER_CRATE_FOR_DEPENDENCIES,
+ MAX_VERSIONS_PER_CRATE_FOR_VERSION_DOWNLOADS,
CratesIORetryableError,
_fetch_json,
crates_io_source,
@@ -261,6 +262,39 @@ class TestGetRows:
f"{CRATES_IO_BASE_URL}/crates/serde/1.0.0/dependencies",
]
+ def test_version_downloads_stamps_crate_and_version_num(self):
+ result = _driver("serde-json").run(
+ "version_downloads",
+ [
+ ScriptedResponse(json=_versions_page(["1.0.1", "1.0.0", "0.9.0"], next_page=None)),
+ ScriptedResponse(
+ json={
+ "version_downloads": [
+ {"version": 1, "downloads": 40, "date": "2026-07-01"},
+ {"version": 1, "downloads": 7, "date": ""},
+ {"downloads": 9, "date": "2026-07-02"},
+ ]
+ }
+ ),
+ ScriptedResponse(status=404),
+ ScriptedResponse(json={"version_downloads": []}),
+ ],
+ )
+
+ # The endpoint returns only the numeric version id, so the crate and version number exist on
+ # the row only because the connector stamps them. Rows missing a primary key part are dropped.
+ assert result.raised is None
+ assert result.rows == [
+ {"version": 1, "downloads": 40, "date": "2026-07-01", "crate": "serde", "version_num": "1.0.1"}
+ ]
+ assert result.urls == [
+ f"{CRATES_IO_BASE_URL}/crates/serde-json/versions?per_page={MAX_VERSIONS_PER_CRATE_FOR_VERSION_DOWNLOADS}&sort=date",
+ # A version whose downloads 404 is skipped rather than failing the crate.
+ f"{CRATES_IO_BASE_URL}/crates/serde-json/1.0.1/downloads",
+ f"{CRATES_IO_BASE_URL}/crates/serde-json/1.0.0/downloads",
+ f"{CRATES_IO_BASE_URL}/crates/serde-json/0.9.0/downloads",
+ ]
+
def test_reverse_dependencies_joins_the_dependent_version(self):
document = {
"dependencies": [