Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): add 3 missing tables to the Modal source (#118333)

Tom Owers9f3b853debeb
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index 911af7c872f3..29b43ce3e6bd 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -8061,10 +8061,10 @@ Today (2): `billing_report_daily`, `billing_report_hourly`
Diffed against: <https://raw.githubusercontent.com/modal-labs/modal-client/main/modal_proto/api.proto>
-- [ ] `Apps and Functions (SDK RPC AppList; SDK RPC AppGetInfo)` — resolve function IDs in billing reports to application names, owners, and deployment state (high)
-- [ ] `Workspace billing summary (SDK RPC WorkspaceBillingSummary, Workspace.billing.summary)` — reconcile metered cost with invoiced cost, credits, and other adjustments (high)
+- [x] `Apps and Functions (SDK RPC AppList; SDK RPC AppGetInfo)` — resolve function IDs in billing reports to application names, owners, and deployment state (high)
+- [x] `Workspace billing summary (SDK RPC WorkspaceBillingSummary, Workspace.billing.summary)` — reconcile metered cost with invoiced cost, credits, and other adjustments (high)
- [ ] `Function statistics (SDK RPC FunctionGetTimeRangeStats, Function.stats)` — measure successful calls, failures, timeouts, latency, and resource utilization, which billing costs cannot show (high)
-- [ ] `Sandboxes (SDK RPC SandboxList/SandboxListV2, Sandbox.list)` — resolve sandbox IDs in billing reports and compare sandbox populations across applications (high)
+- [x] `Sandboxes (SDK RPC SandboxList/SandboxListV2, Sandbox.list)` — resolve sandbox IDs in billing reports and compare sandbox populations across applications (high)
- [ ] `App deployment history (SDK RPC AppDeploymentHistory)` — connect deployment revisions with cost changes, failed calls, and incident periods (medium)
- [ ] `Workspace members (SDK RPC WorkspaceMembersList, Workspace.members.list)` — join application creators with workspace member identities for ownership and adoption reports (medium)
- [ ] `App logs (SDK RPC AppFetchLogs, App.logs.fetch)` — analyze execution errors and runtime activity by function, container, and time (medium)
diff --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.py
index 9728349ee8fa..04e86552b45b 100644
--- 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.py
@@ -17,3 +17,45 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
}
for name, resolution in (("billing_report_daily", "Daily"), ("billing_report_hourly", "Hourly"))
}
+
+CANONICAL_DESCRIPTIONS["billing_summary"] = {
+ "description": "Workspace cost for each monthly billing cycle, before and after adjustments.",
+ "docs_url": "https://modal.com/docs/sdk/py/latest/Workspace#billingsummary",
+ "columns": {
+ "cycle_start": "Start of the billing cycle in UTC.",
+ "cycle_end": "End of the billing cycle in UTC.",
+ "metered_cost": "Cost for the billing cycle before adjustments.",
+ "billed_cost": "Cost actually invoiced for the billing cycle, including all adjustments.",
+ "metered_cost_breakdown": "Metered cost by the Modal resource that generated it.",
+ "adjustments": "Adjustments, such as plan credits, that make up the difference between metered and billed cost.",
+ },
+}
+CANONICAL_DESCRIPTIONS["apps"] = {
+ "description": "Modal Apps that are running, deployed, or recently stopped, in each environment of the workspace.",
+ "docs_url": "https://modal.com/docs/cli/latest/app#modal-app-list",
+ "columns": {
+ "app_id": "Identifier of the App. Billing reports use it as the object ID.",
+ "name": "Name of the App.",
+ "description": "Description of the App.",
+ "state": "Lifecycle state of the App, such as deployed, ephemeral, or stopped.",
+ "environment_name": "Name of the Modal environment that contains the App.",
+ "created_at": "Time when the App was created.",
+ "stopped_at": "Time when the App was stopped.",
+ "n_running_tasks": "Number of containers that run for the App at sync time.",
+ },
+}
+CANONICAL_DESCRIPTIONS["sandboxes"] = {
+ "description": "Modal Sandboxes of each App, including finished Sandboxes.",
+ "docs_url": "https://modal.com/docs/sdk/py/latest/Sandbox#list",
+ "columns": {
+ "id": "Identifier of the Sandbox.",
+ "name": "Name of the Sandbox.",
+ "app_id": "Identifier of the App that contains the Sandbox.",
+ "environment_name": "Name of the Modal environment that contains the Sandbox.",
+ "created_at": "Time when the Sandbox was created.",
+ "finished_at": "Time when the Sandbox finished.",
+ "status": "Final status of the Sandbox, such as success, failure, or timeout. Empty while it runs.",
+ "exit_code": "Exit code of the Sandbox entrypoint after it finished.",
+ "tags": "User-defined tags of the Sandbox.",
+ },
+}
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.py
index de458bfe8045..739a1359d7a7 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/modal/modal.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/modal/modal.py
@@ -4,17 +4,26 @@ from datetime import UTC, datetime, timedelta
from typing import TYPE_CHECKING
import modal
+from google.protobuf.descriptor import EnumDescriptor
from grpclib import GRPCError, Status
+from modal._utils.async_utils import synchronizer
+from modal.client import _Client
+from modal.environments import list_environments
from modal.exception import AuthError, PermissionDeniedError
+from modal_proto import api_pb2
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,
+ APPS,
+ BILLING_REPORT_PARTITION_KEY,
+ BILLING_REPORT_PRIMARY_KEYS,
+ BILLING_REPORT_TABLES,
+ BILLING_SUMMARY,
+ BILLING_SUMMARY_DEFAULT_CYCLES,
+ SANDBOXES,
)
if TYPE_CHECKING:
@@ -52,6 +61,58 @@ def as_utc(value: datetime | str) -> datetime:
return parsed.astimezone(UTC)
+def month_start(value: datetime) -> datetime:
+ return value.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
+
+
+def add_months(value: datetime, months: int) -> datetime:
+ index = value.year * 12 + value.month - 1 + months
+ return value.replace(year=index // 12, month=index % 12 + 1)
+
+
+def from_epoch(value: float) -> datetime | None:
+ return datetime.fromtimestamp(value, UTC) if value else None
+
+
+def enum_label(descriptor: EnumDescriptor, value: int, prefix: str) -> str:
+ member = descriptor.values_by_number.get(value)
+ # The server can send enum values that the pinned SDK does not know yet.
+ return member.name.removeprefix(prefix).lower() if member else str(value)
+
+
+# The SDK has no public call for these RPCs, so this uses the same blocking wrapper as the Modal CLI.
+async def _list_apps(client: _Client, environment_name: str) -> list[api_pb2.AppListResponse.AppListItem]:
+ response = await client.stub.AppList(api_pb2.AppListRequest(environment_name=environment_name))
+ return list(response.apps)
+
+
+async def _list_sandbox_page(
+ client: _Client, app_id: str, environment_name: str, before_timestamp: float
+) -> list[api_pb2.SandboxInfo]:
+ request = api_pb2.SandboxListRequest(
+ app_id=app_id,
+ environment_name=environment_name,
+ before_timestamp=before_timestamp,
+ include_finished=True,
+ )
+ response = await client.stub.SandboxList(request)
+ return list(response.sandboxes)
+
+
+_list_apps_blocking = synchronizer.create_blocking(_list_apps)
+_list_sandbox_page_blocking = synchronizer.create_blocking(_list_sandbox_page)
+
+
+def list_apps(client: modal.Client, environment_name: str) -> list[api_pb2.AppListResponse.AppListItem]:
+ return _list_apps_blocking(client, environment_name)
+
+
+def list_sandbox_page(
+ client: modal.Client, app_id: str, environment_name: str, before_timestamp: float
+) -> list[api_pb2.SandboxInfo]:
+ return _list_sandbox_page_blocking(client, app_id, environment_name, before_timestamp)
+
+
@contextmanager
def billing_client(config: ModalSourceConfig) -> Iterator[modal.Client]:
try:
@@ -92,7 +153,21 @@ def modal_source(
inputs: SourceInputs,
resumable_source_manager: ResumableSourceManager[ModalResumeConfig],
) -> SourceResponse:
- table = schema_for_resource(ENDPOINTS, inputs.schema_name)
+ if inputs.schema_name == BILLING_SUMMARY:
+ return billing_summary_source(config, inputs, resumable_source_manager)
+ if inputs.schema_name == APPS:
+ return apps_source(config, inputs, resumable_source_manager)
+ if inputs.schema_name == SANDBOXES:
+ return sandboxes_source(config, inputs, resumable_source_manager)
+ return billing_report_source(config, inputs, resumable_source_manager)
+
+
+def billing_report_source(
+ config: ModalSourceConfig,
+ inputs: SourceInputs,
+ resumable_source_manager: ResumableSourceManager[ModalResumeConfig],
+) -> SourceResponse:
+ table = schema_for_resource(BILLING_REPORT_TABLES, 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
@@ -140,11 +215,184 @@ def modal_source(
return SourceResponse(
name=inputs.schema_name,
items=get_rows,
- primary_keys=PRIMARY_KEYS,
+ primary_keys=BILLING_REPORT_PRIMARY_KEYS,
column_hints={"cost": "double", "interval_start": "timestamp", "tags": "json"},
- partition_keys=[PARTITION_KEY],
+ partition_keys=[BILLING_REPORT_PARTITION_KEY],
partition_mode="datetime",
partition_format="month",
sort_mode="asc",
on_complete=resumable_source_manager.clear_state,
)
+
+
+def billing_summary_source(
+ config: ModalSourceConfig,
+ inputs: SourceInputs,
+ resumable_source_manager: ResumableSourceManager[ModalResumeConfig],
+) -> SourceResponse:
+ def get_rows() -> Iterator[list[dict[str, object]]]:
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume:
+ last_cycle = as_utc(resume.end)
+ cycle = as_utc(resume.next_window_start)
+ else:
+ last_cycle = month_start(datetime.now(UTC))
+ watermark = inputs.db_incremental_field_last_value if inputs.should_use_incremental_field else None
+ # Re-read the watermark cycle because its cost changes until the cycle is invoiced.
+ cycle = (
+ month_start(as_utc(watermark))
+ if watermark is not None
+ else add_months(last_cycle, 1 - BILLING_SUMMARY_DEFAULT_CYCLES)
+ )
+
+ if cycle > last_cycle:
+ return
+
+ with billing_client(config) as client:
+ billing = modal.Workspace.from_context(client=client).billing
+ while cycle <= last_cycle:
+ summary = billing.summary(cycle=cycle)
+ next_cycle = add_months(cycle, 1)
+ resumable_source_manager.save_state(
+ ModalResumeConfig(next_window_start=next_cycle.isoformat(), end=last_cycle.isoformat())
+ )
+ yield [
+ {
+ "cycle_start": as_utc(summary.start),
+ "cycle_end": as_utc(summary.end),
+ "metered_cost": float(summary.metered_cost),
+ "billed_cost": float(summary.billed_cost),
+ "metered_cost_breakdown": {
+ key: float(value) for key, value in summary.metered_cost_breakdown.items()
+ },
+ "adjustments": {key: float(value) for key, value in summary.adjustments.items()},
+ }
+ ]
+ cycle = next_cycle
+
+ return SourceResponse(
+ name=inputs.schema_name,
+ items=get_rows,
+ primary_keys=["cycle_start"],
+ column_hints={
+ "cycle_start": "timestamp",
+ "cycle_end": "timestamp",
+ "metered_cost": "double",
+ "billed_cost": "double",
+ "metered_cost_breakdown": "json",
+ "adjustments": "json",
+ },
+ sort_mode="asc",
+ on_complete=resumable_source_manager.clear_state,
+ )
+
+
+def app_row(app: api_pb2.AppListResponse.AppListItem, environment_name: str) -> dict[str, object]:
+ return {
+ "app_id": app.app_id,
+ "name": app.name or None,
+ "description": app.description or None,
+ "state": enum_label(api_pb2.AppState.DESCRIPTOR, app.state, "APP_STATE_"),
+ "environment_name": environment_name,
+ "created_at": from_epoch(app.created_at),
+ "stopped_at": from_epoch(app.stopped_at),
+ "n_running_tasks": app.n_running_tasks,
+ }
+
+
+def apps_source(
+ config: ModalSourceConfig,
+ inputs: SourceInputs,
+ resumable_source_manager: ResumableSourceManager[ModalResumeConfig],
+) -> SourceResponse:
+ def get_rows() -> Iterator[list[dict[str, object]]]:
+ with billing_client(config) as client:
+ for environment in list_environments(client=client):
+ rows = [app_row(app, environment.name) for app in list_apps(client, environment.name)]
+ if rows:
+ yield rows
+ resumable_source_manager.safe_point()
+
+ return SourceResponse(
+ name=inputs.schema_name,
+ items=get_rows,
+ primary_keys=["app_id"],
+ column_hints={"created_at": "timestamp", "stopped_at": "timestamp"},
+ partition_keys=["created_at"],
+ partition_mode="datetime",
+ partition_format="month",
+ )
+
+
+def sandbox_row(sandbox: api_pb2.SandboxInfo, environment_name: str) -> dict[str, object]:
+ task = sandbox.task_info
+ resources = sandbox.resource_info
+ finished = task.result.status != api_pb2.GenericResult.GENERIC_STATUS_UNSPECIFIED
+ return {
+ "id": sandbox.id,
+ "name": sandbox.name or None,
+ "app_id": sandbox.app_id,
+ "environment_name": environment_name,
+ "image_id": sandbox.image_id or None,
+ "created_at": from_epoch(sandbox.created_at),
+ "ready_at": from_epoch(sandbox.ready_at) if sandbox.HasField("ready_at") else None,
+ "task_id": task.id or None,
+ "enqueued_at": from_epoch(task.enqueued_at),
+ "started_at": from_epoch(task.started_at),
+ "finished_at": from_epoch(task.finished_at),
+ "status": enum_label(api_pb2.GenericResult.GenericStatus.DESCRIPTOR, task.result.status, "GENERIC_STATUS_")
+ if finished
+ else None,
+ "exit_code": task.result.exitcode if finished else None,
+ "gpu_type": resources.gpu_type or task.gpu_type or None,
+ "milli_cpu": resources.milli_cpu.value or None,
+ "milli_cpu_max": resources.milli_cpu_max or None,
+ "memory_mb": resources.memory_mb.value or None,
+ "memory_mb_max": resources.memory_mb_max or None,
+ "ephemeral_disk_mb": resources.ephemeral_disk_mb or None,
+ "regions": list(sandbox.regions),
+ "timeout_secs": sandbox.timeout_secs or None,
+ "idle_timeout_secs": sandbox.idle_timeout_secs if sandbox.HasField("idle_timeout_secs") else None,
+ "tags": {tag.tag_name: tag.tag_value for tag in sandbox.tags},
+ }
+
+
+def sandboxes_source(
+ config: ModalSourceConfig,
+ inputs: SourceInputs,
+ resumable_source_manager: ResumableSourceManager[ModalResumeConfig],
+) -> SourceResponse:
+ def get_rows() -> Iterator[list[dict[str, object]]]:
+ with billing_client(config) as client:
+ for environment in list_environments(client=client):
+ # Listing by App follows the SDK, which deprecates Environment-wide Sandbox scans.
+ for app in list_apps(client, environment.name):
+ # Zero leaves the cursor unset, so the first page starts at the newest Sandbox.
+ before_timestamp = 0.0
+ while True:
+ page = list_sandbox_page(client, app.app_id, environment.name, before_timestamp)
+ if page:
+ yield [sandbox_row(sandbox, environment.name) for sandbox in page]
+ resumable_source_manager.safe_point()
+ # Pages run newest first; stop if the cursor does not move back in time.
+ if not page or (before_timestamp and page[-1].created_at >= before_timestamp):
+ break
+ before_timestamp = page[-1].created_at
+
+ return SourceResponse(
+ name=inputs.schema_name,
+ items=get_rows,
+ primary_keys=["id"],
+ column_hints={
+ "created_at": "timestamp",
+ "ready_at": "timestamp",
+ "enqueued_at": "timestamp",
+ "started_at": "timestamp",
+ "finished_at": "timestamp",
+ "regions": "json",
+ "tags": "json",
+ },
+ partition_keys=["created_at"],
+ partition_mode="datetime",
+ partition_format="month",
+ )
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.py
index 9848294e7a0b..6ded92e7c5a7 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/modal/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/modal/settings.py
@@ -20,7 +20,7 @@ class BillingTable:
default_incremental_lookback: timedelta
-ENDPOINTS = {
+BILLING_REPORT_TABLES = {
"billing_report_daily": BillingTable(
resolution="d",
default_lookback=timedelta(days=365),
@@ -34,9 +34,18 @@ ENDPOINTS = {
default_incremental_lookback=timedelta(hours=6),
),
}
-INCREMENTAL_FIELDS = {name: [incremental_field("interval_start")] for name in ENDPOINTS}
+BILLING_SUMMARY = "billing_summary"
+APPS = "apps"
+SANDBOXES = "sandboxes"
+ENDPOINTS = (*BILLING_REPORT_TABLES, BILLING_SUMMARY, APPS, SANDBOXES)
+BILLING_SUMMARY_DEFAULT_CYCLES = 12
+
+INCREMENTAL_FIELDS = {
+ **{name: [incremental_field("interval_start")] for name in BILLING_REPORT_TABLES},
+ BILLING_SUMMARY: [incremental_field("cycle_start")],
+}
DEFAULT_INCREMENTAL_LOOKBACK_SECONDS = {
- name: int(table.default_incremental_lookback.total_seconds()) for name, table in ENDPOINTS.items()
+ name: int(table.default_incremental_lookback.total_seconds()) for name, table in BILLING_REPORT_TABLES.items()
}
-PRIMARY_KEYS = ["object_id", "interval_start", "environment_name"]
-PARTITION_KEY = "interval_start"
+BILLING_REPORT_PRIMARY_KEYS = ["object_id", "interval_start", "environment_name"]
+BILLING_REPORT_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.py
index f72c21269326..a3ef179c2c8d 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
@@ -31,6 +31,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.modal.moda
validate_credentials,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.modal.settings import (
+ BILLING_REPORT_TABLES,
+ BILLING_SUMMARY,
DEFAULT_INCREMENTAL_LOOKBACK_SECONDS,
ENDPOINTS,
INCREMENTAL_FIELDS,
@@ -110,7 +112,7 @@ class ModalSource(ResumableSource[ModalSourceConfig, ModalResumeConfig]):
ENDPOINTS,
INCREMENTAL_FIELDS,
names,
- merge_only=ENDPOINTS,
+ merge_only=(*BILLING_REPORT_TABLES, BILLING_SUMMARY),
default_incremental_lookback_seconds=DEFAULT_INCREMENTAL_LOOKBACK_SECONDS,
)
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.py
index 76821b2d65c2..2ed4ceb6df63 100644
--- 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.py
@@ -5,11 +5,14 @@ from typing import cast
import pytest
import time_machine
-from unittest.mock import MagicMock, patch
+from unittest.mock import AsyncMock, MagicMock, PropertyMock, patch
+import modal
from grpclib import GRPCError, Status
+from modal.client import _Client
from modal.exception import AuthError, PermissionDeniedError, ResourceExhaustedError, ServiceError
-from modal.types import BillingReportItem
+from modal.types import BillingReportItem, WorkspaceBillingSummary
+from modal_proto import api_pb2
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
@@ -278,3 +281,280 @@ def test_unknown_table_does_not_connect(
modal_source(config, inputs, manager)
create_client.assert_not_called()
report.assert_not_called()
+
+
+def billing_summary(cycle: datetime) -> WorkspaceBillingSummary:
+ return WorkspaceBillingSummary(
+ start=cycle,
+ end=cycle + timedelta(days=28),
+ metered_cost=Decimal("120.50"),
+ metered_cost_breakdown={"cpu": Decimal("100.25"), "gpu": Decimal("20.25")},
+ adjustments={"credits": Decimal("-30")},
+ billed_cost=Decimal("90.50"),
+ )
+
+
+ ("watermark", "incremental", "resume", "expected_cycles"),
+ [
+ (
+ None,
+ True,
+ None,
+ [datetime(2025, month, 1, tzinfo=UTC) for month in range(4, 13)]
+ + [datetime(2026, month, 1, tzinfo=UTC) for month in range(1, 4)],
+ ),
+ ("2026-01-14T00:00:00Z", True, None, [datetime(2026, month, 1, tzinfo=UTC) for month in range(1, 4)]),
+ ("2025-12-31T23:00:00-02:00", True, None, [datetime(2026, month, 1, tzinfo=UTC) for month in range(1, 4)]),
+ ("2026-03-01T00:00:00Z", True, None, [datetime(2026, 3, 1, tzinfo=UTC)]),
+ (
+ "2026-03-01T00:00:00Z",
+ False,
+ None,
+ [datetime(2025, month, 1, tzinfo=UTC) for month in range(4, 13)]
+ + [datetime(2026, month, 1, tzinfo=UTC) for month in range(1, 4)],
+ ),
+ ("2026-04-01T00:00:00Z", True, None, []),
+ (
+ None,
+ True,
+ ModalResumeConfig(next_window_start="2025-12-01T00:00:00+00:00", end="2026-01-01T00:00:00+00:00"),
+ [datetime(2025, 12, 1, tzinfo=UTC), datetime(2026, 1, 1, tzinfo=UTC)],
+ ),
+ ],
+)
+def test_billing_summary_cycles(
+ config: ModalSourceConfig,
+ inputs: SourceInputs,
+ manager: MagicMock,
+ create_client: MagicMock,
+ workspace: MagicMock,
+ watermark: str | None,
+ incremental: bool,
+ resume: ModalResumeConfig | None,
+ expected_cycles: list[datetime],
+) -> None:
+ inputs.schema_name = "billing_summary"
+ inputs.db_incremental_field_last_value = watermark
+ inputs.should_use_incremental_field = incremental
+ manager.can_resume.return_value = resume is not None
+ manager.load_state.return_value = resume
+ summary = workspace.return_value.billing.summary
+ summary.side_effect = lambda cycle: billing_summary(cycle)
+
+ batches = list(source_items(modal_source(config, inputs, manager)))
+
+ assert [call.kwargs["cycle"] for call in summary.call_args_list] == expected_cycles
+ assert [row["cycle_start"] for batch in batches for row in batch] == expected_cycles
+ assert all(len(batch) == 1 for batch in batches)
+ assert [call.args[0].next_window_start for call in manager.save_state.call_args_list] == [
+ (datetime(cycle.year + cycle.month // 12, cycle.month % 12 + 1, 1, tzinfo=UTC)).isoformat()
+ for cycle in expected_cycles
+ ]
+ if not expected_cycles:
+ create_client.assert_not_called()
+ return
+ assert batches[0][0] == {
+ "cycle_start": expected_cycles[0],
+ "cycle_end": expected_cycles[0] + timedelta(days=28),
+ "metered_cost": 120.5,
+ "billed_cost": 90.5,
+ "metered_cost_breakdown": {"cpu": 100.25, "gpu": 20.25},
+ "adjustments": {"credits": -30.0},
+ }
+ create_client.return_value.__exit__.assert_called_once()
+
+
+def app_item(
+ app_id: str, state: api_pb2.AppState.ValueType = api_pb2.APP_STATE_DEPLOYED
+) -> api_pb2.AppListResponse.AppListItem:
+ return api_pb2.AppListResponse.AppListItem(
+ app_id=app_id,
+ name=f"name-{app_id}",
+ description=f"Example {app_id}",
+ state=state,
+ created_at=NOW.timestamp() - 86400,
+ n_running_tasks=2,
+ )
+
+
+def sandbox_info(sandbox_id: str, created_at: float, finished: bool = True) -> api_pb2.SandboxInfo:
+ return api_pb2.SandboxInfo(
+ id=sandbox_id,
+ app_id="ap-one",
+ created_at=created_at,
+ task_info=api_pb2.TaskInfo(
+ id="ta-test",
+ started_at=created_at + 5,
+ finished_at=created_at + 60 if finished else 0,
+ result=api_pb2.GenericResult(status=api_pb2.GenericResult.GENERIC_STATUS_TIMEOUT, exitcode=137)
+ if finished
+ else None,
+ ),
+ resource_info=api_pb2.ResourceInfo(
+ milli_cpu=api_pb2.ResourceInfo.ResourceValue(value=500),
+ memory_mb=api_pb2.ResourceInfo.ResourceValue(value=1024),
+ ),
+ tags=[api_pb2.SandboxTag(tag_name="team", tag_value="example")],
+ regions=["us-east"],
+ timeout_secs=300,
+ )
+
+
+def stub() -> Iterator[MagicMock]:
+ stub = MagicMock()
+ stub.EnvironmentList = AsyncMock(
+ return_value=api_pb2.EnvironmentListResponse(
+ items=[api_pb2.EnvironmentListItem(name="main"), api_pb2.EnvironmentListItem(name="dev")]
+ )
+ )
+ with patch.object(_Client, "stub", new_callable=PropertyMock, return_value=stub):
+ yield stub
+
+
+def real_client(create_client: MagicMock) -> modal.Client:
+ client = modal.Client("https://api.modal.com", api_pb2.CLIENT_TYPE_CLIENT, ("ak-test", "as-test-secret"))
+ create_client.return_value = client
+ return client
+
+
+def test_apps_list_every_environment(
+ config: ModalSourceConfig, inputs: SourceInputs, manager: MagicMock, real_client: modal.Client, stub: MagicMock
+) -> None:
+ inputs.schema_name = "apps"
+ apps = {"main": [app_item("ap-one"), app_item("ap-two", state=api_pb2.AppState.ValueType(99))], "dev": []}
+ stub.AppList = AsyncMock(side_effect=lambda request: api_pb2.AppListResponse(apps=apps[request.environment_name]))
+
+ batches = list(source_items(modal_source(config, inputs, manager)))
+
+ assert [call.args[0].environment_name for call in stub.AppList.call_args_list] == ["main", "dev"]
+ assert batches == [
+ [
+ {
+ "app_id": "ap-one",
+ "name": "name-ap-one",
+ "description": "Example ap-one",
+ "state": "deployed",
+ "environment_name": "main",
+ "created_at": NOW - timedelta(days=1),
+ "stopped_at": None,
+ "n_running_tasks": 2,
+ },
+ {
+ "app_id": "ap-two",
+ "name": "name-ap-two",
+ "description": "Example ap-two",
+ "state": "99",
+ "environment_name": "main",
+ "created_at": NOW - timedelta(days=1),
+ "stopped_at": None,
+ "n_running_tasks": 2,
+ },
+ ]
+ ]
+ assert manager.safe_point.call_count == 2
+
+
+ ("pages", "expected_cursors", "expected_ids"),
+ [
+ ([[]], [0.0], []),
+ (
+ [
+ [sandbox_info("sb-3", 3000.0), sandbox_info("sb-2", 2000.0)],
+ [sandbox_info("sb-1", 1000.0)],
+ [],
+ ],
+ [0.0, 2000.0, 1000.0],
+ ["sb-3", "sb-2", "sb-1"],
+ ),
+ (
+ [[sandbox_info("sb-2", 2000.0)], [sandbox_info("sb-2", 2000.0)]],
+ [0.0, 2000.0],
+ ["sb-2", "sb-2"],
+ ),
+ ],
+)
+def test_sandboxes_page_back_through_each_app(
+ config: ModalSourceConfig,
+ inputs: SourceInputs,
+ manager: MagicMock,
+ real_client: modal.Client,
+ stub: MagicMock,
+ pages: list[list[api_pb2.SandboxInfo]],
+ expected_cursors: list[float],
+ expected_ids: list[str],
+) -> None:
+ inputs.schema_name = "sandboxes"
+ stub.AppList = AsyncMock(
+ side_effect=lambda request: api_pb2.AppListResponse(
+ apps=[app_item("ap-one")] if request.environment_name == "main" else []
+ )
+ )
+ responses = iter(pages)
+ stub.SandboxList = AsyncMock(side_effect=lambda request: api_pb2.SandboxListResponse(sandboxes=next(responses)))
+
+ rows = [row for batch in source_items(modal_source(config, inputs, manager)) for row in batch]
+
+ requests = [call.args[0] for call in stub.SandboxList.call_args_list]
+ assert [request.before_timestamp for request in requests] == expected_cursors
+ assert all(request.app_id == "ap-one" and request.environment_name == "main" for request in requests)
+ assert all(request.include_finished for request in requests)
+ assert [row["id"] for row in rows] == expected_ids
+ assert manager.safe_point.call_count == len(pages)
+
+
[email protected]("finished", [True, False])
+def test_sandbox_row_shape(
+ config: ModalSourceConfig,
+ inputs: SourceInputs,
+ manager: MagicMock,
+ real_client: modal.Client,
+ stub: MagicMock,
+ finished: bool,
+) -> None:
+ inputs.schema_name = "sandboxes"
+ created_at = NOW.timestamp() - 3600
+ stub.AppList = AsyncMock(
+ side_effect=lambda request: api_pb2.AppListResponse(
+ apps=[app_item("ap-one")] if request.environment_name == "main" else []
+ )
+ )
+ stub.SandboxList = AsyncMock(
+ side_effect=[
+ api_pb2.SandboxListResponse(sandboxes=[sandbox_info("sb-1", created_at, finished=finished)]),
+ api_pb2.SandboxListResponse(),
+ ]
+ )
+
+ (batch,) = list(source_items(modal_source(config, inputs, manager)))
+
+ assert batch == [
+ {
+ "id": "sb-1",
+ "name": None,
+ "app_id": "ap-one",
+ "environment_name": "main",
+ "image_id": None,
+ "created_at": NOW - timedelta(hours=1),
+ "ready_at": None,
+ "task_id": "ta-test",
+ "enqueued_at": None,
+ "started_at": NOW - timedelta(hours=1) + timedelta(seconds=5),
+ "finished_at": NOW - timedelta(hours=1) + timedelta(seconds=60) if finished else None,
+ "status": "timeout" if finished else None,
+ "exit_code": 137 if finished else None,
+ "gpu_type": None,
+ "milli_cpu": 500,
+ "milli_cpu_max": None,
+ "memory_mb": 1024,
+ "memory_mb_max": None,
+ "ephemeral_disk_mb": None,
+ "regions": ["us-east"],
+ "timeout_secs": 300,
+ "idle_timeout_secs": None,
+ "tags": {"team": "example"},
+ }
+ ]