:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(data-warehouse): keep github request pacing during the shutdown grace (#123421)
Tom Owers606999b5550d
diff --git a/posthog/test/repo_invariants/source_raw_sleep_baseline.txt b/posthog/test/repo_invariants/source_raw_sleep_baseline.txtindex 815a1ee63d32..dee5b83d1080 100644--- a/posthog/test/repo_invariants/source_raw_sleep_baseline.txt+++ b/posthog/test/repo_invariants/source_raw_sleep_baseline.txt@@ -10,7 +10,6 @@ databricks/databricks.py::_connect_with_transient_retrydecagon/decagon.py::RequestThrottle.waitdixa/dixa.py::_iter_export_windowsfullstory/fullstory.py::_wait_for_export-github/github.py::_pace_before_requestgladly/gladly.py::_report_rowsgoogle_ads/google_ads.py::_backoff_sleepgoogle_analytics/google_analytics.py::_backoff_sleepdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/github.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/github.pyindex 2400c022cebf..fd59c1960c8c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/github/github.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/github.py@@ -16,7 +16,6 @@ from asgiref.sync import async_to_syncfrom dateutil import parser as dateutil_parserfrom prometheus_client import Counterfrom structlog.types import FilteringBoundLogger-from temporalio import activityfrom tenacity import RetryCallState, retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitterfrom urllib3.util.retry import Retry@@ -38,6 +37,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.basWebhookSyncResult,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.interruptible_wait import (+ interruptible_wait,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.webhook_s3 import WebhookSourceManager@@ -916,10 +918,10 @@ def _pace_before_request(installation_id: str, logger: FilteringBoundLogger) ->inside the budget instead of recovering from it, and leaves the headroom the budget reserves forthe interactive products that share this installation.- The wait is bounded by the worker drain signal rather than by sleep. The pipeline tests for- worker shutdown only between the chunks a source yields, so a plain sleep here would hold a- draining pod for the full wait and delay the hand-off by that much. Waiting on the shutdown event- returns as soon as the pod starts draining, so pacing costs the hand-off nothing.+ The wait ends when the pipeline's hand-off gate says to stop. The pipeline tests for worker+ shutdown only between the chunks a source yields, so a plain sleep here would hold a draining pod+ for the full wait and delay the hand-off by that much. The gate stays closed during the shutdown+ grace, so pacing continues while the run still has time to finish."""# The same ceiling the Retry-After path honors, and safe here for the reason recorded on# GITHUB_MAX_RETRY_AFTER_SECONDS: this runs in the source thread pool, while the activity's@@ -931,10 +933,7 @@ def _pace_before_request(installation_id: str, logger: FilteringBoundLogger) ->returnlogger.debug(f"Github: waiting {pace:.1f}s for egress budget before the next request")- if activity.in_activity():- activity.wait_for_worker_shutdown_sync(timeout=pace)- else:- time.sleep(pace)+ interruptible_wait(pace)def _is_unmapped_client_status(status_code: int) -> bool:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_fetch_page.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_fetch_page.pyindex 5a1be6620545..d6d54c506094 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_fetch_page.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_fetch_page.py@@ -15,6 +15,7 @@ from posthog.egress.github.limiter import GitHubRateResourcefrom posthog.egress.limiter.policies import Priorityfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.base import error_message_matches+from products.warehouse_sources.backend.temporal.data_imports.sources.common.safe_point import activate_safe_pointfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (DriveResult,Script,@@ -287,47 +288,55 @@ def test_fetch_page_waits_for_egress_budget_before_asking_for_it(installation_idwith (mock.patch.object(github, "github_installation_pace_seconds", return_value=pace) as pace_for,- mock.patch.object(github, "activity") as temporal_activity,+ mock.patch.object(github, "interruptible_wait") as wait,mock.patch.object(GithubSource, "_egress_identity", return_value=identity),):- temporal_activity.in_activity.return_value = Trueresult = _drive("issues", [ScriptedResponse(json=[])])assert result.raised is None- expected_waits = [] if expected_wait is None else [mock.call(timeout=expected_wait)]- assert temporal_activity.wait_for_worker_shutdown_sync.call_args_list == expected_waits+ expected_waits = [] if expected_wait is None else [mock.call(expected_wait)]+ assert wait.call_args_list == expected_waitsassert pace_for.called is (installation_id is not None)assert result.paths == ["/repos/o/r/issues"]@pytest.mark.parametrize(- "in_activity,expect_drain_wait,expect_sleep",+ "clock_at_signal,expected_sleeps",[- (True, True, False),- # Outside an activity there is no worker to drain, so a plain sleep is the whole behavior.- (False, False, True),+ # The signal comes after the wait ends, so the wait takes its full length.+ (100.0, [1.0] * 5),+ # The signal comes in the middle of the wait, which is the end of the shutdown grace.+ (3.0, [1.0] * 3),+ # The signal came before the wait, so the wait returns at once.+ (0.0, []),],)-def test_fetch_page_budget_wait_yields_to_a_draining_worker(in_activity, expect_drain_wait, expect_sleep):- # The pipeline tests for worker shutdown only between the chunks a source yields, so a wait that- # slept would hold a draining pod for its full duration and delay the hand-off by that much.- # Waiting on the shutdown event returns the moment the pod starts draining. Nothing about the- # sync looks wrong when this regresses; drains just get slower.+def test_fetch_page_budget_wait_holds_during_the_shutdown_grace_and_ends_after_it(clock_at_signal, expected_sleeps):+ # The signal is the hand-off gate, which stays false for the whole grace. A wait on the raw worker+ # shutdown event returned at the SIGTERM instead, so imports skipped their pacing during the grace.session = mock.Mock()session.request.return_value = _ok_response()identity = github.GithubEgressIdentity(installation_id="123")+ clock = {"now": 0.0}+ sleeps: list[float] = []++ def fake_sleep(seconds: float) -> None:+ sleeps.append(seconds)+ clock["now"] += secondswith (- mock.patch.object(github, "github_installation_pace_seconds", return_value=30.0),- mock.patch.object(github, "activity") as temporal_activity,- mock.patch.object(github.time, "sleep") as sleep,+ mock.patch.object(github, "github_installation_pace_seconds", return_value=5.0),mock.patch.object(github, "make_tracked_session", return_value=session),+ mock.patch("time.sleep", side_effect=fake_sleep),+ activate_safe_point(+ lambda: None,+ covers_framework_checkpoints=False,+ is_shutting_down=lambda: clock["now"] >= clock_at_signal,+ ),):- temporal_activity.in_activity.return_value = in_activitygithub._fetch_page("https://api.github.com/repos/o/r/issues", {}, mock.Mock(), identity)- assert temporal_activity.wait_for_worker_shutdown_sync.called is expect_drain_wait- assert sleep.called is expect_sleep+ assert sleeps == expected_sleepsdef _error_response(status_code: int, message: str, headers: dict[str, str] | None = None) -> mock.Mock: