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 ratchet on resume state saved after a yield (#112727)

Tom Owersb5245a231c8b
diff --git a/.agents/skills/implementing-warehouse-sources/SKILL.md b/.agents/skills/implementing-warehouse-sources/SKILL.md
index fb1478737d64..e9c24be3b22f 100644
--- a/.agents/skills/implementing-warehouse-sources/SKILL.md
+++ b/.agents/skills/implementing-warehouse-sources/SKILL.md
@@ -900,6 +900,7 @@ After changing source fields, re-run `pnpm run generate:source-configs` and `hog
- Endless retries for bad credentials: missing `get_non_retryable_errors`.
- Source won't connect despite a valid token: `validate_credentials(schema_name=None)` probes every resource's scope instead of just the token, so one missing scope — often on a table the user won't sync — blocks the whole source. Probe only the token at create; report per-table scope via `get_endpoint_permissions`.
- Resumable state never saved: forgot to call `save_state`; or called `commit()` on a cursor that covers rows the pipeline has not written yet, which skips them on resume.
+- Resumable state saved after the `yield` it covers: a hand-off loses the state of the last batch, so the next attempt reads that batch again. `posthog/test/repo_invariants/test_resume_state_staged_before_yield.py` fails on a new generator that does this in a loop. Its baseline lists the existing ones and may only get shorter.
- A deploy waits hours on a resumable source: it pages through responses with no rows and never calls `manager.safe_point()`, so it never sees the worker shutdown.
- Webhook rows not landing: schema `is_webhook=False`, or `initial_sync_complete=False`.
- Dependent resource path `KeyError`: pre-format static path placeholders (see Fan-out).
diff --git a/posthog/test/repo_invariants/resume_state_after_yield_baseline.txt b/posthog/test/repo_invariants/resume_state_after_yield_baseline.txt
new file mode 100644
index 000000000000..46ea6f1626a8
--- /dev/null
+++ b/posthog/test/repo_invariants/resume_state_after_yield_baseline.txt
@@ -0,0 +1,413 @@
+acculynx/acculynx.py::_job_pages
+acculynx/acculynx.py::_pages
+adjust/adjust.py::get_rows
+adobe_analytics/adobe_analytics.py::_metadata_batches
+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_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
+anvil/anvil.py::_get_parent_paged_rows
+apollo/apollo.py::get_rows
+app_store_connect/app_store_connect.py::_get_analytics_report
+app_store_connect/app_store_connect.py::_get_app_fanout
+app_store_connect/app_store_connect.py::_get_collection
+app_store_connect/app_store_connect.py::_get_sales_report
+appdynamics/appdynamics.py::_get_windowed_application_rows
+appdynamics/appdynamics.py::get_rows
+appfigures/appfigures.py::_iter_aso
+appfigures/appfigures.py::_iter_aso_stats
+appfigures/appfigures.py::_iter_paged
+appfigures/appfigures.py::_iter_ranks
+appfigures/appfigures.py::_iter_report
+appfollow/appfollow.py::_get_app_fanout
+appfollow/appfollow.py::_get_ratings
+appfollow/appfollow.py::_get_reviews
+apple_search_ads/apple_search_ads.py::_iter_rows
+applovin/applovin.py::get_rows
+appsignal/appsignal.py::_get_incident_rows
+appsignal/appsignal.py::_get_log_line_rows
+appsignal/appsignal.py::_get_metric_timeseries_rows
+appsignal/appsignal.py::_get_performance_trace_rows
+appsignal/appsignal.py::_get_slow_event_action_rows
+appsignal/appsignal.py::_get_trace_span_rows
+appsignal/appsignal.py::_get_windowed_rows
+appsignal/appsignal.py::_walk_aggregate_windows
+ashby/ashby.py::_fanned_out_pages
+automox/automox.py::_iter_fan_out_rows
+automox/automox.py::get_rows
+aviator/aviator.py::_get_fan_out_rows
+awin/awin.py::get_rows
+aws_budgets/aws_budgets.py::_budget_rows
+aws_budgets/aws_budgets.py::_fanout_rows
+aws_cost_anomaly_detection/aws_cost_anomaly_detection.py::get_rows
+aws_cost_explorer/aws_cost_explorer.py::get_rows
+aws_guardduty/aws_guardduty.py::get_rows
+aws_organizations/aws_organizations.py::_checkpointed_rows
+aws_ses/aws_ses.py::_walk_pages
+azure_cost_management/azure_cost_management.py::get_rows
+azure_devops/azure_devops.py::get_rows
+bettermode/bettermode.py::_fan_out_rows
+bettermode/bettermode.py::_get_post_reaction_participant_rows
+bettermode/bettermode.py::get_rows
+bill_com/bill_com.py::get_rows
+bing_ads/utils.py::fetch_data_in_yearly_chunks
+bitbucket/bitbucket.py::_get_fan_out_rows
+bitbucket/bitbucket.py::_get_second_level_fan_out_rows
+bitbucket/bitbucket.py::_get_top_level_rows
+braintree/braintree.py::get_rows
+bugsnag/bugsnag.py::_iter_fan_out
+bugsnag/bugsnag.py::_iter_top_level
+buildbetter/buildbetter.py::_make_paginated_request
+care_quality_commission/care_quality_commission.py::_iter_endpoint_rows
+chatwoot/chatwoot.py::_get_member_rows
+chatwoot/chatwoot.py::_get_message_rows
+chatwoot/chatwoot.py::_get_reporting_event_rows
+chatwoot/chatwoot.py::get_rows
+checkmarx/checkmarx.py::_get_fan_out_rows
+checkmarx/checkmarx.py::get_rows
+checkout_com/payments.py::_get_rows
+checkout_com/reports.py::_report_file_rows
+circleci/circleci.py::get_rows
+circleci_insights/circleci_insights.py::_project_workflow_fan_out_rows
+circleci_insights/circleci_insights.py::_project_workflow_metrics_rows
+circleci_insights/circleci_insights.py::_project_workflow_object_fan_out_rows
+circleci_insights/circleci_insights.py::get_rows
+cisco_duo/cisco_duo.py::_get_fanout_v1_rows
+cisco_duo/cisco_duo.py::_get_list_v1_rows
+cisco_duo/cisco_duo.py::_get_log_v1_rows
+cisco_duo/cisco_duo.py::_get_log_v2_rows
+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
+codecov/codecov.py::_get_fan_out_rows
+codecov/codecov.py::_get_top_level_rows
+cody/cody.py::_get_windowed_rows
+coin_api/coin_api.py::_get_timeseries_rows
+coingecko/coingecko.py::_chart_pages
+coinmarketcap/coinmarketcap.py::get_batch_rows
+coinmarketcap/coinmarketcap.py::get_snapshot_rows
+commercetools/commercetools.py::get_rows
+concord/concord.py::_iter_agreement_fanout
+concord/concord.py::_iter_events_windows
+concord/concord.py::_iter_offset
+concord/concord.py::_iter_page
+confluent_cloud/confluent_cloud.py::_iter_metrics_rows
+convex/convex.py::data_sync
+convex/convex.py::list_snapshot
+copper/copper.py::_iter_related_items
+coralogix/coralogix.py::get_rows
+coupa/coupa.py::get_rows
+coveralls/coveralls.py::get_builds_rows
+cronitor/cronitor.py::_get_invocation_rows
+cronitor/cronitor.py::_get_metric_rows
+cronitor/cronitor.py::_get_paginated_rows
+cronitor/cronitor.py::_get_site_error_rows
+crossref/crossref.py::get_rows
+cursor/cursor.py::_get_spend_rows
+cursor/cursor.py::_paginate_window
+customerly/customerly.py::_get_article_rows
+dagster_cloud/dagster_cloud.py::_iter_fanout_rows
+dagster_cloud/dagster_cloud.py::_iter_insights_rows
+dagster_cloud/dagster_cloud.py::_make_paginated_request
+dataforseo/dataforseo.py::get_rows
+datahub/datahub.py::get_rows
+dbt/dbt.py::_iter_discovery_rows
+dbt/dbt.py::_iter_run_fanout_rows
+dbt/dbt.py::get_rows
+deel/deel.py::_gross_to_net_items
+deepsource/deepsource.py::_fan_out_connection_rows
+deepsource/deepsource.py::_per_repository_object_rows
+deepsource/deepsource.py::_repositories_rows
+deepsource/deepsource.py::_root_connection_rows
+descope/descope.py::_user_history_rows
+dixa/dixa.py::_fan_out_rows
+dixa/dixa.py::get_rows
+dockerhub/dockerhub.py::_audit_log_pages
+dockerhub/dockerhub.py::_cursor_pages
+dockerhub/dockerhub.py::_tag_pages
+docusign/docusign.py::get_rows
+doppler/doppler.py::_get_fan_out_rows
+doppler/doppler.py::get_rows
+dropbox_sign/dropbox_sign.py::get_rows
+dynamodb/dynamodb.py::get_rows
+easypost/easypost.py::get_rows
+ecb_data_portal/ecb_data_portal.py::ecb_data_portal_source._items
+etsy/etsy.py::_offset_pages
+etsy/etsy.py::_windowed_pages
+everhour/everhour.py::get_rows
+exchange_rates_api/exchange_rates_api.py::get_rows
+expo/expo.py::get_rows
+fastly/fastly.py::_get_json_api_rows
+fastly/fastly.py::_get_service_list_rows
+fastly/fastly.py::_iter_billing_pages
+fastly/fastly.py::_iter_services_from_bookmark
+featurebase/featurebase.py::_get_fan_out_rows
+featurebase/featurebase.py::_get_top_level_rows
+financial_modelling/financial_modelling.py::get_rows
+fintoc/fintoc.py::FintocAPI.rows
+firebase/firebase.py::iter_auth_users
+firebase/firebase.py::iter_firestore_collection_group
+firebase/firebase.py::iter_firestore_documents
+firebase/firebase.py::iter_firestore_documents_incremental
+firebase/firebase.py::iter_realtime_database
+fireworks_ai/fireworks_ai.py::_iter_usage_windows
+flagsmith/flagsmith.py::_paginate_resource
+float_app/float_app.py::_report_window_pages
+formbricks/formbricks.py::get_rows
+fred/fred.py::get_rows
+freshsales/freshsales.py::_get_paginated_fanout_rows
+freshsales/freshsales.py::get_rows
+freshservice/freshservice.py::_approvals_source.items
+frill/frill.py::_comment_rows
+frill/frill.py::get_rows
+g2/g2.py::get_rows
+gainsight_cs/gainsight_cs.py::gainsight_cs_source.items
+gainsight_px/gainsight_px.py::_event_pages
+gcore/gcore.py::_statistics
+gerrit/gerrit.py::get_rows
+gitea/gitea.py::_get_fan_out_rows
+gitea/gitea.py::get_rows
+gitguardian/gitguardian.py::get_rows
+github/github.py::_fan_out_get_rows
+github/github.py::get_rows
+gitlab/gitlab.py::get_rows
+gladly/gladly.py::_report_rows
+gladly/gladly.py::get_rows
+gnews/gnews.py::get_rows
+gong/gong.py::_iter_windowed_rows
+google_ads/google_ads.py::_search_as_arrow_tables
+google_analytics/google_analytics.py::google_analytics_source.get_rows
+google_play_console/google_play_console.py::_iter_list_rows
+google_play_console/google_play_console.py::_iter_metric_set_rows
+google_search_console/google_search_console.py::google_search_console_source.get_rows
+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::get_rows
+harvey/harvey.py::_get_audit_log_rows
+harvey/harvey.py::_get_history_rows
+harvey/harvey.py::_get_project_fan_out_rows
+harvey/harvey.py::_get_vault_project_rows
+hatchet/hatchet.py::get_rows
+healthchecks/healthchecks.py::_get_fan_out_rows
+helicone/helicone.py::_prompts_rows
+helicone/helicone.py::_requests_rows
+helicone/helicone.py::_sessions_rows
+honeybadger/honeybadger.py::_get_nested_rows
+honeybadger/honeybadger.py::_get_project_child_rows
+honeybadger/honeybadger.py::_get_project_rows
+honeycomb/honeycomb.py::_iter_board_views
+honeycomb/honeycomb.py::_iter_fan_out
+hubspot/hubspot.py::get_rows
+hyperspell/hyperspell.py::_get_list_rows
+hyperspell/hyperspell.py::get_rows
+impact/impact.py::_get_rows_fanout
+impact/impact.py::_get_rows_nested
+impact/impact.py::_get_rows_simple
+impact_partner/impact_partner.py::_get_rows_simple
+impact_partner/impact_partner.py::_get_rows_windowed
+infisical/infisical.py::_get_audit_log_rows
+infisical/infisical.py::_get_offset_paginated_rows
+inngest/inngest.py::_get_event_rows
+inngest/inngest.py::_get_function_run_rows
+instagram/instagram.py::_account_insight_rows
+instagram/instagram.py::_fanout_rows
+instagram/instagram.py::_media_rows
+instana/instana.py::_get_event_rows
+instana/instana.py::_get_metric_rows
+instana/instana.py::_get_offset_rows
+instana/instana.py::_get_paged_rows
+intercom/intercom.py::_company_segments_generator
+jamf_pro/jamf_pro.py::get_rows
+jellyfish/jellyfish.py::_get_fan_out_rows
+jellyfish/jellyfish.py::_get_month_windowed_rows
+jenkins/jenkins.py::_get_build_rows
+jumpcloud/jumpcloud.py::_get_event_rows
+jumpcloud/jumpcloud.py::_get_rest_rows
+klaus/klaus.py::_iter_endpoint_pages
+klaus/klaus.py::_iter_fanout_pages
+klaviyo/klaviyo.py::_get_fan_out_rows
+klaviyo/klaviyo.py::get_rows
+kong_konnect/kong_konnect.py::get_rows
+kubecost/kubecost.py::get_rows
+lacework/lacework.py::get_rows
+langfuse/langfuse.py::get_rows
+langsmith/langsmith.py::_emit_batches
+linear/linear.py::_make_paginated_request
+linearb/linearb.py::_iter_list_rows
+linkedin_ads/linkedin_ads.py::linkedin_ads_source.get_rows
+linkrunner/linkrunner.py::_get_attributed_user_rows
+linkrunner/linkrunner.py::_get_list_rows
+llama_cloud/llama_cloud.py::get_rows
+lob/lob.py::get_rows
+logz_io/logz_io.py::_iter_scroll_rows
+luma/luma.py::_get_fan_out_rows
+luma/luma.py::_get_top_level_rows
+mailgun/mailgun.py::get_rows
+marketo/marketo.py::_asset_offset_rows
+marketo/marketo.py::_bulk_rows
+marketo/marketo.py::_rest_token_rows
+matomo/matomo.py::get_rows
+mention/mention.py::_alert_rows
+mention/mention.py::_alert_tag_rows
+mention/mention.py::_mention_rows
+meta_ads/meta_ads.py::_iter_simple_pagination
+metaplane/metaplane.py::_get_evaluation_rows
+meteostat/meteostat.py::_get_rows
+mistral_ai/mistral_ai.py::get_rows
+mixpanel/mixpanel.py::_iter_engage
+mixpanel/mixpanel.py::_iter_export
+monte_carlo/monte_carlo.py::_get_alert_rows
+monte_carlo/monte_carlo.py::_get_offset_rows
+monte_carlo/monte_carlo.py::_get_relay_rows
+nager_date/nager_date.py::_country_info_rows
+nager_date/nager_date.py::_next_public_holidays_rows
+nager_date/nager_date.py::_public_holidays_rows
+nebius_ai/nebius_ai.py::get_rows
+new_relic/new_relic.py::_get_event_rows
+new_york_times/new_york_times.py::_get_article_search_rows
+notion/notion.py::_page_fan_out
+notion/notion.py::_search_stream
+notion/notion.py::_users_stream
+npm_registry/npm_registry.py::_iter_downloads
+npm_registry/npm_registry.py::get_rows
+nuget/nuget.py::_get_catalog_event_rows
+nuget/nuget.py::_get_package_rows
+nuget/nuget.py::_get_package_version_rows
+octopus_deploy/octopus_deploy.py::_paginate
+octopus_deploy/octopus_deploy.py::get_rows
+okendo/okendo.py::okendo_source.items
+open_exchange_rates/open_exchange_rates.py::get_rows
+open_meteo/open_meteo.py::_rolling_rows
+open_meteo/open_meteo.py::_windowed_rows
+openrouter/openrouter.py::_get_activity_rows
+openrouter/openrouter.py::_get_offset_rows
+ortto/ortto.py::get_rows
+outbrain/outbrain.py::get_rows
+pabbly_subscriptions_billing/pabbly_subscriptions_billing.py::_iter_fan_out
+pabbly_subscriptions_billing/pabbly_subscriptions_billing.py::_iter_top_level
+packagist/packagist.py::get_rows
+pardot/pardot.py::get_rows
+payfit/payfit.py::_get_payslip_rows
+payfit/payfit.py::get_rows
+pendo/pendo.py::_iter_aggregation
+pendo/pendo.py::_iter_list_endpoint
+persona/persona.py::get_rows
+pinterest_ads/pinterest_ads.py::_iter_entity_rows
+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
+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
+profound/profound.py::_report_pages
+pulumi_cloud/pulumi_cloud.py::_get_audit_log_rows
+pulumi_cloud/pulumi_cloud.py::_get_deployment_rows
+pulumi_cloud/pulumi_cloud.py::_get_resource_rows
+pulumi_cloud/pulumi_cloud.py::_get_stack_rows
+pulumi_cloud/pulumi_cloud.py::_get_stack_update_rows
+pylon/pylon.py::_get_fan_out_rows
+pylon/pylon.py::_get_simple_rows
+pylon/pylon.py::_get_windowed_rows
+qualtrics/qualtrics.py::_iter_collection
+qualtrics/qualtrics.py::get_rows
+qualys_vmdr/qualys_vmdr.py::get_rows
+railway/railway.py::_get_fan_out_rows
+railway/railway.py::_get_top_level_rows
+render/render.py::_get_fan_out_rows
+render/render.py::_get_top_level_rows
+replicate/replicate.py::get_rows
+rokt_ads/rokt_ads.py::rokt_ads_source
+rollbar/rollbar.py::get_rows
+runpod/runpod.py::_iter_billing_rows
+sage_hr/sage_hr.py::_get_windowed_rows
+sage_hr/sage_hr.py::get_rows
+scaleway/scaleway.py::get_rows
+segment/segment.py::get_rows
+sentry/sentry.py::_iter_issue_tag_values_rows
+shippo/shippo.py::_paginate
+shippo/shippo.py::get_rows
+shopify/shopify.py::_make_paginated_shopify_request
+signoz/signoz.py::get_rows
+similarweb/similarweb.py::_paginated_rows
+singular/singular.py::_report_rows
+slack/slack.py::_channel_messages_generator
+smaily/smaily.py::_campaign_statistics_rows
+smaily/smaily.py::_list_rows
+smaily/smaily.py::_segment_subscriber_rows
+snapchat_ads/snapchat_ads.py::_iter_rows
+snowplow/snowplow.py::_get_failed_event_metric_rows
+snowplow/snowplow.py::_get_windowed_job_rows
+sonarqube/sonarqube.py::_iter_simple
+sonarqube/sonarqube.py::_iter_windowed_issues
+sonatype_nexus/sonatype_nexus.py::_get_repository_fanout_rows
+sonatype_nexus/sonatype_nexus.py::get_rows
+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
+squadcast/squadcast.py::_iter_cursor_pages
+squadcast/squadcast.py::_iter_incident_export_windows
+squadcast/squadcast.py::_iter_offset_pages
+squadcast/squadcast.py::get_rows
+square/square.py::get_rows
+squarespace/squarespace.py::get_rows
+statuscake/statuscake.py::_iter_history_rows
+statuscake/statuscake.py::get_rows
+stytch/stytch.py::_get_member_rows
+stytch/stytch.py::_get_search_rows
+stytch/stytch.py::_get_session_rows
+sumo_logic/sumo_logic.py::_get_collector_fan_out_rows
+sumo_logic/sumo_logic.py::_get_log_rows
+sumo_logic/sumo_logic.py::_get_offset_paginated_rows
+sumo_logic/sumo_logic.py::_get_token_paginated_rows
+swarmia/swarmia.py::get_rows
+taboola/taboola.py::get_rows
+tailscale/tailscale.py::_audit_log_rows
+tawk_to/tawk_to.py::_paged_property_rows
+tawk_to/tawk_to.py::get_rows
+teamcity/teamcity.py::_fan_out_rows
+teamcity/teamcity.py::_top_level_rows
+tenable_vulnerability_management/tenable_vulnerability_management.py::_get_export_rows
+terraform_cloud/terraform_cloud.py::_get_fan_out_rows
+terraform_cloud/terraform_cloud.py::_get_top_level_rows
+transistor/transistor.py::get_rows
+travis_ci/travis_ci.py::get_rows
+trigger_dev/trigger_dev.py::_iter_cursor_pages
+trunk_io/trunk_io.py::failing_tests
+twelve_data/twelve_data.py::twelve_data_rows
+ubidots/ubidots.py::get_rows
+ubidots/ubidots.py::get_values_rows
+ubidots/ubidots.py::get_values_rows_v2
+uk_companies_house/uk_companies_house.py::uk_companies_house_source
+unstructured/unstructured.py::get_rows
+uptimerobot/uptimerobot.py::_get_monitor_log_rows
+uptimerobot/uptimerobot.py::_get_response_time_rows
+uptimerobot/uptimerobot.py::_get_top_level_rows
+usersnap/usersnap.py::_get_feedback_rows
+vapi/vapi.py::_drain
+veracode/veracode.py::_iter_fan_out_rows
+veracode/veracode.py::_iter_top_level_rows
+vercel/vercel.py::get_rows
+weights_and_biases/weights_and_biases.py::_get_fan_out_rows
+weights_and_biases/weights_and_biases.py::_get_project_rows
+weights_and_biases/weights_and_biases.py::get_rows
+wikipedia_pageviews/wikipedia_pageviews.py::_get_rows
+wordpress/wordpress.py::get_rows
+writesonic/writesonic.py::_iter_config
+writesonic/writesonic.py::_iter_daily
+youtube_analytics/youtube_analytics.py::get_rows
+zenduty/zenduty.py::_paginate_fan_out
+zenduty/zenduty.py::_paginate_top_level
+zep/zep.py::_fan_out_message_rows
+zep/zep.py::_page_based_rows
+zoho_crm/zoho_crm.py::get_rows
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
new file mode 100644
index 000000000000..f3c3d27e44dd
--- /dev/null
+++ b/posthog/test/repo_invariants/test_resume_state_staged_before_yield.py
@@ -0,0 +1,255 @@
+"""Ratchet on warehouse sources that save resumable state after the `yield` it covers.
+
+The pipeline commits staged state right after it writes a batch, and on a worker shutdown it ends
+the attempt before control returns to the source. State saved after a `yield` is therefore lost for
+the last batch: the next attempt reads that batch again, and an attempt that writes one batch or
+fewer keeps no progress at all. The failure message says how to fix a reported function.
+"""
+
+import ast
+import warnings
+from pathlib import Path
+
+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__"}
+REGENERATE = "python posthog/test/repo_invariants/test_resume_state_staged_before_yield.py"
+
+FUNCTIONS = (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda)
+
+
+def _own_nodes(statement: ast.stmt) -> list[ast.AST]:
+ """The nodes of a statement, without the bodies of functions defined inside it.
+
+ A resume hook defined in a loop body runs when the framework calls it, not where it is written.
+ """
+ nodes: list[ast.AST] = []
+ stack: list[ast.AST] = [statement]
+ while stack:
+ node = stack.pop()
+ nodes.append(node)
+ stack.extend(child for child in ast.iter_child_nodes(node) if not isinstance(child, FUNCTIONS))
+ return nodes
+
+
+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 _loop_blocks(function: ast.FunctionDef | ast.AsyncFunctionDef) -> list[list[ast.stmt]]:
+ """Every statement block that runs once per loop iteration.
+
+ A save after the last `yield` of the whole walk is left alone: the generator ends right after
+ it, and the pipeline then commits the state with the rows it still holds.
+ """
+ blocks: list[list[ast.stmt]] = []
+ stack: list[tuple[ast.AST, bool]] = [(function, False)]
+ while stack:
+ node, in_loop = stack.pop()
+ for field in ("body", "orelse", "finalbody"):
+ block = getattr(node, field, None)
+ if not (isinstance(block, list) and block and isinstance(block[0], ast.stmt)):
+ continue
+ block_in_loop = in_loop or (field == "body" and isinstance(node, ast.For | ast.AsyncFor | ast.While))
+ if block_in_loop:
+ blocks.append(block)
+ stack.extend((statement, block_in_loop) for statement in block if not isinstance(statement, FUNCTIONS))
+ for field in ("handlers", "cases"):
+ stack.extend((child, in_loop) for child in getattr(node, field, None) or [])
+ return blocks
+
+
+def _saves_after_yield(function: ast.FunctionDef | ast.AsyncFunctionDef) -> 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
+ before it, which is the wanted order.
+ """
+ for block in _loop_blocks(function):
+ yielded = False
+ save_is_last = False
+ for statement in block:
+ if isinstance(statement, FUNCTIONS):
+ continue
+ if _yields(statement):
+ # A compound statement that holds both is judged by its own blocks.
+ yielded = True
+ save_is_last = False
+ elif yielded and _saves_state(statement):
+ save_is_last = True
+ if save_is_last:
+ return True
+ return False
+
+
+def _functions_in_source(source: str) -> list[str]:
+ tree = ast.parse(source)
+ names: list[str] = []
+
+ 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}"
+ if _saves_after_yield(child):
+ names.append(qualified)
+ visit(child, f"{qualified}.")
+ elif isinstance(child, ast.ClassDef):
+ visit(child, f"{prefix}{child.name}.")
+ else:
+ visit(child, prefix)
+
+ visit(tree, "")
+ return names
+
+
+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:
+ 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)
+ return sorted(set(found))
+
+
+# The 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 = [
+ (
+ "save_after_the_yield_is_reported",
+ "def rows(manager):\n for page in pages():\n yield page\n manager.save_state(page.cursor)\n",
+ ["rows"],
+ ),
+ (
+ "save_before_the_yield_is_the_wanted_order",
+ "def rows(manager):\n for page in pages():\n manager.save_state(page.cursor)\n yield page\n",
+ [],
+ ),
+ (
+ "conditional_save_after_the_yield_is_reported",
+ "def rows(manager):\n"
+ " for page in pages():\n"
+ " if page.rows:\n"
+ " yield page.rows\n"
+ " if page.cursor:\n"
+ " manager.save_state(page.cursor)\n",
+ ["rows"],
+ ),
+ (
+ "save_after_a_delegated_generator_is_reported",
+ "def rows(manager):\n"
+ " for window in windows():\n"
+ " yield from read(window)\n"
+ " manager.save_state(window.end)\n",
+ ["rows"],
+ ),
+ (
+ "save_between_two_yields_belongs_to_the_second",
+ "def rows(manager):\n"
+ " for page in pages():\n"
+ " yield page.header\n"
+ " manager.save_state(page.cursor)\n"
+ " yield page.rows\n",
+ [],
+ ),
+ (
+ "save_after_the_whole_walk_is_left_alone",
+ "def rows(manager):\n for page in pages():\n yield page\n manager.save_state(finished())\n",
+ [],
+ ),
+ (
+ "save_after_the_yield_inside_a_try_in_a_loop_is_reported",
+ "def rows(manager):\n"
+ " while True:\n"
+ " try:\n"
+ " yield fetch()\n"
+ " manager.save_state(cursor())\n"
+ " except StopIteration:\n"
+ " break\n",
+ ["rows"],
+ ),
+ (
+ "hook_defined_in_the_loop_is_not_a_save_in_the_loop",
+ "def rows(manager):\n"
+ " for window in windows():\n"
+ " yield from read(window)\n"
+ " def hook(state):\n"
+ " manager.save_state(state)\n",
+ [],
+ ),
+ (
+ "nested_function_is_reported_under_its_qualified_name",
+ "def source(manager):\n"
+ " def items():\n"
+ " for page in pages():\n"
+ " yield page\n"
+ " manager.save_state(page.cursor)\n"
+ " return items\n",
+ ["source.items"],
+ ),
+ (
+ "save_in_a_function_that_yields_nothing_is_left_alone",
+ "def checkpoint(manager, cursor):\n manager.save_state(cursor)\n",
+ [],
+ ),
+]
+
+
[email protected](DETECTION_CASES)
+def test_detection(_name: str, source: str, expected: list[str]) -> None:
+ assert _functions_in_source(source) == expected
+
+
+def read_baseline() -> list[str]:
+ return sorted(line for line in BASELINE_PATH.read_text().splitlines() if line.strip())
+
+
+def write_baseline(functions: list[str]) -> None:
+ BASELINE_PATH.write_text("\n".join(functions) + "\n")
+
+
+def test_resume_state_saved_after_a_yield_matches_the_baseline() -> None:
+ scanned = collect_functions()
+ recorded = read_baseline()
+ 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"{BASELINE_PATH.name} no longer matches the repo.\n"
+ "A '+' line is a source generator that calls `save_state` after the `yield` the state covers. "
+ "The pipeline commits staged state right after it writes a batch, and on a worker shutdown it "
+ "ends the attempt before control returns to the source. That state is lost for the last batch, "
+ "so the next attempt reads the batch again, and a full refresh appends it twice. "
+ "Call `save_state` before the `yield` of the batch it covers. "
+ "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__":
+ functions = collect_functions()
+ write_baseline(functions)
+ print(f"baseline written: {len(functions)} functions") # noqa: T201
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/jamf_pro/jamf_pro.py b/products/warehouse_sources/backend/temporal/data_imports/sources/jamf_pro/jamf_pro.py
index 026ce61d80fc..8d24f7917665 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/jamf_pro/jamf_pro.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/jamf_pro/jamf_pro.py
@@ -460,15 +460,15 @@ def _iter_endpoint_pages(
if not results:
break
+ total_count = data.get("totalCount")
+ has_more = total_count is None or (page + 1) * config.page_size < total_count
+ if has_more:
+ resumable_source_manager.save_state(resume_state(page + 1))
+
yield [shape(row) for row in results]
- total_count = data.get("totalCount")
- if total_count is not None and (page + 1) * config.page_size >= total_count:
+ if not has_more:
break
-
- # Save AFTER yielding (and only when more pages remain) so a crash re-yields the last
- # page rather than skipping it — merge dedupes on the primary key.
- resumable_source_manager.save_state(resume_state(page + 1))
page += 1
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/jfrog_artifactory/jfrog_artifactory.py b/products/warehouse_sources/backend/temporal/data_imports/sources/jfrog_artifactory/jfrog_artifactory.py
index 75c3f43a3efa..001753e8fec3 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/jfrog_artifactory/jfrog_artifactory.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/jfrog_artifactory/jfrog_artifactory.py
@@ -378,6 +378,39 @@ def _fetch_related(
yield rows
+def _yield_with_checkpoint(
+ rows: Iterator[list[dict[str, Any]]],
+ next_state: JfrogArtifactoryResumeConfig | None,
+ resumable_source_manager: ResumableSourceManager[JfrogArtifactoryResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ """Hold one batch so the next-page state is staged immediately before the last yield.
+
+ An `aql_related` page expands into zero or more related-row batches. Staging `next_state` as
+ soon as the parent page is read — before any of its related rows are yielded — can commit past
+ a page whose related rows are not all written yet. Staging it right after the last of those
+ batches yields, the pattern the resume-state ratchet forbids, can lose that batch on a worker
+ shutdown. Holding one batch back lets the state land immediately before the batch it allows a
+ resume to skip, exactly when every earlier row is safe to resume past.
+ """
+ try:
+ pending = next(rows)
+ except StopIteration:
+ if next_state is not None:
+ resumable_source_manager.save_state(next_state)
+ resumable_source_manager.safe_point()
+ return
+
+ for batch in rows:
+ yield pending
+ pending = batch
+
+ if next_state is not None:
+ resumable_source_manager.save_state(next_state)
+ yield pending
+ if next_state is not None:
+ resumable_source_manager.safe_point()
+
+
def _iter_aql_pages(
session: requests.Session,
base_url: str,
@@ -388,7 +421,14 @@ def _iter_aql_pages(
should_use_incremental_field: bool,
db_incremental_field_last_value: Any,
incremental_field: str | None,
-) -> Iterator[list[dict[str, Any]]]:
+) -> Iterator[tuple[list[dict[str, Any]], JfrogArtifactoryResumeConfig | None]]:
+ """Yield each AQL page alongside the resume state for the page after it.
+
+ The state is `None` on the last page: the generator ends right after it, and the pipeline then
+ commits whatever state the caller staged for the rows it still holds. A plain `aql` endpoint can
+ save and yield the state's page directly; an `aql_related` endpoint expands one page into
+ several related-row batches first, so it stages the state once all of them are yielded instead.
+ """
resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
if resume is not None and resume.next_offset:
offset = resume.next_offset
@@ -410,16 +450,17 @@ def _iter_aql_pages(
break
has_more = len(results) >= AQL_PAGE_SIZE
- yield [_strip_domain_prefix(item, config.aql_domain) for item in results]
+ next_state = (
+ JfrogArtifactoryResumeConfig(next_offset=offset + len(results), incremental_filter_value=filter_value)
+ if has_more
+ else None
+ )
+
+ yield [_strip_domain_prefix(item, config.aql_domain) for item in results], next_state
if not has_more:
break
offset += len(results)
- # Save AFTER yielding so a crash re-yields the last page rather than skipping it — merge
- # dedupes on the primary key.
- resumable_source_manager.save_state(
- JfrogArtifactoryResumeConfig(next_offset=offset, incremental_filter_value=filter_value)
- )
resumable_source_manager.safe_point()
@@ -471,18 +512,20 @@ def _iter_xray_violations(
break
has_more = len(violations) >= XRAY_PAGE_SIZE
+ if has_more:
+ page += 1
+ if (page - 1) * XRAY_PAGE_SIZE >= XRAY_MAX_SCROLL_ROWS:
+ restart_filter = _xray_restart_filter(violations[-1].get("created"), filter_value)
+ if restart_filter is not None:
+ filter_value, page = restart_filter, 1
+ resumable_source_manager.save_state(
+ JfrogArtifactoryResumeConfig(next_offset=page, incremental_filter_value=filter_value)
+ )
+
yield violations
if not has_more:
break
- page += 1
- if (page - 1) * XRAY_PAGE_SIZE >= XRAY_MAX_SCROLL_ROWS:
- restart_filter = _xray_restart_filter(violations[-1].get("created"), filter_value)
- if restart_filter is not None:
- filter_value, page = restart_filter, 1
- resumable_source_manager.save_state(
- JfrogArtifactoryResumeConfig(next_offset=page, incremental_filter_value=filter_value)
- )
resumable_source_manager.safe_point()
@@ -535,14 +578,21 @@ def get_rows(
)
if config.kind == "aql":
- yield from pages
+ for results, next_state in pages:
+ if next_state is not None:
+ resumable_source_manager.save_state(next_state)
+ yield results
return
- for parents in pages:
- for start in range(0, len(parents), config.aql_related_chunk_size):
- yield from _fetch_related(
+ for parents, next_state in pages:
+ related_batches = (
+ batch
+ for start in range(0, len(parents), config.aql_related_chunk_size)
+ for batch in _fetch_related(
session, base_url, access_token, config, parents[start : start + config.aql_related_chunk_size], logger
)
+ )
+ yield from _yield_with_checkpoint(related_batches, next_state, resumable_source_manager)
def jfrog_artifactory_source(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/jumpcloud/jumpcloud.py b/products/warehouse_sources/backend/temporal/data_imports/sources/jumpcloud/jumpcloud.py
index e005a8efec08..d5308d724bd8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/jumpcloud/jumpcloud.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/jumpcloud/jumpcloud.py
@@ -279,6 +279,31 @@ def _get_child_rows(
skip += len(rows)
+def _yield_with_checkpoint(
+ rows: Iterator[list[dict[str, Any]]],
+ next_state: JumpcloudResumeConfig | None,
+ resumable_source_manager: ResumableSourceManager[JumpcloudResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ """Hold one batch so the next-page state is staged immediately before the last yield."""
+ try:
+ pending = next(rows)
+ except StopIteration:
+ if next_state is not None:
+ resumable_source_manager.save_state(next_state)
+ resumable_source_manager.safe_point()
+ return
+
+ for batch in rows:
+ yield pending
+ pending = batch
+
+ if next_state is not None:
+ resumable_source_manager.save_state(next_state)
+ yield pending
+ if next_state is not None:
+ resumable_source_manager.safe_point()
+
+
def _get_fanout_rows(
session: requests.Session,
base_url: str,
@@ -306,23 +331,25 @@ def _get_fanout_rows(
if not parents:
break
- for parent in parents:
- parent_id = parent.get(parent_config.primary_key)
- if not parent_id:
- continue
- has_children = False
- for rows in _get_child_rows(session, base_url, config, str(parent_id), logger):
- has_children = True
- yield [{**row, parent_id_column: parent_id} for row in rows]
- if not has_children:
- resumable_source_manager.safe_point()
-
- if len(parents) < REST_PAGE_SIZE:
+ def page_rows(parent_page: list[dict[str, Any]] = parents) -> Iterator[list[dict[str, Any]]]:
+ for parent in parent_page:
+ parent_id = parent.get(parent_config.primary_key)
+ if not parent_id:
+ continue
+ has_children = False
+ for rows in _get_child_rows(session, base_url, config, str(parent_id), logger):
+ has_children = True
+ yield [{**row, parent_id_column: parent_id} for row in rows]
+ if not has_children:
+ resumable_source_manager.safe_point()
+
+ has_more = len(parents) >= REST_PAGE_SIZE
+ next_state = JumpcloudResumeConfig(skip=parent_skip + len(parents)) if has_more else None
+ yield from _yield_with_checkpoint(page_rows(), next_state, resumable_source_manager)
+
+ if not has_more:
break
-
parent_skip += len(parents)
- resumable_source_manager.save_state(JumpcloudResumeConfig(skip=parent_skip))
- resumable_source_manager.safe_point()
def _get_event_rows(