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.

chore(data-warehouse): add a source contract test suite with ratchet baselines (#113454)

Tom Owersd45148cd68ef
diff --git a/.agents/skills/implementing-warehouse-sources/SKILL.md b/.agents/skills/implementing-warehouse-sources/SKILL.md
index 909e8b714266..b6f7bab9e59c 100644
--- a/.agents/skills/implementing-warehouse-sources/SKILL.md
+++ b/.agents/skills/implementing-warehouse-sources/SKILL.md
@@ -441,6 +441,29 @@ The `rest_source` framework reaches a safe point after each page and before each
The same condition decides when a `resume_hook` runs. When `items` returns the `Resource` directly, the hook runs before the page reaches the pipeline, so a page and its cursor commit together and a hand-off repeats no rows. When a source wraps the `Resource`, the hook runs when the wrapper asks for the next page, so a hand-off reads the last page again. Return the `Resource` directly when you can: use `data_map`, `add_map` and `add_filter` for row changes. A wrapper that hands each page on unchanged and holds no rows can keep the framework behavior by returning `Resource(wrapper, name=..., hints=resource._hints)` (see the usage report in `anthropic/anthropic.py`).
Do not call `safe_point()` or `commit()` in a `resume_hook`.
+### The source contract
+
+A worker that shuts down hands each running import to another worker. Every source with extraction code must make that possible:
+
+1. Bounded calls: each request has a read timeout, and one request with its retries and waits holds the worker for 5 minutes at most, also after a 429 with a large `Retry-After`.
+2. A safe point for each request: the source makes no more than 3 requests in a row with no yield and no safe point.
+3. Resume state is staged before the `yield` it covers.
+
+`sources/tests/test_source_contract.py` runs each source in the registry against a fake HTTP server that stalls, rate-limits and returns empty pages. It compares the result with `sources/tests/source_contract_baseline.txt`, which lists each source that fails a condition or that the fake server cannot drive. A new source must pass; the baseline may only get shorter.
+`posthog/test/repo_invariants/test_warehouse_source_static_contract.py` and `test_resume_state_staged_before_yield.py` check the same contract in the source text of every source: no raw `time.sleep`, no session call without `timeout=`, no wrapper around a framework `Resource` without a safe point, and no `save_state` after the `yield`.
+
+```bash
+pytest products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_source_contract.py posthog/test/repo_invariants/test_warehouse_source_static_contract.py posthog/test/repo_invariants/test_resume_state_staged_before_yield.py
+```
+
+When a fix makes an entry wrong, regenerate the baseline and commit it:
+
+```bash
+SOURCE_CONTRACT_WRITE_BASELINE=1 pytest products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_source_contract.py -p no:xdist
+python posthog/test/repo_invariants/test_warehouse_source_static_contract.py
+python posthog/test/repo_invariants/test_resume_state_staged_before_yield.py
+```
+
### Webhook source pattern
- Implement `webhook_template` returning a `HogFunctionTemplateDC` that transforms incoming webhook payloads.
diff --git a/posthog/test/repo_invariants/resume_state_after_yield_baseline.txt b/posthog/test/repo_invariants/resume_state_after_yield_baseline.txt
index c06002ebd6b5..42395d02f6c3 100644
--- a/posthog/test/repo_invariants/resume_state_after_yield_baseline.txt
+++ b/posthog/test/repo_invariants/resume_state_after_yield_baseline.txt
@@ -6,12 +6,14 @@ adobe_analytics/adobe_analytics.py::_report_batches
adobe_commerce/adobe_commerce.py::get_rows
adyen/adyen.py::_iter_cursor_pages
adyen/adyen.py::_iter_fanout_pages
+adyen/adyen.py::_iter_offset_pages
adyen/adyen.py::_iter_page_number_pages
adyen/adyen.py::_iter_report_batches
airbrake/airbrake.py::_notices_rows
airbrake/airbrake.py::_project_fan_out_rows
airbrake/airbrake.py::_projects_rows
amplitude/amplitude.py::_get_events_rows
+anthropic/anthropic.py::_iter_analytics_windows
anvil/anvil.py::_get_parent_paged_rows
apollo/apollo.py::get_rows
app_store_connect/app_store_connect.py::_get_analytics_report
@@ -86,6 +88,7 @@ clari/clari.py::get_audit_events
clickhouse_cloud/clickhouse_cloud.py::_iter_usage_cost_rows
clickup/clickup.py::_time_entries_rows
clip/clip.py::clip_source.items
+close/search.py::iter_search_rows
codecov/codecov.py::_get_fan_out_rows
codecov/codecov.py::_get_top_level_rows
cody/cody.py::_get_windowed_rows
@@ -94,6 +97,8 @@ coingecko/coingecko.py::_chart_pages
coinmarketcap/coinmarketcap.py::get_batch_rows
coinmarketcap/coinmarketcap.py::get_snapshot_rows
commercetools/commercetools.py::get_rows
+common/rest_source/rest_client.py::RESTClient.paginate
+common/sql/keyset.py::iter_keyset_pages
concord/concord.py::_iter_agreement_fanout
concord/concord.py::_iter_events_windows
concord/concord.py::_iter_offset
@@ -191,6 +196,7 @@ grafana/grafana.py::_get_annotation_rows
grafana/grafana.py::_get_fan_out_rows
grafana/grafana.py::_get_paged_rows
gridly/gridly.py::_iter_records
+gusto/gusto.py::_paginate
gusto/gusto.py::get_rows
harvey/harvey.py::_get_audit_log_rows
harvey/harvey.py::_get_history_rows
@@ -207,6 +213,8 @@ honeybadger/honeybadger.py::_get_project_rows
honeycomb/honeycomb.py::_iter_board_views
honeycomb/honeycomb.py::_iter_fan_out
hubspot/hubspot.py::get_rows
+hubspot/hubspot.py::get_rows_via_search
+hubspot/hubspot.py::get_rows_via_search._process_results
hyperspell/hyperspell.py::_get_list_rows
hyperspell/hyperspell.py::get_rows
impact/impact.py::_get_rows_fanout
@@ -226,6 +234,7 @@ instana/instana.py::_get_metric_rows
instana/instana.py::_get_offset_rows
instana/instana.py::_get_paged_rows
intercom/intercom.py::_company_segments_generator
+intercom/intercom.py::_conversation_parts_generator
jamf_pro/jamf_pro.py::get_rows
jellyfish/jellyfish.py::_get_fan_out_rows
jellyfish/jellyfish.py::_get_month_windowed_rows
@@ -260,6 +269,7 @@ mention/mention.py::_alert_rows
mention/mention.py::_alert_tag_rows
mention/mention.py::_mention_rows
meta_ads/meta_ads.py::_iter_simple_pagination
+meta_ads/meta_ads.py::_iter_time_range_pagination
metaplane/metaplane.py::_get_evaluation_rows
meteostat/meteostat.py::_get_rows
mistral_ai/mistral_ai.py::get_rows
@@ -305,6 +315,7 @@ pinterest_ads/pinterest_ads.py::_iter_fanned_out_analytics
plaid/plaid.py::get_rows
platform_sh/platform_sh.py::get_rows
polar/polar.py::get_rows
+postgres/postgres.py::postgres_source.get_rows.offset_chunking
power_bi_admin/power_bi_admin.py::_activity_event_pages
power_bi_admin/power_bi_admin.py::_odata_pages
printify/printify.py::_iter_endpoint_pages
@@ -354,6 +365,7 @@ sourcegraph/sourcegraph.py::get_rows
spacelift/spacelift.py::_get_rows
split_io/split_io.py::_paginate_resource
splunk_observability_cloud/splunk_observability_cloud.py::_get_detector_event_rows
+splunk_observability_cloud/splunk_observability_cloud.py::_paginate
squadcast/squadcast.py::_iter_cursor_pages
squadcast/squadcast.py::_iter_incident_export_windows
squadcast/squadcast.py::_iter_offset_pages
@@ -405,6 +417,7 @@ wordpress/wordpress.py::get_rows
writesonic/writesonic.py::_iter_config
writesonic/writesonic.py::_iter_daily
youtube_analytics/youtube_analytics.py::get_rows
+zendesk_sunshine/zendesk_sunshine.py::_object_records_incremental
zenduty/zenduty.py::_paginate_fan_out
zenduty/zenduty.py::_paginate_top_level
zep/zep.py::_fan_out_message_rows
diff --git a/posthog/test/repo_invariants/source_raw_sleep_baseline.txt b/posthog/test/repo_invariants/source_raw_sleep_baseline.txt
new file mode 100644
index 000000000000..815a1ee63d32
--- /dev/null
+++ b/posthog/test/repo_invariants/source_raw_sleep_baseline.txt
@@ -0,0 +1,54 @@
+adobe_analytics/adobe_analytics.py::AdobeAnalyticsClient._pace
+amazon_ads/amazon_ads.py::AmazonAdsClient.await_report_url
+aws_cloudtrail/aws_cloudtrail.py::AwsCloudTrailClient.request
+bigquery/bigquery.py::_with_job_not_found_retry
+bing_ads/utils.py::download_report_file
+clari/clari.py::_run_export_job
+clickhouse/clickhouse.py::_get_client
+crates_io/crates_io.py::_RequestThrottle.wait
+databricks/databricks.py::_connect_with_transient_retry
+decagon/decagon.py::RequestThrottle.wait
+dixa/dixa.py::_iter_export_windows
+fullstory/fullstory.py::_wait_for_export
+github/github.py::_pace_before_request
+gladly/gladly.py::_report_rows
+google_ads/google_ads.py::_backoff_sleep
+google_analytics/google_analytics.py::_backoff_sleep
+google_analytics/google_analytics.py::_run_report
+google_search_console/google_search_console.py::_backoff_sleep
+google_search_console/google_search_console.py::_query_search_analytics
+google_search_console/google_search_console.py::_throttle
+google_sheets/google_sheets.py::_retry_on_transient_api_error
+honeybadger/honeybadger.py::_fetch_page
+instantly/instantly.py::InstantlyThrottledCursorPaginator.update_request
+intercom/intercom.py::_open_companies_scroll
+intercom/intercom.py::_request_with_rate_limit_retry
+intercom/intercom.py::_scroll_companies_get
+iterable/iterable.py::_iter_export
+linkedin_ads/linkedin_ads.py::_backoff_sleep
+marketo/marketo.py::_await_bulk_export
+matomo/matomo.py::get_rows.call
+meta_ads/meta_ads.py::_backoff_sleep
+mixpanel/mixpanel.py::_stream_export_day
+mssql/mssql.py::retry_on_deadlock
+mssql/mssql.py::retry_on_transient_connection_error
+mysql/mysql.py::_connect_with_transient_retry
+mysql/mysql.py::_retry_on_transient_tablet_unavailable
+new_york_times/new_york_times.py::_get_article_search_rows
+notion/notion.py::_RateLimiter.wait
+plaid/plaid.py::get_rows.post
+postgres/cdc/stream_reader.py::PgCDCStreamReader._advance_slot
+postgres/cdc/stream_reader.py::PgCDCStreamReader.read_changes
+postgres/postgres.py::_retry_on_connection_dropped
+postgres/postgres.py::postgres_source
+postgres/postgres.py::postgres_source.get_rows
+postgres/postgres.py::postgres_source.get_rows.offset_chunking.fetch_page
+postgres/postgres.py::postgres_source.get_rows.offset_chunking.handle_recovery_conflict
+qualtrics/qualtrics.py::_export_responses
+redshift/redshift.py::_retry_on_transient_connection_drop
+salesforce/auth.py::salesforce_refresh_access_token
+serpstat/serpstat.py::SerpstatPaginator.update_request
+singular/singular.py::SingularClient.await_download_url
+sumo_logic/sumo_logic.py::_submit_and_poll_search_job
+tenable_vulnerability_management/tenable_vulnerability_management.py::_get_export_rows
+transistor/transistor.py::RequestThrottle.wait
diff --git a/posthog/test/repo_invariants/source_request_without_timeout_baseline.txt b/posthog/test/repo_invariants/source_request_without_timeout_baseline.txt
new file mode 100644
index 000000000000..73c2e34562c2
--- /dev/null
+++ b/posthog/test/repo_invariants/source_request_without_timeout_baseline.txt
@@ -0,0 +1,38 @@
+ably/ably.py::validate_credentials
+agilecrm/agilecrm.py::_fanout_pages
+agilecrm/agilecrm.py::_paginate
+agilecrm/agilecrm.py::_resolve_all_tickets_filter_id
+billomat/billomat.py::validate_credentials
+bluesky/bluesky.py::validate_credentials
+braze/braze.py::_data_series_rows
+braze/braze.py::_details_rows
+dockerhub/dockerhub.py::_audit_log_action_rows
+dockerhub/dockerhub.py::_audit_log_pages
+dockerhub/dockerhub.py::_fetch_jwt
+dockerhub/dockerhub.py::_fetch_page
+dockerhub/dockerhub.py::check_access
+ecb_data_portal/ecb_data_portal.py::_request_csv_rows
+google_analytics/google_analytics.py::_run_report
+google_analytics/google_analytics.py::get_property_metadata
+google_search_console/google_search_console.py::_query_search_analytics
+google_search_console/google_search_console.py::list_sitemaps
+google_search_console/google_search_console.py::list_sites
+inngest/inngest.py::_get_session_run_rows
+polar/polar.py::get_rows
+polar/polar.py::validate_credentials
+quo/quo.py::_paginate
+rokt_ads/rokt_ads.py::RoktAdsClient.access_token
+rokt_ads/rokt_ads.py::RoktAdsClient.get
+rokt_ads/rokt_ads.py::RoktAdsClient.post
+salesforce/auth.py::salesforce_refresh_access_token
+shopify/shopify.py::_get_granted_scopes
+shopify/shopify.py::_make_paginated_shopify_request.execute
+shopify/shopify.py::_probe_resource_permission
+shopify/shopify.py::validate_credentials
+stytch/stytch.py::_get_session_rows
+tvmaze/tvmaze.py::_updates_items
+tyntec_sms/tyntec_sms.py::validate_credentials
+vitally/vitally.py::get_messages
+vitally/vitally.py::list_custom_object_definitions
+who_gho/who_gho.py::validate_credentials
+world_bank/world_bank.py::validate_credentials
diff --git a/posthog/test/repo_invariants/source_wrapped_resource_baseline.txt b/posthog/test/repo_invariants/source_wrapped_resource_baseline.txt
new file mode 100644
index 000000000000..05d365e29dc6
--- /dev/null
+++ b/posthog/test/repo_invariants/source_wrapped_resource_baseline.txt
@@ -0,0 +1,69 @@
+acculynx/acculynx.py::_job_pages
+acculynx/acculynx.py::_pages
+ahrefs/ahrefs.py::ahrefs_source.items
+ashby/ashby.py::_iter_pages
+assemblyai/assemblyai.py::assemblyai_source.items
+aviationstack/aviationstack.py::aviationstack_source.items
+browse_ai/browse_ai.py::browse_ai_source.rows
+cal_com/cal_com.py::_booking_attendees_items
+calendly/calendly.py::calendly_source.get_rows
+callrail/callrail.py::get_rows
+canvas_lms/canvas_lms.py::_non_fanout_source.items
+chargedesk/chargedesk.py::_run_fanout_pass
+chargedesk/chargedesk.py::_run_pass
+checkly/checkly.py::checkly_source.items
+clickup/clickup.py::_all_task_ids
+clickup/clickup.py::_chain_resources
+deel/deel.py::_time_off_event_items
+drip/drip.py::_campaign_subscriber_pages
+dynatrace/dynatrace.py::_endpoint_pages
+emailoctopus/emailoctopus.py::_fan_out_items
+fintoc/fintoc.py::FintocAPI.rows
+flutterwave/flutterwave.py::get_rows
+freshservice/freshservice.py::_approvals_source.items
+fusionauth/fusionauth.py::fusionauth_source.pages
+gainsight_px/gainsight_px.py::_event_pages
+hex/hex.py::hex_source.items
+hoorayhr/hoorayhr.py::_public_holiday_pages
+housecall_pro/housecall_pro.py::get_rows
+hugging_face/hugging_face.py::_repo_pages
+imperva/imperva.py::imperva_source.items
+intercom/intercom.py::intercom_source.iter_resource
+invoiceninja/invoiceninja.py::invoiceninja_source.items
+knock/knock.py::_objects_items
+lago/lago.py::lago_source.items
+leadfeeder/leadfeeder.py::_unified_account_ids
+metabase/metabase.py::get_rows
+moxie/moxie.py::moxie_source.items
+newsdata/newsdata.py::get_rows
+noaa_cdo/noaa_cdo.py::noaa_cdo_source.items
+okendo/okendo.py::okendo_source.items
+okta/okta.py::okta_source.items
+pagerduty/pagerduty.py::pagerduty_source.items
+paymongo/paymongo.py::pull_rows
+pipeliner/pipeliner.py::pipeliner_source.items
+plunk/plunk.py::plunk_source.items
+poplar/poplar.py::poplar_source.rows
+profound/profound.py::_report_pages
+promptwatch/promptwatch.py::promptwatch_source
+retell_ai/retell_ai.py::retell_ai_source.items
+revenuecat/revenuecat.py::revenuecat_api_source.items
+sentinelone/sentinelone.py::sentinelone_source._items
+sentry/sentry.py::_skip_endpoint_on_forbidden
+sevdesk/sevdesk.py::sevdesk_source.get_rows
+shutterstock/shutterstock.py::get_rows
+telli/telli.py::telli_source.get_rows
+twenty/twenty.py::twenty_source.items
+twitter/twitter.py::_iter_pages
+unleash/unleash.py::unleash_source.items
+vitally/vitally.py::vitally_source
+who_gho/who_gho.py::_catalog_pages
+who_gho/who_gho.py::_dimension_values_pages
+who_gho/who_gho.py::_indicator_data_pages
+windmill/windmill.py::windmill_source.items
+workday/workday.py::workday_source.items
+world_bank/world_bank.py::_catalog_pages
+world_bank/world_bank.py::_indicator_data_pages
+xsolla/xsolla.py::xsolla_source.read
+zendesk/zendesk.py::zendesk_source.iter_resource
+zendesk_sunshine/zendesk_sunshine.py::_object_records_incremental
diff --git a/posthog/test/repo_invariants/test_resume_state_staged_before_yield.py b/posthog/test/repo_invariants/test_resume_state_staged_before_yield.py
index f3c3d27e44dd..dcda15ab1a26 100644
--- a/posthog/test/repo_invariants/test_resume_state_staged_before_yield.py
+++ b/posthog/test/repo_invariants/test_resume_state_staged_before_yield.py
@@ -15,7 +15,7 @@ from parameterized import parameterized
REPO_ROOT = Path(__file__).parents[3]
BASELINE_PATH = Path(__file__).parent / "resume_state_after_yield_baseline.txt"
SOURCES_ROOT = REPO_ROOT / "products/warehouse_sources/backend/temporal/data_imports/sources"
-SKIPPED_DIRS = {"common", "tests", "test", "__pycache__"}
+SKIPPED_DIRS = {"tests", "test", "__pycache__"}
REGENERATE = "python posthog/test/repo_invariants/test_resume_state_staged_before_yield.py"
FUNCTIONS = (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda)
@@ -39,10 +39,42 @@ def _yields(statement: ast.stmt) -> bool:
return any(isinstance(node, ast.Yield | ast.YieldFrom) for node in _own_nodes(statement))
-def _saves_state(statement: ast.stmt) -> bool:
- return any(
- isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) and node.func.attr == "save_state"
- for node in _own_nodes(statement)
+def _is_save_call(node: ast.AST, callbacks: frozenset[str] = frozenset()) -> bool:
+ if not isinstance(node, ast.Call):
+ return False
+ if isinstance(node.func, ast.Attribute):
+ return node.func.attr == "save_state"
+ return isinstance(node.func, ast.Name) and node.func.id in callbacks
+
+
+def _saves_state(statement: ast.stmt, callbacks: frozenset[str] = frozenset()) -> bool:
+ return any(_is_save_call(node, callbacks) for node in _own_nodes(statement))
+
+
+def _saving_helpers(tree: ast.Module) -> frozenset[str]:
+ """Functions that call `save_state` and yield nothing. A call to one of them stages state."""
+ return frozenset(
+ node.name
+ for node in ast.walk(tree)
+ if isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef)
+ and any(_saves_state(statement) for statement in node.body)
+ and not any(_yields(statement) for statement in node.body)
+ )
+
+
+def _callback_parameters(tree: ast.Module) -> frozenset[str]:
+ """Keyword names that receive a saving helper, as in `checkpoint=_checkpoint`.
+
+ A generator that takes such a parameter and calls it stages state in a function the generator
+ does not define.
+ """
+ helpers = _saving_helpers(tree)
+ return frozenset(
+ keyword.arg
+ for node in ast.walk(tree)
+ if isinstance(node, ast.Call)
+ for keyword in node.keywords
+ if keyword.arg is not None and isinstance(keyword.value, ast.Name) and keyword.value.id in helpers
)
@@ -69,7 +101,9 @@ def _loop_blocks(function: ast.FunctionDef | ast.AsyncFunctionDef) -> list[list[
return blocks
-def _saves_after_yield(function: ast.FunctionDef | ast.AsyncFunctionDef) -> bool:
+def _saves_after_yield(
+ function: ast.FunctionDef | ast.AsyncFunctionDef, callbacks: frozenset[str] = frozenset()
+) -> bool:
"""Whether a loop of the function saves state after the last `yield` of an iteration.
A save that another `yield` follows in the same block is state for that later batch, staged
@@ -85,49 +119,75 @@ def _saves_after_yield(function: ast.FunctionDef | ast.AsyncFunctionDef) -> bool
# A compound statement that holds both is judged by its own blocks.
yielded = True
save_is_last = False
- elif yielded and _saves_state(statement):
+ elif yielded and _saves_state(statement, callbacks):
save_is_last = True
if save_is_last:
return True
return False
-def _functions_in_source(source: str) -> list[str]:
- tree = ast.parse(source)
+def _parameters(function: ast.FunctionDef | ast.AsyncFunctionDef) -> frozenset[str]:
+ arguments = function.args
+ return frozenset(argument.arg for argument in (*arguments.posonlyargs, *arguments.args, *arguments.kwonlyargs))
+
+
+def _functions_in_tree(tree: ast.Module, callback_parameters: frozenset[str]) -> list[str]:
+ helpers = _saving_helpers(tree)
names: list[str] = []
- def visit(node: ast.AST, prefix: str) -> None:
+ def visit(node: ast.AST, prefix: str, parameters: frozenset[str]) -> None:
for child in ast.iter_child_nodes(node):
if isinstance(child, ast.FunctionDef | ast.AsyncFunctionDef):
qualified = f"{prefix}{child.name}"
- if _saves_after_yield(child):
+ # A callback counts only where it is a parameter of the function, or of one around it.
+ in_scope = parameters | _parameters(child)
+ if _saves_after_yield(child, helpers | (callback_parameters & in_scope)):
names.append(qualified)
- visit(child, f"{qualified}.")
+ visit(child, f"{qualified}.", in_scope)
elif isinstance(child, ast.ClassDef):
- visit(child, f"{prefix}{child.name}.")
+ visit(child, f"{prefix}{child.name}.", parameters)
else:
- visit(child, prefix)
+ visit(child, prefix, parameters)
- visit(tree, "")
+ visit(tree, "", frozenset())
return names
+def _functions_in_source(source: str) -> list[str]:
+ tree = ast.parse(source)
+ return _functions_in_tree(tree, _callback_parameters(tree))
+
+
+def _parse(source: str) -> ast.Module | None:
+ try:
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", SyntaxWarning)
+ return ast.parse(source)
+ except SyntaxError:
+ return None
+
+
def collect_functions() -> list[str]:
- found: list[str] = []
- for path in SOURCES_ROOT.rglob("*.py"):
- relative = path.relative_to(SOURCES_ROOT)
- if SKIPPED_DIRS.intersection(relative.parts) or path.name.startswith("test_"):
- continue
- source = path.read_text(encoding="utf-8", errors="ignore")
- if "save_state" not in source or "yield" not in source:
+ sources: dict[str, str] = {}
+ for file in SOURCES_ROOT.rglob("*.py"):
+ relative = file.relative_to(SOURCES_ROOT)
+ if SKIPPED_DIRS.intersection(relative.parts) or file.name.startswith("test_"):
continue
- try:
- with warnings.catch_warnings():
- warnings.simplefilter("ignore", SyntaxWarning)
- names = _functions_in_source(source)
- except SyntaxError:
- continue
- found.extend(f"{relative.as_posix()}::{name}" for name in names)
+ source = file.read_text(encoding="utf-8", errors="ignore")
+ if "yield" in source or "save_state" in source:
+ sources[relative.as_posix()] = source
+
+ trees = {path: tree for path, source in sources.items() if "save_state" in source and (tree := _parse(source))}
+ # Shared code takes the callback as a parameter, and a source module passes it in. The keyword
+ # names from every module therefore apply to every module.
+ callback_parameters = frozenset[str]().union(*(_callback_parameters(tree) for tree in trees.values()))
+ for path, source in sources.items():
+ if path not in trees and any(name in source for name in callback_parameters) and (tree := _parse(source)):
+ trees[path] = tree
+
+ found: list[str] = []
+ for path, tree in trees.items():
+ found.extend(f"{path}::{name}" for name in _functions_in_tree(tree, callback_parameters))
return sorted(set(found))
@@ -206,6 +266,33 @@ DETECTION_CASES = [
" return items\n",
["source.items"],
),
+ (
+ "save_through_a_local_helper_after_the_yield_is_reported",
+ "def rows(manager):\n"
+ " def checkpoint(cursor):\n"
+ " manager.save_state(cursor)\n"
+ " for page in pages():\n"
+ " yield page\n"
+ " checkpoint(page.cursor)\n",
+ ["rows"],
+ ),
+ (
+ "save_through_a_callback_parameter_after_the_yield_is_reported",
+ "def pages(run_page, checkpoint):\n"
+ " for page in run_page():\n"
+ " yield page\n"
+ " checkpoint(page.key)\n"
+ "def rows(manager):\n"
+ " def _checkpoint(key):\n"
+ " manager.save_state(key)\n"
+ " return pages(run_page, checkpoint=_checkpoint)\n",
+ ["pages"],
+ ),
+ (
+ "call_to_a_parameter_that_no_saving_helper_feeds_is_left_alone",
+ "def pages(run_page, on_page):\n for page in run_page():\n yield page\n on_page(page.key)\n",
+ [],
+ ),
(
"save_in_a_function_that_yields_nothing_is_left_alone",
"def checkpoint(manager, cursor):\n manager.save_state(cursor)\n",
diff --git a/posthog/test/repo_invariants/test_warehouse_source_static_contract.py b/posthog/test/repo_invariants/test_warehouse_source_static_contract.py
new file mode 100644
index 000000000000..7950e2046542
--- /dev/null
+++ b/posthog/test/repo_invariants/test_warehouse_source_static_contract.py
@@ -0,0 +1,323 @@
+"""Ratchets on warehouse source code that can hold a worker with no way to stop it.
+
+A worker that shuts down hands each running import to another worker, but only when the source
+gives control back to the pipeline. Three patterns in source code prevent that, and each one has a
+baseline here that may only get shorter:
+
+- a raw `time.sleep`, which no shutdown can interrupt and which nothing caps;
+- an HTTP call on a session with no `timeout=`, which waits without limit for a stalled server;
+- a generator that wraps a REST framework resource and reaches no safe point, which turns the
+ framework safe points off, so a run of empty pages gives the pipeline nothing to act on.
+
+The behavior tests in `products/warehouse_sources/.../sources/tests/test_source_contract.py` cover
+the sources that a fake HTTP server can drive. These checks cover every source, also the ones that
+use a driver or an SDK.
+"""
+
+import ast
+import sys
+import warnings
+from collections.abc import Callable
+from pathlib import Path
+
+import pytest
+
+REPO_ROOT = Path(__file__).parents[3]
+BASELINE_DIR = Path(__file__).parent
+SOURCES_ROOT = REPO_ROOT / "products/warehouse_sources/backend/temporal/data_imports/sources"
+SKIPPED_DIRS = {"common", "tests", "test", "__pycache__", "generated_configs"}
+REGENERATE = "python posthog/test/repo_invariants/test_warehouse_source_static_contract.py"
+
+FUNCTIONS = (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda)
+HTTP_VERBS = {"get", "post", "put", "patch", "delete", "head", "request", "send"}
+HTTP_MODULES = {"requests", "httpx"}
+RESOURCE_BUILDERS = {"rest_api_resource", "rest_api_resources", "build_dependent_resource", "build_chained_resource"}
+SAFE_POINT_CALLS = {"safe_point", "reach_safe_point"}
+
+Check = Callable[[ast.Module], list[str]]
+
+
+def _own_nodes(node: ast.AST) -> list[ast.AST]:
+ """The nodes of a function or module, without the bodies of functions defined inside it."""
+ nodes: list[ast.AST] = []
+ stack: list[ast.AST] = list(ast.iter_child_nodes(node))
+ while stack:
+ current = stack.pop()
+ nodes.append(current)
+ if not isinstance(current, FUNCTIONS):
+ stack.extend(ast.iter_child_nodes(current))
+ return nodes
+
+
+def _scopes(tree: ast.Module) -> list[tuple[str, ast.AST]]:
+ """Each function of the module with its qualified name, plus the module body as `<module>`."""
+ scopes: list[tuple[str, ast.AST]] = [("<module>", tree)]
+
+ def visit(node: ast.AST, prefix: str) -> None:
+ for child in ast.iter_child_nodes(node):
+ if isinstance(child, ast.FunctionDef | ast.AsyncFunctionDef):
+ qualified = f"{prefix}{child.name}"
+ scopes.append((qualified, child))
+ visit(child, f"{qualified}.")
+ elif isinstance(child, ast.ClassDef):
+ visit(child, f"{prefix}{child.name}.")
+ else:
+ visit(child, prefix)
+
+ visit(tree, "")
+ return scopes
+
+
+def _terminal_name(node: ast.AST) -> str | None:
+ if isinstance(node, ast.Name):
+ return node.id
+ if isinstance(node, ast.Attribute):
+ return node.attr
+ return None
+
+
+def _called_name(node: ast.AST | None) -> str | None:
+ return _terminal_name(node.func) if isinstance(node, ast.Call) else None
+
+
+def raw_sleeps(tree: ast.Module) -> list[str]:
+ sleep_names = {
+ alias.asname or alias.name
+ for node in ast.walk(tree)
+ if isinstance(node, ast.ImportFrom) and node.module == "time"
+ for alias in node.names
+ if alias.name == "sleep"
+ }
+
+ def is_sleep(node: ast.AST) -> bool:
+ if not isinstance(node, ast.Call):
+ return False
+ func = node.func
+ if isinstance(func, ast.Name):
+ return func.id in sleep_names
+ return (
+ isinstance(func, ast.Attribute)
+ and func.attr == "sleep"
+ and isinstance(func.value, ast.Name)
+ and func.value.id == "time"
+ )
+
+ return [name for name, scope in _scopes(tree) if any(is_sleep(node) for node in _own_nodes(scope))]
+
+
+def _is_session_annotation(annotation: ast.AST) -> bool:
+ """A `Session` annotation, also as `Session | None`. Not `dict[str, Callable[[Session], ...]]`."""
+ if isinstance(annotation, ast.BinOp):
+ return _is_session_annotation(annotation.left) or _is_session_annotation(annotation.right)
+ if isinstance(annotation, ast.Constant) and isinstance(annotation.value, str):
+ return "Session" in annotation.value and "[" not in annotation.value
+ return "Session" in (_terminal_name(annotation) or "")
+
+
+def requests_without_timeout(tree: ast.Module) -> list[str]:
+ # A name is a session when `make_tracked_session` builds it, or when its annotation says so.
+ sessions: set[str | None] = set()
+ for node in ast.walk(tree):
+ if isinstance(node, ast.Assign) and _called_name(node.value) == "make_tracked_session":
+ sessions.update(_terminal_name(target) for target in node.targets)
+ elif isinstance(node, ast.AnnAssign) and (
+ _called_name(node.value) == "make_tracked_session" or _is_session_annotation(node.annotation)
+ ):
+ sessions.add(_terminal_name(node.target))
+ elif isinstance(node, ast.arg) and node.annotation is not None and _is_session_annotation(node.annotation):
+ sessions.add(node.arg)
+
+ def is_unbounded_request(node: ast.AST) -> bool:
+ if not (isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) and node.func.attr in HTTP_VERBS):
+ return False
+ receiver = _terminal_name(node.func.value)
+ if receiver is None:
+ return False
+ is_http_module = isinstance(node.func.value, ast.Name) and receiver in HTTP_MODULES
+ if not (is_http_module or receiver in sessions or "session" in receiver.lower()):
+ return False
+ # A `**kwargs` argument can carry the timeout.
+ return not any(keyword.arg in ("timeout", None) for keyword in node.keywords)
+
+ return [name for name, scope in _scopes(tree) if any(is_unbounded_request(node) for node in _own_nodes(scope))]
+
+
+def wrapped_resources_without_safe_point(tree: ast.Module) -> list[str]:
+ def builds_resource(node: ast.AST | None) -> bool:
+ while isinstance(node, ast.Subscript):
+ node = node.value
+ return _called_name(node) in RESOURCE_BUILDERS
+
+ resource_names: set[str] = set()
+ for node in ast.walk(tree):
+ if isinstance(node, ast.Assign | ast.AnnAssign) and builds_resource(node.value):
+ for target in node.targets if isinstance(node, ast.Assign) else [node.target]:
+ resource_names.update(leaf.id for leaf in ast.walk(target) if isinstance(leaf, ast.Name))
+
+ def is_resource(node: ast.AST | None) -> bool:
+ # `iter(resource)` and `enumerate(resource)` still read the resource.
+ while isinstance(node, ast.Call) and _called_name(node) in ("iter", "enumerate") and node.args:
+ node = node.args[0]
+ return builds_resource(node) or (isinstance(node, ast.Name) and node.id in resource_names)
+
+ found: list[str] = []
+ for name, scope in _scopes(tree):
+ if isinstance(scope, ast.Module):
+ continue
+ nodes = _own_nodes(scope)
+ if not any(isinstance(node, ast.Yield | ast.YieldFrom) for node in nodes):
+ continue
+ reads_resource = any(
+ (isinstance(node, ast.YieldFrom) and is_resource(node.value))
+ or (isinstance(node, ast.For | ast.comprehension) and is_resource(node.iter))
+ for node in nodes
+ )
+ if reads_resource and not any(_called_name(node) in SAFE_POINT_CALLS for node in nodes):
+ found.append(name)
+ return found
+
+
+# Each check: the collector, the words of which a file must hold one to be parsed, the baseline file,
+# and what a '+' line means.
+CHECKS: dict[str, tuple[Check, tuple[str, ...], str, str]] = {
+ "raw_sleep": (
+ raw_sleeps,
+ ("sleep",),
+ "source_raw_sleep_baseline.txt",
+ "A '+' line is a source function that calls `time.sleep`. A worker shutdown cannot interrupt that wait, "
+ "and nothing caps it, so one large `Retry-After` value holds the worker. Let the REST client or the "
+ "tracked session own the retry wait. Where the source must wait, cap the wait and reach a safe point "
+ "(`ResumableSourceManager.safe_point()`) before it.",
+ ),
+ "request_without_timeout": (
+ requests_without_timeout,
+ ("ession", "requests.", "httpx."),
+ "source_request_without_timeout_baseline.txt",
+ "A '+' line is a source function that sends an HTTP request on a session with no `timeout=` argument. "
+ "A server that accepts the connection and then sends nothing holds the worker without limit. "
+ "Pass `timeout=(connect_seconds, read_seconds)` at the call.",
+ ),
+ "wrapped_resource": (
+ wrapped_resources_without_safe_point,
+ tuple(RESOURCE_BUILDERS),
+ "source_wrapped_resource_baseline.txt",
+ "A '+' line is a generator that reads a REST framework resource and yields its pages again. The "
+ "framework reaches a safe point after each page only when the pipeline reads the resource directly, "
+ "so behind a wrapper a run of empty pages never lets the pipeline stop the run. Return the resource "
+ "itself as `SourceResponse.items`, or call `ResumableSourceManager.safe_point()` in the wrapper after "
+ "each page that the wrapper has handed on in full.",
+ ),
+}
+
+
+def collect(check: Check, words: tuple[str, ...]) -> list[str]:
+ found: list[str] = []
+ for path in SOURCES_ROOT.rglob("*.py"):
+ relative = path.relative_to(SOURCES_ROOT)
+ if SKIPPED_DIRS.intersection(relative.parts) or path.name.startswith("test_"):
+ continue
+ source = path.read_text(encoding="utf-8", errors="ignore")
+ if not any(word in source for word in words):
+ continue
+ try:
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", SyntaxWarning)
+ tree = ast.parse(source)
+ except SyntaxError:
+ continue
+ found.extend(f"{relative.as_posix()}::{name}" for name in check(tree))
+ return sorted(set(found))
+
+
+# A baseline test cannot catch a detection regression on its own: a function that stops being
+# detected leaves as a '-' line, which reads as a function someone fixed.
+DETECTION_CASES = [
+ ("raw_sleep", "import time\ndef rows():\n time.sleep(5)\n", ["rows"]),
+ ("raw_sleep", "from time import sleep as pause\ndef rows():\n pause(5)\n", ["rows"]),
+ ("raw_sleep", "import time\ntime.sleep(1)\n", ["<module>"]),
+ ("raw_sleep", "import time\nclass Client:\n def get(self):\n time.sleep(1)\n", ["Client.get"]),
+ (
+ "raw_sleep",
+ "import time\ndef rows():\n def wait():\n time.sleep(1)\n wait()\n",
+ ["rows.wait"],
+ ),
+ ("raw_sleep", "import asyncio\ndef rows(manager):\n manager.sleep(5)\n started = time.monotonic()\n", []),
+ ("request_without_timeout", "def rows(session):\n return session.get(url)\n", ["rows"]),
+ ("request_without_timeout", "def rows(session):\n return session.get(url, timeout=30)\n", []),
+ ("request_without_timeout", "def rows(self):\n return self._session.post(url, json=body)\n", ["rows"]),
+ ("request_without_timeout", "def rows(session, **kwargs):\n return session.request('GET', url, **kwargs)\n", []),
+ (
+ "request_without_timeout",
+ "def rows():\n http = make_tracked_session()\n return http.get(url)\n",
+ ["rows"],
+ ),
+ ("request_without_timeout", "def rows(http: requests.Session):\n return http.get(url)\n", ["rows"]),
+ ("request_without_timeout", "import requests\ndef rows():\n return requests.get(url)\n", ["rows"]),
+ ("request_without_timeout", "def rows(cache):\n return cache.get(key)\n", []),
+ (
+ "request_without_timeout",
+ "import requests\nrows: dict[str, Callable[[requests.Session], list]] = {}\ndef pick(name):\n return rows.get(name)\n",
+ [],
+ ),
+ ("request_without_timeout", "def rows(http: requests.Session | None):\n return http.get(url)\n", ["rows"]),
+ (
+ "wrapped_resource",
+ "def rows(config):\n resource = rest_api_resource(config)\n for page in resource:\n yield page\n",
+ ["rows"],
+ ),
+ ("wrapped_resource", "def rows(config):\n yield from rest_api_resources(config)[0]\n", ["rows"]),
+ (
+ "wrapped_resource",
+ "def source(config):\n"
+ " resource = build_dependent_resource(config)\n"
+ " def items():\n"
+ " yield from iter(resource)\n"
+ " return items\n",
+ ["source.items"],
+ ),
+ (
+ "wrapped_resource",
+ "def rows(config, manager):\n"
+ " for page in rest_api_resource(config):\n"
+ " yield page\n"
+ " manager.safe_point()\n",
+ [],
+ ),
+ ("wrapped_resource", "def source(config):\n return rest_api_resource(config)\n", []),
+ ("wrapped_resource", "def rows(pages):\n for page in pages:\n yield page\n", []),
+]
+
+
[email protected](("check", "source", "expected"), DETECTION_CASES)
+def test_detection(check: str, source: str, expected: list[str]) -> None:
+ assert CHECKS[check][0](ast.parse(source)) == expected
+
+
+def read_baseline(file_name: str) -> list[str]:
+ return sorted(line for line in (BASELINE_DIR / file_name).read_text().splitlines() if line.strip())
+
+
[email protected]("check", sorted(CHECKS))
+def test_source_functions_match_the_baseline(check: str) -> None:
+ collector, words, file_name, explanation = CHECKS[check]
+ scanned = collect(collector, words)
+ recorded = read_baseline(file_name)
+ if scanned == recorded:
+ return
+
+ added = [line for line in scanned if line not in recorded]
+ removed = [line for line in recorded if line not in scanned]
+ report = "\n".join([*(f" + {line}" for line in added), *(f" - {line}" for line in removed)])
+ raise AssertionError(
+ f"{file_name} no longer matches the repo.\n"
+ f"{explanation} Do not add the line to the baseline: the list may only get shorter.\n"
+ f"A '-' line means a function was fixed. The file must record that too. Run: {REGENERATE}\n"
+ f"{report}"
+ )
+
+
+if __name__ == "__main__":
+ for collector, words, file_name, _explanation in CHECKS.values():
+ functions = collect(collector, words)
+ (BASELINE_DIR / file_name).write_text("\n".join(functions) + "\n")
+ sys.stdout.write(f"{file_name} written: {len(functions)} functions\n")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tests/contract_harness.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tests/contract_harness.py
new file mode 100644
index 000000000000..6efe856a25f4
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tests/contract_harness.py
@@ -0,0 +1,675 @@
+"""Harness for the source contract tests: a fake network, a fake clock, and one extraction run.
+
+The fake network sits below `requests` and urllib3, at the socket of each HTTP connection. The
+retry layers of the adapter, the REST client and the source all run as they do in production. Their
+waits add to a fake clock and take no real time.
+"""
+
+import io
+import ast
+import sys
+import json
+import time
+import types
+import socket
+import asyncio
+import inspect
+import functools
+import ipaddress
+import contextlib
+import dataclasses
+from collections.abc import Callable, Iterator
+from pathlib import Path
+from typing import Any, Literal
+
+from unittest import mock
+
+from django.db.backends.base.base import BaseDatabaseWrapper
+
+import tenacity
+import structlog
+from urllib3.connection import HTTPConnection, HTTPSConnection
+
+from posthog.dataclasses import frozen
+from posthog.security import url_validation
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (
+ ResumableSource,
+ SimpleSource,
+ _BaseSource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.config import is_config
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.resource import Resource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.safe_point import activate_safe_point
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
+
+# The longest time one request, with all of its retries and waits, may hold a worker.
+REQUEST_BUDGET_SECONDS = 300.0
+# The longest run of requests that a source may make with no yield and no safe point between them.
+MAX_REQUESTS_WITHOUT_SAFE_POINT = 3
+# A hostile `Retry-After` value. A source that sleeps for it holds a worker for a day.
+HOSTILE_RETRY_AFTER_SECONDS = 86400
+
+TIMEOUT = "timeout"
+STALL_BUDGET = "stall-budget"
+RATE_LIMIT_BUDGET = "rate-limit-budget"
+SAFE_POINT = "safe-point"
+
+# A run stops at one of these limits, because the source would not stop by itself.
+_CLOCK_LIMIT_SECONDS = 4 * 3600.0
+_REQUEST_LIMIT = 40
+_EMPTY_PAGE_COUNT = 8
+
+# Modules that open connections outside Python sockets, or from background threads. The fake network
+# cannot see or stop those connections, so a source that imports one of them is never run.
+NATIVE_DRIVER_MODULES = (
+ "confluent_kafka",
+ "databricks",
+ "duckdb",
+ "google.ads",
+ "google.cloud",
+ "grpc",
+ "grpclib",
+ "modal",
+ "psycopg",
+ "pymongo",
+ "pymssql",
+ "snowflake",
+ "temporalio.client",
+ "temporalio.service",
+)
+
+_SOURCES_ROOT = Path(__file__).parents[1]
+_SOURCES_PACKAGE = "products.warehouse_sources.backend.temporal.data_imports.sources"
+_UNSET = object()
+_PUBLIC_ADDRESS = "93.184.216.34"
+_REAL_SLEEP = time.sleep
+_REAL_MONOTONIC = time.monotonic
+_REAL_TIME = time.time
+_REAL_ASYNC_SLEEP = asyncio.sleep
+
+Mode = Literal["stall", "rate_limit", "empty_pages"]
+# Starts one extraction. The manager is None for a source that the pipeline treats as not resumable.
+StartExtraction = Callable[[SourceInputs], tuple[SourceResponse, ResumableSourceManager[Any] | None]]
+
+
+@frozen
+class Scenario:
+ mode: Mode
+ # Requests that get a normal answer before the mode applies. With one, a source whose first
+ # request is an auth exchange reaches its first extraction request.
+ answered_first: int = 0
+ # Answer each GET with a JSON list and not an object. Some endpoints return a bare list.
+ list_bodies: bool = False
+
+
+BOUNDED_CALL_SCENARIOS = (
+ Scenario(mode="stall"),
+ Scenario(mode="stall", answered_first=1),
+ Scenario(mode="rate_limit"),
+ Scenario(mode="rate_limit", answered_first=1),
+)
+SAFE_POINT_SCENARIOS = (Scenario(mode="empty_pages"), Scenario(mode="empty_pages", list_bodies=True))
+
+
+class RunStopped(BaseException):
+ """Ends a run that passed a harness limit. A `BaseException`, so that `except Exception` in a source cannot hide it."""
+
+
+class NetworkBlockedError(OSError):
+ """The source opened a connection that does not go through `requests`, so the fake cannot answer it."""
+
+
+class DatabaseBlockedError(RuntimeError):
+ """The source read the application database, which the contract tests do not have."""
+
+
+def empty_page_body(next_url: str | None, page: int) -> dict[str, Any]:
+ """A page with no rows, in the shapes that most paginators and token exchanges read.
+
+ With `next_url` the page points at a next page in each common way, so a paginator continues.
+ """
+ row_keys = ("data", "results", "items", "records", "result", "values", "value", "list", "rows", "entries")
+ body: dict[str, Any] = dict.fromkeys(row_keys, [])
+ body.update({"access_token": "contract-token", "token": "contract-token", "token_type": "Bearer"})
+ body["expires_in"] = 3600
+ if next_url is not None:
+ cursor = f"contract-cursor-{page}"
+ body.update(
+ {
+ "next": next_url,
+ "next_page": next_url,
+ "next_url": next_url,
+ "next_cursor": cursor,
+ "nextCursor": cursor,
+ "cursor": cursor,
+ "next_page_token": cursor,
+ "nextPageToken": cursor,
+ "has_more": True,
+ "hasMore": True,
+ "has_next": True,
+ "links": {"next": next_url},
+ "paging": {"next": {"after": cursor, "link": next_url}, "cursors": {"after": cursor}},
+ "pagination": {"next": next_url, "next_cursor": cursor, "has_more": True, "next_page": page + 1},
+ "meta": {"next_cursor": cursor, "has_more": True, "next": next_url, "next_page": page + 1},
+ "response_metadata": {"next_cursor": cursor},
+ }
+ )
+ return body
+
+
+class FakeNetwork:
+ """Answers every HTTP request as the scenario says, and records what the source did."""
+
+ def __init__(self, scenario: Scenario) -> None:
+ self.scenario = scenario
+ self.elapsed = 0.0
+ self.requests = 0
+ self.unbounded_requests = 0
+ self.blocked_connections = 0
+ self.blocked_database_reads = 0
+ self.longest_request_seconds = 0.0
+ self.longest_run_without_progress = 0
+ self.error: BaseException | None = None
+ self._request_key: bytes | None = None
+ self._request_started = 0.0
+ self._run_without_progress = 0
+
+ def advance(self, seconds: float | None) -> None:
+ if seconds is not None and seconds > 0:
+ self.elapsed += seconds
+ self.longest_request_seconds = max(self.longest_request_seconds, self.elapsed - self._request_started)
+ if self.elapsed > _CLOCK_LIMIT_SECONDS:
+ raise RunStopped("clock limit")
+
+ def note_progress(self) -> None:
+ """The source yielded an item or reached a safe point, so the pipeline could act."""
+ self._run_without_progress = 0
+
+ def respond(self, origin: str, sent: bytes, read_timeout: Any) -> io.BytesIO:
+ request_line = sent.split(b"\r\n", 1)[0]
+ method, _, target = request_line.partition(b" ")
+ path = target.rsplit(b" ", 1)[0].decode("latin-1") or "/"
+
+ # Attempts for the same method and URL, one after the other, are one request with its retries.
+ if request_line != self._request_key:
+ self._request_key = request_line
+ self._request_started = self.elapsed
+ self.requests += 1
+ self._run_without_progress += 1
+ self.longest_run_without_progress = max(self.longest_run_without_progress, self._run_without_progress)
+ if self.requests > _REQUEST_LIMIT:
+ raise RunStopped("request limit")
+
+ mode = self.scenario.mode
+ answered = self.requests <= self.scenario.answered_first
+ if mode == "stall" and not answered:
+ if read_timeout is None or read_timeout is _UNSET:
+ self.unbounded_requests += 1
+ raise RunStopped("request with no read timeout")
+ self.advance(float(read_timeout))
+ raise TimeoutError("timed out")
+
+ if mode == "rate_limit" and not answered:
+ return _http_response(
+ b"429 Too Many Requests", b"{}", [b"Retry-After: " + str(HOSTILE_RETRY_AFTER_SECONDS).encode()]
+ )
+
+ last = mode == "empty_pages" and self.requests >= _EMPTY_PAGE_COUNT
+ next_url = None if last else f"{origin}{path.split('?', 1)[0]}?contract_page={self.requests + 1}"
+ headers = [] if next_url is None else [b"Link: <" + next_url.encode() + b'>; rel="next"']
+ if self.scenario.list_bodies and method == b"GET":
+ return _http_response(b"200 OK", b"[]", headers)
+ return _http_response(b"200 OK", json.dumps(empty_page_body(next_url, self.requests)).encode(), headers)
+
+
+def _http_response(status: bytes, body: bytes, headers: list[bytes]) -> io.BytesIO:
+ lines = [
+ b"HTTP/1.1 " + status,
+ b"Content-Type: application/json",
+ b"Content-Length: " + str(len(body)).encode(),
+ b"Connection: close",
+ *headers,
+ ]
+ return io.BytesIO(b"\r\n".join(lines) + b"\r\n\r\n" + body)
+
+
+class _FailingStream(io.RawIOBase):
+ def __init__(self, error: BaseException) -> None:
+ super().__init__()
+ self._error = error
+
+ def readable(self) -> bool:
+ return True
+
+ def readline(self, size: int | None = -1) -> bytes:
+ raise self._error
+
+ def readinto(self, buffer: Any) -> int:
+ raise self._error
+
+
+class _FakeSocket:
+ def __init__(self, network: FakeNetwork, origin: str) -> None:
+ self._network = network
+ self._origin = origin
+ self._sent = b""
+ self._read_timeout: Any = _UNSET
+
+ def settimeout(self, value: Any) -> None:
+ self._read_timeout = value
+
+ def gettimeout(self) -> Any:
+ return None if self._read_timeout is _UNSET else self._read_timeout
+
+ def sendall(self, data: Any, *args: Any) -> None:
+ self._sent += bytes(data)
+
+ def send(self, data: Any, *args: Any) -> int:
+ self._sent += bytes(data)
+ return len(data)
+
+ def makefile(self, *args: Any, **kwargs: Any) -> io.IOBase:
+ sent, self._sent = self._sent, b""
+ try:
+ return self._network.respond(self._origin, sent, self._read_timeout)
+ except (TimeoutError, RunStopped) as error:
+ # A real socket fails at the first read, and not when `http.client` wraps it.
+ return _FailingStream(error)
+
+ def setsockopt(self, *args: Any) -> None:
+ pass
+
+ def shutdown(self, *args: Any) -> None:
+ pass
+
+ def close(self) -> None:
+ pass
+
+
+class _MemoryRedis:
+ def __init__(self) -> None:
+ self._data: dict[str, Any] = {}
+
+ def ping(self) -> bool:
+ return True
+
+ def set(self, key: str, value: Any, **kwargs: Any) -> None:
+ self._data[key] = value
+
+ def get(self, key: str) -> Any:
+ return self._data.get(key)
+
+ def exists(self, key: str) -> int:
+ return int(key in self._data)
+
+ def delete(self, key: str) -> None:
+ self._data.pop(key, None)
+
+
+def _sleep_aliases() -> list[tuple[Any, str]]:
+ """Each `from time import sleep` binding in a loaded source module. A patch of `time.sleep` does not reach them."""
+ aliases: list[tuple[Any, str]] = []
+ for module_name, module in list(sys.modules.items()):
+ if not module_name.startswith(_SOURCES_PACKAGE):
+ continue
+ aliases.extend((module, name) for name, value in list(vars(module).items()) if value is _REAL_SLEEP)
+ return aliases
+
+
+def _controller_of(value: Any) -> tenacity.Retrying | None:
+ if isinstance(value, staticmethod | classmethod):
+ value = value.__func__
+ if not isinstance(value, types.FunctionType):
+ return None
+ controller = value.__dict__.get("retry")
+ return controller if isinstance(controller, tenacity.Retrying) else None
+
+
+def _retry_controllers() -> list[tenacity.Retrying]:
+ """Each synchronous tenacity controller that a `@retry` decorator put on a function or a method.
+
+ A test can replace the `sleep` of one for the rest of the process, for example
+ `RESTClient._send_request.retry.sleep = lambda *_: None`. That wait then never reaches the fake
+ clock, and the verdict of every later source depends on which tests ran before.
+ """
+ controllers: dict[int, tenacity.Retrying] = {}
+ for module in list(sys.modules.values()):
+ for value in list(getattr(module, "__dict__", {}).values()):
+ candidates = list(vars(value).values()) if inspect.isclass(value) else []
+ for candidate in [value, *candidates]:
+ if (controller := _controller_of(candidate)) is not None:
+ controllers[id(controller)] = controller
+ return list(controllers.values())
+
+
+def _waits_on_the_fake_clock(sleep: Callable[[float], None]) -> Iterator[None]:
+ """Give each retry controller the fake `sleep`, and put back what each one had. This is cheaper than `mock.patch`."""
+ controllers = _retry_controllers()
+ originals = [controller.sleep for controller in controllers]
+ for controller in controllers:
+ controller.sleep = sleep
+ try:
+ yield
+ finally:
+ for controller, original in zip(controllers, originals):
+ controller.sleep = original
+
+
+def fake_environment(scenario: Scenario) -> Iterator[FakeNetwork]:
+ """Route HTTP to a `FakeNetwork`, block every other connection, and make each wait advance a fake clock."""
+ network = FakeNetwork(scenario)
+ redis = _MemoryRedis()
+
+ def connect(connection: Any) -> None:
+ scheme = "https" if isinstance(connection, HTTPSConnection) else "http"
+ default_port = 443 if scheme == "https" else 80
+ port = "" if connection.port in (None, default_port) else f":{connection.port}"
+ connection.sock = _FakeSocket(network, f"{scheme}://{connection.host}{port}")
+ connection.is_verified = True
+
+ def blocked_connection(*args: Any, **kwargs: Any) -> Any:
+ network.blocked_connections += 1
+ raise NetworkBlockedError("the contract tests allow no real connection")
+
+ def blocked_database(*args: Any, **kwargs: Any) -> Any:
+ network.blocked_database_reads += 1
+ raise DatabaseBlockedError("the contract tests have no database")
+
+ # A source that checks its host before it connects gets a public address. Nothing connects to it.
+ def resolve(host: Any, port: Any, *args: Any, **kwargs: Any) -> list[Any]:
+ return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", (_PUBLIC_ADDRESS, int(port or 0)))]
+
+ def resolve_host_ips(host: str) -> set[Any]:
+ return {ipaddress.ip_address(_PUBLIC_ADDRESS)}
+
+ def sleep(seconds: float) -> None:
+ network.advance(seconds)
+
+ async def async_sleep(seconds: float, result: Any = None) -> Any:
+ network.advance(seconds)
+ return await _REAL_ASYNC_SLEEP(0, result)
+
+ @contextlib.contextmanager
+ def memory_redis(_manager: Any) -> Iterator[_MemoryRedis]:
+ yield redis
+
+ patches: list[Any] = [
+ mock.patch.object(HTTPConnection, "connect", connect),
+ mock.patch.object(HTTPSConnection, "connect", connect),
+ mock.patch.object(socket.socket, "connect", blocked_connection),
+ mock.patch.object(socket.socket, "connect_ex", blocked_connection),
+ mock.patch.object(socket.socket, "sendto", blocked_connection),
+ mock.patch.object(socket, "create_connection", blocked_connection),
+ mock.patch.object(socket, "getaddrinfo", resolve),
+ mock.patch.object(url_validation, "resolve_host_ips", resolve_host_ips),
+ mock.patch.object(BaseDatabaseWrapper, "ensure_connection", blocked_database),
+ mock.patch.object(time, "sleep", sleep),
+ mock.patch.object(time, "monotonic", lambda: _REAL_MONOTONIC() + network.elapsed),
+ mock.patch.object(time, "time", lambda: _REAL_TIME() + network.elapsed),
+ mock.patch.object(asyncio, "sleep", async_sleep),
+ mock.patch.object(ResumableSourceManager, "_get_redis", memory_redis),
+ *(mock.patch.object(module, name, sleep) for module, name in _sleep_aliases()),
+ _waits_on_the_fake_clock(sleep),
+ ]
+ with contextlib.ExitStack() as stack:
+ for patch in patches:
+ stack.enter_context(patch)
+ yield network
+
+
+def is_stub(source: _BaseSource[Any]) -> bool:
+ """Whether the source has no extraction code: its class still has the base `source_for_pipeline` stub."""
+ extraction = getattr(type(source), "source_for_pipeline", None)
+ return extraction in (SimpleSource.source_for_pipeline, ResumableSource.source_for_pipeline)
+
+
+def _imports_of_source_directory(directory: str) -> tuple[frozenset[str], frozenset[str]]:
+ """The modules that a source directory imports, and the other source directories it imports from."""
+ modules: set[str] = set()
+ for path in (_SOURCES_ROOT / directory).rglob("*.py"):
+ if path.name.startswith("test_") or "tests" in path.parts:
+ continue
+ for node in ast.walk(ast.parse(path.read_text(encoding="utf-8"))):
+ if isinstance(node, ast.Import):
+ modules.update(alias.name for alias in node.names)
+ elif isinstance(node, ast.ImportFrom) and node.module and node.level == 0:
+ modules.add(node.module)
+ prefix = f"{_SOURCES_PACKAGE}."
+ siblings = {module[len(prefix) :].split(".")[0] for module in modules if module.startswith(prefix)}
+ return frozenset(modules), frozenset(siblings - {directory, "common", "generated_configs"})
+
+
+def native_driver(source: _BaseSource[Any]) -> str | None:
+ """The first module of `NATIVE_DRIVER_MODULES` that the source imports, also through another source."""
+ pending = [type(source).__module__[len(_SOURCES_PACKAGE) + 1 :].split(".")[0]]
+ seen: set[str] = set()
+ while pending:
+ directory = pending.pop()
+ if directory in seen or not (_SOURCES_ROOT / directory).is_dir():
+ continue
+ seen.add(directory)
+ modules, siblings = _imports_of_source_directory(directory)
+ for driver in NATIVE_DRIVER_MODULES:
+ if any(module == driver or module.startswith(f"{driver}.") for module in modules):
+ return driver
+ pending.extend(siblings)
+ return None
+
+
+_PLACEHOLDERS_BY_NAME = (
+ ("url", "https://contract.example.com"),
+ ("host", "contract.example.com"),
+ ("domain", "contract.example.com"),
+ ("region", "us-east-1"),
+ ("date", "2024-01-01"),
+)
+_UUID = "00000000-0000-4000-8000-000000000000"
+
+
+def _placeholder_config(config_class: type, text: str | None, fill_optional: bool) -> Any:
+ kwargs: dict[str, Any] = {}
+ annotations = inspect.get_annotations(config_class)
+ for field in dataclasses.fields(config_class):
+ if not field.init:
+ continue
+ annotation = annotations.get(field.name, field.type)
+ required = field.default is dataclasses.MISSING and field.default_factory is dataclasses.MISSING
+ if not required and not (fill_optional and field.default is None and "str" in str(annotation)):
+ continue
+ if isinstance(annotation, type) and is_config(annotation):
+ kwargs[field.name] = _placeholder_config(annotation, text, fill_optional)
+ elif annotation in (int, "int"):
+ kwargs[field.name] = 1
+ elif annotation in (bool, "bool"):
+ kwargs[field.name] = False
+ elif text is not None:
+ kwargs[field.name] = text
+ else:
+ kwargs[field.name] = next(
+ (value for fragment, value in _PLACEHOLDERS_BY_NAME if fragment in field.name), "contract"
+ )
+ return config_class(**kwargs)
+
+
+def placeholder_configs(config_class: type) -> Iterator[Any]:
+ """Configs with a plausible value in each field. They hold no credential and reach no real host.
+
+ A source validates its fields before the first request, and the valid shapes differ. The
+ variants cover the common ones: a host or a URL, a bare subdomain, a number, a UUID, and a
+ source that needs one of its optional credential fields.
+ """
+ for text, fill_optional in ((None, False), ("contract", False), (None, True), ("1", False), (_UUID, False)):
+ try:
+ yield _placeholder_config(config_class, text, fill_optional)
+ except Exception:
+ continue
+
+
+def source_inputs(schema_name: str) -> SourceInputs:
+ return SourceInputs(
+ schema_name=schema_name,
+ schema_id="00000000-0000-4000-8000-000000000001",
+ source_id="00000000-0000-4000-8000-000000000002",
+ team_id=1,
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ db_incremental_field_earliest_value=None,
+ incremental_field=None,
+ incremental_field_type=None,
+ job_id="00000000-0000-4000-8000-000000000003",
+ logger=structlog.get_logger("source_contract"),
+ reset_pipeline=False,
+ )
+
+
+def start_source(source: _BaseSource[Any], config: Any) -> StartExtraction:
+ def start(inputs: SourceInputs) -> tuple[SourceResponse, ResumableSourceManager[Any] | None]:
+ if isinstance(source, ResumableSource):
+ manager = source.get_resumable_source_manager(inputs)
+ return source.source_for_pipeline(config, manager, inputs), manager
+ assert isinstance(source, SimpleSource)
+ return source.source_for_pipeline(config, inputs), None
+
+ return start
+
+
+async def _drain_async(items: Any, on_item: Callable[[], None]) -> None:
+ async for _ in items:
+ on_item()
+
+
+def run_extraction(start: StartExtraction, schema_name: str, scenario: Scenario) -> FakeNetwork:
+ """Run one extraction to its end, or to its first error, and return what the fake network recorded."""
+ with fake_environment(scenario) as network:
+ try:
+ response, manager = start(source_inputs(schema_name))
+ items = response.items()
+ with contextlib.ExitStack() as stack:
+ # The pipeline installs the safe-point hook only for a resumable source, and the
+ # framework safe points count only when the pipeline reads the framework `Resource`.
+ if manager is not None:
+ stack.enter_context(
+ activate_safe_point(
+ network.note_progress, covers_framework_checkpoints=isinstance(items, Resource)
+ )
+ )
+ if hasattr(items, "__aiter__"):
+ asyncio.run(_drain_async(items, network.note_progress))
+ else:
+ for _ in items:
+ network.note_progress()
+ except (Exception, RunStopped) as error:
+ # Most scenarios end in an error. The verdict comes from what the network recorded.
+ network.error = error
+ return network
+
+
+@frozen
+class Verdict:
+ failed: frozenset[str]
+ requests: int
+ blocked_connections: int
+ blocked_database_reads: int
+ # Whether an empty-page run made enough requests for the safe-point condition to mean something.
+ safe_point_exercised: bool
+ first_error: BaseException | None
+
+
+def check_extraction(start: StartExtraction, schema_names: list[str]) -> Verdict:
+ """Run the scenarios against the first schema and the last one.
+
+ The bounded-call scenarios run one time, against the first of the two schemas that sends a request.
+ A source uses one HTTP client for all of its schemas, and a webhook-fed schema sends no request.
+ """
+ failed: set[str] = set()
+ runs: list[FakeNetwork] = []
+ safe_point_exercised = False
+ bounded_calls_checked = False
+ for schema_name in dict.fromkeys([schema_names[0], schema_names[-1]]):
+ scenarios = (*SAFE_POINT_SCENARIOS, *(() if bounded_calls_checked else BOUNDED_CALL_SCENARIOS))
+ for scenario in scenarios:
+ network = run_extraction(start, schema_name, scenario)
+ runs.append(network)
+ over_budget = network.longest_request_seconds > REQUEST_BUDGET_SECONDS
+ if scenario.mode == "stall":
+ if network.unbounded_requests:
+ failed.add(TIMEOUT)
+ elif over_budget:
+ failed.add(STALL_BUDGET)
+ elif scenario.mode == "rate_limit":
+ if over_budget:
+ failed.add(RATE_LIMIT_BUDGET)
+ else:
+ bounded_calls_checked |= network.requests > 0
+ safe_point_exercised |= network.requests > MAX_REQUESTS_WITHOUT_SAFE_POINT
+ if network.longest_run_without_progress > MAX_REQUESTS_WITHOUT_SAFE_POINT:
+ failed.add(SAFE_POINT)
+ return Verdict(
+ failed=frozenset(failed),
+ requests=sum(network.requests for network in runs),
+ blocked_connections=sum(network.blocked_connections for network in runs),
+ blocked_database_reads=sum(network.blocked_database_reads for network in runs),
+ safe_point_exercised=safe_point_exercised,
+ first_error=next((network.error for network in runs if network.error is not None), None),
+ )
+
+
+@frozen
+class SourceStatus:
+ """`pass`, `fail:<condition>,...` or `not-checkable:<reason>`."""
+
+ status: str
+ safe_point_exercised: bool = False
+ # For a source that is not checkable: the error that ended the attempt.
+ detail: str = ""
+
+
+def check_source(source: _BaseSource[Any]) -> SourceStatus:
+ driver = native_driver(source)
+ if driver is not None:
+ return SourceStatus(status=f"not-checkable:driver:{driver}")
+
+ result = SourceStatus(status="not-checkable:config")
+ for config in placeholder_configs(source._config_class):
+ result = _check_source_with_config(source, config)
+ # The other reasons do not depend on the placeholder values.
+ if result.status not in ("not-checkable:schemas", "not-checkable:no-request"):
+ break
+ return result
+
+
+def _check_source_with_config(source: _BaseSource[Any], config: Any) -> SourceStatus:
+ with fake_environment(Scenario(mode="empty_pages")) as discovery:
+ try:
+ schema_names = [schema.name for schema in source.get_schemas(config, team_id=1)]
+ except (Exception, RunStopped) as error:
+ discovery.error = error
+ schema_names = []
+ if not schema_names:
+ reason = _not_checkable(discovery.blocked_database_reads, discovery.blocked_connections, "schemas")
+ return SourceStatus(status=reason, detail=repr(discovery.error))
+
+ verdict = check_extraction(start_source(source, config), schema_names)
+ if verdict.failed:
+ return SourceStatus(
+ status=f"fail:{','.join(sorted(verdict.failed))}", safe_point_exercised=verdict.safe_point_exercised
+ )
+ if verdict.requests == 0:
+ reason = _not_checkable(verdict.blocked_database_reads, verdict.blocked_connections, "no-request")
+ return SourceStatus(status=reason, detail=repr(verdict.first_error))
+ return SourceStatus(status="pass", safe_point_exercised=verdict.safe_point_exercised)
+
+
+def _not_checkable(blocked_database_reads: int, blocked_connections: int, otherwise: str) -> str:
+ if blocked_database_reads:
+ return "not-checkable:database"
+ if blocked_connections:
+ return "not-checkable:transport"
+ return f"not-checkable:{otherwise}"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tests/source_contract_baseline.txt b/products/warehouse_sources/backend/temporal/data_imports/sources/tests/source_contract_baseline.txt
new file mode 100644
index 000000000000..87ebad26d620
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tests/source_contract_baseline.txt
@@ -0,0 +1,860 @@
+Ably fail:rate-limit-budget,timeout
+AbnormalSecurity fail:rate-limit-budget,stall-budget
+Acast fail:rate-limit-budget,stall-budget
+Acculynx fail:rate-limit-budget,stall-budget
+ActiveCampaign fail:rate-limit-budget,timeout
+AdRoll fail:rate-limit-budget,timeout
+Adjust fail:rate-limit-budget,safe-point,stall-budget
+AdobeAnalytics fail:rate-limit-budget
+AdobeCommerce fail:rate-limit-budget,stall-budget
+Adyen fail:rate-limit-budget,safe-point,stall-budget
+Aftership fail:rate-limit-budget,timeout
+AgileCRM fail:rate-limit-budget,timeout
+Aha fail:rate-limit-budget,timeout
+AhaIdeas fail:rate-limit-budget,timeout
+Ahrefs fail:rate-limit-budget,stall-budget
+AirOps fail:rate-limit-budget,timeout
+Airbrake fail:rate-limit-budget,stall-budget
+Aircall fail:rate-limit-budget,timeout
+Airtable fail:rate-limit-budget,timeout
+Airwallex fail:rate-limit-budget,timeout
+Aiven fail:rate-limit-budget,timeout
+Alegra fail:rate-limit-budget,stall-budget
+Algolia fail:rate-limit-budget,timeout
+Alguna fail:rate-limit-budget,timeout
+AlphaVantage fail:rate-limit-budget,stall-budget
+AmazonAds fail:rate-limit-budget,stall-budget
+Amplemarket fail:rate-limit-budget,timeout
+Amplitude fail:rate-limit-budget,stall-budget
+Anthropic fail:rate-limit-budget,safe-point,timeout
+Anvil fail:rate-limit-budget
+ApifyDataset fail:rate-limit-budget,timeout
+Apitally fail:rate-limit-budget,timeout
+Apollo fail:rate-limit-budget,stall-budget
+AppLovin fail:rate-limit-budget,safe-point,stall-budget
+AppStoreConnect not-checkable:no-request
+Appdynamics fail:stall-budget
+Appfigures fail:rate-limit-budget,stall-budget
+Appfollow fail:rate-limit-budget,stall-budget
+AppleSearchAds not-checkable:no-request
+AppsFlyer fail:rate-limit-budget,safe-point,stall-budget
+Appsignal fail:safe-point,stall-budget
+Appstack fail:rate-limit-budget,timeout
+Arcade fail:rate-limit-budget,stall-budget
+Argocd fail:stall-budget
+Asaas fail:rate-limit-budget,timeout
+Asana fail:rate-limit-budget,timeout
+Ashby fail:rate-limit-budget,timeout
+Asknicely fail:rate-limit-budget,timeout
+AssemblyAI fail:rate-limit-budget,timeout
+Astronomer fail:rate-limit-budget,stall-budget
+Attentive not-checkable:database
+Attio fail:rate-limit-budget,timeout
+Auth0 fail:rate-limit-budget
+Automox fail:rate-limit-budget,stall-budget
+Autumn fail:rate-limit-budget,timeout
+Avalara fail:rate-limit-budget,timeout
+Aviationstack fail:rate-limit-budget,timeout
+Aviator fail:rate-limit-budget,stall-budget
+Awin fail:rate-limit-budget,stall-budget
+AwsBatch fail:rate-limit-budget
+AwsBudgets fail:rate-limit-budget
+AwsCloudTrail fail:rate-limit-budget
+AwsComputeOptimizer fail:rate-limit-budget
+AwsConfig fail:rate-limit-budget
+AwsCostAnomalyDetection fail:rate-limit-budget,stall-budget
+AwsCostExplorer fail:rate-limit-budget,safe-point,stall-budget
+AwsGlueDataCatalog fail:rate-limit-budget
+AwsGuardduty fail:rate-limit-budget
+AwsIamAccessAnalyzer fail:rate-limit-budget
+AwsInspector fail:rate-limit-budget
+AwsMacie fail:rate-limit-budget
+AwsOrganizations fail:rate-limit-budget,stall-budget
+AwsSagemaker fail:rate-limit-budget
+AwsSavingsPlans fail:rate-limit-budget
+AwsSecurityHub fail:rate-limit-budget
+AwsSes fail:rate-limit-budget,stall-budget
+AwsStepFunctions fail:rate-limit-budget
+AwsSystemsManager fail:rate-limit-budget
+AwsWaf fail:stall-budget
+Axiom fail:rate-limit-budget,stall-budget
+AzureApplicationInsights fail:rate-limit-budget,stall-budget
+AzureCostManagement not-checkable:no-request
+AzureDevOps fail:rate-limit-budget,stall-budget
+Babelforce fail:rate-limit-budget,timeout
+BackMarket fail:rate-limit-budget,timeout
+BambooHR fail:rate-limit-budget,timeout
+Baserow not-checkable:schemas
+Baseten fail:rate-limit-budget,timeout
+Beamer fail:rate-limit-budget,timeout
+Beehiiv fail:rate-limit-budget,stall-budget
+BetterStack fail:rate-limit-budget,timeout
+BigCommerce fail:rate-limit-budget,timeout
+BigMailer fail:rate-limit-budget,safe-point,timeout
+BigQuery not-checkable:driver:google.cloud
+Bigeye fail:rate-limit-budget,stall-budget
+Billomat fail:rate-limit-budget,timeout
+BingAds not-checkable:database
+BingWebmasterTools fail:rate-limit-budget
+Bitbucket fail:rate-limit-budget,safe-point,stall-budget
+Bitrise fail:rate-limit-budget,timeout
+BlandAI fail:rate-limit-budget,timeout
+Blogger fail:rate-limit-budget,timeout
+Bloomerang fail:rate-limit-budget,timeout
+Bluesky fail:rate-limit-budget,timeout
+Bluetally fail:rate-limit-budget,timeout
+BoldSign fail:rate-limit-budget,timeout
+Braintree fail:stall-budget
+Braintrust fail:rate-limit-budget,stall-budget
+Braze fail:rate-limit-budget,timeout
+Breezometer not-checkable:no-request
+Brevo fail:rate-limit-budget,timeout
+Brex fail:rate-limit-budget,timeout
+BrowseAI fail:rate-limit-budget,stall-budget
+BrowserUse fail:rate-limit-budget,timeout
+Browserbase fail:rate-limit-budget,timeout
+Bugherd fail:rate-limit-budget,timeout
+Bugsnag fail:rate-limit-budget,safe-point,stall-budget
+Buildium fail:rate-limit-budget,stall-budget
+Buildkite fail:rate-limit-budget,timeout
+Bunny fail:rate-limit-budget,timeout
+Buttondown fail:rate-limit-budget,timeout
+BuyMeACoffee fail:rate-limit-budget,stall-budget
+Buzzsprout fail:rate-limit-budget,timeout
+CalCom fail:rate-limit-budget,safe-point,timeout
+Calendarific fail:rate-limit-budget,stall-budget
+Calendly fail:rate-limit-budget
+CallRail fail:rate-limit-budget,timeout
+CampaignMonitor fail:rate-limit-budget,timeout
+Campayn fail:rate-limit-budget,timeout
+Campfire fail:rate-limit-budget,stall-budget
+Canny fail:rate-limit-budget,timeout
+CanvasLms fail:rate-limit-budget,safe-point,stall-budget
+CapsuleCRM fail:rate-limit-budget,timeout
+CareQualityCommission fail:rate-limit-budget,stall-budget
+CastAi fail:rate-limit-budget,timeout
+Catchpoint fail:rate-limit-budget,stall-budget
+CdcOpenData fail:rate-limit-budget,timeout
+Census fail:rate-limit-budget,timeout
+Chameleon fail:rate-limit-budget,timeout
+Chargebee fail:rate-limit-budget,timeout
+Chargedesk fail:rate-limit-budget,stall-budget
+Chargify fail:rate-limit-budget,timeout
+ChartHop fail:rate-limit-budget
+ChartMogul fail:rate-limit-budget,stall-budget
+Chatwoot not-checkable:database
+Checkly fail:rate-limit-budget,stall-budget
+Checkmarx fail:rate-limit-budget,stall-budget
+CheckoutCom fail:rate-limit-budget,timeout
+Churnkey fail:rate-limit-budget,timeout
+Cimis fail:rate-limit-budget,stall-budget
+CircleCI fail:rate-limit-budget,safe-point,stall-budget
+CircleciInsights fail:rate-limit-budget,safe-point,stall-budget
+CiscoDuo not-checkable:no-request
+CiscoMeraki fail:rate-limit-budget,stall-budget
+Clari fail:stall-budget
+Clarifai fail:rate-limit-budget,stall-budget
+Clay not-checkable:schemas
+Clerk fail:rate-limit-budget,timeout
+Clever fail:rate-limit-budget,timeout
+ClickHouse not-checkable:schemas
+ClickUp fail:rate-limit-budget,stall-budget
+ClickhouseCloud fail:rate-limit-budget,stall-budget
+Cliniko fail:rate-limit-budget,timeout
+Clip fail:rate-limit-budget,stall-budget
+Clockify fail:rate-limit-budget,timeout
+Clockodo fail:rate-limit-budget,timeout
+Close fail:rate-limit-budget
+Cloudability fail:rate-limit-budget,timeout
+Cloudbeds fail:rate-limit-budget,timeout
+Cloudflare fail:rate-limit-budget,timeout
+Cloudinary fail:rate-limit-budget,timeout
+Cloudsmith fail:rate-limit-budget,timeout
+Cloudzero fail:rate-limit-budget,timeout
+Coassemble fail:rate-limit-budget,timeout
+Coda fail:rate-limit-budget,safe-point,timeout
+Codacy fail:rate-limit-budget,stall-budget
+Codecov fail:rate-limit-budget,safe-point,stall-budget
+Codefresh fail:rate-limit-budget,timeout
+Codemagic fail:rate-limit-budget,timeout
+Codescene fail:rate-limit-budget,timeout
+Cody fail:stall-budget
+Cohere fail:rate-limit-budget,timeout
+CoinApi fail:rate-limit-budget,stall-budget
+CoinGecko fail:rate-limit-budget,stall-budget
+CoinMarketCap fail:rate-limit-budget,safe-point,timeout
+Commercetools fail:rate-limit-budget,stall-budget
+Companycam fail:rate-limit-budget,timeout
+Concord fail:rate-limit-budget,stall-budget
+Conekta fail:rate-limit-budget,timeout
+ConfigCat fail:rate-limit-budget,timeout
+Confluence fail:rate-limit-budget,timeout
+ConfluentCloud fail:rate-limit-budget,stall-budget
+ConvertKit fail:rate-limit-budget,timeout
+Convex not-checkable:schemas
+Coolify fail:rate-limit-budget,stall-budget
+Copper fail:rate-limit-budget,timeout
+Coralogix fail:stall-budget
+Cortex fail:rate-limit-budget,timeout
+Coupa fail:rate-limit-budget,stall-budget
+Courier fail:rate-limit-budget,timeout
+Coveralls not-checkable:no-request
+CratesIO fail:rate-limit-budget,stall-budget
+Cronitor fail:rate-limit-budget,stall-budget
+Crossref fail:rate-limit-budget
+Crunchbase fail:rate-limit-budget,timeout
+CultureAmp fail:rate-limit-budget,timeout
+Cursor fail:safe-point,stall-budget
+Custom not-checkable:schemas
+CustomerIO fail:rate-limit-budget,stall-budget
+Customerly fail:rate-limit-budget,stall-budget
+DagsterCloud fail:stall-budget
+DataForSEO fail:stall-budget
+Databricks not-checkable:driver:databricks
+Datadog fail:rate-limit-budget,safe-point,stall-budget
+Datahub fail:rate-limit-budget,stall-budget
+Dbt fail:rate-limit-budget,stall-budget
+Debugbear fail:rate-limit-budget
+Decagon fail:rate-limit-budget,stall-budget
+Deel fail:rate-limit-budget,timeout
+Deepgram fail:rate-limit-budget,timeout
+Deepsource fail:rate-limit-budget,stall-budget
+Demodesk fail:rate-limit-budget,timeout
+DenoDeploy fail:rate-limit-budget,timeout
+Depot not-checkable:no-request
+Descope fail:rate-limit-budget,timeout
+Develocity fail:rate-limit-budget,stall-budget
+DevinAI fail:rate-limit-budget,timeout
+DigitalOcean fail:rate-limit-budget,timeout
+DingConnect fail:rate-limit-budget,timeout
+Discourse fail:rate-limit-budget,safe-point,stall-budget
+Dixa fail:rate-limit-budget,safe-point,stall-budget
+DoIt not-checkable:schemas
+Dockerhub fail:rate-limit-budget,safe-point,stall-budget
+Docuseal fail:rate-limit-budget,timeout
+Docusign not-checkable:no-request
+DodoPayments fail:rate-limit-budget,stall-budget
+Donorbox fail:rate-limit-budget,stall-budget
+Doppler fail:rate-limit-budget,stall-budget
+Dovetail fail:rate-limit-budget,timeout
+Drata fail:rate-limit-budget,timeout
+Drip fail:rate-limit-budget,stall-budget
+DropboxSign fail:rate-limit-budget,stall-budget
+Dub fail:rate-limit-budget,timeout
+Dynamics365 not-checkable:no-request
+Dynamics365BusinessCentral fail:rate-limit-budget,stall-budget
+DynamoDB not-checkable:schemas
+Dynatrace fail:rate-limit-budget,timeout
+E2B fail:rate-limit-budget,timeout
+EConomic fail:rate-limit-budget,timeout
+EZOfficeInventory fail:rate-limit-budget,timeout
+Easybill fail:rate-limit-budget,timeout
+Easypost fail:rate-limit-budget,stall-budget
+Easypromos fail:rate-limit-budget,timeout
+EcbDataPortal fail:rate-limit-budget,safe-point,timeout
+Elasticemail fail:rate-limit-budget,timeout
+Elasticsearch not-checkable:schemas
+ElectricityMaps fail:rate-limit-budget,stall-budget
+ElevenLabs fail:rate-limit-budget,timeout
+EmailOctopus fail:rate-limit-budget,timeout
+Embrace fail:rate-limit-budget,stall-budget
+Env0 fail:rate-limit-budget,timeout
+Eppo fail:rate-limit-budget,timeout
+Etsy fail:rate-limit-budget
+Eventbrite fail:rate-limit-budget,timeout
+Eventee fail:rate-limit-budget,timeout
+Eventzilla fail:rate-limit-budget,timeout
+Everhour fail:rate-limit-budget,stall-budget
+ExchangeRatesApi fail:rate-limit-budget,stall-budget
+Factorial fail:rate-limit-budget,timeout
+Faire fail:rate-limit-budget,timeout
+Fastly fail:rate-limit-budget,safe-point,stall-budget
+Featurebase not-checkable:database
+Fieldpulse fail:rate-limit-budget,stall-budget
+Fillout fail:rate-limit-budget,timeout
+Finage fail:stall-budget
+FinancialModelling fail:rate-limit-budget,safe-point,stall-budget
+Finnhub fail:rate-limit-budget,stall-budget
+Finnworlds fail:rate-limit-budget,stall-budget
+Fintoc not-checkable:database
+FireHydrant fail:rate-limit-budget,timeout
+Firebase not-checkable:schemas
+Firecrawl fail:rate-limit-budget,timeout
+FireworksAI fail:rate-limit-budget,timeout
+FirstPromoter fail:rate-limit-budget,timeout
+Flagsmith fail:safe-point,stall-budget
+Fleetio fail:rate-limit-budget,timeout
+Flexmail fail:rate-limit-budget,timeout
+FloatApp fail:rate-limit-budget,timeout
+Flowlu fail:rate-limit-budget,timeout
+Flutterwave fail:rate-limit-budget,timeout
+FlyIo fail:rate-limit-budget,timeout
+Folk fail:rate-limit-budget,timeout
+Formbricks fail:rate-limit-budget,safe-point,stall-budget
+Fourthwall fail:rate-limit-budget,stall-budget
+Framer not-checkable:no-request
+Fred fail:rate-limit-budget
+Freshcaller fail:rate-limit-budget,timeout
+Freshchat fail:rate-limit-budget,timeout
+Freshdesk fail:rate-limit-budget,timeout
+Freshsales fail:rate-limit-budget,stall-budget
+Freshservice fail:rate-limit-budget,timeout
+Frill fail:rate-limit-budget,stall-budget
+Front fail:rate-limit-budget,timeout
+Frontegg fail:rate-limit-budget,stall-budget
+Fulcrum fail:rate-limit-budget,timeout
+FullStory fail:rate-limit-budget,timeout
+FusionAuth fail:rate-limit-budget,timeout
+G2 fail:rate-limit-budget,safe-point
+GNews fail:rate-limit-budget,stall-budget
+GainsightCs fail:rate-limit-budget
+GainsightPx fail:rate-limit-budget,safe-point,timeout
+Gcore fail:rate-limit-budget,stall-budget
+Gerrit fail:rate-limit-budget,stall-budget
+Getdx fail:rate-limit-budget,stall-budget
+Giphy fail:rate-limit-budget,timeout
+GitBook fail:rate-limit-budget,timeout
+GitLab fail:rate-limit-budget,stall-budget
+Gitea fail:rate-limit-budget,stall-budget
+Gitguardian fail:rate-limit-budget,safe-point,stall-budget
+Github not-checkable:schemas
+Givebutter fail:rate-limit-budget,stall-budget
+Gladly fail:rate-limit-budget,stall-budget
+Glassfrog fail:rate-limit-budget,timeout
+Gleif fail:rate-limit-budget,timeout
+GoCardless fail:rate-limit-budget,timeout
+GoLogin fail:rate-limit-budget,stall-budget
+Goldcast fail:rate-limit-budget,timeout
+Gong fail:rate-limit-budget,stall-budget
+GoogleAds not-checkable:driver:google.ads
+GoogleAnalytics not-checkable:database
+GooglePageSpeedInsights fail:stall-budget
+GooglePlayConsole not-checkable:no-request
+GoogleSearchConsole not-checkable:database
+GoogleSheets not-checkable:schemas
+GoogleWebfonts fail:rate-limit-budget,timeout
+Gorgias fail:rate-limit-budget,stall-budget
+Grafana fail:stall-budget
+GrafanaIRM not-checkable:no-request
+Granola fail:rate-limit-budget,timeout
+Greenhouse fail:rate-limit-budget,timeout
+Gridly fail:rate-limit-budget,stall-budget
+Groq fail:rate-limit-budget,safe-point,timeout
+GrowthBook fail:rate-limit-budget,stall-budget
+Guardian fail:rate-limit-budget,timeout
+Gumroad fail:rate-limit-budget,stall-budget
+Guru fail:rate-limit-budget,timeout
+Gusto fail:rate-limit-budget
+Harness fail:rate-limit-budget,stall-budget
+Harvest fail:rate-limit-budget,stall-budget
+Harvey fail:rate-limit-budget,stall-budget
+Hatchet not-checkable:no-request
+Healthchecks fail:rate-limit-budget,stall-budget
+Height fail:rate-limit-budget,timeout
+Helicone fail:stall-budget
+Hellobaton fail:rate-limit-budget,timeout
+HelpScout not-checkable:database
+Heroku fail:rate-limit-budget,timeout
+Hetzner fail:rate-limit-budget,stall-budget
+Hex fail:rate-limit-budget,timeout
+HeyGen fail:rate-limit-budget,stall-budget
+HeyReach fail:rate-limit-budget,stall-budget
+HiBob fail:rate-limit-budget,timeout
+Hightouch fail:rate-limit-budget,timeout
+Hitpay fail:rate-limit-budget,safe-point,timeout
+Honeybadger fail:rate-limit-budget,safe-point,stall-budget
+Honeycomb fail:rate-limit-budget,stall-budget
+Hookdeck fail:rate-limit-budget,timeout
+HoorayHR fail:rate-limit-budget,stall-budget
+HousecallPro fail:rate-limit-budget,timeout
+Hubplanner fail:rate-limit-budget,timeout
+Hubspot not-checkable:database
+HuggingFace fail:rate-limit-budget,timeout
+Humanitec fail:rate-limit-budget,stall-budget
+Humanitix fail:rate-limit-budget,timeout
+Huntr fail:rate-limit-budget,stall-budget
+Hyperspell fail:rate-limit-budget,safe-point,stall-budget
+Hyros fail:rate-limit-budget,timeout
+IP2Whois fail:rate-limit-budget,stall-budget
+Imagga fail:rate-limit-budget,timeout
+Impact fail:rate-limit-budget
+ImpactPartner fail:rate-limit-budget
+Imperva fail:rate-limit-budget,stall-budget
+IncidentIo fail:rate-limit-budget,timeout
+Inflowinventory fail:rate-limit-budget,timeout
+Inngest fail:rate-limit-budget,stall-budget
+Insightly fail:rate-limit-budget,timeout
+Instagram not-checkable:database
+Instana fail:rate-limit-budget,safe-point,stall-budget
+Instantly fail:rate-limit-budget,stall-budget
+Instatus fail:rate-limit-budget,timeout
+Intercom not-checkable:database
+Intruder fail:rate-limit-budget,timeout
+Invoiced fail:rate-limit-budget,timeout
+Invoiceninja fail:rate-limit-budget,timeout
+Iterable fail:rate-limit-budget,timeout
+JamfPro fail:rate-limit-budget,stall-budget
+Jellyfish fail:stall-budget
+Jenkins fail:rate-limit-budget,stall-budget
+JfrogArtifactory fail:rate-limit-budget,stall-budget
+Jira fail:rate-limit-budget,timeout
+JobNimbus fail:rate-limit-budget,timeout
+Jotform fail:rate-limit-budget,timeout
+JudgeMeReviews fail:rate-limit-budget,timeout
+Jumpcloud fail:rate-limit-budget,stall-budget
+JustCall fail:rate-limit-budget,timeout
+JustSift fail:rate-limit-budget,timeout
+K6Cloud fail:rate-limit-budget,stall-budget
+Kafka not-checkable:driver:confluent_kafka
+Kalshi fail:rate-limit-budget,timeout
+Kandji fail:rate-limit-budget,safe-point,timeout
+KapaAI fail:rate-limit-budget,safe-point,stall-budget
+Katana fail:rate-limit-budget,timeout
+Kernel fail:rate-limit-budget,safe-point,stall-budget
+Kestra not-checkable:no-request
+Kickscale fail:rate-limit-budget,timeout
+Kisi fail:rate-limit-budget,stall-budget
+Klaus fail:rate-limit-budget,stall-budget
+Klaviyo fail:rate-limit-budget,safe-point,stall-budget
+Knock fail:rate-limit-budget,timeout
+Knowbe4 fail:rate-limit-budget,timeout
+Kommo fail:rate-limit-budget,stall-budget
+Komodor fail:rate-limit-budget,stall-budget
+KongKonnect fail:stall-budget
+Koyeb fail:rate-limit-budget,timeout
+Kubecost fail:rate-limit-budget,stall-budget
+Kustomer fail:rate-limit-budget,timeout
+Lacework fail:rate-limit-budget,safe-point,stall-budget
+Lago fail:rate-limit-budget,timeout
+LambdaLabs fail:rate-limit-budget,timeout
+LangSmith fail:rate-limit-budget,stall-budget
+Langfuse fail:rate-limit-budget,stall-budget
+Lattice fail:rate-limit-budget,timeout
+LaunchDarkly fail:rate-limit-budget,timeout
+Leadfeeder fail:rate-limit-budget,timeout
+Leexi fail:rate-limit-budget,timeout
+Lemlist fail:rate-limit-budget,timeout
+LemonSqueezy fail:rate-limit-budget,timeout
+LessAnnoyingCRM fail:rate-limit-budget,timeout
+Lever fail:rate-limit-budget,timeout
+LexwareOffice fail:rate-limit-budget,stall-budget
+Lightdash fail:rate-limit-budget,stall-budget
+Lightfield fail:rate-limit-budget,timeout
+LightspeedRetail fail:rate-limit-budget,timeout
+Linear not-checkable:database
+Linearb fail:rate-limit-budget,stall-budget
+LingoDev fail:rate-limit-budget,timeout
+LinkedinAds not-checkable:database
+Linkrunner fail:rate-limit-budget,stall-budget
+Linode fail:rate-limit-budget,timeout
+LlamaCloud fail:rate-limit-budget,safe-point,stall-budget
+Lob fail:rate-limit-budget,stall-budget
+Lodgify fail:rate-limit-budget,stall-budget
+Logicmonitor not-checkable:no-request
+LogzIO fail:stall-budget
+LoopReturns fail:rate-limit-budget,timeout
+Loops fail:rate-limit-budget,stall-budget
+Lovable fail:rate-limit-budget,safe-point,stall-budget
+Luma fail:rate-limit-budget,safe-point,stall-budget
+MSSQL not-checkable:driver:pymssql
+Mailchimp fail:rate-limit-budget,timeout
+MailerLite fail:rate-limit-budget,timeout
+MailerSend fail:rate-limit-budget,safe-point,timeout
+Mailgun fail:rate-limit-budget,stall-budget
+Mailjet fail:rate-limit-budget,timeout
+Mailosaur fail:rate-limit-budget,timeout
+Mailtrap fail:rate-limit-budget,timeout
+Marketo fail:rate-limit-budget,stall-budget
+Marketstack fail:rate-limit-budget,timeout
+Matomo fail:stall-budget
+Maxio fail:rate-limit-budget,timeout
+Medusa fail:rate-limit-budget,stall-budget
+Mem0 fail:rate-limit-budget,safe-point,timeout
+Membrain fail:rate-limit-budget,stall-budget
+Mention fail:rate-limit-budget,safe-point,stall-budget
+MercadoPago fail:rate-limit-budget,stall-budget
+Mercury fail:rate-limit-budget,timeout
+MetaAds not-checkable:database
+Metabase fail:rate-limit-budget,timeout
+Metaplane fail:rate-limit-budget,stall-budget
+Meteostat fail:rate-limit-budget,safe-point
+Metorial fail:rate-limit-budget,timeout
+Metronome fail:rate-limit-budget,stall-budget
+Mezmo fail:rate-limit-budget,stall-budget
+MicrosoftClarity fail:rate-limit-budget
+MicrosoftDefenderCloudApps fail:rate-limit-budget,stall-budget
+MightyNetworks fail:rate-limit-budget,timeout
+Mintlify fail:rate-limit-budget,stall-budget
+MistralAI fail:rate-limit-budget,stall-budget
+MixMax fail:rate-limit-budget,timeout
+Mixpanel fail:rate-limit-budget,stall-budget
+MoEngage fail:rate-limit-budget,safe-point,stall-budget
+Modal not-checkable:driver:grpclib
+Mollie fail:rate-limit-budget,timeout
+Monday fail:stall-budget
+MongoDB not-checkable:driver:pymongo
+Mono fail:rate-limit-budget,stall-budget
+MonteCarlo fail:safe-point,stall-budget
+Motherduck not-checkable:driver:duckdb
+Motion fail:rate-limit-budget,stall-budget
+Moxie fail:rate-limit-budget,stall-budget
+Mux fail:rate-limit-budget,timeout
+MyHours fail:rate-limit-budget,safe-point,timeout
+MySQL not-checkable:driver:psycopg
+N8n fail:rate-limit-budget,timeout
+NagerDate fail:rate-limit-budget
+NebiusAI fail:rate-limit-budget,stall-budget
+Neo4j not-checkable:schemas
+Neon not-checkable:driver:psycopg
+Netlify fail:rate-limit-budget,timeout
+NewRelic fail:safe-point,stall-budget
+NewYorkTimes fail:rate-limit-budget,stall-budget
+NewsApi fail:rate-limit-budget,timeout
+NewsData fail:rate-limit-budget,timeout
+NoCRM fail:rate-limit-budget,timeout
+NoaaCdo fail:rate-limit-budget,stall-budget
+Northflank fail:rate-limit-budget,stall-budget
+NorthpassLMS fail:rate-limit-budget,timeout
+Notion fail:rate-limit-budget,safe-point,stall-budget
+NpmRegistry fail:rate-limit-budget,safe-point
+Nuget fail:rate-limit-budget,stall-budget
+Nuntly fail:rate-limit-budget,timeout
+OPUSWatch fail:rate-limit-budget,timeout
+Octolens fail:rate-limit-budget,timeout
+OctopusDeploy fail:stall-budget
+Okendo fail:rate-limit-budget,timeout
+Okta fail:rate-limit-budget,timeout
+Omni fail:rate-limit-budget,timeout
+Omnisend fail:rate-limit-budget,stall-budget
+Oncehub fail:rate-limit-budget,timeout
+OneHundredMs fail:rate-limit-budget,stall-budget
+OnePassword fail:rate-limit-budget,timeout
+Onepagecrm fail:rate-limit-budget,timeout
+Onfleet fail:rate-limit-budget,timeout
+OpenAI fail:rate-limit-budget,timeout
+OpenAIAds fail:rate-limit-budget,timeout
+OpenAQ fail:rate-limit-budget,timeout
+OpenExchangeRates fail:rate-limit-budget,stall-budget
+OpenFDA fail:rate-limit-budget,timeout
+OpenMeteo not-checkable:no-request
+OpenRouter fail:rate-limit-budget,stall-budget
+OpenWeather not-checkable:no-request
+Openalex fail:rate-limit-budget,timeout
+Opencorporates fail:rate-limit-budget,timeout
+OpinionStage fail:rate-limit-budget,timeout
+OpnPayments fail:rate-limit-budget,timeout
+Opsgenie fail:rate-limit-budget,timeout
+Optimizely fail:rate-limit-budget,safe-point,timeout
+Orb fail:rate-limit-budget,timeout
+OrcaSecurity fail:rate-limit-budget,timeout
+Ortto fail:safe-point,stall-budget
+Oura fail:rate-limit-budget,timeout
+Ownerrez fail:rate-limit-budget,timeout
+PabblySubscriptionsBilling fail:rate-limit-budget,safe-point,stall-budget
+Packagist fail:rate-limit-budget,stall-budget
+Paddle fail:rate-limit-budget,timeout
+PagerDuty fail:rate-limit-budget,timeout
+PandaDoc fail:rate-limit-budget,timeout
+Paperform fail:rate-limit-budget,timeout
+Papersign fail:rate-limit-budget,timeout
+Pardot not-checkable:database
+PartnerStack fail:rate-limit-budget,timeout
+Partnerize fail:rate-limit-budget,timeout
+PayFit fail:stall-budget
+Paymongo fail:rate-limit-budget,stall-budget
+Paystack fail:rate-limit-budget,timeout
+PeecAI fail:rate-limit-budget,stall-budget
+Pendo fail:rate-limit-budget,stall-budget
+Perigon fail:rate-limit-budget,timeout
+PersistIq fail:rate-limit-budget,timeout
+Persona fail:rate-limit-budget,stall-budget
+Personio fail:rate-limit-budget,timeout
+Pexels fail:rate-limit-budget,timeout
+Phyllo fail:rate-limit-budget,timeout
+Picqer fail:rate-limit-budget,timeout
+Pinecone fail:rate-limit-budget,stall-budget
+Pingdom fail:rate-limit-budget,timeout
+PinterestAds not-checkable:database
+Pipedrive not-checkable:database
+Pipeliner fail:rate-limit-budget,safe-point,timeout
+Plaid fail:stall-budget
+PlanetScaleMySQL not-checkable:driver:psycopg
+PlanetScalePostgres not-checkable:driver:psycopg
+Planhat fail:rate-limit-budget,timeout
+PlatformSh fail:rate-limit-budget,stall-budget
+Plausible fail:rate-limit-budget,timeout
+Plivo fail:rate-limit-budget,timeout
+Plunk fail:rate-limit-budget,safe-point,timeout
+PluralsightFlow fail:rate-limit-budget,timeout
+Polar fail:rate-limit-budget,timeout
+Polymarket fail:rate-limit-budget,timeout
+Poplar fail:rate-limit-budget,stall-budget
+Postgres not-checkable:driver:psycopg
+Postmark fail:rate-limit-budget,timeout
+Postscript fail:rate-limit-budget,timeout
+PowerBiAdmin fail:rate-limit-budget,safe-point,stall-budget
+PrefectCloud fail:rate-limit-budget,timeout
+Pretix fail:rate-limit-budget,timeout
+Printify fail:rate-limit-budget,stall-budget
+Productboard fail:rate-limit-budget,timeout
+Productive fail:rate-limit-budget,stall-budget
+Profound fail:rate-limit-budget,stall-budget
+PromptWatch fail:rate-limit-budget
+PromptingCompany fail:rate-limit-budget,stall-budget
+ProofpointTap not-checkable:no-request
+Propertyware fail:rate-limit-budget,timeout
+PulumiCloud fail:rate-limit-budget,stall-budget
+PyPI fail:rate-limit-budget,stall-budget
+Pylon fail:rate-limit-budget,safe-point,stall-budget
+Qdrant fail:rate-limit-budget,stall-budget
+Qonto fail:rate-limit-budget,stall-budget
+Qualaroo fail:rate-limit-budget,timeout
+Qualtrics fail:rate-limit-budget
+QualysVmdr fail:rate-limit-budget,stall-budget
+Quo fail:rate-limit-budget,timeout
+RKICovid fail:rate-limit-budget
+Railway fail:stall-budget
+Ramp fail:rate-limit-budget,timeout
+Rapid7Insightvm fail:rate-limit-budget,timeout
+Raygun fail:rate-limit-budget,timeout
+Razorpay fail:rate-limit-budget,timeout
+RecallAI fail:rate-limit-budget,timeout
+Recharge fail:rate-limit-budget,timeout
+Recreation fail:rate-limit-budget,timeout
+Recruitee fail:rate-limit-budget,timeout
+Recurly fail:rate-limit-budget,timeout
+RedditAds not-checkable:database
+Redshift not-checkable:driver:psycopg
+ReferralHero fail:rate-limit-budget,stall-budget
+Render fail:rate-limit-budget,stall-budget
+RentCast fail:rate-limit-budget,timeout
+Replicate fail:rate-limit-budget,safe-point,stall-budget
+ReplyIo fail:rate-limit-budget,timeout
+Resend fail:rate-limit-budget,timeout
+RetellAI fail:rate-limit-budget,stall-budget
+Retently fail:rate-limit-budget,timeout
+RevenueCat fail:rate-limit-budget,safe-point,timeout
+Reverb fail:rate-limit-budget,timeout
+RevolutMerchant fail:rate-limit-budget,stall-budget
+Rippling fail:rate-limit-budget,timeout
+Roark fail:rate-limit-budget,timeout
+Rocketlane fail:rate-limit-budget,timeout
+RoktAds fail:rate-limit-budget,timeout
+Rollbar fail:rate-limit-budget,stall-budget
+Rootly fail:rate-limit-budget,timeout
+Rss fail:rate-limit-budget,timeout
+Rubygems fail:rate-limit-budget,stall-budget
+Ruddr fail:rate-limit-budget,timeout
+RunPod fail:rate-limit-budget,safe-point,stall-budget
+SFTP not-checkable:transport
+SafetyCulture fail:rate-limit-budget,timeout
+SageHR fail:rate-limit-budget,safe-point,stall-budget
+SalesLoft fail:rate-limit-budget,timeout
+Salesflare fail:rate-limit-budget,timeout
+Salesforce not-checkable:database
+SavvyCal fail:rate-limit-budget,timeout
+ScaleAI fail:rate-limit-budget,timeout
+Scaleway fail:rate-limit-budget,safe-point
+Scalr fail:rate-limit-budget,stall-budget
+Scrunch fail:rate-limit-budget,stall-budget
+Secoda fail:rate-limit-budget,timeout
+Secureframe fail:rate-limit-budget,timeout
+Segment fail:rate-limit-budget,stall-budget
+SelectStar fail:rate-limit-budget,timeout
+SemanticScholar fail:rate-limit-budget,stall-budget
+Semaphore fail:rate-limit-budget,stall-budget
+Semgrep fail:rate-limit-budget,timeout
+Semrush fail:rate-limit-budget,stall-budget
+SendGrid fail:rate-limit-budget,timeout
+Sendowl fail:rate-limit-budget,timeout
+Sentinelone fail:rate-limit-budget,timeout
+Sentry fail:rate-limit-budget,timeout
+Sequenzy fail:rate-limit-budget,timeout
+Serpstat fail:rate-limit-budget,stall-budget
+ServiceNow fail:rate-limit-budget,timeout
+Servicem8 fail:rate-limit-budget,timeout
+Sevdesk fail:rate-limit-budget,safe-point,stall-budget
+SevenShifts fail:rate-limit-budget,stall-budget
+SharePoint fail:rate-limit-budget,stall-budget
+ShipStation fail:rate-limit-budget,timeout
+Shipmail fail:rate-limit-budget,stall-budget
+Shippo fail:rate-limit-budget,safe-point,stall-budget
+ShopWired fail:rate-limit-budget,timeout
+Shopify fail:timeout
+Shortcut fail:rate-limit-budget,timeout
+Shortio fail:rate-limit-budget,timeout
+Shutterstock fail:rate-limit-budget,timeout
+SigNoz fail:stall-budget
+SigmaComputing fail:rate-limit-budget,timeout
+Sim fail:rate-limit-budget,stall-budget
+SimFin fail:rate-limit-budget
+Similarweb fail:rate-limit-budget
+SimpleCast fail:rate-limit-budget,timeout
+Simplesat fail:rate-limit-budget,timeout
+Singlestore fail:rate-limit-budget,timeout
+Singular fail:stall-budget
+Skyvern fail:rate-limit-budget,timeout
+Slack not-checkable:schemas
+Slash fail:rate-limit-budget,stall-budget
+Sleekplan fail:rate-limit-budget,stall-budget
+Smaily fail:rate-limit-budget,safe-point,stall-budget
+SmartEngage fail:rate-limit-budget,timeout
+Smartlead fail:rate-limit-budget,timeout
+Smartreach fail:rate-limit-budget,timeout
+Smartsheet fail:rate-limit-budget,timeout
+Smartwaiver fail:rate-limit-budget,timeout
+SnapchatAds not-checkable:database
+Snowflake not-checkable:driver:snowflake
+Snowplow fail:rate-limit-budget,stall-budget
+Snyk fail:rate-limit-budget,timeout
+SodaCloud fail:rate-limit-budget,stall-budget
+SolarwindsServiceDesk fail:rate-limit-budget,timeout
+SonarCloud fail:rate-limit-budget,timeout
+Sonarqube fail:rate-limit-budget,stall-budget
+SonatypeNexus fail:rate-limit-budget,stall-budget
+Sourcegraph fail:stall-budget
+Spacelift fail:stall-budget
+SparkPost fail:rate-limit-budget,timeout
+Speedcurve fail:rate-limit-budget,stall-budget
+SplitIo fail:rate-limit-budget,stall-budget
+SplunkObservabilityCloud fail:rate-limit-budget,stall-budget
+SpotIo fail:rate-limit-budget,timeout
+SpotlerCRM fail:rate-limit-budget,timeout
+Sprig fail:rate-limit-budget,timeout
+Squadcast fail:rate-limit-budget,stall-budget
+Square fail:rate-limit-budget,safe-point,stall-budget
+Squarespace fail:rate-limit-budget,stall-budget
+StackOverflowForTeams fail:rate-limit-budget,timeout
+Statuscake fail:rate-limit-budget,stall-budget
+Statuspage fail:rate-limit-budget,timeout
+Stigg fail:rate-limit-budget,timeout
+StockData fail:rate-limit-budget,timeout
+Strato fail:rate-limit-budget,stall-budget
+StreamElements fail:rate-limit-budget
+Stripe not-checkable:database
+Stytch fail:stall-budget
+SumoLogic fail:safe-point,stall-budget
+Supabase not-checkable:driver:psycopg
+SurveyMonkey fail:rate-limit-budget,timeout
+SurveySparrow fail:rate-limit-budget,timeout
+Survicate fail:rate-limit-budget,stall-budget
+Svix fail:rate-limit-budget,timeout
+Swarmia fail:rate-limit-budget,safe-point,stall-budget
+Synthesia fail:rate-limit-budget,stall-budget
+Systeme fail:rate-limit-budget,stall-budget
+TMDb fail:rate-limit-budget,timeout
+TVMaze fail:rate-limit-budget,timeout
+Taboola fail:rate-limit-budget,stall-budget
+Tailscale fail:rate-limit-budget,safe-point,stall-budget
+Tally fail:rate-limit-budget,timeout
+Tavus fail:rate-limit-budget,timeout
+TawkTo fail:stall-budget
+Teachable fail:rate-limit-budget,timeout
+Teamcity fail:rate-limit-budget,stall-budget
+Teamtailor fail:rate-limit-budget,timeout
+TeamupFitness fail:rate-limit-budget,stall-budget
+Teamwork fail:rate-limit-budget,timeout
+Telli fail:rate-limit-budget,stall-budget
+Telnyx fail:rate-limit-budget,timeout
+Tempo fail:rate-limit-budget,timeout
+TemporalIO not-checkable:driver:temporalio.client
+TenableVulnerabilityManagement fail:stall-budget
+Tenjin fail:rate-limit-budget,timeout
+TerraformCloud fail:rate-limit-budget,safe-point,stall-budget
+Testrail fail:rate-limit-budget,stall-budget
+Thinkific fail:rate-limit-budget,timeout
+ThinkificCourses fail:rate-limit-budget,timeout
+Thousandeyes fail:rate-limit-budget,stall-budget
+TicketTailor fail:rate-limit-budget,timeout
+Ticketmaster fail:rate-limit-budget,stall-budget
+TikTokAds not-checkable:database
+Tinyemail fail:rate-limit-budget,timeout
+Todoist fail:rate-limit-budget,timeout
+TogetherAI fail:rate-limit-budget,timeout
+Torii fail:rate-limit-budget,timeout
+Transistor fail:rate-limit-budget,stall-budget
+TravisCI fail:rate-limit-budget,stall-budget
+Trello fail:rate-limit-budget,timeout
+Tremendous fail:rate-limit-budget,timeout
+TriggerDev fail:rate-limit-budget,stall-budget
+Trino not-checkable:schemas
+TrunkIo fail:rate-limit-budget,safe-point,timeout
+TrustPilot fail:rate-limit-budget
+Trustradius fail:rate-limit-budget,stall-budget
+Turso fail:rate-limit-budget,timeout
+TwelveData fail:rate-limit-budget
+TwelveLabs fail:rate-limit-budget,timeout
+Twenty fail:rate-limit-budget,stall-budget
+Twilio fail:rate-limit-budget,timeout
+Twitter fail:rate-limit-budget,stall-budget
+TwitterAds not-checkable:database
+TyntecSMS fail:rate-limit-budget,timeout
+Typeform fail:rate-limit-budget,timeout
+USCensus fail:rate-limit-budget,stall-budget
+Ubidots fail:rate-limit-budget,safe-point,stall-budget
+UkCompaniesHouse fail:rate-limit-budget,stall-budget
+Unleash fail:rate-limit-budget,safe-point,timeout
+Unstructured fail:rate-limit-budget,stall-budget
+UpPromote not-checkable:database
+Upstash fail:rate-limit-budget,timeout
+Uptimerobot fail:stall-budget
+UsBea fail:rate-limit-budget,stall-budget
+UsEia fail:rate-limit-budget,stall-budget
+UsTreasuryFiscalData fail:rate-limit-budget,stall-budget
+Usersnap fail:rate-limit-budget,stall-budget
+Uservoice fail:rate-limit-budget,timeout
+Vantage fail:rate-limit-budget,timeout
+Vapi fail:rate-limit-budget,stall-budget
+Veeqo fail:rate-limit-budget,timeout
+Vellum fail:rate-limit-budget,timeout
+Vendr fail:rate-limit-budget,timeout
+Veracode fail:stall-budget
+Vercel fail:rate-limit-budget,stall-budget
+Vimeo fail:rate-limit-budget,stall-budget
+Vitally fail:rate-limit-budget,safe-point,timeout
+Vultr fail:rate-limit-budget,timeout
+Wasabi fail:rate-limit-budget,timeout
+Watchmode fail:rate-limit-budget,timeout
+Waydev fail:rate-limit-budget,timeout
+Webflow fail:rate-limit-budget,timeout
+WeightsAndBiases fail:stall-budget
+WhoGho fail:rate-limit-budget,stall-budget
+Whop fail:rate-limit-budget,timeout
+WikipediaPageviews fail:rate-limit-budget,safe-point
+Windmill fail:rate-limit-budget,timeout
+WooCommerce fail:rate-limit-budget,timeout
+Wordpress fail:rate-limit-budget,stall-budget
+WorkOS not-checkable:database
+Workable fail:rate-limit-budget,timeout
+Workday fail:rate-limit-budget,stall-budget
+Workiz fail:rate-limit-budget,timeout
+WorldBank fail:rate-limit-budget,timeout
+Wrike not-checkable:no-request
+Writesonic fail:rate-limit-budget,safe-point,stall-budget
+Wufoo fail:rate-limit-budget,timeout
+Xendit fail:rate-limit-budget,timeout
+Xmatters fail:rate-limit-budget,timeout
+Xsolla fail:rate-limit-budget,timeout
+Ynab fail:rate-limit-budget,timeout
+Yoco fail:rate-limit-budget,stall-budget
+YouSign fail:rate-limit-budget,timeout
+YouTubeAnalytics not-checkable:database
+ZapSign fail:rate-limit-budget,safe-point,timeout
+ZapierSupportedStorage fail:rate-limit-budget,safe-point,stall-budget
+Zendesk fail:rate-limit-budget,timeout
+ZendeskSell fail:rate-limit-budget,timeout
+ZendeskSunshine fail:rate-limit-budget,timeout
+Zenduty fail:rate-limit-budget,safe-point,stall-budget
+Zenloop fail:rate-limit-budget,timeout
+Zep fail:rate-limit-budget,stall-budget
+Zero fail:rate-limit-budget
+ZohoCRM fail:rate-limit-budget
+ZonkaFeedback fail:rate-limit-budget,timeout
+Zoom fail:rate-limit-budget,timeout
+Zuora fail:rate-limit-budget,timeout
+Zylo fail:rate-limit-budget,timeout
+shared-path:rest-client-paginate fail:rate-limit-budget,safe-point,timeout
+shared-path:rest-framework-resource fail:rate-limit-budget,timeout
+shared-path:rest-framework-resource-with-timeout fail:rate-limit-budget,stall-budget
+shared-path:rest-framework-wrapped-resource fail:rate-limit-budget,safe-point,timeout
+shared-path:tracked-session fail:rate-limit-budget
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_source_contract.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_source_contract.py
new file mode 100644
index 000000000000..de0a523aba87
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_source_contract.py
@@ -0,0 +1,377 @@
+"""The source contract: an extraction never holds a worker for long, and it gives control back often.
+
+A worker that shuts down hands its imports to another worker. That works only when each source
+(1) puts a deadline on each call and a limit on its retries and waits, and (2) gives control back
+to the pipeline after each request, with a yield or a safe point. These tests run each source in the
+registry against a fake HTTP server that stalls, rate-limits, or returns empty pages.
+
+`source_contract_baseline.txt` lists each source that fails a condition or that the fake cannot
+drive. A source that is not in the file must pass. An entry that no longer matches must change, so
+the list of failures only gets shorter.
+"""
+
+import os
+import sys
+import time
+from collections import Counter
+from collections.abc import Iterator
+from pathlib import Path
+from typing import Any, cast
+
+import pytest
+
+import requests
+import tenacity
+from urllib3.util.retry import Retry
+
+import products.warehouse_sources.backend.temporal.data_imports.sources._load_all # noqa: F401
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http.transport import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import rest_api_resource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ JSONResponseCursorPaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import RESTClient
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import RESTAPIConfig
+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, SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.tests.contract_harness import (
+ RATE_LIMIT_BUDGET,
+ SAFE_POINT,
+ STALL_BUDGET,
+ TIMEOUT,
+ Scenario,
+ SourceStatus,
+ StartExtraction,
+ check_extraction,
+ check_source,
+ fake_environment,
+ is_stub,
+)
+
+BASELINE_PATH = Path(__file__).parent / "source_contract_baseline.txt"
+WRITE_BASELINE_VARIABLE = "SOURCE_CONTRACT_WRITE_BASELINE"
+TEST_PATH = "products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_source_contract.py"
+REGENERATE = f"{WRITE_BASELINE_VARIABLE}=1 pytest {TEST_PATH} -p no:xdist"
+
+BASE_URL = "https://contract.example.com"
+PAGES_URL = f"{BASE_URL}/rows"
+NO_ADAPTER_RETRY = Retry(total=0)
+
+# A stub is a source directory with a `source.py` and no extraction code: its class still has the
+# base `source_for_pipeline`. The contract does not apply to it until the extraction code ships.
+IMPLEMENTED_SOURCES = {
+ str(source_type.value): source
+ for source_type, source in SourceRegistry.get_all_sources().items()
+ if not is_stub(source)
+}
+
+
+def _response(items: Any) -> SourceResponse:
+ return SourceResponse(name="rows", items=lambda: items, primary_keys=None)
+
+
+def _manager(inputs: SourceInputs) -> ResumableSourceManager[Any]:
+ return ResumableSourceManager(inputs, dict)
+
+
+def _framework_config(request_timeout: tuple[float, float] | None = None) -> RESTAPIConfig:
+ config: RESTAPIConfig = {
+ "client": {
+ "base_url": BASE_URL,
+ "paginator": JSONResponseCursorPaginator(cursor_path="next_cursor", cursor_param="cursor"),
+ },
+ "resources": [{"name": "rows", "endpoint": {"path": "/rows", "data_selector": "data"}}],
+ }
+ if request_timeout is not None:
+ config["client"]["request_timeout"] = request_timeout
+ return config
+
+
+def _framework_resource(inputs: SourceInputs) -> tuple[SourceResponse, ResumableSourceManager[Any] | None]:
+ manager = _manager(inputs)
+ resource = rest_api_resource(_framework_config(), inputs.team_id, inputs.job_id, None)
+ return _response(resource), manager
+
+
+def _framework_resource_with_timeout(
+ inputs: SourceInputs,
+) -> tuple[SourceResponse, ResumableSourceManager[Any] | None]:
+ manager = _manager(inputs)
+ resource = rest_api_resource(_framework_config((10, 60)), inputs.team_id, inputs.job_id, None)
+ return _response(resource), manager
+
+
+def _wrapped_framework_resource(inputs: SourceInputs) -> tuple[SourceResponse, ResumableSourceManager[Any] | None]:
+ manager = _manager(inputs)
+ resource = rest_api_resource(_framework_config(), inputs.team_id, inputs.job_id, None)
+
+ def rows() -> Iterator[Any]:
+ yield from resource
+
+ return _response(rows()), manager
+
+
+def _rest_client_paginate(inputs: SourceInputs) -> tuple[SourceResponse, ResumableSourceManager[Any] | None]:
+ manager = _manager(inputs)
+ client = RESTClient(base_url=BASE_URL)
+
+ def rows() -> Iterator[Any]:
+ paginator = JSONResponseCursorPaginator(cursor_path="next_cursor", cursor_param="cursor")
+ for page in client.paginate("/rows", paginator=paginator, data_selector="data"):
+ if page:
+ yield page
+
+ return _response(rows()), manager
+
+
+def _session_pages(session: requests.Session, **request_kwargs: Any) -> Iterator[list[Any]]:
+ url: str | None = PAGES_URL
+ while url:
+ response = session.get(url, **request_kwargs)
+ response.raise_for_status()
+ body = response.json()
+ yield body["data"]
+ url = body.get("next")
+
+
+def _tracked_session(inputs: SourceInputs) -> tuple[SourceResponse, ResumableSourceManager[Any] | None]:
+ manager = _manager(inputs)
+
+ def rows() -> Iterator[Any]:
+ for page in _session_pages(make_tracked_session(), timeout=(10, 60)):
+ if page:
+ yield page
+ manager.safe_point()
+
+ return _response(rows()), manager
+
+
+# The shared paths that most sources are built on. Each one has a baseline entry of its own, so a
+# fix in the shared code removes the entry here and the entries of the sources that the fix covers.
+SHARED_PATHS: dict[str, StartExtraction] = {
+ "shared-path:rest-framework-resource": _framework_resource,
+ "shared-path:rest-framework-resource-with-timeout": _framework_resource_with_timeout,
+ "shared-path:rest-framework-wrapped-resource": _wrapped_framework_resource,
+ "shared-path:rest-client-paginate": _rest_client_paginate,
+ "shared-path:tracked-session": _tracked_session,
+}
+
+
+def _bespoke(
+ *,
+ timeout: Any = (10, 30),
+ attempts: int = 1,
+ honor_retry_after: bool = False,
+ safe_point: bool = False,
+ resumable: bool = True,
+) -> StartExtraction:
+ def start(inputs: SourceInputs) -> tuple[SourceResponse, ResumableSourceManager[Any] | None]:
+ manager = _manager(inputs)
+ session = make_tracked_session(retry=NO_ADAPTER_RETRY)
+
+ def get(url: str) -> requests.Response:
+ for attempt in range(attempts):
+ try:
+ response = session.get(url, timeout=timeout)
+ except (requests.Timeout, requests.ConnectionError):
+ if attempt == attempts - 1:
+ raise
+ continue
+ if response.status_code == 429 and honor_retry_after:
+ # The harness replaces `time.sleep` with its fake clock.
+ time.sleep(float(response.headers["Retry-After"]))
+ continue
+ return response
+ raise RuntimeError("no attempt is left")
+
+ def rows() -> Iterator[Any]:
+ url: str | None = PAGES_URL
+ while url:
+ response = get(url)
+ response.raise_for_status()
+ body = response.json()
+ if body["data"]:
+ yield body["data"]
+ if safe_point:
+ manager.safe_point()
+ url = body.get("next")
+
+ return _response(rows()), manager if resumable else None
+
+ return start
+
+
+DETECTION_CASES = [
+ ("bounded_call_with_a_safe_point_per_page_passes", _bespoke(safe_point=True), set()),
+ ("request_with_no_timeout", _bespoke(timeout=None, safe_point=True), {TIMEOUT}),
+ ("request_with_no_read_timeout", _bespoke(timeout=(10, None), safe_point=True), {TIMEOUT}),
+ ("retries_that_pass_the_budget", _bespoke(attempts=20, safe_point=True), {STALL_BUDGET}),
+ ("retries_inside_the_budget_pass", _bespoke(attempts=5, safe_point=True), set()),
+ ("uncapped_retry_after_wait", _bespoke(honor_retry_after=True, safe_point=True), {RATE_LIMIT_BUDGET}),
+ ("empty_pages_with_no_safe_point", _bespoke(), {SAFE_POINT}),
+ (
+ "safe_points_do_not_count_when_the_pipeline_installs_no_hook",
+ _bespoke(safe_point=True, resumable=False),
+ {SAFE_POINT},
+ ),
+]
+
+
+ ("start", "expected"), [case[1:] for case in DETECTION_CASES], ids=[c[0] for c in DETECTION_CASES]
+)
+def test_harness_detects_each_condition(start: StartExtraction, expected: set[str]) -> None:
+ assert check_extraction(start, ["rows"]).failed == expected
+
+
[email protected](stop=tenacity.stop_after_attempt(2), wait=tenacity.wait_fixed(400))
+def _retried_call() -> None:
+ return None
+
+
+def test_retry_waits_reach_the_fake_clock_after_a_test_replaced_them(monkeypatch: pytest.MonkeyPatch) -> None:
+ # Some source tests assign `RESTClient._send_request.retry.sleep` and never put it back. The
+ # verdict of a source must not depend on whether such a test ran earlier in the same process.
+ controller = cast(Any, _retried_call).retry
+ monkeypatch.setattr(controller, "sleep", lambda *_: None)
+ with fake_environment(Scenario(mode="stall")):
+ assert controller.sleep is time.sleep
+ assert controller.sleep is not time.sleep
+
+
+def read_baseline() -> dict[str, str]:
+ entries: dict[str, str] = {}
+ for line in BASELINE_PATH.read_text().splitlines():
+ if line.strip():
+ name, status = line.split(" ", 1)
+ entries[name] = status
+ return entries
+
+
+def _status_of(name: str) -> SourceStatus:
+ if name in SHARED_PATHS:
+ verdict = check_extraction(SHARED_PATHS[name], ["rows"])
+ status = f"fail:{','.join(sorted(verdict.failed))}" if verdict.failed else "pass"
+ return SourceStatus(status=status, safe_point_exercised=verdict.safe_point_exercised)
+ return check_source(IMPLEMENTED_SOURCES[name])
+
+
+# A source that sets its timeouts still runs the retry code of these shared paths. While a path
+# fails a budget, no source on it can pass that budget, so a new source may fail it too.
+PATHS_THAT_SET_A_TIMEOUT = ("shared-path:rest-framework-resource-with-timeout", "shared-path:tracked-session")
+INHERITABLE_CONDITIONS = {STALL_BUDGET, RATE_LIMIT_BUDGET}
+
+
+def _conditions(status: str) -> set[str]:
+ return set(status[len("fail:") :].split(",")) if status.startswith("fail:") else set()
+
+
+def matches_baseline(name: str, status: str, baseline: dict[str, str]) -> bool:
+ if name in baseline:
+ return status == baseline[name]
+ shared_failures = set[str]().union(*(_conditions(baseline.get(path, "pass")) for path in PATHS_THAT_SET_A_TIMEOUT))
+ inherited = INHERITABLE_CONDITIONS & shared_failures
+ return status == "pass" or (status.startswith("fail:") and _conditions(status) <= inherited)
+
+
+SHARED_CODE_FAILS_BUDGETS = dict.fromkeys(PATHS_THAT_SET_A_TIMEOUT, "fail:rate-limit-budget,stall-budget")
+RATCHET_CASES = [
+ ("recorded_failure_that_is_unchanged", "Old", "fail:timeout", {"Old": "fail:timeout"}, True),
+ ("recorded_failure_that_now_passes_must_leave_the_file", "Old", "pass", {"Old": "fail:timeout"}, False),
+ ("recorded_failure_that_got_shorter_must_change", "Old", "fail:timeout", {"Old": "fail:safe-point,timeout"}, False),
+ ("recorded_failure_that_got_longer", "Old", "fail:safe-point,timeout", {"Old": "fail:timeout"}, False),
+ ("new_source_that_passes", "New", "pass", {}, True),
+ ("new_source_with_no_timeout", "New", "fail:timeout", SHARED_CODE_FAILS_BUDGETS, False),
+ ("new_source_that_is_not_checkable_needs_an_entry", "New", "not-checkable:schemas", {}, False),
+ (
+ "new_source_that_fails_a_budget_the_shared_code_fails",
+ "New",
+ "fail:stall-budget",
+ SHARED_CODE_FAILS_BUDGETS,
+ True,
+ ),
+ ("new_source_that_fails_a_budget_the_shared_code_meets", "New", "fail:stall-budget", {}, False),
+ (
+ "new_source_with_no_safe_point",
+ "New",
+ "fail:rate-limit-budget,safe-point",
+ SHARED_CODE_FAILS_BUDGETS,
+ False,
+ ),
+]
+
+
+ ("name", "status", "baseline", "expected"), [case[1:] for case in RATCHET_CASES], ids=[c[0] for c in RATCHET_CASES]
+)
+def test_ratchet_rule(name: str, status: str, baseline: dict[str, str], expected: bool) -> None:
+ assert matches_baseline(name, status, baseline) is expected
+
+
+_observed: dict[str, SourceStatus] = {}
+
+
[email protected](scope="module", autouse=True)
+def _write_baseline_when_asked() -> Iterator[None]:
+ yield
+ if not os.environ.get(WRITE_BASELINE_VARIABLE):
+ return
+ lines = [f"{name} {result.status}" for name, result in sorted(_observed.items()) if result.status != "pass"]
+ BASELINE_PATH.write_text("\n".join(lines) + "\n")
+
+ sources = {name: result for name, result in _observed.items() if name in IMPLEMENTED_SOURCES}
+ checked = {name: result for name, result in sources.items() if not result.status.startswith("not-checkable")}
+ counts = Counter(
+ part
+ for result in sources.values()
+ for part in (
+ [f"fail:{condition}" for condition in result.status[5:].split(",")]
+ if result.status.startswith("fail:")
+ else [result.status]
+ )
+ )
+ exercised = sum(result.safe_point_exercised for result in checked.values())
+ summary = [
+ f"{BASELINE_PATH.name} written: {len(lines)} entries for {len(sources)} sources with extraction code",
+ f" checked: {len(checked)}, of which {exercised} made enough requests to exercise the safe-point condition",
+ *(f" {count:4d} {status}" for status, count in sorted(counts.items())),
+ ]
+ sys.stdout.write("\n".join(summary) + "\n")
+
+
[email protected]("name", [*SHARED_PATHS, *sorted(IMPLEMENTED_SOURCES)])
+def test_source_meets_the_contract_or_matches_the_baseline(name: str) -> None:
+ result = _status_of(name)
+ _observed[name] = result
+ if os.environ.get(WRITE_BASELINE_VARIABLE):
+ return
+
+ baseline = read_baseline()
+ recorded = baseline.get(name, "pass")
+ detail = f" The attempt ended with: {result.detail}" if result.detail else ""
+ assert matches_baseline(name, result.status, baseline), (
+ f"{name}: the contract check gives `{result.status}`, and {BASELINE_PATH.name} records `{recorded}`.\n"
+ "`fail:timeout`: a request has no read timeout, so a stalled server holds the worker without limit. "
+ "Set `request_timeout` in the REST client config, or pass `timeout=` to each session call.\n"
+ "`fail:stall-budget`: one request and its retries can wait more than "
+ "5 minutes for a server that never answers. Lower the timeout or the retry count.\n"
+ "`fail:rate-limit-budget`: one request can wait more than 5 minutes after a 429 with a large "
+ "`Retry-After`. Cap the wait, and fail the attempt when the cap is not enough.\n"
+ "`fail:safe-point`: more than 3 requests in a row gave no yield and no safe point, so the pipeline "
+ "cannot stop the run on empty pages. Return the framework resource itself as `SourceResponse.items`, "
+ "or call `ResumableSourceManager.safe_point()` after each request. The pipeline gives safe points only "
+ "to a `ResumableSource`, so a source that pages through an endpoint must be one.\n"
+ "`not-checkable:*`: the fake HTTP server could not drive this source. A new source that uses a "
+ "driver or an SDK needs a reviewed entry in the baseline, with the deadlines stated in the pull request."
+ f"{detail}\n"
+ "A new source must pass. Do not add a `fail` entry for it. One exception: while the baseline "
+ f"lists a budget failure for {' or '.join(PATHS_THAT_SET_A_TIMEOUT)}, a new source may fail that "
+ "budget, because the shared retry code decides it.\n"
+ f"When a source improved, the file must record that too. Run: {REGENERATE}"
+ )
+
+
+def test_baseline_lists_only_known_names() -> None:
+ unknown = sorted(set(read_baseline()) - set(IMPLEMENTED_SOURCES) - set(SHARED_PATHS))
+ assert not unknown, f"{BASELINE_PATH.name} lists names that are not implemented sources. Run: {REGENERATE}"