: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 the modal import source (#112637)
Tom Owers011c3769fdaf
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 535c75dde72d..b444325a1f35 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -541,6 +541,7 @@ the row lists both.| mistral_ai | HTTP | requests | ✅ || mixmax | HTTP | requests | ✅ || mixpanel | HTTP | requests | ✅ |+| modal | gRPC | modal (vendor SDK) | ⚠️ Vendor SDK || moengage | HTTP | requests + `rest_source.RESTClient` | ✅ || mollie | HTTP | requests | ✅ || monday | HTTP (GraphQL) | requests | ✅ |@@ -907,6 +908,7 @@ the row lists both.### Notes on partially-tracked sources+- **modal** uses grpclib inside its SDK without a channel or interceptor hook, so gRPC traffic bypasses tracking.- **bing_ads** uses Microsoft's `bingads` Python SDK, which builds its own HTTP transport via `suds-py3` forthe SOAP API and a separate Reporting client. The SDK does not expose a session or HTTP-client injectionhook today. Outbound traffic from this source bypasses the tracked transport.@@ -1277,7 +1279,6 @@ doesn't conflict with concurrent PRs.- mirakl- miro- missive-- modal- mode- moesif- monacodiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/schema.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/schema.pyindex 5ece51f45b04..e444b3966e9d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/schema.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/schema.py@@ -172,6 +172,7 @@ def build_endpoint_schemas(descriptions: Mapping[str, str] | None = None,should_sync_default: Mapping[str, bool] | None = None,supports_webhooks: Collection[str] = (),+ default_incremental_lookback_seconds: Mapping[str, int] | None = None,) -> list[SourceSchema]:"""Build the ``SourceSchema`` list for a static endpoint-catalog source's ``get_schemas``.@@ -182,11 +183,14 @@ def build_endpoint_schemas(- ``append_only``: endpoints that support append but not incremental merge.- ``merge_only``: endpoints that support incremental merge but not append.- ``descriptions`` / ``should_sync_default`` / ``supports_webhooks``: per-endpoint metadata.+ - ``default_incremental_lookback_seconds``: per-endpoint default overlap re-read window, for+ endpoints whose recent rows get restated upstream (see ``SourceSchema``'s field doc).``names`` (the schema-picker filter) keeps only the requested endpoints when set."""descriptions = descriptions or {}should_sync_default = should_sync_default or {}+ default_incremental_lookback_seconds = default_incremental_lookback_seconds or {}schemas = []for name in endpoints:fields = incremental_fields.get(name) or []@@ -202,6 +206,7 @@ def build_endpoint_schemas(description=descriptions.get(name),should_sync_default=should_sync_default.get(name, True),supports_webhooks=name in supports_webhooks,+ default_incremental_lookback_seconds=default_incremental_lookback_seconds.get(name),))diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test_source_schema.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test_source_schema.pyindex 9e3b809d95f7..c89233bc693f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test_source_schema.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test_source_schema.py@@ -237,3 +237,12 @@ class TestBuildEndpointSchemas:assert schemas["contacts"].description is Noneassert (schemas["events"].should_sync_default, schemas["campaigns"].should_sync_default) == (False, True)assert (schemas["contacts"].supports_webhooks, schemas["campaigns"].supports_webhooks) == (True, False)++ def test_default_incremental_lookback_seconds_reaches_the_schema(self) -> None:+ # Endpoints whose recent rows get restated upstream (e.g. a billing report whose latest+ # days can still change) set a per-endpoint default lookback; dropping it here would+ # freeze those rows at their first-imported value on every later incremental run.+ schemas = {s.name: s for s in self._build(default_incremental_lookback_seconds={"contacts": 86400})}++ assert schemas["contacts"].default_incremental_lookback_seconds == 86400+ assert schemas["campaigns"].default_incremental_lookback_seconds is Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/modal.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/modal.pyindex f0c3ceb6de30..4e8dc6792e7d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/modal.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/modal.py@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass ModalSourceConfig(config.Config):- pass+ token_id: str+ token_secret: strdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/modal/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/modal/canonical_descriptions.pynew file mode 100644index 000000000000..9728349ee8fa--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/modal/canonical_descriptions.py@@ -0,0 +1,19 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ name: {+ "description": f"{resolution} workspace costs by Modal object and environment.",+ "docs_url": "https://modal.com/docs/sdk/py/latest/Workspace#billingreport",+ "columns": {+ "object_id": "Identifier of the Modal object that incurred the cost, such as an App.",+ "description": "Description of the Modal object that incurred the cost.",+ "environment_name": "Name of the Modal environment that contains the object.",+ "interval_start": "Start of the billing interval in UTC.",+ "cost": "Cost for the billing interval before credits, reservations, and the network egress allowance.",+ "tags": "User-defined tags associated with the object during the billing interval.",+ },+ }+ for name, resolution in (("billing_report_daily", "Daily"), ("billing_report_hourly", "Hourly"))+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/modal/modal.py b/products/warehouse_sources/backend/temporal/data_imports/sources/modal/modal.pynew file mode 100644index 000000000000..de458bfe8045--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/modal/modal.py@@ -0,0 +1,150 @@+from collections.abc import Iterator+from contextlib import contextmanager+from datetime import UTC, datetime, timedelta+from typing import TYPE_CHECKING++import modal+from grpclib import GRPCError, Status+from modal.exception import AuthError, PermissionDeniedError++from posthog.dataclasses import frozen++from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import schema_for_resource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.modal.settings import (+ ENDPOINTS,+ PARTITION_KEY,+ PRIMARY_KEYS,+)++if TYPE_CHECKING:+ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+ from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs+ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.modal import (+ ModalSourceConfig,+ )+++AUTH_ERROR = "Modal authentication failed. Check your token ID and token secret."+PERMISSION_ERROR = (+ "Modal billing access was denied. Use a Team or Enterprise plan with a token that can read workspace billing."+)+++class ModalAuthenticationError(Exception):+ pass+++class ModalPermissionError(Exception):+ pass+++@frozen+class ModalResumeConfig:+ next_window_start: str+ end: str+++def as_utc(value: datetime | str) -> datetime:+ parsed = datetime.fromisoformat(value) if isinstance(value, str) else value+ if parsed.tzinfo is None:+ return parsed.replace(tzinfo=UTC)+ return parsed.astimezone(UTC)+++@contextmanager+def billing_client(config: ModalSourceConfig) -> Iterator[modal.Client]:+ try:+ client = modal.Client.from_credentials(config.token_id, config.token_secret)+ try:+ yield client+ finally:+ # from_credentials opens the client, so entering it again would open it twice.+ client.__exit__(None, None, None)+ except AuthError:+ raise ModalAuthenticationError(AUTH_ERROR) from None+ except PermissionDeniedError:+ raise ModalPermissionError(PERMISSION_ERROR) from None+ except modal.Error:+ raise+ except GRPCError as error:+ if error.status == Status.UNAUTHENTICATED:+ raise ModalAuthenticationError(AUTH_ERROR) from None+ if error.status == Status.PERMISSION_DENIED:+ raise ModalPermissionError(PERMISSION_ERROR) from None+ raise+++def validate_credentials(config: ModalSourceConfig) -> tuple[bool, str | None]:+ end = datetime.now(UTC).replace(hour=0, minute=0, second=0, microsecond=0)+ try:+ with billing_client(config) as client:+ modal.Workspace.from_context(client=client).billing.report(+ start=end - timedelta(days=1), end=end, resolution="d", tag_names=["*"]+ )+ except (ModalAuthenticationError, ModalPermissionError) as error:+ return False, str(error)+ return True, None+++def modal_source(+ config: ModalSourceConfig,+ inputs: SourceInputs,+ resumable_source_manager: ResumableSourceManager[ModalResumeConfig],+) -> SourceResponse:+ table = schema_for_resource(ENDPOINTS, inputs.schema_name)++ def get_rows() -> Iterator[list[dict[str, object]]]:+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ end = as_utc(resume.end) if resume else datetime.now(UTC)+ if resume:+ start = as_utc(resume.next_window_start)+ else:+ watermark = inputs.db_incremental_field_last_value if inputs.should_use_incremental_field else None+ start = as_utc(watermark) if watermark is not None else end - table.default_lookback+ # Re-read the watermark interval because its cost can change after the previous sync.+ start = start.replace(minute=0, second=0, microsecond=0)+ if table.resolution == "d":+ start = start.replace(hour=0)++ if start >= end:+ return++ with billing_client(config) as client:+ workspace = modal.Workspace.from_context(client=client)+ while start < end:+ window_end = min(start + table.window_size, end)+ report = workspace.billing.report(+ start=start, end=window_end, resolution=table.resolution, tag_names=["*"]+ )+ ordered = sorted(report, key=lambda item: as_utc(item.interval_start))+ rows: list[dict[str, object]] = [+ {+ "object_id": item.object_id,+ "description": item.description,+ "environment_name": item.environment_name,+ "interval_start": as_utc(item.interval_start),+ "cost": float(item.cost),+ "tags": dict(item.tags),+ }+ for item in ordered+ ]+ resumable_source_manager.save_state(+ ModalResumeConfig(next_window_start=window_end.isoformat(), end=end.isoformat())+ )+ if rows:+ yield rows+ resumable_source_manager.safe_point()+ start = window_end++ return SourceResponse(+ name=inputs.schema_name,+ items=get_rows,+ primary_keys=PRIMARY_KEYS,+ column_hints={"cost": "double", "interval_start": "timestamp", "tags": "json"},+ partition_keys=[PARTITION_KEY],+ partition_mode="datetime",+ partition_format="month",+ sort_mode="asc",+ on_complete=resumable_source_manager.clear_state,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/modal/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/modal/settings.pynew file mode 100644index 000000000000..9848294e7a0b--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/modal/settings.py@@ -0,0 +1,42 @@+from datetime import timedelta+from typing import Literal++from posthog.dataclasses import frozen++from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field+++@frozen+class BillingTable:+ resolution: Literal["d", "h"]+ default_lookback: timedelta+ window_size: timedelta+ # Modal's billing docs say report data usually lands within minutes, but collection delays+ # can occur. `modal_source` already re-reads the watermark's own interval every sync to pick+ # up its latest cost, but that only covers the single most recent interval. This shifts the+ # watermark used for the source query back further, so each incremental run re-reads a+ # trailing overlap window and also catches a delayed interval older than the last one synced.+ # Merge dedupes the re-read rows on the primary key.+ default_incremental_lookback: timedelta+++ENDPOINTS = {+ "billing_report_daily": BillingTable(+ resolution="d",+ default_lookback=timedelta(days=365),+ window_size=timedelta(days=30),+ default_incremental_lookback=timedelta(days=3),+ ),+ "billing_report_hourly": BillingTable(+ resolution="h",+ default_lookback=timedelta(days=30),+ window_size=timedelta(days=2),+ default_incremental_lookback=timedelta(hours=6),+ ),+}+INCREMENTAL_FIELDS = {name: [incremental_field("interval_start")] for name in ENDPOINTS}+DEFAULT_INCREMENTAL_LOOKBACK_SECONDS = {+ name: int(table.default_incremental_lookback.total_seconds()) for name, table in ENDPOINTS.items()+}+PRIMARY_KEYS = ["object_id", "interval_start", "environment_name"]+PARTITION_KEY = "interval_start"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/modal/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/modal/source.pyindex cbab7c7adaf7..398e5360c875 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/modal/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/modal/source.py@@ -1,15 +1,46 @@from typing import cast-from products.warehouse_sources.backend.facade.source_config import DataWarehouseSourceCategory, SourceConfig-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.facade.source_config import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+)+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 (+ SourceSchema,+ build_endpoint_schemas,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.modal import ModalSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.modal.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.modal.modal import (+ AUTH_ERROR,+ PERMISSION_ERROR,+ ModalResumeConfig,+ modal_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.modal.settings import (+ DEFAULT_INCREMENTAL_LOOKBACK_SECONDS,+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class ModalSource(SimpleSource[ModalSourceConfig]):- """Placeholder for a future Modal data warehouse source."""+class ModalSource(ResumableSource[ModalSourceConfig, ModalResumeConfig]):+ lists_tables_without_credentials = True+ api_docs_url = "https://modal.com/docs/sdk/py/latest/Workspace#billingreport"@propertydef source_type(self) -> ExternalDataSourceType:@@ -22,6 +53,75 @@ class ModalSource(SimpleSource[ModalSourceConfig]):category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Modal",iconPath="/static/services/modal.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ caption=(+ "Create a token in [Modal settings](https://modal.com/settings). "+ "Use a service-user token with workspace billing access. "+ "A Team or Enterprise plan is required for [Workspace billing reports](https://modal.com/docs/sdk/py/latest/Workspace#billingreport). "+ "The first sync imports 365 days of daily reports or 30 days of hourly reports."+ ),+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="token_id",+ label="Token ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="ak-...",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="token_secret",+ label="Token secret",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="as-...",+ secret=True,+ ),+ ],+ ),+ releaseStatus=ReleaseStatus.ALPHA,)++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {AUTH_ERROR: AUTH_ERROR, PERMISSION_ERROR: PERMISSION_ERROR}++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: ModalSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ return build_endpoint_schemas(+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ names,+ merge_only=ENDPOINTS,+ default_incremental_lookback_seconds=DEFAULT_INCREMENTAL_LOOKBACK_SECONDS,+ )++ def validate_credentials(+ self,+ config: ModalSourceConfig,+ team_id: int,+ schema_name: str | None = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ return validate_credentials(config)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[ModalResumeConfig]:+ return ResumableSourceManager(inputs, ModalResumeConfig)++ def source_for_pipeline(+ self,+ config: ModalSourceConfig,+ resumable_source_manager: ResumableSourceManager[ModalResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return modal_source(config, inputs, resumable_source_manager)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/modal/tests/test_modal.py b/products/warehouse_sources/backend/temporal/data_imports/sources/modal/tests/test_modal.pynew file mode 100644index 000000000000..76c83e40194c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/modal/tests/test_modal.py@@ -0,0 +1,389 @@+from collections.abc import Iterable, Iterator+from datetime import UTC, datetime, timedelta, timezone+from decimal import Decimal+from typing import cast++import pytest+import time_machine+from unittest.mock import MagicMock, patch++from grpclib import GRPCError, Status+from modal.exception import AuthError, PermissionDeniedError, ResourceExhaustedError, ServiceError+from modal.types import BillingReportItem++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 UnknownResourceError+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.modal import ModalSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.modal.modal import (+ ModalAuthenticationError,+ ModalPermissionError,+ ModalResumeConfig,+ modal_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.modal.source import ModalSource++NOW = datetime(2026, 3, 15, 12, 34, 56, tzinfo=UTC)++[email protected](autouse=True)+def frozen_clock() -> Iterator[None]:+ with time_machine.travel(NOW, tick=False):+ yield+++def config() -> ModalSourceConfig:+ return ModalSourceConfig.from_dict({"token_id": "ak-test", "token_secret": "as-test-secret"})+++def inputs() -> SourceInputs:+ return SourceInputs(+ schema_name="billing_report_daily",+ schema_id="schema-test",+ source_id="source-test",+ team_id=1,+ should_use_incremental_field=True,+ db_incremental_field_last_value="2026-03-14T00:00:00Z",+ db_incremental_field_earliest_value=None,+ incremental_field="interval_start",+ incremental_field_type=None,+ job_id="job-test",+ logger=MagicMock(),+ reset_pipeline=False,+ )+++def manager() -> MagicMock:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False+ return manager+++def create_client() -> Iterator[MagicMock]:+ with patch("modal.Client.from_credentials") as create:+ yield create+++def workspace() -> Iterator[MagicMock]:+ with patch("modal.Workspace.from_context") as from_context:+ yield from_context+++def report(workspace: MagicMock) -> MagicMock:+ report = workspace.return_value.billing.report+ report.return_value = []+ return report+++def source_items(response: SourceResponse) -> Iterable[list[dict[str, object]]]:+ return cast(Iterable[list[dict[str, object]]], response.items())+++def billing_item(interval_start: datetime, cost: str = "1.23456789") -> BillingReportItem:+ return BillingReportItem(+ object_id="ap-test",+ description="Example app",+ environment_name="main",+ interval_start=interval_start,+ cost=Decimal(cost),+ cost_by_resource={"cpu": Decimal(cost)},+ tags={"team": "example", "project": "billing-test"},+ )+++ ("table", "watermark", "incremental", "expected_start", "window_days", "resolution"),+ [+ ("daily", "2026-01-01T18:45:00Z", True, datetime(2026, 1, 1, tzinfo=UTC), 30, "d"),+ ("hourly", "2026-03-10T18:45:00Z", True, datetime(2026, 3, 10, 18, tzinfo=UTC), 2, "h"),+ ("daily", None, True, datetime(2025, 3, 15, tzinfo=UTC), 30, "d"),+ ("hourly", None, True, datetime(2026, 2, 13, 12, tzinfo=UTC), 2, "h"),+ ("daily", "2026-03-14T00:00:00Z", False, datetime(2025, 3, 15, tzinfo=UTC), 30, "d"),+ ("hourly", "2026-03-14T00:00:00Z", False, datetime(2026, 2, 13, 12, tzinfo=UTC), 2, "h"),+ ("hourly", "2026-03-15T11:25:00-02:00", True, datetime(2026, 3, 15, 13, tzinfo=UTC), 2, "h"),+ ("daily", "2026-03-16T00:00:00Z", True, datetime(2026, 3, 16, tzinfo=UTC), 30, "d"),+ ("hourly", datetime(2026, 3, 14, 18, 30), True, datetime(2026, 3, 14, 18, tzinfo=UTC), 2, "h"),+ ],+)+def test_forward_windows(+ config: ModalSourceConfig,+ inputs: SourceInputs,+ manager: MagicMock,+ create_client: MagicMock,+ workspace: MagicMock,+ report: MagicMock,+ table: str,+ watermark: datetime | str | None,+ incremental: bool,+ expected_start: datetime,+ window_days: int,+ resolution: str,+) -> None:+ inputs.schema_name = f"billing_report_{table}"+ inputs.db_incremental_field_last_value = watermark+ inputs.should_use_incremental_field = incremental+ assert list(source_items(modal_source(config, inputs, manager))) == []++ if expected_start >= NOW:+ report.assert_not_called()+ create_client.assert_not_called()+ workspace.assert_not_called()+ return++ calls = [call.kwargs for call in report.call_args_list]+ assert calls[0]["start"] == expected_start+ assert calls[-1]["end"] == NOW+ for index, request in enumerate(calls):+ assert request["start"] < request["end"] <= NOW+ assert request["end"] - request["start"] <= timedelta(days=window_days)+ assert request["resolution"] == resolution+ assert request["tag_names"] == ["*"]+ if index:+ assert request["start"] == calls[index - 1]["end"]+ assert manager.safe_point.call_count == len(calls)+ assert [call.args[0].next_window_start for call in manager.save_state.call_args_list] == [+ request["end"].isoformat() for request in calls+ ]+ create_client.assert_called_once_with("ak-test", "as-test-secret")+ workspace.assert_called_once_with(client=create_client.return_value)+ create_client.return_value.__exit__.assert_called_once()++[email protected]("tz", [None, UTC, timezone(timedelta(hours=5, minutes=30))])[email protected]("cost", ["0", "1.23456789", "-0.125"])+def test_rows_are_sorted_and_normalized(+ config: ModalSourceConfig,+ inputs: SourceInputs,+ manager: MagicMock,+ create_client: MagicMock,+ report: MagicMock,+ tz: timezone | None,+ cost: str,+) -> None:+ early = datetime(2026, 3, 14, tzinfo=tz)+ late = early + timedelta(hours=1)+ original = [billing_item(late, cost), billing_item(early, cost)]+ report.return_value = original+ response = modal_source(config, inputs, manager)+ (rows,) = list(source_items(response))+ expected_early = early.replace(tzinfo=UTC) if tz is None else early.astimezone(UTC)+ assert [row["interval_start"] for row in rows] == [expected_early, expected_early + timedelta(hours=1)]+ assert rows[0] == {+ "object_id": "ap-test",+ "description": "Example app",+ "environment_name": "main",+ "interval_start": expected_early,+ "cost": float(Decimal(cost)),+ "tags": {"team": "example", "project": "billing-test"},+ }+ assert isinstance(rows[0]["cost"], float)+ assert rows[0]["tags"] is not original[1].tags+ assert original[0].cost == Decimal(cost)+ manager.clear_state.assert_not_called()+ assert response.on_complete is not None+ response.on_complete()+ manager.clear_state.assert_called_once()+++ ("object_id", "description", "environment_name", "cost", "cost_by_resource", "tags"),+ [+ ("ap-first", "First app", "main", "1.23456789", {"cpu": Decimal("1.23456789")}, {"team": "example"}),+ ("ap-second", "Second app", "staging", "0", {}, {}),+ ],+)+def test_report_item_conversion(+ config: ModalSourceConfig,+ inputs: SourceInputs,+ manager: MagicMock,+ report: MagicMock,+ object_id: str,+ description: str,+ environment_name: str,+ cost: str,+ cost_by_resource: dict[str, Decimal],+ tags: dict[str, str],+) -> None:+ interval_start = datetime(2026, 3, 14, tzinfo=UTC)+ item = BillingReportItem(+ object_id=object_id,+ description=description,+ environment_name=environment_name,+ interval_start=interval_start,+ cost=Decimal(cost),+ cost_by_resource=cost_by_resource,+ tags=tags,+ )+ report.return_value = [item]++ (rows,) = list(source_items(modal_source(config, inputs, manager)))++ assert rows == [+ {+ "object_id": object_id,+ "description": description,+ "environment_name": environment_name,+ "interval_start": interval_start,+ "cost": float(Decimal(cost)),+ "tags": tags,+ }+ ]+ assert rows[0]["tags"] is not item.tags++[email protected]("has_rows", [True, False])+def test_retry_resumes_after_saved_window(+ config: ModalSourceConfig,+ inputs: SourceInputs,+ manager: MagicMock,+ create_client: MagicMock,+ report: MagicMock,+ has_rows: bool,+) -> None:+ inputs.schema_name = "billing_report_hourly"+ inputs.db_incremental_field_last_value = "2026-03-10T00:00:00Z"+ rows = [billing_item(datetime(2026, 3, 10, tzinfo=UTC))] if has_rows else []+ report.side_effect = [rows, ServiceError("temporary failure")]+ iterator = iter(source_items(modal_source(config, inputs, manager)))+ if has_rows:+ assert next(iterator)+ manager.save_state.assert_called_once()+ with pytest.raises(ServiceError, match="temporary failure"):+ list(iterator)+ saved = manager.save_state.call_args.args[0]+ assert saved == ModalResumeConfig(next_window_start="2026-03-12T00:00:00+00:00", end=NOW.isoformat())+ create_client.return_value.__exit__.assert_called_once()+ manager.clear_state.assert_not_called()++ manager.can_resume.return_value = True+ manager.load_state.return_value = saved+ report.reset_mock()+ report.side_effect = None+ report.return_value = []+ with time_machine.travel(NOW + timedelta(days=1), tick=False):+ assert list(source_items(modal_source(config, inputs, manager))) == []+ assert report.call_args_list[0].kwargs["start"] == datetime(2026, 3, 12, tzinfo=UTC)+ assert report.call_args_list[-1].kwargs["end"] == NOW++[email protected]("state", [None, ModalResumeConfig(next_window_start=NOW.isoformat(), end=NOW.isoformat())])+def test_resume_without_work(+ config: ModalSourceConfig,+ inputs: SourceInputs,+ manager: MagicMock,+ create_client: MagicMock,+ report: MagicMock,+ state: ModalResumeConfig | None,+) -> None:+ manager.can_resume.return_value = True+ manager.load_state.return_value = state+ list(source_items(modal_source(config, inputs, manager)))+ assert report.call_count == (1 if state is None else 0)++[email protected]("during_creation", [False, True])+ ("error", "mapped_type", "message"),+ [+ (+ AuthError("invalid token"),+ ModalAuthenticationError,+ "Modal authentication failed. Check your token ID and token secret.",+ ),+ (+ PermissionDeniedError("denied"),+ ModalPermissionError,+ "Modal billing access was denied. Use a Team or Enterprise plan with a token that can read workspace billing.",+ ),+ (+ GRPCError(Status.UNAUTHENTICATED, "invalid token"),+ ModalAuthenticationError,+ "Modal authentication failed. Check your token ID and token secret.",+ ),+ (+ GRPCError(Status.PERMISSION_DENIED, "denied"),+ ModalPermissionError,+ "Modal billing access was denied. Use a Team or Enterprise plan with a token that can read workspace billing.",+ ),+ ],+)+def test_auth_and_permission_errors(+ config: ModalSourceConfig,+ inputs: SourceInputs,+ manager: MagicMock,+ create_client: MagicMock,+ report: MagicMock,+ during_creation: bool,+ error: Exception,+ mapped_type: type[Exception],+ message: str,+) -> None:+ (create_client if during_creation else report).side_effect = error+ assert validate_credentials(config) == (False, message)+ with pytest.raises(mapped_type) as raised:+ list(source_items(modal_source(config, inputs, manager)))+ assert str(raised.value) == message+ assert any(pattern in str(raised.value) for pattern in ModalSource().get_non_retryable_errors())+ assert create_client.return_value.__exit__.call_count == (0 if during_creation else 2)+ manager.save_state.assert_not_called()+++ "error",+ [ServiceError("unavailable"), ResourceExhaustedError("rate limit"), GRPCError(Status.UNAVAILABLE, "unavailable")],+)+def test_transient_errors_propagate(+ config: ModalSourceConfig,+ create_client: MagicMock,+ report: MagicMock,+ error: Exception,+) -> None:+ report.side_effect = error+ with pytest.raises(type(error)) as raised:+ validate_credentials(config)+ assert raised.value is error+ assert not any(pattern in str(error) for pattern in ModalSource().get_non_retryable_errors())+ create_client.return_value.__exit__.assert_called_once()+++def test_credential_probe_uses_one_complete_day(+ config: ModalSourceConfig, create_client: MagicMock, workspace: MagicMock, report: MagicMock+) -> None:+ assert validate_credentials(config) == (True, None)+ report.assert_called_once_with(+ start=datetime(2026, 3, 14, tzinfo=UTC),+ end=datetime(2026, 3, 15, tzinfo=UTC),+ resolution="d",+ tag_names=["*"],+ )+ workspace.assert_called_once_with(client=create_client.return_value)+ create_client.return_value.__exit__.assert_called_once()+++def test_unknown_table_does_not_connect(+ config: ModalSourceConfig, inputs: SourceInputs, manager: MagicMock, create_client: MagicMock, report: MagicMock+) -> None:+ inputs.schema_name = "unknown"+ with pytest.raises(UnknownResourceError):+ modal_source(config, inputs, manager)+ create_client.assert_not_called()+ report.assert_not_called()+++ ("schema_name", "expected_seconds"),+ [("billing_report_daily", 3 * 24 * 60 * 60), ("billing_report_hourly", 6 * 60 * 60)],+)+def test_get_schemas_sets_a_default_incremental_lookback(schema_name: str, expected_seconds: int) -> None:+ # Modal keeps restating recent billing costs, so each table needs a default overlap re-read+ # window; dropping it would freeze a day's or hour's cost at its first-imported value.+ config = ModalSourceConfig.from_dict({"token_id": "ak-test", "token_secret": "as-test-secret"})+ schemas = {s.name: s for s in ModalSource().get_schemas(config, team_id=1)}+ assert schemas[schema_name].default_incremental_lookback_seconds == expected_seconds