:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(warehouse-sources): add crates.io dependency and lookup tables (#103713)
Tom Owers935cc8014a9f
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.mdindex 8ca775ee2ef2..1f33875bd791 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@@ -2135,14 +2135,14 @@ Note: Coveralls has an unusually small read surface: only GET /api/v1/repos is a## CratesIO — gaps-Today (4): `crates`, `downloads`, `owners`, `versions`+Today (8): `categories`, `crates`, `dependencies`, `downloads`, `keywords`, `owners`, `reverse_dependencies`, `versions`Diffed against: <https://crates.io/api/openapi.json>-- [ ] `/api/v1/crates/{name}/{version}/dependencies` — per-version dependency edges - the dependency graph is the main analytical object crates.io exposes (high)-- [ ] `/api/v1/crates/{name}/reverse_dependencies` — who depends on your crate; the headline adoption metric for a crate owner (high)-- [ ] `/api/v1/categories (and /api/v1/category_slugs)` — lookup table resolving the category slugs carried on every crate record (medium)-- [ ] `/api/v1/keywords` — lookup table resolving the keyword IDs on crates, plus per-keyword crate counts (medium)+- [x] `/api/v1/crates/{name}/{version}/dependencies` — per-version dependency edges - the dependency graph is the main analytical object crates.io exposes (high)+- [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)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.pyindex 4008dbc5eddc..31970546b78d 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@@ -2,12 +2,12 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.canCanonicalDescriptions,)-_DATA_ACCESS_DOCS = "https://crates.io/data-access"+_API_DOCS = "https://doc.rust-lang.org/cargo/reference/registry-web-api.html"CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"crates": {"description": "Crate metadata from the crates.io API crate detail endpoint, one row per configured crate.",- "docs_url": _DATA_ACCESS_DOCS,+ "docs_url": _API_DOCS,"columns": {"id": "Globally unique crate name (the crate's identifier on crates.io).","name": "Crate name as registered on crates.io.",@@ -36,7 +36,7 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {},"versions": {"description": "Published versions across every configured crate, one row per version.",- "docs_url": _DATA_ACCESS_DOCS,+ "docs_url": _API_DOCS,"columns": {"id": "Registry-wide unique numeric version id.","crate": "Name of the crate the version belongs to.",@@ -70,7 +70,7 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"downloads": {"description": "Daily download counts per version of each configured crate, over the trailing ~90-day ""window the crates.io API exposes.",- "docs_url": _DATA_ACCESS_DOCS,+ "docs_url": _API_DOCS,"columns": {"crate": "Canonical crate name (injected by the connector; not returned by the endpoint).","version": "Registry-wide numeric version id, or 0 for downloads crates.io reports only in "@@ -79,9 +79,76 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"downloads": "Number of downloads on that day.",},},+ "dependencies": {+ "description": "Dependencies declared by the most recent versions of each configured crate, one row "+ "per dependency edge.",+ "docs_url": _API_DOCS,+ "columns": {+ "crate": "Canonical name of the crate that declares the dependency (injected by the connector; "+ "not returned by the endpoint).",+ "version_num": "Version number of the crate that declares the dependency (injected by the "+ "connector; not returned by the endpoint).",+ "version_id": "Registry-wide numeric id of the version that declares the dependency.",+ "id": "Opaque numeric id of the dependency edge.",+ "crate_id": "Name of the crate being depended on.",+ "req": "Semver requirement the dependency is declared with (e.g. `^1.0`).",+ "kind": "Dependency kind: `normal`, `dev`, or `build`.",+ "optional": "Whether the dependency is optional.",+ "default_features": "Whether default features are enabled for the dependency.",+ "features": "Features explicitly enabled for the dependency.",+ "target": "Target platform the dependency applies to, if it is platform-specific.",+ "downloads": "Always 0. crates.io only fills this field in on the reverse dependencies endpoint.",+ },+ },+ "reverse_dependencies": {+ "description": "Versions of other crates that depend on each configured crate, one row per dependency edge.",+ "docs_url": _API_DOCS,+ "columns": {+ "crate": "Canonical name of the configured crate being depended on.",+ "dependent_crate": "Name of the crate that declares the dependency (injected by the connector "+ "from the response's version list).",+ "dependent_version_num": "Version number of the crate that declares the dependency (injected by "+ "the connector from the response's version list).",+ "version_id": "Registry-wide numeric id of the version that declares the dependency.",+ "id": "Opaque numeric id of the dependency edge.",+ "crate_id": "Name of the crate being depended on; the same as `crate`.",+ "req": "Semver requirement the dependency is declared with (e.g. `^1.0`).",+ "kind": "Dependency kind: `normal`, `dev`, or `build`.",+ "optional": "Whether the dependency is optional.",+ "default_features": "Whether default features are enabled for the dependency.",+ "features": "Features explicitly enabled for the dependency.",+ "target": "Target platform the dependency applies to, if it is platform-specific.",+ "downloads": "All-time download count of the dependent crate named by `dependent_crate`, "+ "across every one of its versions.",+ },+ },+ "categories": {+ "description": "Every category on crates.io, one row per category. Resolves the category slugs "+ "carried on crate records.",+ "docs_url": _API_DOCS,+ "columns": {+ "id": "Opaque identifier of the category; the same value as `slug`.",+ "category": "Display name of the category, including its parent path (e.g. `Game development`).",+ "slug": "URL slug of the category, as carried in a crate's `categories` field.",+ "description": "Description of what belongs in the category.",+ "created_at": "When the category was added to crates.io.",+ "crates_cnt": "Number of crates in the category.",+ },+ },+ "keywords": {+ "description": "Every keyword on crates.io, one row per keyword. Resolves the keywords carried on "+ "crate records.",+ "docs_url": _API_DOCS,+ "columns": {+ "id": "Opaque identifier of the keyword; the same value as `keyword`.",+ "keyword": "The keyword itself, as carried in a crate's `keywords` field.",+ "created_at": "When the keyword was first used on crates.io.",+ "crates_cnt": "Number of crates using the keyword.",+ },+ },"owners": {"description": "Owners (users and teams) of each configured crate, one row per owner.",- "docs_url": _DATA_ACCESS_DOCS,+ "docs_url": _API_DOCS,"columns": {"crate": "Canonical crate name (injected by the connector; not returned by the endpoint).","id": "Registry-wide unique numeric id of the owning user or team.",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.pyindex d6f5ff848f2c..a7e51e961602 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@@ -2,7 +2,7 @@ import reimport timefrom collections.abc import Callable, Iteratorfrom typing import Any-from urllib.parse import quote+from urllib.parse import quote, urlencodeimport requestsfrom structlog.types import FilteringBoundLogger@@ -35,6 +35,23 @@ MAX_CRATES = 500VERSIONS_PER_PAGE = 100+# crates.io rejects a larger page size on its paginated list endpoints with a 400.+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.+MAX_VERSIONS_PER_CRATE_FOR_DEPENDENCIES = 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++# Termination guard for the registry-wide lookup endpoints. The walk normally stops on the first+# short page, so this only trips if the API stops signalling the end of the list.+MAX_LIST_PAGES = 1000+# Rows for a single crate are yielded in bounded chunks so a crate with a huge version history# never forces one oversized in-memory Arrow conversion downstream. The pipeline batches on top of# this, so the exact value only caps the per-yield list size.@@ -267,6 +284,149 @@ def _owner_rows(yield row+def _iter_list_pages(+ session: requests.Session,+ throttle: _RequestThrottle,+ url: str,+ collection: str,+ logger: FilteringBoundLogger,+ max_pages: int,+ params: dict[str, str] | None = None,+) -> Iterator[dict[str, Any]]:+ """Yield each page document of a page-numbered crates.io list endpoint.++ ``collection`` is the response key holding the page's rows, which is what decides when the walk+ ends: crates.io keeps serving pages past the end of the list, returning an empty array rather+ than an error, and `meta.total` drops to 0 there, so a short page is the only reliable signal.+ """+ for page in range(1, max_pages + 1):+ query = urlencode({**(params or {}), "per_page": LIST_PER_PAGE, "page": page})+ document = _fetch_json(session, throttle, f"{url}?{query}", logger)+ if document is None:+ return+ yield document+ if len(document.get(collection) or []) < LIST_PER_PAGE:+ return++ logger.warning(f"crates.io: page cap reached, results may be truncated: url={url}, max_pages={max_pages}")+++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.+ """+ query = urlencode({"per_page": MAX_VERSIONS_PER_CRATE_FOR_DEPENDENCIES, "sort": "date"})+ document = _fetch_json(session, throttle, f"{_crate_url(crate)}/versions?{query}", logger)+ if document is None:+ return++ versions = [+ version for version in (document.get("versions") or []) if isinstance(version, dict) and version.get("num")+ ]+ 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"crate={crate}, synced={len(versions)}, total={total}"+ )++ for version in versions:+ num = str(version["num"])+ dependencies = _fetch_json(session, throttle, f"{_crate_url(crate)}/{quote(num, safe='')}/dependencies", logger)+ if dependencies is None:+ continue+ for dependency in dependencies.get("dependencies") or []:+ if not isinstance(dependency, dict):+ continue+ row = dict(dependency)+ # 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,+ crate: str,+ logger: FilteringBoundLogger,+) -> Iterator[dict[str, Any]]:+ """One row per version of another crate that depends on this crate.++ Each page carries the dependency edges and, separately, the dependent versions they point at,+ so the dependent crate and version number are joined onto the edge here. Without that a row+ only identifies the dependent by a numeric version id.+ """+ url = f"{_crate_url(crate)}/reverse_dependencies"+ for document in _iter_list_pages(+ session, throttle, url, "dependencies", logger, max_pages=MAX_REVERSE_DEPENDENCY_PAGES+ ):+ versions_by_id = {+ version["id"]: version+ for version in (document.get("versions") or [])+ if isinstance(version, dict) and version.get("id") is not None+ }+ for dependency in document.get("dependencies") or []:+ if not isinstance(dependency, dict):+ continue+ row = dict(dependency)+ # On this endpoint `crate_id` is the crate being depended on, already in canonical form.+ row["crate"] = dependency.get("crate_id") or crate+ version = versions_by_id.get(dependency.get("version_id")) or {}+ row["dependent_crate"] = version.get("crate")+ row["dependent_version_num"] = version.get("num")+ yield row+++def _category_rows(+ session: requests.Session,+ throttle: _RequestThrottle,+ logger: FilteringBoundLogger,+) -> Iterator[dict[str, Any]]:+ """One row per crates.io category. Registry-wide, so it does not depend on the configured crates."""+ for document in _iter_list_pages(+ session,+ throttle,+ f"{CRATES_IO_BASE_URL}/categories",+ "categories",+ logger,+ max_pages=MAX_LIST_PAGES,+ # Alphabetical is the API default, but the walk is page-numbered, so an explicit stable+ # order stops rows shifting across page boundaries while the sync runs.+ params={"sort": "alpha"},+ ):+ for row in document.get("categories") or []:+ if isinstance(row, dict):+ yield row+++def _keyword_rows(+ session: requests.Session,+ throttle: _RequestThrottle,+ logger: FilteringBoundLogger,+) -> Iterator[dict[str, Any]]:+ """One row per crates.io keyword. Registry-wide, so it does not depend on the configured crates."""+ for document in _iter_list_pages(+ session,+ throttle,+ f"{CRATES_IO_BASE_URL}/keywords",+ "keywords",+ logger,+ max_pages=MAX_LIST_PAGES,+ params={"sort": "alpha"},+ ):+ for row in document.get("keywords") or []:+ if isinstance(row, dict):+ yield row++_ROW_BUILDERS: dict[str, Callable[[requests.Session, _RequestThrottle, str, FilteringBoundLogger], Iterator[dict[str, Any]]]] = {@@ -274,6 +434,16 @@ _ROW_BUILDERS: dict["versions": _version_rows,"downloads": _download_rows,"owners": _owner_rows,+ "dependencies": _dependency_rows,+ "reverse_dependencies": _reverse_dependency_rows,+}++# Registry-wide lookup tables: one pass per sync rather than one pass per configured crate.+_GLOBAL_ROW_BUILDERS: dict[+ str, Callable[[requests.Session, _RequestThrottle, FilteringBoundLogger], Iterator[dict[str, Any]]]+] = {+ "categories": _category_rows,+ "keywords": _keyword_rows,}@@ -304,29 +474,41 @@ def validate_credentials(crates_raw: str | None) -> tuple[bool, str | None]:return False, f"crates.io API returned an unexpected status code: {response.status_code}"+def _chunked(rows: Iterator[dict[str, Any]]) -> Iterator[list[dict[str, Any]]]:+ """Stream rows into bounded chunks.++ A crate with a very large version history, or a registry-wide lookup table, is never+ materialized as one oversized list, and each yield caps the downstream Arrow conversion. The+ pipeline batches on top of this.+ """+ chunk: list[dict[str, Any]] = []+ for row in rows:+ chunk.append(row)+ if len(chunk) >= MAX_ROWS_PER_BATCH:+ yield chunk+ chunk = []+ if chunk:+ yield chunk++def get_rows(endpoint: str,crates: list[str],logger: FilteringBoundLogger,) -> Iterator[list[dict[str, Any]]]:- build_rows = _ROW_BUILDERS[endpoint]- # One session reused across every crate so urllib3 keeps the connection alive; the User-Agent- # is mandatory under the crates.io crawler policy.+ # One session reused across every request so urllib3 keeps the connection alive; the+ # User-Agent is mandatory under the crates.io crawler policy.session = make_tracked_session(headers={"User-Agent": USER_AGENT})throttle = _RequestThrottle(THROTTLE_SECONDS)+ build_global_rows = _GLOBAL_ROW_BUILDERS.get(endpoint)+ if build_global_rows is not None:+ yield from _chunked(build_global_rows(session, throttle, logger))+ return++ build_rows = _ROW_BUILDERS[endpoint]for crate in crates:- # Stream the builder into bounded chunks: a crate with a very large version history is- # never materialized as one oversized list, and each yield caps the downstream Arrow- # conversion. The pipeline batches on top of this.- chunk: list[dict[str, Any]] = []- for row in build_rows(session, throttle, crate, logger):- chunk.append(row)- if len(chunk) >= MAX_ROWS_PER_BATCH:- yield chunk- chunk = []- if chunk:- yield chunk+ yield from _chunked(build_rows(session, throttle, crate, logger))def crates_io_source(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.pyindex de8aaa55dc1a..2684578e54b4 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@@ -69,6 +69,35 @@ CRATES_IO_ENDPOINTS: dict[str, CratesIOEndpointConfig] = {primary_keys=["crate", "id"],description="Owners (users and teams) of each configured crate.",),+ "dependencies": CratesIOEndpointConfig(+ name="dependencies",+ # crates.io documents the dependency id only as "an opaque identifier", so the version it+ # belongs to keeps the key unique even if that id is ever scoped per version.+ primary_keys=["version_id", "id"],+ description="Dependencies declared by the most recent versions of each configured crate, "+ "one row per dependency edge.",+ ),+ "reverse_dependencies": CratesIOEndpointConfig(+ name="reverse_dependencies",+ # The same caveat as `dependencies`, with the depended-on crate as the scope because that+ # is what the endpoint is keyed by.+ primary_keys=["crate", "id"],+ description="Versions of other crates that depend on each configured crate, one row per dependency edge.",+ ),+ "categories": CratesIOEndpointConfig(+ name="categories",+ # Registry-wide table, so the category slug is unique on its own.+ primary_keys=["id"],+ description="Every category on crates.io, resolving the category slugs carried on crate "+ "records, with the number of crates in each.",+ ),+ "keywords": CratesIOEndpointConfig(+ name="keywords",+ # Registry-wide table, so the keyword is unique on its own.+ primary_keys=["id"],+ description="Every keyword on crates.io, resolving the keywords carried on crate records, "+ "with the number of crates using each.",+ ),}ENDPOINTS = tuple(CRATES_IO_ENDPOINTS.keys())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.pyindex 295302144f04..09c8ffa83348 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@@ -48,7 +48,7 @@ class CratesIOSource(SimpleSource[CratesIOSourceConfig]):label="crates.io",releaseStatus=ReleaseStatus.ALPHA,keywords=["rust", "cargo", "crates"],- caption="""Pull metadata, versions, owners, and daily download counts for Rust crates from the [crates.io](https://crates.io) API into the PostHog Data warehouse.+ caption="""Pull metadata, versions, owners, dependencies, and daily download counts for Rust crates from the [crates.io](https://crates.io) API into the PostHog Data warehouse.crates.io's read APIs are public, so no credentials are required. There is no practical way to sync the whole registry, so enter the crate names you want to track, one per line (or comma-separated). For example:@@ -58,7 +58,7 @@ tokioposthog-rs```-Each sync fetches the current data for every configured crate. 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 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.""",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.pyindex db99128fed2e..daf90e9ca4f8 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@@ -11,6 +11,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.crates_io.CRATES_IO_BASE_URL,EXTRA_DOWNLOADS_VERSION_ID,MAX_CRATES,+ MAX_VERSIONS_PER_CRATE_FOR_DEPENDENCIES,USER_AGENT,CratesIORetryableError,_canonical_name,@@ -70,6 +71,15 @@ def _versions_page(nums: list[str], next_page: str | None) -> dict[str, Any]:}+def _dependencies_document(version_id: int, crate_ids: list[str]) -> dict[str, Any]:+ return {+ "dependencies": [+ {"id": 100 + index, "version_id": version_id, "crate_id": crate_id, "kind": "normal"}+ for index, crate_id in enumerate(crate_ids)+ ]+ }++def _downloads_document() -> dict[str, Any]:return {"version_downloads": [@@ -285,6 +295,114 @@ class TestGetRows:assert batches == [[{"id": 3618, "login": "dtolnay", "kind": "user", "crate": "serde"}]]+ def test_dependencies_stamps_parent_crate_and_version(self):+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:+ mock_session.return_value.get.side_effect = [+ _response(200, _versions_page(["1.0.1", "1.0.0"], next_page=None)),+ _response(200, _dependencies_document(1, ["serde_derive"])),+ _response(404),+ ]++ batches = list(get_rows("dependencies", ["serde"], structlog.get_logger()))++ urls = [call[0][0] for call in mock_session.return_value.get.call_args_list]++ # The endpoint's own `crate_id` names the crate being depended on, so the declaring crate+ # and version only exist on the row because the connector stamps them.+ assert [row for batch in batches for row in batch] == [+ {+ "id": 100,+ "version_id": 1,+ "crate_id": "serde_derive",+ "kind": "normal",+ "crate": "serde",+ "version_num": "1.0.1",+ }+ ]+ # Only the most recently published versions are walked, so the version list must be capped+ # and date-sorted. Sorting by semver would drop a backport released onto an older line.+ assert urls[0] == (+ f"{CRATES_IO_BASE_URL}/crates/serde/versions?per_page={MAX_VERSIONS_PER_CRATE_FOR_DEPENDENCIES}&sort=date"+ )+ # A version whose dependencies 404 is skipped rather than failing the crate.+ assert urls[1:] == [+ f"{CRATES_IO_BASE_URL}/crates/serde/1.0.1/dependencies",+ f"{CRATES_IO_BASE_URL}/crates/serde/1.0.0/dependencies",+ ]++ def test_reverse_dependencies_joins_the_dependent_version(self):+ document = {+ "dependencies": [+ {"id": 1, "version_id": 900, "crate_id": "posthog-rs"},+ {"id": 2, "version_id": 999, "crate_id": "posthog-rs"},+ ],+ "versions": [{"id": 900, "crate": "tauri-plugin-posthog", "num": "0.2.4"}],+ "meta": {"total": 2},+ }+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:+ mock_session.return_value.get.side_effect = [_response(200, document)]++ batches = list(get_rows("reverse_dependencies", ["posthog-rs"], structlog.get_logger()))++ rows = [row for batch in batches for row in batch]+ # Without the join a row identifies its dependent only by a numeric version id.+ assert (rows[0]["crate"], rows[0]["dependent_crate"], rows[0]["dependent_version_num"]) == (+ "posthog-rs",+ "tauri-plugin-posthog",+ "0.2.4",+ )+ # An edge whose version is missing from the page still yields, with no dependent stamped.+ assert (rows[1]["dependent_crate"], rows[1]["dependent_version_num"]) == (None, None)++ def test_reverse_dependencies_walks_pages_until_a_short_one(self, monkeypatch):+ monkeypatch.setattr(f"{MODULE}.LIST_PER_PAGE", 2)+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:+ mock_session.return_value.get.side_effect = [+ _response(200, {"dependencies": [{"id": 1}, {"id": 2}], "versions": []}),+ _response(200, {"dependencies": [{"id": 3}], "versions": []}),+ ]++ batches = list(get_rows("reverse_dependencies", ["posthog-rs"], structlog.get_logger()))++ urls = [call[0][0] for call in mock_session.return_value.get.call_args_list]++ assert [row["id"] for batch in batches for row in batch] == [1, 2, 3]+ base = f"{CRATES_IO_BASE_URL}/crates/posthog-rs/reverse_dependencies"+ assert urls == [f"{base}?per_page=2&page=1", f"{base}?per_page=2&page=2"]++ def test_reverse_dependencies_stops_at_the_page_cap(self, monkeypatch):+ # crates.io serves empty pages past the end of the list instead of erroring, so a crate+ # with tens of thousands of reverse dependencies must not walk the list unbounded.+ monkeypatch.setattr(f"{MODULE}.LIST_PER_PAGE", 1)+ monkeypatch.setattr(f"{MODULE}.MAX_REVERSE_DEPENDENCY_PAGES", 3)+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:+ mock_session.return_value.get.return_value = _response(200, {"dependencies": [{"id": 1}], "versions": []})++ batches = list(get_rows("reverse_dependencies", ["serde"], structlog.get_logger()))++ request_count = mock_session.return_value.get.call_count++ assert request_count == 3+ assert len([row for batch in batches for row in batch]) == 3++ @pytest.mark.parametrize("endpoint", ["categories", "keywords"])+ def test_registry_wide_lookups_are_walked_once(self, endpoint, monkeypatch):+ monkeypatch.setattr(f"{MODULE}.LIST_PER_PAGE", 2)+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:+ mock_session.return_value.get.side_effect = [+ _response(200, {endpoint: [{"id": "a"}, {"id": "b"}]}),+ _response(200, {endpoint: [{"id": "c"}]}),+ ]++ batches = list(get_rows(endpoint, ["serde", "tokio"], structlog.get_logger()))++ urls = [call[0][0] for call in mock_session.return_value.get.call_args_list]++ assert [row["id"] for batch in batches for row in batch] == ["a", "b", "c"]+ # These tables cover the whole registry, so two configured crates must not walk them twice.+ base = f"{CRATES_IO_BASE_URL}/{endpoint}"+ assert urls == [f"{base}?sort=alpha&per_page=2&page=1", f"{base}?sort=alpha&per_page=2&page=2"]+def test_chunks_large_version_history(self, monkeypatch):# A crate with a large version history must not be yielded as one oversized list; it's# split into bounded chunks so downstream Arrow conversion stays capped.