: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): implement weights_and_biases import source (#71217)
Tom Owers0fd7b2ee6a9a
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex edca1f67c248..d57bbfc88179 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -484,6 +484,7 @@ the row lists both.| vitally | HTTP | requests + `rest_source.RESTClient` | ✅ || vultr | HTTP | requests + `rest_source.RESTClient` | ✅ || webflow | HTTP | requests | ✅ |+| weights_and_biases | HTTP (GraphQL) | requests | ✅ || windmill | HTTP | requests | ✅ || woocommerce | HTTP | requests + `rest_source.RESTClient` | ✅ || wordpress | HTTP | requests | ✅ |@@ -966,7 +967,6 @@ doesn't conflict with concurrent PRs.- waiteraid- wasabi- watchmode-- weights_and_biases- when_i_work- wikipedia_pageviews- workdaydiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex 9c495712fc8c..72030e529c44 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py@@ -4536,7 +4536,9 @@ class WebflowSourceConfig(config.Config):@config.configclass WeightsAndBiasesSourceConfig(config.Config):- pass+ api_key: str+ entity: str+ host: str | None = None@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/weights_and_biases/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/weights_and_biases/canonical_descriptions.pynew file mode 100644index 000000000000..9fdbaeb8ef6d--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/weights_and_biases/canonical_descriptions.py@@ -0,0 +1,102 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "projects": {+ "description": "A project groups the runs, sweeps, reports and artifacts for one ML workstream within the entity.",+ "docs_url": "https://docs.wandb.ai/ref/python/public-api/projects/",+ "columns": {+ "id": "Globally unique identifier for the project.",+ "name": "Name of the project, unique within its entity.",+ "entityName": "Entity (username or team) that owns the project.",+ "description": "Free-text description of the project.",+ "createdAt": "When the project was created.",+ "updatedAt": "When the project was last updated.",+ "totalRuns": "Number of runs logged to the project.",+ },+ },+ "runs": {+ "description": "A single execution of a training or evaluation script, with its configuration, tags and summary metrics.",+ "docs_url": "https://docs.wandb.ai/ref/python/public-api/runs/",+ "columns": {+ "id": "Globally unique identifier for the run.",+ "name": "Short unique run ID within the project (e.g. a1b2c3d4).",+ "displayName": "Human-readable run name shown in the W&B UI (e.g. sunny-sun-6).",+ "state": "Run state: running, finished, crashed, failed or killed.",+ "notes": "Free-text notes attached to the run.",+ "group": "Group name used to organize related runs (e.g. one distributed training job).",+ "jobType": "Job type label used to distinguish runs within a group (e.g. train, eval).",+ "tags": "List of tags applied to the run.",+ "config": "JSON-encoded hyperparameters and inputs logged for the run.",+ "summaryMetrics": "JSON-encoded final summary values of the metrics logged during the run.",+ "systemMetrics": "JSON-encoded final system metrics (GPU, CPU, memory) sampled during the run.",+ "host": "Hostname of the machine the run executed on.",+ "commit": "Git commit SHA of the code the run executed, when available.",+ "sweepName": "Name of the sweep the run belongs to, when launched by a sweep.",+ "createdAt": "When the run was created.",+ "updatedAt": "When the run was last updated.",+ "heartbeatAt": "Last time the run reported a heartbeat; advances while the run is active.",+ "user": "User who started the run.",+ "projectName": "Name of the project the run belongs to.",+ },+ },+ "sweeps": {+ "description": "A hyperparameter search that launches and coordinates a set of runs.",+ "docs_url": "https://docs.wandb.ai/ref/python/public-api/sweeps/",+ "columns": {+ "id": "Globally unique identifier for the sweep.",+ "name": "Short unique sweep ID within the project.",+ "displayName": "Human-readable sweep name shown in the W&B UI.",+ "state": "Sweep state: pending, running, paused, finished, canceled or crashed.",+ "method": "Search strategy: grid, random or bayes.",+ "config": "YAML sweep configuration, including the parameter search space and target metric.",+ "createdAt": "When the sweep was created.",+ "updatedAt": "When the sweep was last updated.",+ "heartbeatAt": "Last time a sweep agent reported a heartbeat.",+ "runCount": "Number of runs the sweep has launched.",+ "runCountExpected": "Number of runs the sweep is expected to launch, when bounded.",+ "bestLoss": "Best value of the sweep's target metric across its runs.",+ "user": "User who created the sweep.",+ "projectName": "Name of the project the sweep belongs to.",+ },+ },+ "reports": {+ "description": "A saved report (workspace view) documenting and visualizing runs in a project.",+ "docs_url": "https://docs.wandb.ai/guides/reports/",+ "columns": {+ "id": "Globally unique identifier for the report.",+ "name": "Internal name of the report.",+ "displayName": "Title of the report shown in the W&B UI.",+ "description": "Free-text description of the report.",+ "type": "View type of the report (e.g. runs).",+ "projectName": "Name of the project the report belongs to.",+ "entityName": "Entity (username or team) that owns the report.",+ "viewCount": "Number of times the report has been viewed.",+ "createdAt": "When the report was created.",+ "updatedAt": "When the report was last updated.",+ "user": "User who created the report.",+ },+ },+ "artifacts": {+ "description": "A single artifact version: an immutable snapshot of a dataset, model or other files tracked for lineage.",+ "docs_url": "https://docs.wandb.ai/ref/python/public-api/artifacts/",+ "columns": {+ "id": "Globally unique identifier for the artifact version.",+ "digest": "Content checksum of the artifact version.",+ "description": "Free-text description of the artifact version.",+ "state": "Artifact state: pending, committed or deleted.",+ "size": "Total size of the artifact version in bytes.",+ "fileCount": "Number of files in the artifact version.",+ "versionIndex": "Zero-based version number within the collection (v0, v1, ...).",+ "metadata": "JSON-encoded user-supplied metadata attached to the artifact version.",+ "commitHash": "Commit hash identifying this version within its collection.",+ "createdAt": "When the artifact version was created.",+ "updatedAt": "When the artifact version was last updated.",+ "version": "Version alias within the collection (e.g. v3).",+ "projectName": "Name of the project the artifact belongs to.",+ "artifactTypeName": "Artifact type (e.g. model, dataset, wandb-history).",+ "collectionName": "Artifact collection (sequence or portfolio) the version belongs to.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/weights_and_biases/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/weights_and_biases/settings.pynew file mode 100644index 000000000000..76cd7bc3ead8--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/weights_and_biases/settings.py@@ -0,0 +1,59 @@+from dataclasses import dataclass, field++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++# Verified server-side against the live GraphQL API: `runs(filters:)` honors MongoDB-style+# `{"createdAt": {"$gt": ...}}` / `{"heartbeatAt": {"$gt": ...}}` filters (a future-dated+# cutoff returns zero rows). `heartbeatAt` advances while a run is active, so it also picks+# up state/summary changes on recently active runs that a `createdAt` cursor would miss.+_RUN_INCREMENTAL_FIELDS: list[IncrementalField] = [+ {+ "label": "createdAt",+ "type": IncrementalFieldType.DateTime,+ "field": "createdAt",+ "field_type": IncrementalFieldType.DateTime,+ },+ {+ "label": "heartbeatAt",+ "type": IncrementalFieldType.DateTime,+ "field": "heartbeatAt",+ "field_type": IncrementalFieldType.DateTime,+ },+]+++@dataclass+class WeightsAndBiasesEndpointConfig:+ # GraphQL node ids are globally unique (they encode entity + project), so a single-column+ # key stays unique even though fan-out endpoints aggregate rows from every project.+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ partition_key: str = "createdAt"+ description: str | None = None+++WANDB_ENDPOINTS: dict[str, WeightsAndBiasesEndpointConfig] = {+ "projects": WeightsAndBiasesEndpointConfig(),+ "runs": WeightsAndBiasesEndpointConfig(+ incremental_fields=_RUN_INCREMENTAL_FIELDS,+ description=(+ "One row per run across every project in the entity, including config, tags and "+ "summary metrics. Incremental syncs filter server-side on createdAt or heartbeatAt; "+ "pick heartbeatAt to also pick up state and metric changes on recently active runs"+ ),+ ),+ "sweeps": WeightsAndBiasesEndpointConfig(),+ "reports": WeightsAndBiasesEndpointConfig(),+ "artifacts": WeightsAndBiasesEndpointConfig(+ description=(+ "One row per artifact version across every project, walked per artifact type and "+ "collection. Projects with many run-history artifacts can make this table large"+ ),+ ),+}++ENDPOINTS = tuple(WANDB_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in WANDB_ENDPOINTS.items() if config.incremental_fields+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/weights_and_biases/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/weights_and_biases/source.pyindex 0444fa7ae293..04b9cb355c34 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/weights_and_biases/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/weights_and_biases/source.py@@ -1,32 +1,180 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import (WeightsAndBiasesSourceConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.weights_and_biases.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ WANDB_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.weights_and_biases.weights_and_biases import (+ WeightsAndBiasesConfigError,+ WeightsAndBiasesResumeConfig,+ validate_credentials as validate_wandb_credentials,+ validate_host as validate_wandb_host,+ weights_and_biases_source,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class WeightsAndBiasesSource(SimpleSource[WeightsAndBiasesSourceConfig]):+class WeightsAndBiasesSource(ResumableSource[WeightsAndBiasesSourceConfig, WeightsAndBiasesResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.WEIGHTSANDBIASES+ @property+ def connection_host_fields(self) -> list[str]:+ # `entity` selects which W&B account's projects/runs/artifacts the stored key pulls, so+ # changing it retargets the preserved credential at different data. Require the key to be+ # re-entered on change. (`host` — where the key is actually sent — is already handled by+ # the framework's separate `host`-field check.)+ return ["entity"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.WEIGHTS_AND_BIASES,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Weights & Biases",+ releaseStatus=ReleaseStatus.ALPHA,+ keywords=["wandb", "ml", "experiment tracking", "mlops"],+ caption="""Enter your Weights & Biases API key to pull your experiment tracking data into the PostHog Data warehouse.++You can find your API key at [wandb.ai/authorize](https://wandb.ai/authorize). The entity is the username or team whose projects you want to sync.++If you use W&B Dedicated Cloud or a self-managed server, set the host to your deployment's URL (for example `https://acme.wandb.io`). Leave it empty for W&B SaaS cloud.""",iconPath="/static/services/weights_and_biases.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/weights-and-biases",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="entity",+ label="Entity (username or team)",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="my-team",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="host",+ label="Host (Dedicated Cloud or self-managed only)",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="https://api.wandb.ai",+ secret=False,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.weights_and_biases.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized": "Your Weights & Biases API key is invalid or has been revoked. Generate a new key at wandb.ai/authorize, then reconnect.",+ "403 Client Error: Forbidden": "Your Weights & Biases API key does not have access to this data. Check the key's permissions on the entity, then reconnect.",+ "Weights & Biases GraphQL error: permission denied": "Your Weights & Biases API key does not have access to this entity or project. Check the entity name and the key's permissions.",+ }++ def get_schemas(+ self,+ config: WeightsAndBiasesSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=INCREMENTAL_FIELDS.get(endpoint) is not None,+ # Runs mutate after creation (state, summary metrics), so merge is the only+ # safe write mode — append would keep stale duplicates.+ supports_append=False,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ description=WANDB_ENDPOINTS[endpoint].description,+ )+ for endpoint in ENDPOINTS+ ]++ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]++ return schemas++ def validate_credentials(+ self, config: WeightsAndBiasesSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ try:+ validate_wandb_host(config.host)+ except WeightsAndBiasesConfigError as err:+ return False, str(err)++ if validate_wandb_credentials(config.api_key, config.host):+ return True, None++ return False, "Invalid Weights & Biases API key"++ def get_resumable_source_manager(+ self, inputs: SourceInputs+ ) -> ResumableSourceManager[WeightsAndBiasesResumeConfig]:+ return ResumableSourceManager[WeightsAndBiasesResumeConfig](inputs, WeightsAndBiasesResumeConfig)++ def source_for_pipeline(+ self,+ config: WeightsAndBiasesSourceConfig,+ resumable_source_manager: ResumableSourceManager[WeightsAndBiasesResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return weights_and_biases_source(+ api_key=config.api_key,+ host=config.host,+ entity=config.entity,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,+ incremental_field=inputs.incremental_field,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/weights_and_biases/tests/test_weights_and_biases.py b/products/warehouse_sources/backend/temporal/data_imports/sources/weights_and_biases/tests/test_weights_and_biases.pynew file mode 100644index 000000000000..35d754ce2a4b--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/weights_and_biases/tests/test_weights_and_biases.py@@ -0,0 +1,455 @@+import json+import threading+from datetime import UTC, date, datetime+from typing import Any++import pytest+from unittest import mock++from products.warehouse_sources.backend.temporal.data_imports.sources.weights_and_biases.settings import (+ ENDPOINTS,+ WANDB_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.weights_and_biases.weights_and_biases import (+ PAGE_SIZE,+ WeightsAndBiasesConfigError,+ WeightsAndBiasesGraphQLError,+ WeightsAndBiasesResumeConfig,+ _format_timestamp,+ _graphql_url,+ get_rows,+ validate_credentials,+ validate_host,+ weights_and_biases_source,+)++_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.weights_and_biases.weights_and_biases"+++def _make_manager(resume_state: WeightsAndBiasesResumeConfig | None = None) -> mock.MagicMock:+ manager = mock.MagicMock()+ manager.can_resume.return_value = resume_state is not None+ manager.load_state.return_value = resume_state+ return manager+++def _connection_response(+ connection_path: tuple[str, ...],+ edges: list[dict[str, Any]],+ has_next: bool = False,+ end_cursor: str | None = None,+) -> mock.MagicMock:+ data: Any = {+ "edges": edges,+ "pageInfo": {"endCursor": end_cursor or (edges[-1].get("cursor") if edges else None), "hasNextPage": has_next},+ }+ for key in reversed(connection_path):+ data = {key: data}+ return _ok_response({"data": data})+++def _ok_response(payload: dict[str, Any]) -> mock.MagicMock:+ # _execute reads the body in chunks via response.raw.read(...) until EOF (empty bytes), under a+ # size + time cap, not response.json(). One chunk with the payload, then EOF.+ resp = mock.MagicMock()+ resp.status_code = 200+ resp.ok = True+ resp.headers = {}+ resp.raw.read.side_effect = [json.dumps(payload).encode(), b""]+ return resp+++def _project_edge(name: str) -> dict[str, Any]:+ return {"node": {"id": f"proj-id-{name}", "name": name, "createdAt": "2024-01-01T00:00:00Z"}}+++def _run_edge(run_id: str) -> dict[str, Any]:+ return {"node": {"id": run_id, "name": run_id, "state": "finished", "createdAt": "2024-01-01T00:00:00Z"}}+++def _projects_response(names: list[str], has_next: bool = False, end_cursor: str | None = None) -> mock.MagicMock:+ return _connection_response(("models",), [_project_edge(n) for n in names], has_next, end_cursor)+++class TestGraphQLUrl:+ @pytest.mark.parametrize(+ "host, expected",+ [+ (None, "https://api.wandb.ai/graphql"),+ ("", "https://api.wandb.ai/graphql"),+ (" ", "https://api.wandb.ai/graphql"),+ ("https://acme.wandb.io", "https://acme.wandb.io/graphql"),+ ("https://acme.wandb.io/", "https://acme.wandb.io/graphql"),+ # A bare host is assumed https rather than rejected — users routinely paste one.+ ("acme.wandb.io", "https://acme.wandb.io/graphql"),+ ],+ )+ # is_url_allowed runs real DNS when DEBUG=False (as in CI); the fake hosts here aren't SSRF+ # cases, so allow them deterministically.+ @mock.patch(f"{_MODULE}.is_url_allowed", return_value=(True, None))+ def test_host_normalization(self, _mock_allowed, host, expected):+ assert _graphql_url(host) == expected++ @pytest.mark.parametrize("host", ["http://acme.wandb.io", "http://api.wandb.ai", "ftp://acme.wandb.io"])+ def test_non_https_host_is_rejected(self, host):+ # The API key is sent as HTTP Basic auth, so a plaintext scheme would leak it on the wire.+ with pytest.raises(WeightsAndBiasesConfigError, match="https"):+ _graphql_url(host)+ with pytest.raises(WeightsAndBiasesConfigError, match="https"):+ validate_host(host)++ @mock.patch(f"{_MODULE}.is_url_allowed", return_value=(False, "blocked: private IP"))+ def test_ssrf_blocked_host_is_rejected(self, _mock_allowed):+ # A custom host resolving to an internal/metadata address must be refused before any+ # request leaves the worker (defense-in-depth over the Smokescreen egress proxy).+ with pytest.raises(WeightsAndBiasesConfigError, match="not allowed"):+ _graphql_url("https://internal.example")+ with pytest.raises(WeightsAndBiasesConfigError, match="not allowed"):+ validate_host("https://internal.example")+++class TestFormatTimestamp:+ @pytest.mark.parametrize(+ "value, expected",+ [+ (datetime(2024, 1, 2, 3, 4, 5, tzinfo=UTC), "2024-01-02T03:04:05Z"),+ (datetime(2024, 1, 2, 3, 4, 5), "2024-01-02T03:04:05Z"),+ (date(2024, 1, 2), "2024-01-02T00:00:00Z"),+ ("2024-01-02T03:04:05Z", "2024-01-02T03:04:05Z"),+ ],+ )+ def test_format_values(self, value, expected):+ assert _format_timestamp(value) == expected+++class TestValidateCredentials:+ @pytest.mark.parametrize(+ "viewer, expected",+ [+ ({"id": "abc", "username": "someone"}, True),+ (None, False), # the API returns 200 with viewer=null for a bad key+ ],+ )+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_viewer_presence_decides_validity(self, mock_session, viewer, expected):+ mock_session.return_value.post.return_value = _ok_response({"data": {"viewer": viewer}})++ assert validate_credentials("key", None) is expected++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_invalid_on_exception(self, mock_session):+ mock_session.return_value.post.side_effect = Exception("boom")+ assert validate_credentials("key", None) is False++ @mock.patch(f"{_MODULE}.is_url_allowed", return_value=(True, None))+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_session_uses_basic_auth_with_api_username(self, mock_session, _mock_allowed):+ mock_session.return_value.post.return_value = _ok_response({"data": {"viewer": {"id": "abc"}}})++ validate_credentials("secret-key", "https://acme.wandb.io")++ assert mock_session.return_value.auth == ("api", "secret-key")+ assert mock_session.return_value.post.call_args.args[0] == "https://acme.wandb.io/graphql"+++class TestProjectsEndpoint:+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_paginates_and_saves_state_after_yield(self, mock_session):+ mock_session.return_value.post.side_effect = [+ _projects_response(["p1", "p2"], has_next=True, end_cursor="cur-1"),+ _projects_response(["p3"], has_next=False),+ ]++ manager = _make_manager()+ batches = list(get_rows("key", None, "acme", "projects", mock.MagicMock(), manager))++ assert [row["name"] for batch in batches for row in batch] == ["p1", "p2", "p3"]+ manager.save_state.assert_called_once()+ assert manager.save_state.call_args.args[0].cursor == "cur-1"+ second_vars = mock_session.return_value.post.call_args_list[1].kwargs["json"]["variables"]+ assert second_vars["after"] == "cur-1"+ assert second_vars["first"] == PAGE_SIZE++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_empty_edges_page_with_has_next_keeps_paginating(self, mock_session):+ # The live API returns empty edges with hasNextPage=true for pages whose rows are+ # hidden from the caller — terminating on the empty page would silently truncate.+ mock_session.return_value.post.side_effect = [+ _connection_response(("models",), [], has_next=True, end_cursor="cur-1"),+ _projects_response(["p1"], has_next=False),+ ]++ batches = list(get_rows("key", None, "acme", "projects", mock.MagicMock(), _make_manager()))++ assert [row["name"] for batch in batches for row in batch] == ["p1"]++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_non_advancing_cursor_terminates(self, mock_session):+ mock_session.return_value.post.side_effect = [+ _projects_response(["p1"], has_next=True, end_cursor="cur-1"),+ _projects_response(["p2"], has_next=True, end_cursor="cur-1"),+ ]++ batches = list(get_rows("key", None, "acme", "projects", mock.MagicMock(), _make_manager()))++ assert mock_session.return_value.post.call_count == 2+ assert [row["name"] for batch in batches for row in batch] == ["p1", "p2"]++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_resumes_from_saved_cursor(self, mock_session):+ mock_session.return_value.post.return_value = _projects_response(["p9"], has_next=False)++ manager = _make_manager(WeightsAndBiasesResumeConfig(cursor="cur-resume"))+ list(get_rows("key", None, "acme", "projects", mock.MagicMock(), manager))++ variables = mock_session.return_value.post.call_args.kwargs["json"]["variables"]+ assert variables["after"] == "cur-resume"+++class TestRunsEndpoint:+ @pytest.mark.parametrize(+ "incremental_field, expected_filter_key, expected_order",+ [+ ("createdAt", "createdAt", "+created_at"),+ ("heartbeatAt", "heartbeatAt", "+heartbeat_at"),+ # An unknown/legacy field falls back to the stable default rather than sending a+ # filter the server would reject.+ ("nonsense", "createdAt", "+created_at"),+ ],+ )+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_incremental_filter_and_order(self, mock_session, incremental_field, expected_filter_key, expected_order):+ mock_session.return_value.post.side_effect = [+ _projects_response(["proj-a"]),+ _connection_response(("project", "runs"), []),+ ]++ list(+ get_rows(+ "key",+ None,+ "acme",+ "runs",+ mock.MagicMock(),+ _make_manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2024, 1, 2, tzinfo=UTC),+ incremental_field=incremental_field,+ )+ )++ variables = mock_session.return_value.post.call_args.kwargs["json"]["variables"]+ assert json.loads(variables["filters"]) == {expected_filter_key: {"$gt": "2024-01-02T00:00:00Z"}}+ assert variables["order"] == expected_order++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_full_refresh_has_null_filters_and_stable_order(self, mock_session):+ mock_session.return_value.post.side_effect = [+ _projects_response(["proj-a"]),+ _connection_response(("project", "runs"), []),+ ]++ list(get_rows("key", None, "acme", "runs", mock.MagicMock(), _make_manager()))++ variables = mock_session.return_value.post.call_args.kwargs["json"]["variables"]+ assert variables["filters"] is None+ assert variables["order"] == "+created_at"++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_rows_carry_project_name_and_state_saved_per_page(self, mock_session):+ mock_session.return_value.post.side_effect = [+ _projects_response(["proj-a"]),+ _connection_response(("project", "runs"), [_run_edge("r1")], has_next=True, end_cursor="cur-1"),+ _connection_response(("project", "runs"), [_run_edge("r2")], has_next=False),+ ]++ manager = _make_manager()+ batches = list(get_rows("key", None, "acme", "runs", mock.MagicMock(), manager))++ rows = [row for batch in batches for row in batch]+ assert [(row["id"], row["projectName"]) for row in rows] == [("r1", "proj-a"), ("r2", "proj-a")]+ manager.save_state.assert_called_once()+ saved = manager.save_state.call_args.args[0]+ assert (saved.project, saved.cursor) == ("proj-a", "cur-1")++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_fan_out_resumes_from_bookmarked_project(self, mock_session):+ mock_session.return_value.post.side_effect = [+ _projects_response(["proj-a", "proj-b", "proj-c"]),+ _connection_response(("project", "runs"), [_run_edge("rb")], has_next=False),+ _connection_response(("project", "runs"), [_run_edge("rc")], has_next=False),+ ]++ manager = _make_manager(WeightsAndBiasesResumeConfig(project="proj-b", cursor="cur-9"))+ batches = list(get_rows("key", None, "acme", "runs", mock.MagicMock(), manager))++ run_calls = [+ call.kwargs["json"]["variables"]+ for call in mock_session.return_value.post.call_args_list+ if call.kwargs["json"]["variables"].get("project")+ ]+ # proj-a is skipped entirely; only the resumed-into project uses the saved cursor.+ assert [(v["project"], v["after"]) for v in run_calls] == [("proj-b", "cur-9"), ("proj-c", None)]+ assert [row["id"] for batch in batches for row in batch] == ["rb", "rc"]+ # The bookmark advanced to proj-c once proj-b completed.+ assert (manager.save_state.call_args.args[0].project, manager.save_state.call_args.args[0].cursor) == (+ "proj-c",+ None,+ )++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_deleted_bookmarked_project_restarts_from_first(self, mock_session):+ mock_session.return_value.post.side_effect = [+ _projects_response(["proj-a"]),+ _connection_response(("project", "runs"), [_run_edge("ra")], has_next=False),+ ]++ manager = _make_manager(WeightsAndBiasesResumeConfig(project="deleted-proj", cursor="cur-9"))+ batches = list(get_rows("key", None, "acme", "runs", mock.MagicMock(), manager))++ run_vars = mock_session.return_value.post.call_args.kwargs["json"]["variables"]+ assert (run_vars["project"], run_vars["after"]) == ("proj-a", None)+ assert [row["id"] for batch in batches for row in batch] == ["ra"]+++class TestArtifactsEndpoint:+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_rows_carry_parent_identifiers(self, mock_session):+ artifact_edge = {+ "version": "v3",+ "node": {"id": "art-1", "digest": "abc", "state": "COMMITTED", "createdAt": "2024-01-01T00:00:00Z"},+ }+ mock_session.return_value.post.side_effect = [+ _projects_response(["proj-a"]),+ _connection_response(("project", "artifactTypes"), [{"node": {"name": "model"}}]),+ _connection_response(("project", "artifactType", "artifactCollections"), [{"node": {"name": "coll-1"}}]),+ _connection_response(("project", "artifactType", "artifactCollection", "artifacts"), [artifact_edge]),+ ]++ batches = list(get_rows("key", None, "acme", "artifacts", mock.MagicMock(), _make_manager()))++ rows = [row for batch in batches for row in batch]+ assert len(rows) == 1+ assert rows[0]["id"] == "art-1"+ assert rows[0]["version"] == "v3"+ assert rows[0]["projectName"] == "proj-a"+ assert rows[0]["artifactTypeName"] == "model"+ assert rows[0]["collectionName"] == "coll-1"++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_artifact_type_deleted_mid_sync_is_skipped(self, mock_session):+ null_type_resp = _ok_response({"data": {"project": {"artifactType": None}}})+ mock_session.return_value.post.side_effect = [+ _projects_response(["proj-a"]),+ _connection_response(("project", "artifactTypes"), [{"node": {"name": "model"}}]),+ null_type_resp,+ ]++ batches = list(get_rows("key", None, "acme", "artifacts", mock.MagicMock(), _make_manager()))++ assert batches == []+++class TestErrors:+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_graphql_error_raises(self, mock_session):+ mock_session.return_value.post.return_value = _ok_response({"errors": [{"message": "permission denied"}]})++ with pytest.raises(WeightsAndBiasesGraphQLError, match="permission denied"):+ list(get_rows("key", None, "acme", "projects", mock.MagicMock(), _make_manager()))++ def test_unknown_endpoint_raises(self):+ with pytest.raises(ValueError, match="Unknown Weights & Biases endpoint"):+ list(get_rows("key", None, "acme", "nope", mock.MagicMock(), _make_manager()))++ @mock.patch(f"{_MODULE}.MAX_PAGES_PER_CONNECTION", 3)+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_pagination_stops_at_page_cap(self, mock_session):+ # A hostile host that returns hasNextPage=true with a fresh cursor forever must not loop+ # indefinitely — the page cap bounds it.+ counter = {"n": 0}++ def endless_post(*args, **kwargs):+ counter["n"] += 1+ return _projects_response([f"proj-{counter['n']}"], has_next=True, end_cursor=f"c{counter['n']}")++ mock_session.return_value.post.side_effect = endless_post++ batches = list(get_rows("key", None, "acme", "projects", mock.MagicMock(), _make_manager()))++ assert mock_session.return_value.post.call_count == 3+ assert len(batches) == 3++ @mock.patch(f"{_MODULE}.MAX_RESPONSE_BYTES", 16)+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_oversized_response_body_is_rejected(self, mock_session):+ # The host is customer-controlled; an unbounded body must not be buffered into a worker.+ oversized = mock.MagicMock()+ oversized.status_code = 200+ oversized.ok = True+ oversized.headers = {}+ oversized.raw.read.return_value = b"x" * 17+ mock_session.return_value.post.return_value = oversized++ with pytest.raises(WeightsAndBiasesGraphQLError, match="oversized"):+ list(get_rows("key", None, "acme", "projects", mock.MagicMock(), _make_manager()))++ @mock.patch(f"{_MODULE}.MAX_TRANSFER_SECONDS", 0.2)+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_slow_response_exceeding_transfer_deadline_is_rejected(self, mock_session):+ # A host that keeps a read blocked (dripping bytes below the per-read inactivity timeout)+ # must still be cut off by the wall-clock deadline, which interrupts the blocked read by+ # closing the response. The read here blocks until close() releases it.+ release = threading.Event()+ resp = mock.MagicMock()+ resp.status_code = 200+ resp.ok = True+ resp.headers = {}+ resp.raw.read.side_effect = lambda *a, **k: (release.wait(timeout=5), b"")[1]+ resp.close.side_effect = release.set+ mock_session.return_value.post.return_value = resp++ with pytest.raises(WeightsAndBiasesGraphQLError, match="deadline"):+ list(get_rows("key", None, "acme", "projects", mock.MagicMock(), _make_manager()))++ assert resp.close.called++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_forced_content_encoding_is_rejected(self, mock_session):+ # We request Accept-Encoding: identity and read the body undecoded; a host that compresses+ # anyway (a decompression-bomb vector) must be rejected rather than decoded.+ compressed = mock.MagicMock()+ compressed.status_code = 200+ compressed.ok = True+ compressed.headers = {"Content-Encoding": "gzip"}+ mock_session.return_value.post.return_value = compressed++ with pytest.raises(WeightsAndBiasesGraphQLError, match="Content-Encoding"):+ list(get_rows("key", None, "acme", "projects", mock.MagicMock(), _make_manager()))++ @mock.patch(f"{_MODULE}.MAX_RETAINED_PROJECT_NAME_BYTES", 10)+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_oversized_fan_out_project_list_is_rejected(self, mock_session):+ # A hostile host can page project names back indefinitely; the fan-out enumeration must+ # stop buffering them before the retained list can exhaust a worker.+ mock_session.return_value.post.side_effect = [+ _projects_response(["p" * 4], has_next=True, end_cursor="c1"),+ _projects_response(["q" * 8], has_next=False),+ ]++ with pytest.raises(WeightsAndBiasesGraphQLError, match="unreasonably large project list"):+ list(get_rows("key", None, "acme", "runs", mock.MagicMock(), _make_manager()))+++class TestSourceResponse:+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ def test_response_metadata_per_endpoint(self, endpoint):+ response = weights_and_biases_source("key", None, "acme", endpoint, mock.MagicMock(), _make_manager())++ assert response.name == endpoint+ assert response.primary_keys == WANDB_ENDPOINTS[endpoint].primary_keys+ # Fan-out over projects means rows only ascend within one project — the watermark+ # commits at run end.+ assert response.sort_mode == "desc"+ assert response.partition_mode == "datetime"+ assert response.partition_keys == ["createdAt"]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/weights_and_biases/tests/test_weights_and_biases_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/weights_and_biases/tests/test_weights_and_biases_source.pynew file mode 100644index 000000000000..c046a5e03e92--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/weights_and_biases/tests/test_weights_and_biases_source.py@@ -0,0 +1,162 @@+import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import (+ WeightsAndBiasesSourceConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.weights_and_biases.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.weights_and_biases.source import (+ WeightsAndBiasesSource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.weights_and_biases.weights_and_biases import (+ WeightsAndBiasesResumeConfig,+)+from products.warehouse_sources.backend.types import ExternalDataSourceType++_SOURCE_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.weights_and_biases.source"+++class TestWeightsAndBiasesSource:+ def setup_method(self):+ self.source = WeightsAndBiasesSource()+ self.team_id = 123+ self.config = WeightsAndBiasesSourceConfig(api_key="wb-key", entity="acme")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.WEIGHTSANDBIASES++ def test_entity_is_a_connection_host_field(self):+ # Changing `entity` retargets the stored key at another W&B account's data, so the update+ # serializer must re-require the key — guard against dropping that from the override.+ assert "entity" in self.source.connection_host_fields++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "WeightsAndBiases"+ assert config.label == "Weights & Biases"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is None+ assert [f.name for f in config.fields] == ["api_key", "entity", "host"]++ def test_api_key_field_is_secret_password(self):+ config = self.source.get_source_config+ key_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")+ assert key_field.type == SourceFieldInputConfigType.PASSWORD+ assert key_field.secret is True+ assert key_field.required is True++ def test_host_field_is_optional(self):+ config = self.source.get_source_config+ host_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "host")+ assert host_field.required is False++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://api.wandb.ai/graphql",+ "401 Client Error: Unauthorized for url: https://acme.wandb.io/graphql",+ "Weights & Biases GraphQL error: permission denied",+ ],+ )+ def test_non_retryable_errors_match_auth_failures(self, observed_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable_errors)++ @pytest.mark.parametrize(+ "other_error",+ [+ "500 Server Error for url: https://api.wandb.ai/graphql",+ "Weights & Biases GraphQL error: something went wrong",+ ],+ )+ def test_non_retryable_errors_do_not_match_transient_failures(self, other_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable_errors)++ def test_get_schemas(self):+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}++ assert set(schemas) == set(ENDPOINTS)+ # Only runs has a verified server-side timestamp filter; everything else is full refresh.+ assert [name for name, schema in schemas.items() if schema.supports_incremental] == ["runs"]+ # Runs mutate after creation, so merge is the only safe write mode.+ assert not any(schema.supports_append for schema in schemas.values())+ assert [f["field"] for f in schemas["runs"].incremental_fields] == ["createdAt", "heartbeatAt"]+ assert schemas["runs"].incremental_fields == INCREMENTAL_FIELDS["runs"]++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["runs", "nope"])+ assert [schema.name for schema in schemas] == ["runs"]++ @pytest.mark.parametrize(+ "mock_return, expected_valid, expected_message",+ [+ (True, True, None),+ (False, False, "Invalid Weights & Biases API key"),+ ],+ )+ @mock.patch(f"{_SOURCE_MODULE}.validate_wandb_credentials")+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid, expected_message):+ mock_validate.return_value = mock_return++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is expected_valid+ assert error_message == expected_message+ mock_validate.assert_called_once_with("wb-key", None)++ @mock.patch(f"{_SOURCE_MODULE}.validate_wandb_credentials")+ def test_validate_credentials_rejects_non_https_host_before_api_call(self, mock_validate):+ config = WeightsAndBiasesSourceConfig(api_key="wb-key", entity="acme", host="http://acme.wandb.io")++ is_valid, error_message = self.source.validate_credentials(config, self.team_id)++ assert is_valid is False+ assert error_message is not None and "https" in error_message+ mock_validate.assert_not_called()++ def test_get_resumable_source_manager_binds_resume_config(self):+ manager = self.source.get_resumable_source_manager(mock.MagicMock())++ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is WeightsAndBiasesResumeConfig++ @mock.patch(f"{_SOURCE_MODULE}.weights_and_biases_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_wandb_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "runs"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2024-01-02T03:04:05Z"+ inputs.incremental_field = "heartbeatAt"+ manager = mock.MagicMock()+ config = WeightsAndBiasesSourceConfig(api_key="wb-key", entity="acme", host="https://acme.wandb.io")++ self.source.source_for_pipeline(config, manager, inputs)++ kwargs = mock_wandb_source.call_args.kwargs+ assert kwargs["api_key"] == "wb-key"+ assert kwargs["entity"] == "acme"+ assert kwargs["host"] == "https://acme.wandb.io"+ assert kwargs["endpoint"] == "runs"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2024-01-02T03:04:05Z"+ assert kwargs["incremental_field"] == "heartbeatAt"++ @mock.patch(f"{_SOURCE_MODULE}.weights_and_biases_source")+ def test_source_for_pipeline_omits_last_value_on_full_refresh(self, mock_wandb_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "projects"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2024-01-02T03:04:05Z"++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ assert mock_wandb_source.call_args.kwargs["db_incremental_field_last_value"] is Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/weights_and_biases/weights_and_biases.py b/products/warehouse_sources/backend/temporal/data_imports/sources/weights_and_biases/weights_and_biases.pynew file mode 100644index 000000000000..ebb05fc8ef34--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/weights_and_biases/weights_and_biases.py@@ -0,0 +1,663 @@+import json+import threading+import dataclasses+from collections.abc import Callable, Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional+from urllib.parse import urlsplit++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from posthog.security.url_validation import is_url_allowed++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.weights_and_biases.settings import WANDB_ENDPOINTS++WANDB_DEFAULT_HOST = "https://api.wandb.ai"+PAGE_SIZE = 50+REQUEST_TIMEOUT_SECONDS = 60+MAX_RETRY_ATTEMPTS = 5+# The API key travels as HTTP Basic auth, and the host is customer-controlled, so cap the body+# we read from it. A page of 50 runs carries config/summaryMetrics JSON blobs but stays well+# under this; the cap only exists to stop a hostile or misconfigured host exhausting a shared+# warehouse worker with an unbounded (or slowly streamed) response.+MAX_RESPONSE_BYTES = 100 * 1024 * 1024+# Bound pagination against a hostile or misconfigured host that keeps returning+# hasNextPage=true with a fresh cursor forever (matching sibling sources). At PAGE_SIZE=50 this+# is 5M rows per connection — far beyond any real entity — so a legitimate sync never hits it,+# while a runaway server can't loop indefinitely or grow the enumerated project list without end.+MAX_PAGES_PER_CONNECTION = 100_000+# Fan-out endpoints (runs/sweeps/reports/artifacts) enumerate every project name up front to+# drive iteration and resume. That list is the one piece of state that grows with the response,+# so bound it: a customer-controlled host could otherwise page back millions of large project+# names (each page is capped, but the accumulated list is not) and exhaust a shared worker. The+# caps sit far above any real entity's project count/name length, so a legitimate sync never+# trips them.+MAX_FAN_OUT_PROJECTS = 250_000+MAX_RETAINED_PROJECT_NAME_BYTES = 16 * 1024 * 1024+RESPONSE_READ_CHUNK_BYTES = 1024 * 1024+# Wall-clock ceiling for consuming a single response body. The request timeout is a per-read+# inactivity limit, so a host that drips a byte before each timeout could hold a worker for the+# whole import; this bounds total transfer time regardless of drip cadence.+MAX_TRANSFER_SECONDS = 120++# Advertised incremental field (row column, camelCase as the API returns it) -> the ascending+# order key the runs connection accepts. Both filter + order verified against the live API.+RUN_INCREMENTAL_SORT_KEYS: dict[str, str] = {+ "createdAt": "+created_at",+ "heartbeatAt": "+heartbeat_at",+}+_DEFAULT_RUN_INCREMENTAL_FIELD = "createdAt"+++class WeightsAndBiasesRetryableError(Exception):+ pass+++class WeightsAndBiasesGraphQLError(Exception):+ pass+++class WeightsAndBiasesConfigError(Exception):+ pass+++class WeightsAndBiasesResumeConfig:+ # Project-name bookmark for the fan-out endpoints (runs, sweeps, reports, artifacts). A+ # stable name (not a positional index) so projects added/removed between a crash and the+ # retry can't resume us into the wrong project. None for the top-level projects endpoint.+ project: str | None = None+ # Relay endCursor within the current connection. None means "start the connection at its+ # first page" — used when the bookmark advances to the next project. Artifacts resume at+ # project granularity only (nested type/collection cursors aren't representable), so a+ # resumed project re-walks its artifacts and merge dedupes on the primary key.+ cursor: str | None = None+++_PROJECTS_QUERY = """+query Projects($entity: String!, $first: Int!, $after: String) {+ models(entityName: $entity, first: $first, after: $after) {+ edges { node { id name entityName description createdAt updatedAt totalRuns } }+ pageInfo { endCursor hasNextPage }+ }+}+"""++_RUNS_QUERY = """+query Runs($entity: String!, $project: String!, $filters: JSONString, $order: String, $first: Int!, $after: String) {+ project(entityName: $entity, name: $project) {+ runs(filters: $filters, order: $order, first: $first, after: $after) {+ edges {+ node {+ id name displayName state notes group jobType tags config summaryMetrics systemMetrics+ host commit sweepName createdAt updatedAt heartbeatAt user { username }+ }+ }+ pageInfo { endCursor hasNextPage }+ }+ }+}+"""++_SWEEPS_QUERY = """+query Sweeps($entity: String!, $project: String!, $first: Int!, $after: String) {+ project(entityName: $entity, name: $project) {+ sweeps(first: $first, after: $after) {+ edges {+ node {+ id name displayName state method config createdAt updatedAt heartbeatAt+ runCount runCountExpected bestLoss user { username }+ }+ }+ pageInfo { endCursor hasNextPage }+ }+ }+}+"""++_REPORTS_QUERY = """+query Reports($entity: String!, $project: String!, $first: Int!, $after: String) {+ project(entityName: $entity, name: $project) {+ allViews(viewType: "runs", first: $first, after: $after) {+ edges {+ node {+ id name displayName description type projectName entityName viewCount+ createdAt updatedAt user { username }+ }+ }+ pageInfo { endCursor hasNextPage }+ }+ }+}+"""++_ARTIFACT_TYPES_QUERY = """+query ArtifactTypes($entity: String!, $project: String!, $first: Int!, $after: String) {+ project(entityName: $entity, name: $project) {+ artifactTypes(first: $first, after: $after) {+ edges { node { name } }+ pageInfo { endCursor hasNextPage }+ }+ }+}+"""++_ARTIFACT_COLLECTIONS_QUERY = """+query ArtifactCollections($entity: String!, $project: String!, $type: String!, $first: Int!, $after: String) {+ project(entityName: $entity, name: $project) {+ artifactType(name: $type) {+ artifactCollections(first: $first, after: $after) {+ edges { node { name } }+ pageInfo { endCursor hasNextPage }+ }+ }+ }+}+"""++_ARTIFACTS_QUERY = """+query ArtifactVersions($entity: String!, $project: String!, $type: String!, $collection: String!, $first: Int!, $after: String) {+ project(entityName: $entity, name: $project) {+ artifactType(name: $type) {+ artifactCollection(name: $collection) {+ artifacts(first: $first, after: $after) {+ edges {+ version+ node {+ id digest description state size fileCount versionIndex metadata commitHash+ createdAt updatedAt+ }+ }+ pageInfo { endCursor hasNextPage }+ }+ }+ }+ }+}+"""++_VIEWER_QUERY = "query Viewer { viewer { id username } }"+++def _get_session(api_key: str) -> requests.Session:+ # Raw GraphQL authenticates with HTTP basic auth, username "api" — the same credentials+ # `wandb login` writes to .netrc for the official SDK. Redirects are disabled as+ # defense-in-depth: the host is validated up front, and W&B's GraphQL API responds+ # directly, so pinning traffic to the validated host closes a redirect-based SSRF path.+ # Accept-Encoding: identity so a compliant host returns uncompressed bytes; combined with+ # reading the body undecoded (see _read_response_body) the size cap bounds true wire bytes,+ # so a customer-controlled host can't ship a small gzip that expands to gigabytes in memory.+ session = make_tracked_session(+ headers={"Accept-Encoding": "identity"}, redact_values=(api_key,), allow_redirects=False+ )+ session.auth = ("api", api_key)+ return session+++def _graphql_url(host: str | None) -> str:+ # Dedicated Cloud / self-managed deployments serve the same GraphQL API on an+ # account-specific base URL (e.g. https://acme.wandb.io).+ base = (host or "").strip().rstrip("/")+ if not base:+ return f"{WANDB_DEFAULT_HOST}/graphql"+ # Tolerate a bare host (users routinely paste "acme.wandb.io"); only prepend https when no+ # scheme is present. An explicit http:// is rejected — the key is sent as HTTP Basic auth,+ # so a plaintext scheme would expose it to anyone observing the network path.+ if "://" not in base:+ base = f"https://{base}"+ if urlsplit(base).scheme != "https":+ raise WeightsAndBiasesConfigError(+ "The Weights & Biases host must use https (for example https://acme.wandb.io)."+ )+ url = f"{base}/graphql"+ # Defense-in-depth SSRF check (the Smokescreen egress proxy is the load-bearing control): a+ # custom host is user-supplied, so reject localhost, cloud-metadata, internal domains and+ # private IPs before any request leaves the worker. Runs at credential validation and again+ # on every sync, since both build the URL here.+ allowed, reason = is_url_allowed(url)+ if not allowed:+ raise WeightsAndBiasesConfigError(f"The Weights & Biases host is not allowed: {reason}")+ return url+++def validate_host(host: str | None) -> None:+ """Raise WeightsAndBiasesConfigError if a custom host isn't an https URL."""+ _graphql_url(host)+++def _format_timestamp(value: Any) -> str:+ """Format an incremental cursor as ISO 8601 UTC with Z suffix for a `$gt` filter."""+ if isinstance(value, datetime):+ dt = value if value.tzinfo else value.replace(tzinfo=UTC)+ return dt.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")+ if isinstance(value, date):+ return value.strftime("%Y-%m-%dT00:00:00Z")+ return str(value)+++def _read_response_body(response: requests.Response) -> bytes:+ """Read a streamed response body under a size cap and a hard wall-clock deadline.++ The host is customer-controlled, so neither total size nor total transfer time can be trusted.+ The read runs on a worker thread so the deadline can interrupt it mid-read: urllib3's blocking+ read won't return while a hostile host drips bytes below the per-read inactivity timeout, so a+ between-reads time check alone can't bound total transfer time. On timeout we close the response+ (which unblocks the stalled read) and raise; an oversized body aborts the same way.+ """+ buffer = bytearray()+ failure: list[BaseException] = []++ def _drain() -> None:+ try:+ while True:+ # decode_content=False: buffer the raw wire bytes without decompressing, so the+ # cap below applies to what actually crossed the network. Decoding here would let+ # a hostile host's gzip bomb balloon a single chunk past the cap before we check.+ chunk = response.raw.read(RESPONSE_READ_CHUNK_BYTES, decode_content=False)+ if not chunk:+ return+ buffer.extend(chunk)+ if len(buffer) > MAX_RESPONSE_BYTES:+ return+ except BaseException as exc: # re-raised to the caller once the thread joins+ failure.append(exc)++ reader = threading.Thread(target=_drain, name="wandb-response-reader", daemon=True)+ reader.start()+ reader.join(MAX_TRANSFER_SECONDS)++ if reader.is_alive():+ response.close() # unblock the drip-stalled read so the daemon thread can exit+ raise WeightsAndBiasesGraphQLError("Weights & Biases response exceeded the transfer deadline")+ if failure:+ raise failure[0]+ if len(buffer) > MAX_RESPONSE_BYTES:+ response.close()+ raise WeightsAndBiasesGraphQLError("Weights & Biases API returned an oversized response body")+ return bytes(buffer)+++def _execute(+ session: requests.Session,+ url: str,+ query: str,+ variables: dict[str, Any],+ logger: FilteringBoundLogger,+) -> dict[str, Any]:+ # stream=True so the body isn't buffered before we read it under a cap below.+ response = session.post(+ url, json={"query": query, "variables": variables}, timeout=REQUEST_TIMEOUT_SECONDS, stream=True+ )++ if response.status_code == 429 or response.status_code >= 500:+ response.close()+ raise WeightsAndBiasesRetryableError(f"Weights & Biases API error (retryable): status={response.status_code}")++ # We requested Accept-Encoding: identity and read the body undecoded. A host that compresses+ # anyway is either misbehaving or hostile (a decompression bomb), so reject it rather than+ # decode an untrusted, potentially unbounded body.+ content_encoding = response.headers.get("Content-Encoding")+ if content_encoding and content_encoding.strip().lower() not in ("", "identity"):+ response.close()+ raise WeightsAndBiasesGraphQLError(+ f"Weights & Biases API returned an unexpected Content-Encoding: {content_encoding}"+ )++ raw = _read_response_body(response)++ if not response.ok:+ logger.error(+ f"Weights & Biases API error: status={response.status_code}, body={raw[:2000].decode('utf-8', 'replace')}"+ )+ response.raise_for_status()++ body = json.loads(raw)+ errors = body.get("errors")+ if errors:+ message = "; ".join(str(error.get("message", error)) for error in errors)+ raise WeightsAndBiasesGraphQLError(f"Weights & Biases GraphQL error: {message}")++ return body.get("data") or {}+++class _NoopLogger:+ def error(self, *args: Any, **kwargs: Any) -> None:+ return None+++def validate_credentials(api_key: str, host: str | None) -> bool:+ """Confirm the API key is genuine with the viewer query.++ The API returns 200 with `viewer: null` for a missing/invalid key rather than a 401, so+ validity is a non-null viewer.+ """+ try:+ session = _get_session(api_key)+ data = _execute(session, _graphql_url(host), _VIEWER_QUERY, {}, _NoopLogger()) # type: ignore[arg-type]+ return bool(data.get("viewer"))+ except Exception:+ return False+++def _iter_connection(+ execute: Callable[[str, dict[str, Any]], dict[str, Any]],+ query: str,+ variables: dict[str, Any],+ connection_path: tuple[str, ...],+ logger: FilteringBoundLogger,+ after: str | None = None,+) -> Iterator[tuple[list[dict[str, Any]], str | None, bool]]:+ """Yield (edges, end_cursor, has_next) pages of a Relay connection.++ Termination follows pageInfo, not edge count: the API returns empty edges with+ hasNextPage=true for pages whose rows are hidden from the caller (verified live), so+ stopping on an empty page would silently truncate. A non-advancing cursor breaks the+ loop as a guard against looping on the same page forever, and MAX_PAGES_PER_CONNECTION+ caps a host that keeps advancing the cursor indefinitely.+ """+ for _ in range(MAX_PAGES_PER_CONNECTION):+ data = execute(query, {**variables, "after": after})+ connection: Any = data+ for key in connection_path:+ connection = (connection or {}).get(key)+ if connection is None:+ # Parent object deleted (or hidden) between enumeration and this fetch.+ return++ edges = connection.get("edges") or []+ page_info = connection.get("pageInfo") or {}+ end_cursor = page_info.get("endCursor")++ yield edges, end_cursor, bool(page_info.get("hasNextPage"))++ if not page_info.get("hasNextPage") or not end_cursor or end_cursor == after:+ return+ after = end_cursor++ logger.warning(+ f"Weights & Biases: hit the {MAX_PAGES_PER_CONNECTION}-page cap for {connection_path}, stopping pagination"+ )+++def _iter_all_project_names(+ execute: Callable[[str, dict[str, Any]], dict[str, Any]], entity: str, logger: FilteringBoundLogger+) -> Iterator[str]:+ for edges, _end_cursor, _has_next in _iter_connection(+ execute, _PROJECTS_QUERY, {"entity": entity, "first": PAGE_SIZE}, ("models",), logger+ ):+ for edge in edges:+ node = edge.get("node")+ if node and node.get("name"):+ yield node["name"]+++def _collect_fan_out_project_names(+ execute: Callable[[str, dict[str, Any]], dict[str, Any]], entity: str, logger: FilteringBoundLogger+) -> list[str]:+ """Materialise every project name for a fan-out sync under a hard retained-state cap.++ The host is customer-controlled, so refuse to buffer an unbounded list — abort once the+ retained names exceed either cap rather than let a hostile host grow worker memory without+ end. Both caps are far beyond any real entity, so a legitimate sync never hits them.+ """+ names: list[str] = []+ retained_bytes = 0+ for name in _iter_all_project_names(execute, entity, logger):+ names.append(name)+ retained_bytes += len(name.encode("utf-8"))+ if len(names) > MAX_FAN_OUT_PROJECTS or retained_bytes > MAX_RETAINED_PROJECT_NAME_BYTES:+ raise WeightsAndBiasesGraphQLError(+ "Weights & Biases returned an unreasonably large project list; refusing to buffer it"+ )+ return names+++def _get_project_rows(+ execute: Callable[[str, dict[str, Any]], dict[str, Any]],+ entity: str,+ after: str | None,+ resumable_source_manager: ResumableSourceManager[WeightsAndBiasesResumeConfig],+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ for edges, end_cursor, has_next in _iter_connection(+ execute, _PROJECTS_QUERY, {"entity": entity, "first": PAGE_SIZE}, ("models",), logger, after=after+ ):+ rows = [edge["node"] for edge in edges if edge.get("node")]+ if rows:+ yield rows+ # Save AFTER yielding (and only when more pages remain) so a crash re-yields the last+ # page rather than skipping it — merge dedupes on the primary key.+ if has_next:+ resumable_source_manager.save_state(WeightsAndBiasesResumeConfig(cursor=end_cursor))+++def _run_query_variables(+ entity: str,+ project: str,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+ incremental_field: str | None,+) -> dict[str, Any]:+ field_name = _DEFAULT_RUN_INCREMENTAL_FIELD+ if should_use_incremental_field and incremental_field in RUN_INCREMENTAL_SORT_KEYS:+ field_name = incremental_field++ filters: str | None = None+ if should_use_incremental_field and db_incremental_field_last_value is not None:+ filters = json.dumps({field_name: {"$gt": _format_timestamp(db_incremental_field_last_value)}})++ return {+ "entity": entity,+ "project": project,+ "filters": filters,+ # Always sort explicitly on a stable monotonic field so page boundaries can't skip or+ # duplicate rows as new runs land mid-sync.+ "order": RUN_INCREMENTAL_SORT_KEYS[field_name],+ "first": PAGE_SIZE,+ }+++def _get_fan_out_rows(+ execute: Callable[[str, dict[str, Any]], dict[str, Any]],+ query: str,+ variables: dict[str, Any],+ connection_path: tuple[str, ...],+ project: str,+ after: str | None,+ resumable_source_manager: ResumableSourceManager[WeightsAndBiasesResumeConfig],+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ for edges, end_cursor, has_next in _iter_connection(+ execute, query, variables, connection_path, logger, after=after+ ):+ rows = [{**edge["node"], "projectName": project} for edge in edges if edge.get("node")]+ if rows:+ yield rows+ if has_next:+ resumable_source_manager.save_state(WeightsAndBiasesResumeConfig(project=project, cursor=end_cursor))+++def _get_artifact_rows(+ execute: Callable[[str, dict[str, Any]], dict[str, Any]],+ entity: str,+ project: str,+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ """Walk project -> artifact types -> collections -> versions, one row per artifact version."""+ base = {"entity": entity, "project": project, "first": PAGE_SIZE}++ for type_edges, _c, _h in _iter_connection(+ execute, _ARTIFACT_TYPES_QUERY, base, ("project", "artifactTypes"), logger+ ):+ for type_edge in type_edges:+ type_name = (type_edge.get("node") or {}).get("name")+ if not type_name:+ continue++ for collection_edges, _c2, _h2 in _iter_connection(+ execute,+ _ARTIFACT_COLLECTIONS_QUERY,+ {**base, "type": type_name},+ ("project", "artifactType", "artifactCollections"),+ logger,+ ):+ for collection_edge in collection_edges:+ collection_name = (collection_edge.get("node") or {}).get("name")+ if not collection_name:+ continue++ for artifact_edges, _c3, _h3 in _iter_connection(+ execute,+ _ARTIFACTS_QUERY,+ {**base, "type": type_name, "collection": collection_name},+ ("project", "artifactType", "artifactCollection", "artifacts"),+ logger,+ ):+ rows = [+ {+ **edge["node"],+ "version": edge.get("version"),+ "projectName": project,+ "artifactTypeName": type_name,+ "collectionName": collection_name,+ }+ for edge in artifact_edges+ if edge.get("node")+ ]+ if rows:+ yield rows+++def get_rows(+ api_key: str,+ host: str | None,+ entity: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[WeightsAndBiasesResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+ incremental_field: str | None = None,+) -> Iterator[list[dict[str, Any]]]:+ if endpoint not in WANDB_ENDPOINTS:+ raise ValueError(f"Unknown Weights & Biases endpoint: {endpoint}")++ session = _get_session(api_key)+ url = _graphql_url(host)++ @retry(+ retry=retry_if_exception_type((WeightsAndBiasesRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),+ # Rate limits are 50-200 req/min per key depending on plan, so back off generously.+ wait=wait_exponential_jitter(initial=2, max=90),+ reraise=True,+ )+ def execute(query: str, variables: dict[str, Any]) -> dict[str, Any]:+ return _execute(session, url, query, variables, logger)++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None++ if endpoint == "projects":+ after = resume.cursor if resume else None+ yield from _get_project_rows(execute, entity, after, resumable_source_manager, logger)+ return++ # Fan-out endpoints iterate every project in the entity. Resolve the saved project-name+ # bookmark to the slice still to process; if the bookmarked project no longer exists,+ # start over from the first project (merge dedupes re-pulled rows on the primary key).+ project_names = _collect_fan_out_project_names(execute, entity, logger)+ remaining = project_names+ resume_cursor: str | None = None+ if resume is not None and resume.project is not None and resume.project in project_names:+ remaining = project_names[project_names.index(resume.project) :]+ resume_cursor = resume.cursor+ logger.debug(f"Weights & Biases: resuming {endpoint} from project={resume.project}")++ for index, project in enumerate(remaining):+ if endpoint == "runs":+ variables = _run_query_variables(+ entity, project, should_use_incremental_field, db_incremental_field_last_value, incremental_field+ )+ yield from _get_fan_out_rows(+ execute,+ _RUNS_QUERY,+ variables,+ ("project", "runs"),+ project,+ resume_cursor,+ resumable_source_manager,+ logger,+ )+ elif endpoint == "sweeps":+ yield from _get_fan_out_rows(+ execute,+ _SWEEPS_QUERY,+ {"entity": entity, "project": project, "first": PAGE_SIZE},+ ("project", "sweeps"),+ project,+ resume_cursor,+ resumable_source_manager,+ logger,+ )+ elif endpoint == "reports":+ yield from _get_fan_out_rows(+ execute,+ _REPORTS_QUERY,+ {"entity": entity, "project": project, "first": PAGE_SIZE},+ ("project", "allViews"),+ project,+ resume_cursor,+ resumable_source_manager,+ logger,+ )+ else: # artifacts+ yield from _get_artifact_rows(execute, entity, project, logger)++ resume_cursor = None # only the resumed-into project uses the saved cursor+ # Advance the bookmark so a crash between projects resumes at the next one.+ if index + 1 < len(remaining):+ resumable_source_manager.save_state(WeightsAndBiasesResumeConfig(project=remaining[index + 1]))+++def weights_and_biases_source(+ api_key: str,+ host: str | None,+ entity: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[WeightsAndBiasesResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ incremental_field: str | None = None,+) -> SourceResponse:+ endpoint_config = WANDB_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ host=host,+ entity=entity,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ incremental_field=incremental_field,+ ),+ primary_keys=list(endpoint_config.primary_keys),+ partition_count=1,+ partition_size=1,+ partition_mode="datetime",+ partition_format="month",+ partition_keys=[endpoint_config.partition_key],+ # Fan-out over projects means rows only ascend within a single project, so the+ # pipeline commits the incremental watermark when a run completes rather than+ # per batch.+ sort_mode="desc",+ )