:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): add tracked gRPC transport for warehouse sources (#60439)
Tom Owers437e9d237ecf
diff --git a/.agents/skills/implementing-warehouse-sources/SKILL.md b/.agents/skills/implementing-warehouse-sources/SKILL.mdindex a5f215eb50da..9475eaf86ed3 100644--- a/.agents/skills/implementing-warehouse-sources/SKILL.md+++ b/.agents/skills/implementing-warehouse-sources/SKILL.md@@ -187,14 +187,33 @@ log line and OTel metric, and participates in opt-in sample capture.gspread `authorize(credentials, session=...)`, BigQuery via `AuthorizedSession` + `TrackedHTTPAdapter`),inject one. Reference patterns live in `stripe/stripe.py`, `google_sheets/google_sheets.py`, and`bigquery/bigquery.py`.-- For vendor SDKs with no injection seam (today: `bingads`, `linkedin-api`'s `RestliClient`, anything- pure-gRPC), add a `# nosemgrep: data-imports-http-transport-...` pragma with a one-line reason and record- the source as `⚠️ Vendor SDK` in `SOURCES.md`.+- For vendor SDKs with no injection seam (today: `bingads`, `linkedin-api`'s `RestliClient`), add a+ `# nosemgrep: data-imports-http-transport-...` pragma with a one-line reason and record the source as+ `⚠️ Vendor SDK` in `SOURCES.md`.+- gRPC SDKs are **not** exempt — they have their own tracked transport (see below).CI enforces this via `.semgrep/rules/data-imports-http-transport.yaml`. The rule bans direct `requests.Session()`,`requests.<verb>(...)`, and `httpx.Client/AsyncClient/<verb>` inside `sources/**`. Type-only imports(`from requests import Response`, `from requests.exceptions import HTTPError`) remain allowed.+## Outbound gRPC must go through the tracked gRPC transport++gRPC calls from `sources/**` ride client interceptors from+`posthog.temporal.data_imports.sources.common.grpc`, which attach the same `JobContext` labels to logs and+OTel metrics (`data_import_grpc_*`) and feed opt-in sample capture (protobuf → scrubbed JSON). Two seams:++- For SDKs that accept an `interceptors=` list (google-ads `GoogleAdsClient.get_service(...)`), pass+ `interceptors=tracked_interceptors(host)` on **every** `get_service` call — google-ads rebuilds the channel+ per call, so the interceptors must be re-supplied each time. Reference: `google_ads/google_ads.py`.+- For SDKs that accept a `channel=` / `transport=` (BigQuery Storage Read API), build the credential-bearing+ channel, wrap it with `make_tracked_channel(channel, host=...)`, then hand it to the transport. Reference:+ `bigquery/bigquery.py:bigquery_storage_read_client`.++CI enforces this via `.semgrep/rules/data-imports-grpc-transport.yaml`, which bans raw `grpc.*_channel(...)`+and direct `BigQueryReadClient(...)` / `GoogleAdsClient(...)` construction inside `sources/**` (outside the+`common/grpc/` package and the two reference source files). Operators arm sample capture with+`python manage.py warehouse_sources_capture_grpc_samples enable ...`.+## Updating SOURCES.md`posthog/temporal/data_imports/sources/SOURCES.md` is the inventory of every registered source, its@@ -210,7 +229,8 @@ whenever you:or move from `requests` to a vendor SDK. Update both the comm method and tracked-transport columns.Keep the entries alphabetical within each table. If you add a partially-tracked source, also append a-short "Notes on partially-tracked sources" entry explaining what blocks tracking (no SDK seam, gRPC, etc.).+short "Notes on partially-tracked sources" entry explaining what blocks tracking (e.g. a vendor SDK with no+session/interceptor seam).## Required coding conventionsdiff --git a/.semgrep/rules/data-imports-grpc-transport.py b/.semgrep/rules/data-imports-grpc-transport.pynew file mode 100644index 000000000000..ae06d223d2c3--- /dev/null+++ b/.semgrep/rules/data-imports-grpc-transport.py@@ -0,0 +1,106 @@+# Test cases for data-imports-grpc-transport rules.+# These fixtures are matched against the rule patterns by `pytest .semgrep/`.+# ruff: noqa: F401, F841, E501+#+# `paths.include` in the rule scopes the matchers to+# `posthog/temporal/data_imports/sources/**`, but for the test fixture the+# paths setting is ignored — semgrep applies the rule directly to this file.++import grpc+from grpc import RpcError, StatusCode++from google.ads.googleads.client import GoogleAdsClient+from google.cloud import bigquery_storage+from google.cloud.bigquery_storage import BigQueryReadClient+++# ============================================================+# Should flag: raw grpc channels+# ============================================================+++def bad_secure_channel():+ # ruleid: data-imports-grpc-transport-raw-channel+ return grpc.secure_channel("host:443", None)+++def bad_insecure_channel():+ # ruleid: data-imports-grpc-transport-raw-channel+ return grpc.insecure_channel("host:443")+++def bad_aio_secure_channel():+ # ruleid: data-imports-grpc-transport-raw-channel+ return grpc.aio.secure_channel("host:443", None)+++def bad_aio_insecure_channel():+ # ruleid: data-imports-grpc-transport-raw-channel+ return grpc.aio.insecure_channel("host:443")+++# ============================================================+# Should flag: BigQuery Storage read client+# ============================================================+++def bad_bq_read_client_qualified(credentials):+ # ruleid: data-imports-grpc-transport-bigquery-read-client+ return bigquery_storage.BigQueryReadClient(credentials=credentials)+++def bad_bq_read_client_bare(credentials):+ # ruleid: data-imports-grpc-transport-bigquery-read-client+ return BigQueryReadClient(credentials=credentials)+++# ============================================================+# Should flag: Google Ads client construction+# ============================================================+++def bad_google_ads_client(credentials):+ # ruleid: data-imports-grpc-transport-google-ads-client+ return GoogleAdsClient(credentials=credentials, developer_token="x")+++def bad_google_ads_load_from_dict(config):+ # ruleid: data-imports-grpc-transport-google-ads-client+ return GoogleAdsClient.load_from_dict(config)+++# ============================================================+# Should NOT flag: type and exception imports / handling+# ============================================================+++def ok_status_code_use(code: StatusCode) -> None:+ pass+++def ok_exception_handling():+ try:+ do_something()+ except RpcError:+ pass+++def do_something() -> None:+ pass+++# ============================================================+# Should NOT flag: the tracked transport (the supported paths)+# ============================================================+++def ok_tracked_channel(channel):+ from posthog.temporal.data_imports.sources.common.grpc import make_tracked_channel++ return make_tracked_channel(channel, host="host")+++def ok_tracked_interceptors(client):+ from posthog.temporal.data_imports.sources.common.grpc import tracked_interceptors++ return client.get_service("GoogleAdsService", interceptors=tracked_interceptors("host"))diff --git a/.semgrep/rules/data-imports-grpc-transport.yaml b/.semgrep/rules/data-imports-grpc-transport.yamlnew file mode 100644index 000000000000..1ff88942a312--- /dev/null+++ b/.semgrep/rules/data-imports-grpc-transport.yaml@@ -0,0 +1,107 @@+# Warehouse-source gRPC calls must go through the tracked gRPC transport so they+# participate in gRPC logging, metrics, and sample capture (see+# posthog/temporal/data_imports/sources/common/grpc/). Raw `grpc.secure_channel`+# / `grpc.insecure_channel` channels, and direct vendor gRPC-client construction,+# bypass the transport.+#+# Two supported seams:+# - SDKs that accept an `interceptors=` list (google-ads `get_service`):+# client.get_service("...", interceptors=tracked_interceptors(host))+# - SDKs that accept a `channel=` / `transport=` (BigQuery Storage):+# make_tracked_channel(create_channel(credentials=...), host=host)+#+# Type/exception imports from grpc remain allowed — only channel/client+# construction is banned.+rules:+ - id: data-imports-grpc-transport-raw-channel+ pattern-either:+ - pattern: grpc.secure_channel(...)+ - pattern: grpc.insecure_channel(...)+ - pattern: grpc.aio.secure_channel(...)+ - pattern: grpc.aio.insecure_channel(...)+ message: |+ Build the channel through the tracked gRPC transport instead of a raw+ `grpc.*_channel(...)`. Use `make_tracked_channel(channel, host=...)`+ from `posthog.temporal.data_imports.sources.common.grpc` so every RPC+ is logged, metered, and eligible for sample capture.++ If a vendor SDK forces a raw channel and exposes no interceptor seam,+ add `# nosemgrep: data-imports-grpc-transport-raw-channel` with a reason.+ languages: [python]+ severity: ERROR+ metadata:+ category: best-practice+ subcategory: audit+ confidence: HIGH+ paths:+ include:+ - '**/posthog/temporal/data_imports/sources/**'+ exclude:+ - '**/posthog/temporal/data_imports/sources/common/grpc/**'+ - '**/test/**'+ - '**/tests/**'+ - '**/test_*.py'++ - id: data-imports-grpc-transport-bigquery-read-client+ pattern-either:+ - pattern: bigquery_storage.BigQueryReadClient(...)+ - pattern: BigQueryReadClient(...)+ message: |+ Construct the BigQuery Storage read client through a tracked channel so+ its gRPC traffic is observed. Build the channel with+ `BigQueryReadGrpcTransport.create_channel(host=..., credentials=...)`,+ wrap it via `make_tracked_channel(channel, host=...)`, then pass it as+ `BigQueryReadGrpcTransport(channel=tracked)` to the client — see+ `bigquery/bigquery.py:bigquery_storage_read_client`.++ If you must construct it raw, add+ `# nosemgrep: data-imports-grpc-transport-bigquery-read-client` with a reason.+ languages: [python]+ severity: ERROR+ metadata:+ category: best-practice+ subcategory: audit+ confidence: HIGH+ paths:+ include:+ - '**/posthog/temporal/data_imports/sources/**'+ exclude:+ - '**/posthog/temporal/data_imports/sources/common/grpc/**'+ # bigquery.py constructs the client itself, but routes the channel+ # through make_tracked_channel — the enforced invariant there is the+ # tracked channel, not avoiding the constructor.+ - '**/posthog/temporal/data_imports/sources/bigquery/bigquery.py'+ - '**/test/**'+ - '**/tests/**'+ - '**/test_*.py'++ - id: data-imports-grpc-transport-google-ads-client+ pattern-either:+ - pattern: GoogleAdsClient(...)+ - pattern: GoogleAdsClient.load_from_dict(...)+ message: |+ The Google Ads client talks gRPC; route its service calls through the+ tracked transport by passing `interceptors=tracked_interceptors(host)`+ to every `client.get_service(...)` call — see+ `google_ads/google_ads.py`.++ If you must construct the client elsewhere, add+ `# nosemgrep: data-imports-grpc-transport-google-ads-client` with a reason.+ languages: [python]+ severity: ERROR+ metadata:+ category: best-practice+ subcategory: audit+ confidence: HIGH+ paths:+ include:+ - '**/posthog/temporal/data_imports/sources/**'+ exclude:+ - '**/posthog/temporal/data_imports/sources/common/grpc/**'+ # google_ads.py constructs the client but the enforced invariant is+ # passing tracked_interceptors(...) to get_service, not avoiding the+ # constructor (google-ads exposes no other seam).+ - '**/posthog/temporal/data_imports/sources/google_ads/google_ads.py'+ - '**/test/**'+ - '**/tests/**'+ - '**/test_*.py'diff --git a/posthog/management/commands/test/test_warehouse_sources_capture_grpc_samples.py b/posthog/management/commands/test/test_warehouse_sources_capture_grpc_samples.pynew file mode 100644index 000000000000..4dbe256c5f73--- /dev/null+++ b/posthog/management/commands/test/test_warehouse_sources_capture_grpc_samples.py@@ -0,0 +1,274 @@+import json+from io import StringIO++import pytest+from unittest.mock import MagicMock, patch++from django.core.management import call_command++from posthog.temporal.data_imports.sources.common.grpc.sampling import (+ CAPTURE_CONFIG_REDIS_KEY,+ CAPTURE_COUNTER_KEY_PREFIX,+)+from posthog.temporal.data_imports.sources.common.sample_scrub import CaptureConfig++COMMAND = "warehouse_sources_capture_grpc_samples"+++def fake_redis():+ """Minimal in-memory fake of the redis client surface the command uses."""+ store: dict[bytes, bytes] = {}+ ttls: dict[bytes, int] = {}++ client = MagicMock()++ def _set(key, value, ex=None):+ if isinstance(key, str):+ key = key.encode()+ if isinstance(value, str):+ value = value.encode()+ store[key] = value+ if ex is not None:+ ttls[key] = ex++ def _get(key):+ if isinstance(key, str):+ key = key.encode()+ return store.get(key)++ def _ttl(key):+ if isinstance(key, str):+ key = key.encode()+ return ttls.get(key, -1)++ def _delete(*keys):+ deleted = 0+ for k in keys:+ if isinstance(k, str):+ k = k.encode()+ if k in store:+ del store[k]+ ttls.pop(k, None)+ deleted += 1+ return deleted++ def _scan(cursor=0, match=None, count=200):+ if match is None:+ keys = list(store.keys())+ else:+ prefix = match.rstrip("*").encode() if isinstance(match, str) else match+ keys = [k for k in store.keys() if k.startswith(prefix)]+ return 0, keys++ client.set.side_effect = _set+ client.get.side_effect = _get+ client.ttl.side_effect = _ttl+ client.delete.side_effect = _delete+ client.scan.side_effect = _scan+ client._store = store++ with patch("posthog.management.commands.warehouse_sources_capture_grpc_samples.get_client", return_value=client):+ yield client+++def _run(*args: str) -> str:+ out = StringIO()+ call_command(COMMAND, *args, stdout=out)+ return out.getvalue()+++# ---------------------------------------------------------------------------+# enable+# ---------------------------------------------------------------------------+++def test_enable_writes_redis_key_with_ttl(fake_redis):+ output = _run("enable", "--source-type", "google_ads", "--limit", "10", "--ttl", "30m")++ raw = fake_redis._store.get(CAPTURE_CONFIG_REDIS_KEY.encode())+ assert raw is not None+ config = json.loads(raw)+ assert config["capture_id"]+ assert config["rules"][0]["source_type"] == "google_ads"+ assert config["rules"][0]["limit"] == 10+ assert fake_redis.set.call_args.kwargs["ex"] == 30 * 60+ assert "Capture enabled" in output+ assert "warehouse-sources-grpc-samples" in output+++def test_enable_defaults_filters_to_wildcard(fake_redis):+ _run("enable")+ raw = fake_redis._store.get(CAPTURE_CONFIG_REDIS_KEY.encode())+ rule = json.loads(raw)["rules"][0]+ assert rule["source_type"] == "*"+ assert rule["response_code"] == "*"+ assert rule["team_id"] == "*"+ assert rule["schema_id"] == "*"+++def test_enable_with_grpc_status_class(fake_redis):+ _run("enable", "--response-code", "resource_exhausted", "--limit", "5", "--ttl", "5m")+ raw = fake_redis._store.get(CAPTURE_CONFIG_REDIS_KEY.encode())+ rule = json.loads(raw)["rules"][0]+ assert rule["response_code"] == "resource_exhausted"+++ "ttl_str,expected_seconds",+ [+ ("30s", 30),+ ("5m", 5 * 60),+ ("2h", 2 * 60 * 60),+ ("1d", 86400),+ ("600", 600),+ ],+)+def test_enable_parses_ttl_units(fake_redis, ttl_str, expected_seconds):+ _run("enable", "--ttl", ttl_str)+ assert fake_redis.set.call_args.kwargs["ex"] == expected_seconds+++def test_enable_rejects_ttl_above_max(fake_redis):+ with pytest.raises(ValueError, match="exceeds max"):+ _run("enable", "--ttl", "48h")+++def test_enable_rejects_invalid_ttl(fake_redis):+ with pytest.raises(ValueError, match="invalid ttl"):+ _run("enable", "--ttl", "not-a-duration")+++def test_enable_supports_extra_rules(fake_redis):+ _run(+ "enable",+ "--source-type",+ "google_ads",+ "--limit",+ "100",+ "--ttl",+ "30m",+ "--rule",+ "source_type=bigquery,response_code=*,team_id=12,limit=10",+ "--rule",+ "source_type=google_ads,response_code=unavailable,limit=5",+ )++ raw = fake_redis._store.get(CAPTURE_CONFIG_REDIS_KEY.encode())+ rules = json.loads(raw)["rules"]+ assert len(rules) == 3+ assert rules[0]["source_type"] == "google_ads" and rules[0]["limit"] == 100+ assert rules[1]["source_type"] == "bigquery" and rules[1]["team_id"] == "12"+ assert rules[2]["response_code"] == "unavailable"+++def test_enable_pure_rule_flags_drop_implicit_wildcard_primary(fake_redis):+ """Driving capture purely via --rule must not prepend the all-wildcard primary.++ Otherwise (first-match-wins) the wildcard primary would shadow every targeted+ rule. Mirrors the multi-rule example in the command docstring.+ """+ _run(+ "enable",+ "--ttl",+ "1h",+ "--rule",+ "source_type=google_ads,response_code=resource_exhausted,limit=20",+ "--rule",+ "source_type=bigquery,response_code=*,team_id=12,limit=10",+ )++ raw = fake_redis._store.get(CAPTURE_CONFIG_REDIS_KEY.encode())+ rules = json.loads(raw)["rules"]+ assert len(rules) == 2+ assert rules[0]["source_type"] == "google_ads"+ assert rules[1]["source_type"] == "bigquery"+++def test_enable_keeps_primary_when_it_has_an_explicit_filter(fake_redis):+ """A primary with any explicit filter is kept alongside --rule entries."""+ _run(+ "enable",+ "--source-type",+ "google_ads",+ "--ttl",+ "1h",+ "--rule",+ "source_type=bigquery,limit=10",+ )+ raw = fake_redis._store.get(CAPTURE_CONFIG_REDIS_KEY.encode())+ rules = json.loads(raw)["rules"]+ assert len(rules) == 2+ assert rules[0]["source_type"] == "google_ads"+ assert rules[1]["source_type"] == "bigquery"+++def test_enable_extra_rule_inherits_default_limit(fake_redis):+ # No explicit primary filter + a --rule → the wildcard primary is dropped, so+ # the bigquery rule is the only rule and still inherits the --limit default.+ _run("enable", "--limit", "42", "--ttl", "30m", "--rule", "source_type=bigquery")+ raw = fake_redis._store.get(CAPTURE_CONFIG_REDIS_KEY.encode())+ rules = json.loads(raw)["rules"]+ assert len(rules) == 1+ assert rules[0]["source_type"] == "bigquery"+ assert rules[0]["limit"] == 42+++def test_enable_rejects_malformed_rule(fake_redis):+ with pytest.raises(ValueError, match="invalid rule fragment"):+ _run("enable", "--ttl", "30m", "--rule", "no-equals-sign")+++# ---------------------------------------------------------------------------+# disable+# ---------------------------------------------------------------------------+++def test_disable_clears_key_and_counters(fake_redis):+ config = CaptureConfig(capture_id="cap-7", rules=())+ fake_redis._store[CAPTURE_CONFIG_REDIS_KEY.encode()] = config.to_json().encode()+ fake_redis._store[f"{CAPTURE_COUNTER_KEY_PREFIX}:cap-7:0".encode()] = b"3"+ fake_redis._store[f"{CAPTURE_COUNTER_KEY_PREFIX}:cap-7:seq:google_ads".encode()] = b"5"++ output = _run("disable")++ assert CAPTURE_CONFIG_REDIS_KEY.encode() not in fake_redis._store+ assert f"{CAPTURE_COUNTER_KEY_PREFIX}:cap-7:0".encode() not in fake_redis._store+ assert f"{CAPTURE_COUNTER_KEY_PREFIX}:cap-7:seq:google_ads".encode() not in fake_redis._store+ assert "Capture disabled" in output+++def test_disable_when_already_disabled_is_noop(fake_redis):+ output = _run("disable")+ assert "already disabled" in output+++# ---------------------------------------------------------------------------+# list+# ---------------------------------------------------------------------------+++def test_list_when_disabled(fake_redis):+ output = _run("list")+ assert "not currently enabled" in output+++def test_list_prints_active_config(fake_redis):+ _run("enable", "--source-type", "google_ads", "--response-code", "unavailable", "--limit", "20", "--ttl", "30m")+ output = _run("list")++ assert "capture_id:" in output+ assert "rules (1):" in output+ assert "source_type='google_ads'" in output+ assert "response_code='unavailable'" in output+ assert "limit=20" in output+++def test_list_shows_per_rule_used_count(fake_redis):+ _run("enable", "--limit", "10", "--ttl", "30m")+ raw = fake_redis._store[CAPTURE_CONFIG_REDIS_KEY.encode()]+ cap_id = json.loads(raw)["capture_id"]+ fake_redis._store[f"{CAPTURE_COUNTER_KEY_PREFIX}:{cap_id}:0".encode()] = b"3"++ output = _run("list")+ assert "used=3/10" in outputdiff --git a/posthog/management/commands/warehouse_sources_capture_grpc_samples.py b/posthog/management/commands/warehouse_sources_capture_grpc_samples.pynew file mode 100644index 000000000000..a237850123e3--- /dev/null+++ b/posthog/management/commands/warehouse_sources_capture_grpc_samples.py@@ -0,0 +1,220 @@+"""Enable, disable, or inspect gRPC sample capture for warehouse-source syncs.++Sample capture writes anonymized request/response pairs to S3 for use as test+fixtures. It's controlled by a single Redis key (`data_imports:grpc_sample_capture`)+with a TTL — when the key expires, capture stops automatically.++Usage:++ # Enable capture for all UNAVAILABLE google_ads calls, capped at 50 samples, for 30 minutes+ python manage.py warehouse_sources_capture_grpc_samples enable \+ --source-type google_ads --response-code unavailable --limit 50 --ttl 30m++ # Multiple rules: pass --rule N times. Rules are evaluated in order and+ # the FIRST matching rule wins, so put the most specific rule first.+ python manage.py warehouse_sources_capture_grpc_samples enable \+ --rule source_type=google_ads,response_code=resource_exhausted,limit=20 \+ --rule source_type=bigquery,response_code=*,team_id=12,limit=10 \+ --ttl 1h++ # Inspect the active config+ python manage.py warehouse_sources_capture_grpc_samples list++ # Disable early (clears the Redis key + counters)+ python manage.py warehouse_sources_capture_grpc_samples disable+"""++from __future__ import annotations++import re+import uuid+from typing import Any++from django.core.management.base import BaseCommand, CommandParser++from posthog.redis import get_client+from posthog.temporal.data_imports.sources.common.grpc.sampling import (+ CAPTURE_CONFIG_REDIS_KEY,+ CAPTURE_COUNTER_KEY_PREFIX,+ MAX_CONFIG_TTL_SECONDS,+ S3_PREFIX,+)+from posthog.temporal.data_imports.sources.common.sample_scrub import WILDCARD, CaptureConfig, CaptureRule++_TTL_RE = re.compile(r"^(\d+)([smhd])$")+++def _parse_ttl(value: str) -> int:+ """Parse a duration like ``30m``, ``2h``, ``1d``, ``600s`` into seconds."""+ if not value:+ raise ValueError("ttl is required")+ match = _TTL_RE.match(value.strip().lower())+ if not match:+ # Plain integer falls back to seconds+ try:+ return int(value)+ except ValueError as exc:+ raise ValueError(f"invalid ttl {value!r} — use e.g. 30m, 2h, 1d, or seconds") from exc+ n = int(match.group(1))+ unit = match.group(2)+ multipliers = {"s": 1, "m": 60, "h": 3600, "d": 86400}+ return n * multipliers[unit]+++def _parse_rule_kv(spec: str, default_limit: int) -> CaptureRule:+ """Parse a `key=value,key=value` rule spec into a CaptureRule."""+ fields: dict[str, Any] = {}+ for part in spec.split(","):+ part = part.strip()+ if not part:+ continue+ if "=" not in part:+ raise ValueError(f"invalid rule fragment {part!r}, expected key=value")+ key, _, val = part.partition("=")+ fields[key.strip()] = val.strip()+ fields.setdefault("limit", default_limit)+ return CaptureRule.from_dict(fields)+++class Command(BaseCommand):+ help = "Manage gRPC sample capture for warehouse-source syncs."++ def add_arguments(self, parser: CommandParser) -> None:+ sub = parser.add_subparsers(dest="action", required=True)++ enable = sub.add_parser("enable", help="Enable capture")+ enable.add_argument("--source-type", default=WILDCARD, help="Filter by source type (default: *)")+ enable.add_argument(+ "--response-code",+ default=WILDCARD,+ help="gRPC status class or code, e.g. ok / unavailable / resource_exhausted / 14 (default: *)",+ )+ enable.add_argument("--team-id", default=WILDCARD, help="Filter by team_id (default: *)")+ enable.add_argument("--schema-id", default=WILDCARD, help="Filter by schema id (default: *)")+ enable.add_argument("--limit", type=int, default=50, help="Max samples per rule (default: 50)")+ enable.add_argument(+ "--ttl",+ default="30m",+ help="How long capture stays enabled — e.g. 30m, 2h, 1d (default: 30m)",+ )+ enable.add_argument(+ "--rule",+ action="append",+ default=[],+ help="Add an extra rule as 'key=value,key=value'. Repeatable. Rules are evaluated in declared order; first match wins.",+ )++ sub.add_parser("disable", help="Disable capture (clears the Redis key + counters)")+ sub.add_parser("list", help="Print the active capture config, if any")++ def handle(self, *args: Any, **options: Any) -> None:+ action = options["action"]+ if action == "enable":+ self._enable(options)+ elif action == "disable":+ self._disable()+ elif action == "list":+ self._list()+ else:+ raise ValueError(f"Unknown action: {action}")++ def _emit(self, *lines: str) -> None:+ for line in lines:+ self.stdout.write(line)++ def _enable(self, options: dict[str, Any]) -> None:+ ttl_seconds = _parse_ttl(options["ttl"])+ if ttl_seconds <= 0:+ raise ValueError("ttl must be positive")+ if ttl_seconds > MAX_CONFIG_TTL_SECONDS:+ raise ValueError(f"ttl {ttl_seconds}s exceeds max {MAX_CONFIG_TTL_SECONDS}s (24h)")++ primary = CaptureRule(+ source_type=options["source_type"],+ response_code=options["response_code"],+ team_id=options["team_id"],+ schema_id=options["schema_id"],+ limit=options["limit"],+ )+ extra = [_parse_rule_kv(raw, default_limit=options["limit"]) for raw in options["rule"]]++ # Rules are first-match-wins. An all-wildcard primary built purely from+ # flag defaults would shadow every `--rule` entry (they'd be dead code),+ # so when the operator drives capture entirely via `--rule` we drop the+ # implicit primary. A primary with any explicit filter is always kept.+ primary_is_wildcard = (+ primary.source_type == WILDCARD+ and primary.response_code == WILDCARD+ and primary.team_id == WILDCARD+ and primary.schema_id == WILDCARD+ )+ rules: list[CaptureRule] = extra if (extra and primary_is_wildcard) else [primary, *extra]++ capture_id = uuid.uuid4().hex+ config = CaptureConfig(capture_id=capture_id, rules=tuple(rules))++ client = get_client()+ client.set(CAPTURE_CONFIG_REDIS_KEY, config.to_json(), ex=ttl_seconds)++ self._emit(f"Capture enabled — capture_id={capture_id}, ttl={ttl_seconds}s", "Rules:")+ for index, rule in enumerate(config.rules):+ self._emit(f" [{index}] {rule}")+ self._emit(+ "",+ f"S3 prefix: {S3_PREFIX}/{capture_id}/",+ "",+ "Capture stops automatically when the Redis key expires. Run with `disable` to stop early.",+ )++ def _disable(self) -> None:+ client = get_client()+ existing = client.get(CAPTURE_CONFIG_REDIS_KEY)+ if not existing:+ self._emit("Capture is already disabled (no config in Redis)")+ return++ config = CaptureConfig.from_json(existing)+ client.delete(CAPTURE_CONFIG_REDIS_KEY)+ if config is not None:+ # Best-effort cleanup of the per-rule and per-source counters.+ counter_pattern = f"{CAPTURE_COUNTER_KEY_PREFIX}:{config.capture_id}:*"+ try:+ cursor = 0+ deleted = 0+ while True:+ cursor, keys = client.scan(cursor=cursor, match=counter_pattern, count=200)+ if keys:+ deleted += client.delete(*keys)+ if cursor == 0:+ break+ self._emit(f"Capture disabled — deleted {deleted} counter keys for capture_id={config.capture_id}")+ except Exception as exc:+ # Don't fail the command — the config key is already gone, capture has stopped.+ self._emit(f"Capture disabled — counter cleanup partial (Redis: {exc})")+ else:+ self._emit("Capture disabled — capture_id was unparseable, skipped counter cleanup")++ def _list(self) -> None:+ client = get_client()+ existing = client.get(CAPTURE_CONFIG_REDIS_KEY)+ if not existing:+ self._emit("Capture is not currently enabled")+ return+ config = CaptureConfig.from_json(existing)+ if config is None:+ self._emit("Capture key present but unparseable")+ return+ ttl = client.ttl(CAPTURE_CONFIG_REDIS_KEY)+ self._emit(+ f"capture_id: {config.capture_id}",+ f"ttl_seconds_remaining: {ttl}",+ f"S3 prefix: {S3_PREFIX}/{config.capture_id}/",+ f"rules ({len(config.rules)}):",+ )+ for index, rule in enumerate(config.rules):+ counter_key = f"{CAPTURE_COUNTER_KEY_PREFIX}:{config.capture_id}:{index}"+ try:+ used = int(client.get(counter_key) or 0)+ except Exception:+ used = -1+ self._emit(f" [{index}] used={used}/{rule.limit}: {rule}")diff --git a/posthog/management/commands/warehouse_sources_capture_http_samples.py b/posthog/management/commands/warehouse_sources_capture_http_samples.pyindex e83cc1259bd3..1367d035e47d 100644--- a/posthog/management/commands/warehouse_sources_capture_http_samples.py+++ b/posthog/management/commands/warehouse_sources_capture_http_samples.py@@ -37,10 +37,8 @@ from posthog.temporal.data_imports.sources.common.http.sampling import (CAPTURE_CONFIG_REDIS_KEY,CAPTURE_COUNTER_KEY_PREFIX,MAX_CONFIG_TTL_SECONDS,- WILDCARD,- CaptureConfig,- CaptureRule,)+from posthog.temporal.data_imports.sources.common.sample_scrub import WILDCARD, CaptureConfig, CaptureRule_TTL_RE = re.compile(r"^(\d+)([smhd])$")diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.mdindex 551a87eda714..d20823a99d79 100644--- a/posthog/temporal/data_imports/sources/SOURCES.md+++ b/posthog/temporal/data_imports/sources/SOURCES.md@@ -22,7 +22,7 @@ new source / vendor-SDK / migration PR.| ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- || **HTTP** | REST/JSON over HTTPS via the `requests` library. Routed through `make_tracked_session()` (see [common/http/](common/http/)). || **HTTP (vendor SDK)** | The vendor ships its own SDK that wraps HTTP. Where the SDK exposes a session/transport hook, we inject `make_tracked_session()` so the calls are still tracked. |-| **gRPC** | The vendor SDK uses gRPC over HTTP/2 (binary, not REST). The tracked HTTP transport does not currently apply. |+| **gRPC** | The vendor SDK uses gRPC over HTTP/2 (binary, not REST). Routed through the [tracked gRPC transport](common/grpc/) via client interceptors (see `common/grpc/`). || **DB protocol** | Native database wire protocol via a driver (e.g. PostgreSQL, MySQL, Snowflake). Not HTTP. || **Webhook (S3-buffered)** | Vendor pushes events to a webhook endpoint; payloads are buffered to S3 by the `WebhookSourceManager` and consumed by the pipeline. |@@ -35,7 +35,7 @@ the row lists both.| ------------- | --------------------------------------------------------------------------------------------------------------------------------------- || ✅ Tracked | Outbound calls go through `make_tracked_session()` (or the equivalent vendor-SDK injection). || ⚠️ Vendor SDK | Vendor SDK has no session/transport hook we can use. Outbound HTTP bypasses our logging/metrics today. May need a `# nosemgrep` pragma. |-| ➖ N/A | Source uses a non-HTTP protocol (DB driver, gRPC, etc.) — the HTTP transport doesn't apply. |+| ➖ N/A | Source uses a native DB wire protocol (Postgres, MySQL, Snowflake, …) — neither the HTTP nor gRPC transport applies. || — | Source is scaffolded; no transport in use yet. |---@@ -45,7 +45,7 @@ the row lists both.| Source | Comm method | Primary library | Tracked transport || ------------- | --------------------------- | --------------------------------------------------------------- | --------------------------- || attio | HTTP | requests + `rest_source.RESTClient` | ✅ |-| bigquery | HTTP + gRPC | google-cloud-bigquery + bigquery-storage | ✅ (HTTP), ➖ (gRPC) |+| bigquery | HTTP + gRPC | google-cloud-bigquery + bigquery-storage | ✅ (HTTP + gRPC) || bing_ads | HTTP (vendor SDK, SOAP) | bingads SDK | ⚠️ || buildbetter | HTTP | requests | ✅ || chargebee | HTTP | requests + `rest_source.RESTClient` | ✅ |@@ -55,7 +55,7 @@ the row lists both.| customer_io | HTTP + Webhook | requests + `WebhookSourceManager` | ✅ (App API) / ➖ (webhook) || doit | HTTP | requests | ✅ || github | HTTP | requests | ✅ |-| google_ads | gRPC | google-ads (googleads.client) | ➖ |+| google_ads | gRPC | google-ads (googleads.client) | ✅ || google_sheets | HTTP (vendor SDK) | gspread | ✅ || hubspot | HTTP | requests | ✅ || klaviyo | HTTP | requests | ✅ |@@ -83,6 +83,7 @@ the row lists both.| snowflake | DB protocol | snowflake-connector-python | ➖ || stripe | HTTP (vendor SDK) + Webhook | stripe (StripeClient + RequestsClient) + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) || supabase | DB protocol | psycopg (delegates to PostgresSource) | ➖ |+| temporalio | gRPC (vendor SDK) | temporalio (`Client`, Rust core via `temporalio.bridge`) | ⚠️ || tiktok_ads | HTTP | requests + `rest_source.RESTClient` | ✅ || typeform | HTTP | requests + `rest_source.RESTClient` | ✅ || vitally | HTTP | requests + `rest_source.RESTClient` | ✅ |@@ -97,8 +98,18 @@ the row lists both.- **linkedin_ads** uses `linkedin-api`'s `RestliClient`, which constructs its own internal `requests.Session`.We don't yet have a session-injection seam on it, so outbound calls bypass the tracked transport. (The fileimports `requests` only for exception types — those references are expected and don't need a pragma.)-- **bigquery's** Storage Read API uses gRPC; only the metadata/management traffic via the BigQuery REST API- is HTTP, and that HTTP path is tracked via `AuthorizedSession` + a mounted `TrackedHTTPAdapter`.+- **temporalio** talks gRPC, but the Python `temporalio` SDK runs its entire gRPC stack in a Rust core+ (`temporalio.bridge`, a PyO3 module) — service RPCs dispatch through `ServiceClient._rpc_call` into the+ bridge, so there is no Python `grpc.Channel` or client-interceptor seam for the tracked gRPC transport to+ wrap. (`Client.connect(interceptors=...)` accepts high-level `temporalio.client.Interceptor`s, a different+ abstraction that wouldn't feed the gRPC observer/metrics.) Outbound traffic bypasses the tracked transport.+- **bigquery** uses two transports: the metadata/management traffic via the BigQuery REST API is HTTP,+ tracked via `AuthorizedSession` + a mounted `TrackedHTTPAdapter`; the Storage Read API uses gRPC,+ tracked via `BigQueryReadGrpcTransport(channel=make_tracked_channel(...))` so `create_read_session` and+ `read_rows` ride the tracked gRPC interceptors.+- **google_ads** is pure gRPC. Every `GoogleAdsClient.get_service(...)` call passes+ `interceptors=tracked_interceptors(host)` so its unary calls (`search`, `search_google_ads_fields`) are+ logged, metered, and eligible for sample capture.---@@ -116,7 +127,7 @@ instagram, intercom, iterable, jira, kafka, launchdarkly, lever, mailerlite, maimicrosoft_teams, mixpanel, monday, netsuite, notion, okta, omnisend, onedrive, oracle, outreach,pagerduty, pardot, paypal, pendo, pipedrive, plaid, postmark, productboard, quickbooks, recharge,recurly, ringcentral, salesloft, sendgrid, servicenow, sftp, sharepoint, shortcut, smartsheet,-square, surveymonkey, temporalio, trello, twilio, twitter_ads, webflow, woocommerce, workday, wrike, xero,+square, surveymonkey, trello, twilio, twitter_ads, webflow, woocommerce, workday, wrike, xero,youtube_analytics, zoho_crm, zoom, zuora.---@@ -132,9 +143,16 @@ Update SOURCES.md whenever you:- **Switch a source's protocol** (e.g. swap a REST client for a gRPC SDK, or add webhook supportalongside the pull API).-The semgrep rule [`data-imports-http-transport`](/.semgrep/rules/data-imports-http-transport.yaml) enforces-that direct `requests.<verb>` / `requests.Session()` / `httpx.*` calls inside `sources/` go through the-tracked transport. Vendor SDKs that genuinely cannot be intercepted should both:+Two semgrep rules enforce the tracked transports inside `sources/`:-1. Carry a `# nosemgrep: data-imports-http-transport-...` pragma at the call site, with a one-line reason.+- [`data-imports-http-transport`](/.semgrep/rules/data-imports-http-transport.yaml) bans direct+ `requests.<verb>` / `requests.Session()` / `httpx.*` — route through `make_tracked_session()`.+- [`data-imports-grpc-transport`](/.semgrep/rules/data-imports-grpc-transport.yaml) bans raw+ `grpc.*_channel(...)` and direct `BigQueryReadClient(...)` / `GoogleAdsClient(...)` construction —+ route through `make_tracked_channel(...)` (for `channel=`/`transport=` SDKs) or+ `tracked_interceptors(host)` (for `interceptors=` SDKs).++Vendor SDKs that genuinely cannot be intercepted should both:++1. Carry a `# nosemgrep: data-imports-...-transport-...` pragma at the call site, with a one-line reason.2. Be listed here under "Notes on partially-tracked sources" with the `⚠️ Vendor SDK` row state.diff --git a/posthog/temporal/data_imports/sources/bigquery/bigquery.py b/posthog/temporal/data_imports/sources/bigquery/bigquery.pyindex fe0891c2bc75..78bbd15e474f 100644--- a/posthog/temporal/data_imports/sources/bigquery/bigquery.py+++ b/posthog/temporal/data_imports/sources/bigquery/bigquery.py@@ -26,6 +26,7 @@ from google.api_core.exceptions import Forbiddenfrom google.auth.transport.requests import AuthorizedSessionfrom google.cloud import bigquery, bigquery_storagefrom google.cloud.bigquery.job import QueryJobConfig+from google.cloud.bigquery_storage_v1.services.big_query_read.transports.grpc import BigQueryReadGrpcTransportfrom google.oauth2 import service_accountfrom structlog.types import FilteringBoundLogger@@ -38,6 +39,7 @@ from posthog.temporal.data_imports.pipelines.helpers import (from posthog.temporal.data_imports.pipelines.pipeline.consts import DEFAULT_TABLE_SIZE_BYTESfrom posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponsefrom posthog.temporal.data_imports.pipelines.pipeline.utils import DEFAULT_PARTITION_TARGET_SIZE_IN_BYTES+from posthog.temporal.data_imports.sources.common.grpc import make_tracked_channelfrom posthog.temporal.data_imports.sources.common.http import DEFAULT_RETRY, TrackedHTTPAdapterfrom posthog.temporal.data_imports.sources.common.sql import compute_projected_columnsfrom posthog.temporal.data_imports.sources.common.sql.identifiers import BacktickIdentifierQuoter@@ -59,6 +61,10 @@ __all__ = ["validate_bigquery_credentials",]+# Host used both to build the Storage Read API gRPC channel and to label the+# tracked gRPC transport's logs/metrics.+BIGQUERY_STORAGE_HOST = "bigquerystorage.googleapis.com"+def build_destination_table_prefix(schema_id: str | None) -> str:return f"__posthog_import_{schema_id.replace('-', '_') if schema_id else ''}"@@ -142,11 +148,24 @@ def bigquery_storage_read_client(scopes=["https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/cloud-platform"],)- client = bigquery_storage.BigQueryReadClient(- credentials=credentials,- )+ # Build the credential-bearing gRPC channel ourselves, wrap it in the tracked+ # interceptors, then hand it to the transport. Passing a `channel` makes the+ # transport ignore credentials, so they must already be baked into the channel+ # via `create_channel(credentials=...)`. This routes the Storage Read API's+ # create_read_session (unary) + read_rows (server-streaming) RPCs through our+ # logging / metrics / sample-capture pipeline.+ channel = BigQueryReadGrpcTransport.create_channel(host=BIGQUERY_STORAGE_HOST, credentials=credentials)+ tracked_channel = make_tracked_channel(channel, host=BIGQUERY_STORAGE_HOST)+ transport = BigQueryReadGrpcTransport(channel=tracked_channel)- yield client+ try:+ client = bigquery_storage.BigQueryReadClient(transport=transport)+ yield client+ finally:+ # We own the channel (built above), so we must close it — otherwise each+ # sync leaks an open gRPC channel + its file descriptors. Closing the+ # transport closes the underlying channel.+ transport.close()def delete_table(diff --git a/posthog/temporal/data_imports/sources/common/grpc/__init__.py b/posthog/temporal/data_imports/sources/common/grpc/__init__.pynew file mode 100644index 000000000000..d52966999681--- /dev/null+++ b/posthog/temporal/data_imports/sources/common/grpc/__init__.py@@ -0,0 +1,13 @@+from posthog.temporal.data_imports.sources.common.grpc.transport import (+ TrackedUnaryStreamClientInterceptor,+ TrackedUnaryUnaryClientInterceptor,+ make_tracked_channel,+ tracked_interceptors,+)++__all__ = [+ "TrackedUnaryStreamClientInterceptor",+ "TrackedUnaryUnaryClientInterceptor",+ "make_tracked_channel",+ "tracked_interceptors",+]diff --git a/posthog/temporal/data_imports/sources/common/grpc/metrics.py b/posthog/temporal/data_imports/sources/common/grpc/metrics.pynew file mode 100644index 000000000000..8c6d19cc7cf3--- /dev/null+++ b/posthog/temporal/data_imports/sources/common/grpc/metrics.py@@ -0,0 +1,182 @@+"""OpenTelemetry instruments for the tracked gRPC transport.++Mirrors `common/http/metrics.py`. Cardinality is bounded by+`(team_id, source_type, method, status_class)`. The full gRPC method string+(`/package.Service/Method`) is itself low-cardinality — a handful of RPCs per+source — so it is safe to use directly as a metric label.++`workflow.metric_meter()` is only valid inside a Temporal workflow or+activity. Outside of that — for example a unit test that directly drives the+interceptor without spinning up Temporal — the helpers fall back to no-op+recorders so that tests don't have to mock the workflow runtime.++Instruments are cached per `(team_id, source_type)` so the OTel SDK only sees+one create-call per labelled meter, not one per RPC. The cache is per-process,+populated lazily, and never invalidated. Tests can call+`_reset_cache_for_tests()` to clear it.+"""++from __future__ import annotations++import logging+import threading+from typing import TYPE_CHECKING, Any, Protocol++from temporalio import workflow++import grpc++if TYPE_CHECKING:+ from temporalio.common import MetricCounter, MetricHistogram++logger = logging.getLogger(__name__)+++class _NullCounter:+ def add(self, value: int, additional_attributes: dict[str, Any] | None = None) -> None:+ return None+++class _NullHistogram:+ def record(self, value: int, additional_attributes: dict[str, Any] | None = None) -> None:+ return None+++class _CounterLike(Protocol):+ def add(self, value: int, additional_attributes: dict[str, Any] | None = None) -> None: ...+++class _HistogramLike(Protocol):+ def record(self, value: int, additional_attributes: dict[str, Any] | None = None) -> None: ...+++_INSTRUMENT_LOCK = threading.Lock()+_REQUESTS_COUNTER_CACHE: dict[tuple[int, str], _CounterLike] = {}+_RESPONSE_BYTES_HISTOGRAM_CACHE: dict[tuple[int, str], _HistogramLike] = {}+_LATENCY_HISTOGRAM_CACHE: dict[tuple[int, str], _HistogramLike] = {}+++def _safe_metric_meter() -> Any | None:+ try:+ return workflow.metric_meter()+ except Exception:+ # Not inside a workflow / activity — fall through to no-op recorders.+ return None+++def _reset_cache_for_tests() -> None:+ """Test hook — clear the per-`(team_id, source_type)` instrument caches."""+ with _INSTRUMENT_LOCK:+ _REQUESTS_COUNTER_CACHE.clear()+ _RESPONSE_BYTES_HISTOGRAM_CACHE.clear()+ _LATENCY_HISTOGRAM_CACHE.clear()+++def get_grpc_requests_counter(team_id: int, source_type: str) -> _CounterLike | MetricCounter:+ key = (team_id, source_type)+ cached = _REQUESTS_COUNTER_CACHE.get(key)+ if cached is not None:+ return cached+ with _INSTRUMENT_LOCK:+ cached = _REQUESTS_COUNTER_CACHE.get(key)+ if cached is not None:+ return cached+ meter = _safe_metric_meter()+ if meter is None:+ instrument: _CounterLike = _NullCounter()+ else:+ instrument = meter.with_additional_attributes(+ {"team_id": str(team_id), "source_type": source_type}+ ).create_counter(+ "data_import_grpc_requests_total",+ "Outbound gRPC calls issued by warehouse source syncs.",+ )+ _REQUESTS_COUNTER_CACHE[key] = instrument+ return instrument+++def get_grpc_response_bytes_histogram(team_id: int, source_type: str) -> _HistogramLike | MetricHistogram:+ key = (team_id, source_type)+ cached = _RESPONSE_BYTES_HISTOGRAM_CACHE.get(key)+ if cached is not None:+ return cached+ with _INSTRUMENT_LOCK:+ cached = _RESPONSE_BYTES_HISTOGRAM_CACHE.get(key)+ if cached is not None:+ return cached+ meter = _safe_metric_meter()+ if meter is None:+ instrument: _HistogramLike = _NullHistogram()+ else:+ instrument = meter.with_additional_attributes(+ {"team_id": str(team_id), "source_type": source_type}+ ).create_histogram(+ "data_import_grpc_response_bytes",+ "Serialized size of gRPC response messages in bytes.",+ unit="By",+ )+ _RESPONSE_BYTES_HISTOGRAM_CACHE[key] = instrument+ return instrument+++def get_grpc_latency_histogram(team_id: int, source_type: str) -> _HistogramLike | MetricHistogram:+ key = (team_id, source_type)+ cached = _LATENCY_HISTOGRAM_CACHE.get(key)+ if cached is not None:+ return cached+ with _INSTRUMENT_LOCK:+ cached = _LATENCY_HISTOGRAM_CACHE.get(key)+ if cached is not None:+ return cached+ meter = _safe_metric_meter()+ if meter is None:+ instrument: _HistogramLike = _NullHistogram()+ else:+ instrument = meter.with_additional_attributes(+ {"team_id": str(team_id), "source_type": source_type}+ ).create_histogram(+ "data_import_grpc_latency_ms",+ "Outbound gRPC call latency in milliseconds (time to completion).",+ unit="ms",+ )+ _LATENCY_HISTOGRAM_CACHE[key] = instrument+ return instrument+++# gRPC status codes grouped into low-cardinality buckets. RESOURCE_EXHAUSTED+# (quota) gets its own bucket because it's the dominant failure mode for+# warehouse syncs and operators want to alert on it specifically.+_CLIENT_ERROR_CODES = frozenset(+ {+ grpc.StatusCode.INVALID_ARGUMENT,+ grpc.StatusCode.NOT_FOUND,+ grpc.StatusCode.ALREADY_EXISTS,+ grpc.StatusCode.PERMISSION_DENIED,+ grpc.StatusCode.UNAUTHENTICATED,+ grpc.StatusCode.FAILED_PRECONDITION,+ grpc.StatusCode.OUT_OF_RANGE,+ }+)+_UNAVAILABLE_CODES = frozenset(+ {+ grpc.StatusCode.DEADLINE_EXCEEDED,+ grpc.StatusCode.UNAVAILABLE,+ grpc.StatusCode.ABORTED,+ }+)+++def status_class(code: grpc.StatusCode | None) -> str:+ """Map a `grpc.StatusCode` to a low-cardinality bucket string."""+ if code is None:+ return "error"+ if code == grpc.StatusCode.OK:+ return "ok"+ if code == grpc.StatusCode.RESOURCE_EXHAUSTED:+ return "resource_exhausted"+ if code in _CLIENT_ERROR_CODES:+ return "client_error"+ if code in _UNAVAILABLE_CODES:+ return "unavailable"+ # INTERNAL, UNKNOWN, DATA_LOSS, UNIMPLEMENTED, CANCELLED, and anything else.+ return "server_error"diff --git a/posthog/temporal/data_imports/sources/common/grpc/observer.py b/posthog/temporal/data_imports/sources/common/grpc/observer.pynew file mode 100644index 000000000000..e3ff0956ecb1--- /dev/null+++ b/posthog/temporal/data_imports/sources/common/grpc/observer.py@@ -0,0 +1,183 @@+"""Per-call observer for the tracked gRPC transport.++The interceptors call `record_unary` / `record_stream` once per outbound gRPC+call — both successful and failed. The observer:++- emits a structlog log line with the method, host, status, latency and sizes,+ plus all `JobContext` labels;+- updates OTel counters/histograms labelled by `team_id`, `source_type`,+ `method`, and `status_class`;+- delegates to the sampling subsystem, which is a cheap no-op when capture is+ disabled in Redis.++Both the metrics call and the sampling call are wrapped in `try/except` — the+observer must never raise into the call path. A broken telemetry layer cannot+become a sync failure.+"""++from __future__ import annotations++import time+import logging+from dataclasses import dataclass+from typing import Any++import structlog++from posthog.temporal.data_imports.sources.common.grpc.metrics import (+ get_grpc_latency_histogram,+ get_grpc_requests_counter,+ get_grpc_response_bytes_histogram,+ status_class,+)+from posthog.temporal.data_imports.sources.common.grpc.proto_utils import message_byte_size+from posthog.temporal.data_imports.sources.common.grpc.sampling import maybe_capture+from posthog.temporal.data_imports.sources.common.job_context import JobContext, current_job_context++import grpc++logger = structlog.get_logger(__name__)+_fallback_logger = logging.getLogger(__name__)+++@dataclass(frozen=True)+class GrpcRequestRecord:+ method: str+ host: str+ request_bytes: int+ response_bytes: int+ status_class: str+ status_code_num: int | None+ latency_ms: int+ message_count: int | None+ error_class: str | None+++def _elapsed_ms(started_at_monotonic: float) -> int:+ return max(0, int((time.monotonic() - started_at_monotonic) * 1000))+++def _status_code_num(code: grpc.StatusCode | None) -> int | None:+ if code is None:+ return None+ try:+ return int(code.value[0])+ except Exception:+ return None+++def record_unary(+ *,+ method: str,+ host: str,+ request: Any,+ response: Any,+ code: grpc.StatusCode | None,+ exception: BaseException | None,+ started_at_monotonic: float,+) -> None:+ """Log + meter a single unary-unary gRPC call. Never raises."""+ response_bytes = message_byte_size(response) if response is not None else 0+ record = GrpcRequestRecord(+ method=method,+ host=host,+ request_bytes=message_byte_size(request),+ response_bytes=response_bytes,+ status_class=status_class(code),+ status_code_num=_status_code_num(code),+ latency_ms=_elapsed_ms(started_at_monotonic),+ message_count=1 if response is not None else 0,+ error_class=type(exception).__name__ if exception is not None else None,+ )+ response_messages = [response] if response is not None else []+ _emit(record, request=request, response_messages=response_messages, exception=exception)+++def record_stream(+ *,+ method: str,+ host: str,+ request: Any,+ retained_responses: list[Any],+ response_bytes: int,+ message_count: int,+ code: grpc.StatusCode | None,+ exception: BaseException | None,+ started_at_monotonic: float,+) -> None:+ """Log + meter a single unary-stream gRPC call. Never raises."""+ record = GrpcRequestRecord(+ method=method,+ host=host,+ request_bytes=message_byte_size(request),+ response_bytes=response_bytes,+ status_class=status_class(code),+ status_code_num=_status_code_num(code),+ latency_ms=_elapsed_ms(started_at_monotonic),+ message_count=message_count,+ error_class=type(exception).__name__ if exception is not None else None,+ )+ _emit(record, request=request, response_messages=retained_responses, exception=exception)+++def _emit(+ record: GrpcRequestRecord,+ *,+ request: Any,+ response_messages: list[Any],+ exception: BaseException | None,+) -> None:+ ctx = current_job_context()+ _emit_log(record, ctx=ctx)+ _emit_metrics(record, ctx=ctx)+ _maybe_capture_sample(record, request=request, response_messages=response_messages, ctx=ctx, exception=exception)+++def _emit_log(record: GrpcRequestRecord, *, ctx: JobContext | None) -> None:+ fields: dict[str, Any] = {+ "method": record.method,+ "host": record.host,+ "status_class": record.status_class,+ "status_code": record.status_code_num,+ "latency_ms": record.latency_ms,+ "request_bytes": record.request_bytes,+ "response_bytes": record.response_bytes,+ "message_count": record.message_count,+ "error_class": record.error_class,+ }+ if ctx is not None:+ fields.update(ctx.as_log_fields())++ if record.error_class is not None or record.status_class != "ok":+ logger.warning(f"data_imports.grpc.call {record.method}", **fields)+ else:+ logger.debug(f"data_imports.grpc.call {record.method}", **fields)+++def _emit_metrics(record: GrpcRequestRecord, *, ctx: JobContext | None) -> None:+ if ctx is None:+ return+ try:+ attrs = {"method": record.method, "status_class": record.status_class}+ get_grpc_requests_counter(ctx.team_id, ctx.source_type).add(1, attrs)+ get_grpc_latency_histogram(ctx.team_id, ctx.source_type).record(record.latency_ms, attrs)+ if record.response_bytes:+ get_grpc_response_bytes_histogram(ctx.team_id, ctx.source_type).record(record.response_bytes, attrs)+ except Exception:+ _fallback_logger.debug("Failed to record gRPC metric", exc_info=True)+++def _maybe_capture_sample(+ record: GrpcRequestRecord,+ *,+ request: Any,+ response_messages: list[Any],+ ctx: JobContext | None,+ exception: BaseException | None,+) -> None:+ if ctx is None:+ return+ try:+ maybe_capture(request=request, response_messages=response_messages, record=record, ctx=ctx)+ except Exception:+ _fallback_logger.debug("Failed to capture gRPC sample", exc_info=True)diff --git a/posthog/temporal/data_imports/sources/common/grpc/proto_utils.py b/posthog/temporal/data_imports/sources/common/grpc/proto_utils.pynew file mode 100644index 000000000000..846acb628451--- /dev/null+++ b/posthog/temporal/data_imports/sources/common/grpc/proto_utils.py@@ -0,0 +1,130 @@+"""Protobuf helpers for the tracked gRPC transport.++`message_byte_size` reports the serialized size of a protobuf message for+metrics (guarded — returns 0 for anything that isn't a message).++`message_to_scrubbed_dict` converts a message to a JSON-shaped dict for sample+capture. It walks the message via protobuf reflection so it can:++- replace `bytes` fields with a `<bytes:N>` placeholder rather than emitting+ them base64-encoded. A raw `bytes` field can carry bulk payloads — e.g.+ BigQuery Storage `ReadRowsResponse.arrow_record_batch.serialized_record_batch`+ holds the actual table rows — that scrubadub can't see inside, so we never+ serialize them into a sample;+- drop auth-bearing keys by name (`developer_token`, `refresh_token`, …);+- scrub string leaves via scrubadub.++Well-known `google.protobuf.*` types (Struct, Timestamp, wrappers, …) are+delegated to `MessageToDict`, which renders them canonically and carries no+bytes-of-concern.+"""++from __future__ import annotations++import logging+from typing import Any++from google.protobuf.descriptor import FieldDescriptor++from posthog.temporal.data_imports.sources.common.sample_scrub import REDACT_FIELD_NAMES, scrub_value++logger = logging.getLogger(__name__)++_REDACTED_KEY_VALUE = "REDACTED"+++def message_byte_size(message: Any) -> int:+ """Return `message.ByteSize()` if `message` is a protobuf message, else 0.++ By the time a request reaches a client interceptor, gapic has already+ coerced any dict argument into a serialized protobuf message — but we guard+ anyway so a non-message value (or a mock in tests) never raises.+ """+ byte_size = getattr(message, "ByteSize", None)+ if byte_size is None:+ return 0+ try:+ return int(byte_size())+ except Exception:+ return 0+++def _bytes_placeholder(value: bytes) -> str:+ try:+ return f"<bytes:{len(value)}>"+ except Exception:+ return "<bytes>"+++def _convert_scalar_or_message(field: FieldDescriptor, value: Any) -> Any:+ if field.type == FieldDescriptor.TYPE_BYTES:+ return _bytes_placeholder(value)+ if field.type == FieldDescriptor.TYPE_MESSAGE:+ return _proto_to_safe_dict(value)+ if field.type == FieldDescriptor.TYPE_ENUM:+ enum_value = field.enum_type.values_by_number.get(value)+ return enum_value.name if enum_value is not None else value+ return value+++def _convert_field(field: FieldDescriptor, value: Any) -> Any:+ if field.label == FieldDescriptor.LABEL_REPEATED:+ message_type = field.message_type+ if message_type is not None and message_type.GetOptions().map_entry:+ value_field = message_type.fields_by_name["value"]+ return {str(k): _convert_scalar_or_message(value_field, v) for k, v in value.items()}+ return [_convert_scalar_or_message(field, item) for item in value]+ return _convert_scalar_or_message(field, value)+++def _proto_to_safe_dict(message: Any) -> Any:+ """Recursively convert a protobuf message to a dict, redacting bytes fields.++ Well-known `google.protobuf.*` types are delegated to `MessageToDict` — they+ render canonically and don't carry bulk-bytes fields we need to guard.+ """+ descriptor = getattr(message, "DESCRIPTOR", None)+ if descriptor is None:+ return message++ if descriptor.full_name.startswith("google.protobuf."):+ from google.protobuf.json_format import MessageToDict++ return MessageToDict(message, preserving_proto_field_name=True)++ result: dict[str, Any] = {}+ for field, value in message.ListFields():+ result[field.name] = _convert_field(field, value)+ return result+++def _redact_keys(value: Any) -> Any:+ """Drop auth-bearing dict keys by name (developer_token, refresh_token, …)."""+ if isinstance(value, dict):+ return {+ k: (_REDACTED_KEY_VALUE if str(k).lower() in REDACT_FIELD_NAMES else _redact_keys(v))+ for k, v in value.items()+ }+ if isinstance(value, list):+ return [_redact_keys(item) for item in value]+ return value+++def message_to_scrubbed_dict(message: Any) -> Any:+ """Convert a protobuf message to a scrubbed JSON-shaped dict.++ Falls back to scrubbing the raw value if `message` isn't a protobuf message+ (e.g. a dict request that gapic hadn't coerced yet). Bytes fields become a+ size placeholder, auth keys are dropped by name, and scrubadub runs over the+ remaining string leaves.+ """+ if hasattr(message, "DESCRIPTOR"):+ try:+ as_dict = _proto_to_safe_dict(message)+ except Exception:+ logger.debug("Failed to convert protobuf message to dict", exc_info=True)+ return "<proto_conversion_failed>"+ else:+ as_dict = message++ return scrub_value(_redact_keys(as_dict))diff --git a/posthog/temporal/data_imports/sources/common/grpc/sampling.py b/posthog/temporal/data_imports/sources/common/grpc/sampling.pynew file mode 100644index 000000000000..61ab65f11697--- /dev/null+++ b/posthog/temporal/data_imports/sources/common/grpc/sampling.py@@ -0,0 +1,244 @@+"""Sample capture for tracked gRPC calls.++Mirrors `common/http/sampling.py` but for protobuf. When the singleton Redis+key `data_imports:grpc_sample_capture` is set, matching gRPC calls are+anonymized (protobuf → scrubbed JSON) and uploaded to object storage under+`warehouse-sources-grpc-samples/{capture_id}/{source_type}/{seq}.json`.++Operator workflow:++1. `python manage.py warehouse_sources_capture_grpc_samples ...` writes the+ config + TTL into Redis.+2. Active syncs see the config (refresh window ~30s) and start writing matching+ samples to S3.+3. After TTL expiry the config disappears; capture stops automatically.++`response_code` in a rule matches the gRPC status class (`ok`, `unavailable`,+`resource_exhausted`, `client_error`, `server_error`, `error`) or the numeric+gRPC status code (0-16). Streaming responses are truncated to the first few+messages and the whole payload is capped to keep S3 objects small.+"""++from __future__ import annotations++import json+import time+import uuid+import logging+import threading+from typing import TYPE_CHECKING, Any++from django.conf import settings++from posthog.redis import get_client+from posthog.storage import object_storage+from posthog.temporal.data_imports.sources.common.grpc.proto_utils import message_to_scrubbed_dict+from posthog.temporal.data_imports.sources.common.sample_scrub import WILDCARD, CaptureConfig, CaptureRule++if TYPE_CHECKING:+ from posthog.temporal.data_imports.sources.common.grpc.observer import GrpcRequestRecord+ from posthog.temporal.data_imports.sources.common.job_context import JobContext++logger = logging.getLogger(__name__)++CAPTURE_CONFIG_REDIS_KEY = "data_imports:grpc_sample_capture"+CAPTURE_COUNTER_KEY_PREFIX = "data_imports:grpc_sample_capture:counter"+S3_PREFIX = "warehouse-sources-grpc-samples"+CONFIG_CACHE_TTL_SECONDS = 30+MAX_CONFIG_TTL_SECONDS = 24 * 60 * 60+# Number of streamed response messages retained for a captured sample, and the+# byte ceiling for the whole serialized payload. Streaming reads (e.g. BigQuery+# Storage) can return huge volumes; we keep only a small head for fixture use.+MAX_CAPTURED_RESPONSE_MESSAGES = 3+MAX_SAMPLE_BYTES = 256 * 1024+++def is_capture_armed() -> bool:+ """Cheap check used by the stream interceptor to decide whether to retain messages."""+ return _load_config() is not None+++# In-process cache of the parsed Redis config — separate from the HTTP cache so+# the two key spaces don't collide. Thread-safe because the interceptor runs+# from worker threads in the source iterator pool.+_CONFIG_LOCK = threading.Lock()+_cached_config: CaptureConfig | None = None+_cached_config_fetched_at: float = 0.0+++def _now() -> float:+ return time.monotonic()+++def _load_config() -> CaptureConfig | None:+ global _cached_config, _cached_config_fetched_at++ with _CONFIG_LOCK:+ if _now() - _cached_config_fetched_at < CONFIG_CACHE_TTL_SECONDS:+ return _cached_config++ try:+ raw = get_client().get(CAPTURE_CONFIG_REDIS_KEY)+ except Exception:+ logger.debug("Capture-config Redis fetch failed", exc_info=True)+ _cached_config_fetched_at = _now()+ return _cached_config++ _cached_config_fetched_at = _now()+ if raw is None:+ _cached_config = None+ return None++ config = CaptureConfig.from_json(raw)+ _cached_config = config+ return config+++def _reset_cache_for_tests() -> None:+ """Test hook — clears the in-process cache."""+ global _cached_config, _cached_config_fetched_at+ with _CONFIG_LOCK:+ _cached_config = None+ _cached_config_fetched_at = 0.0+++def _counter_key(capture_id: str, rule_index: int) -> str:+ return f"{CAPTURE_COUNTER_KEY_PREFIX}:{capture_id}:{rule_index}"+++def _try_reserve_slot(capture_id: str, rule_index: int, limit: int) -> bool:+ """Atomically claim a sample slot. Returns True if the sample should be kept."""+ if limit <= 0:+ return False+ try:+ client = get_client()+ key = _counter_key(capture_id, rule_index)+ new_value = client.incr(key)+ try:+ ttl = client.ttl(CAPTURE_CONFIG_REDIS_KEY)+ client.expire(key, max(int(ttl) if isinstance(ttl, int) and ttl > 0 else MAX_CONFIG_TTL_SECONDS, 60))+ except Exception:+ logger.debug("Failed to set TTL on capture counter", exc_info=True)+ return int(new_value) <= limit+ except Exception:+ logger.debug("Failed to reserve sample slot", exc_info=True)+ return False+++def _sample_object_key(capture_id: str, source_type: str, sequence: int) -> str:+ return f"{S3_PREFIX}/{capture_id}/{source_type}/{sequence:06d}.json"+++def _matches_grpc_status(rule_value: str, status_class: str, status_code_num: int | None) -> bool:+ if rule_value == WILDCARD:+ return True+ if rule_value == status_class:+ return True+ if status_code_num is not None and rule_value == str(status_code_num):+ return True+ return False+++def _first_match(+ rules: tuple[CaptureRule, ...],+ *,+ source_type: str,+ status_class: str,+ status_code_num: int | None,+ team_id: int,+ schema_id: str,+) -> tuple[int, CaptureRule] | None:+ for index, rule in enumerate(rules):+ if rule.matches_dimensions(+ source_type=source_type, team_id=team_id, schema_id=schema_id+ ) and _matches_grpc_status(rule.response_code, status_class, status_code_num):+ return index, rule+ return None+++def _next_sequence(capture_id: str, source_type: str) -> int:+ """Per-source monotonic sequence — used only to give each S3 key a unique suffix."""+ try:+ client = get_client()+ return int(client.incr(f"{CAPTURE_COUNTER_KEY_PREFIX}:{capture_id}:seq:{source_type}"))+ except Exception:+ return int(uuid.uuid4().int >> 96)+++def maybe_capture(+ *,+ request: Any,+ response_messages: list[Any],+ record: GrpcRequestRecord,+ ctx: JobContext,+) -> None:+ """Entry point used by the observer. No-op when no rule matches."""+ config = _load_config()+ if config is None:+ return++ matching = _first_match(+ config.rules,+ source_type=ctx.source_type,+ status_class=record.status_class,+ status_code_num=record.status_code_num,+ team_id=ctx.team_id,+ schema_id=ctx.external_data_schema_id,+ )+ if matching is None:+ return++ rule_index, rule = matching+ if not _try_reserve_slot(config.capture_id, rule_index, rule.limit):+ return++ payload = _build_sample_payload(request=request, response_messages=response_messages, record=record, ctx=ctx)+ sequence = _next_sequence(config.capture_id, ctx.source_type)+ key = _sample_object_key(config.capture_id, ctx.source_type, sequence)+ bucket = settings.OBJECT_STORAGE_BUCKET+ try:+ object_storage.write(key, payload, bucket=bucket)+ except Exception:+ logger.debug("Failed to write gRPC sample to object storage", exc_info=True)+++def _build_sample_payload(+ *,+ request: Any,+ response_messages: list[Any],+ record: GrpcRequestRecord,+ ctx: JobContext,+) -> str:+ retained = response_messages[:MAX_CAPTURED_RESPONSE_MESSAGES]+ response_truncated = (record.message_count is not None and record.message_count > len(retained)) or len(+ response_messages+ ) > len(retained)++ sample: dict[str, Any] = {+ "captured_at_unix_ms": int(time.time() * 1000),+ "context": ctx.as_log_fields(),+ "request": {+ "method": record.method,+ "host": record.host,+ "message": message_to_scrubbed_dict(request),+ },+ "response": {+ "status_class": record.status_class,+ "status_code": record.status_code_num,+ "messages": [message_to_scrubbed_dict(m) for m in retained],+ "message_count": record.message_count,+ "truncated": response_truncated,+ "latency_ms": record.latency_ms,+ },+ }++ serialized = json.dumps(sample, default=str)+ if len(serialized.encode("utf-8", errors="ignore")) <= MAX_SAMPLE_BYTES:+ return serialized++ # Over the byte ceiling — drop response message bodies but keep the shape /+ # metadata so the sample is still useful as a fixture skeleton.+ sample["response"]["messages"] = []+ sample["response"]["truncated"] = True+ sample["response"]["dropped_for_size"] = True+ return json.dumps(sample, default=str)diff --git a/posthog/temporal/data_imports/sources/common/grpc/transport.py b/posthog/temporal/data_imports/sources/common/grpc/transport.pynew file mode 100644index 000000000000..ff5f3e00df80--- /dev/null+++ b/posthog/temporal/data_imports/sources/common/grpc/transport.py@@ -0,0 +1,208 @@+"""Tracked gRPC client interceptors.++`tracked_interceptors(host)` returns the interceptor list to hand to SDKs that+accept an `interceptors=` argument (e.g. google-ads' `GoogleAdsClient.get_service`).+`make_tracked_channel(channel, host=...)` wraps an already-built, credential-bearing+channel for SDKs that accept a `channel=` / `transport=` argument (e.g. BigQuery+Storage).++Both interceptors feed the observer once per call — unary-unary on return,+unary-stream on stream completion or error. Telemetry is wrapped in try/except+so it can never raise into the call path; a broken observer must not turn into+a sync failure. Streaming responses are sized-and-released (never buffered);+only a small head of messages is retained, and only when sample capture is armed.+"""++from __future__ import annotations++import time+from collections.abc import Iterator+from typing import Any++from posthog.temporal.data_imports.sources.common.grpc.observer import record_stream, record_unary+from posthog.temporal.data_imports.sources.common.grpc.proto_utils import message_byte_size+from posthog.temporal.data_imports.sources.common.grpc.sampling import MAX_CAPTURED_RESPONSE_MESSAGES, is_capture_armed++import grpc+++def _safe_code(obj: Any) -> grpc.StatusCode | None:+ code_fn = getattr(obj, "code", None)+ if code_fn is None:+ return None+ try:+ return code_fn()+ except Exception:+ return None+++def _resolve_unary_outcome(outcome: Any) -> tuple[grpc.StatusCode | None, Any, BaseException | None]:+ """Extract (status_code, response, exception) from a unary continuation result.++ In this grpc version the unary continuation performs the RPC synchronously,+ so reading `.code()` / `.exception()` / `.result()` neither blocks nor+ re-issues the call.+ """+ if isinstance(outcome, grpc.RpcError):+ return _safe_code(outcome), None, outcome++ # An interceptor continuation returns a call/future (resolved synchronously+ # in this grpc version). But be defensive: some stubs/continuations hand back+ # the response message directly. Anything without the call surface+ # (`.exception()` / `.result()` / `.code()`) is treated as an already-resolved+ # successful response, so we still size it correctly rather than recording a+ # spurious error.+ if not (hasattr(outcome, "exception") and hasattr(outcome, "result")):+ return grpc.StatusCode.OK, outcome, None++ try:+ exc = outcome.exception()+ except Exception:+ exc = None+ if exc is not None:+ return _safe_code(outcome), None, exc++ try:+ response = outcome.result()+ except grpc.RpcError as rpc_error:+ return _safe_code(rpc_error), None, rpc_error+ except Exception as error:+ return _safe_code(outcome), None, error++ return _safe_code(outcome) or grpc.StatusCode.OK, response, None+++class TrackedUnaryUnaryClientInterceptor(grpc.UnaryUnaryClientInterceptor):+ def __init__(self, host: str) -> None:+ self._host = host++ def intercept_unary_unary(self, continuation: Any, client_call_details: Any, request: Any) -> Any:+ started = time.monotonic()+ outcome = continuation(client_call_details, request)+ try:+ code, response, exception = _resolve_unary_outcome(outcome)+ record_unary(+ method=getattr(client_call_details, "method", "") or "",+ host=self._host,+ request=request,+ response=response,+ code=code,+ exception=exception,+ started_at_monotonic=started,+ )+ except Exception:+ # Telemetry must never mask the real call outcome.+ pass+ return outcome+++class TrackedUnaryStreamClientInterceptor(grpc.UnaryStreamClientInterceptor):+ def __init__(self, host: str) -> None:+ self._host = host++ def intercept_unary_stream(self, continuation: Any, client_call_details: Any, request: Any) -> Any:+ started = time.monotonic()+ response_iter = continuation(client_call_details, request)+ return _TrackedStreamWrapper(+ response_iter,+ host=self._host,+ method=getattr(client_call_details, "method", "") or "",+ request=request,+ started_at_monotonic=started,+ )+++class _TrackedStreamWrapper(Iterator[Any]):+ """Wrap a unary-stream response iterator to time, size and (optionally) sample it.++ Messages are sized and released as they pass through — never buffered. Only+ the first `MAX_CAPTURED_RESPONSE_MESSAGES` are retained, and only when sample+ capture is armed. Recording happens exactly once, on stream completion or the+ first error.+ """++ def __init__(+ self, response_iter: Any, *, host: str, method: str, request: Any, started_at_monotonic: float+ ) -> None:+ self._iter = response_iter+ self._host = host+ self._method = method+ self._request = request+ self._started = started_at_monotonic+ self._response_bytes = 0+ self._message_count = 0+ self._retained: list[Any] = []+ self._armed = self._safe_is_armed()+ self._recorded = False++ @staticmethod+ def _safe_is_armed() -> bool:+ try:+ return is_capture_armed()+ except Exception:+ return False++ def __iter__(self) -> _TrackedStreamWrapper:+ return self++ def __next__(self) -> Any:+ try:+ message = next(self._iter)+ except StopIteration:+ self._record(code=grpc.StatusCode.OK, exception=None)+ raise+ except grpc.RpcError as rpc_error:+ self._record(code=_safe_code(rpc_error), exception=rpc_error)+ raise+ except Exception as error:+ self._record(code=None, exception=error)+ raise++ self._message_count += 1+ self._response_bytes += message_byte_size(message)+ if self._armed and len(self._retained) < MAX_CAPTURED_RESPONSE_MESSAGES:+ self._retained.append(message)+ return message++ def _record(self, *, code: grpc.StatusCode | None, exception: BaseException | None) -> None:+ if self._recorded:+ return+ self._recorded = True+ try:+ record_stream(+ method=self._method,+ host=self._host,+ request=self._request,+ retained_responses=self._retained,+ response_bytes=self._response_bytes,+ message_count=self._message_count,+ code=code,+ exception=exception,+ started_at_monotonic=self._started,+ )+ except Exception:+ pass++ def close(self) -> None:+ # A consumer that stops early (explicit close, cancellation, generator+ # teardown) never drives __next__ to its terminal StopIteration/error,+ # so record the partial stream here before tearing the iterator down.+ # The _recorded guard keeps this idempotent if __next__ already fired.+ self._record(code=None, exception=None)+ inner_close = getattr(self._iter, "close", None)+ if inner_close is not None:+ inner_close()++ def __getattr__(self, name: str) -> Any:+ # Delegate Call-surface methods (cancel, trailing_metadata, …) the SDK+ # may reach for on the response object to the wrapped iterator.+ return getattr(self._iter, name)+++def tracked_interceptors(host: str) -> list[grpc.UnaryUnaryClientInterceptor | grpc.UnaryStreamClientInterceptor]:+ return [TrackedUnaryUnaryClientInterceptor(host), TrackedUnaryStreamClientInterceptor(host)]+++def make_tracked_channel(channel: grpc.Channel, *, host: str) -> grpc.Channel:+ """Wrap a credential-bearing channel so every RPC rides the tracked interceptors."""+ return grpc.intercept_channel(channel, *tracked_interceptors(host))diff --git a/posthog/temporal/data_imports/sources/common/http/context.py b/posthog/temporal/data_imports/sources/common/http/context.pyindex 11892ee5fe08..3a478653be2d 100644--- a/posthog/temporal/data_imports/sources/common/http/context.py+++ b/posthog/temporal/data_imports/sources/common/http/context.py@@ -1,146 +1,31 @@-"""Per-job HTTP context.--The activity that runs a warehouse-source sync sets a `JobContext` once at-its entry point. The tracked HTTP transport reads it on every request to-attach `team_id`, `source_type`, `external_data_schema_id`,-`external_data_source_id`, and `external_data_job_id` to logs, metrics and-sample-capture decisions.--Stored in a `contextvars.ContextVar` so it propagates across the source-generator's thread-pool boundary — see `pipelines/pipeline/pipeline.py`'s-`copy_context()` snapshot, which already preserves contextvars when calls-hop into the executor.+"""Backwards-compatible re-export of the transport-neutral job context.++`JobContext` and the bind/scoped/current helpers moved to+`posthog.temporal.data_imports.sources.common.job_context` so both the HTTP+and gRPC tracked transports can share them. This module re-exports the same+objects (including the private names a few HTTP tests reach into) so existing+`from ...common.http.context import ...` and `from ...common.http import ...`+imports keep working."""from __future__ import annotations-import contextvars-import dataclasses-from collections.abc import Iterator-from contextlib import contextmanager-from typing import TYPE_CHECKING--from structlog.contextvars import bind_contextvars, unbind_contextvars--if TYPE_CHECKING:- import uuid--[email protected](frozen=True)-class JobContext:- team_id: int- source_type: str- external_data_source_id: str- external_data_schema_id: str- external_data_job_id: str-- def as_log_fields(self) -> dict[str, int | str]:- return {- "team_id": self.team_id,- "source_type": self.source_type,- "external_data_source_id": self.external_data_source_id,- "external_data_schema_id": self.external_data_schema_id,- "external_data_job_id": self.external_data_job_id,- }---_current_job_context: contextvars.ContextVar[JobContext | None] = contextvars.ContextVar(- "data_imports_http_job_context", default=None+from posthog.temporal.data_imports.sources.common.job_context import (+ _BOUND_LOG_FIELD_NAMES,+ JobContext,+ _current_job_context,+ _make_context,+ bind_job_context,+ current_job_context,+ scoped_job_context,)--_BOUND_LOG_FIELD_NAMES: tuple[str, ...] = (- "source_type",- "external_data_source_id",- "external_data_schema_id",- "external_data_job_id",-)---def current_job_context() -> JobContext | None:- return _current_job_context.get()---def _make_context(- *,- team_id: int,- source_type: str,- external_data_source_id: str | uuid.UUID,- external_data_schema_id: str | uuid.UUID,- external_data_job_id: str,-) -> JobContext:- return JobContext(- team_id=team_id,- source_type=source_type,- external_data_source_id=str(external_data_source_id),- external_data_schema_id=str(external_data_schema_id),- external_data_job_id=external_data_job_id,- )---def bind_job_context(- *,- team_id: int,- source_type: str,- external_data_source_id: str | uuid.UUID,- external_data_schema_id: str | uuid.UUID,- external_data_job_id: str,-) -> JobContext:- """Set the current `JobContext` and bind matching structlog contextvars.-- Mirrors the existing pattern in `import_data_activity_sync` where- `bind_contextvars(team_id=...)` is called without an explicit unbind —- each activity invocation rebinds before doing work. The contextvar is- per-task / per-thread, so concurrent activities don't leak.- """- ctx = _make_context(- team_id=team_id,- source_type=source_type,- external_data_source_id=external_data_source_id,- external_data_schema_id=external_data_schema_id,- external_data_job_id=external_data_job_id,- )- _current_job_context.set(ctx)- bind_contextvars(- source_type=ctx.source_type,- external_data_source_id=ctx.external_data_source_id,- external_data_schema_id=ctx.external_data_schema_id,- external_data_job_id=ctx.external_data_job_id,- )- return ctx---@contextmanager-def scoped_job_context(- *,- team_id: int,- source_type: str,- external_data_source_id: str | uuid.UUID,- external_data_schema_id: str | uuid.UUID,- external_data_job_id: str,-) -> Iterator[JobContext]:- """Context-manager variant for tests / synthetic call sites.-- Resets the contextvar and unbinds structlog contextvars on exit so- test isolation isn't dependent on subsequent activities overwriting- state.- """- ctx = _make_context(- team_id=team_id,- source_type=source_type,- external_data_source_id=external_data_source_id,- external_data_schema_id=external_data_schema_id,- external_data_job_id=external_data_job_id,- )- token = _current_job_context.set(ctx)- bind_contextvars(- source_type=ctx.source_type,- external_data_source_id=ctx.external_data_source_id,- external_data_schema_id=ctx.external_data_schema_id,- external_data_job_id=ctx.external_data_job_id,- )- try:- yield ctx- finally:- _current_job_context.reset(token)- unbind_contextvars(*_BOUND_LOG_FIELD_NAMES)+__all__ = [+ "JobContext",+ "bind_job_context",+ "current_job_context",+ "scoped_job_context",+ "_make_context",+ "_current_job_context",+ "_BOUND_LOG_FIELD_NAMES",+]diff --git a/posthog/temporal/data_imports/sources/common/http/sampling.py b/posthog/temporal/data_imports/sources/common/http/sampling.pyindex 4f5f4caefc93..c5cb8a02bef6 100644--- a/posthog/temporal/data_imports/sources/common/http/sampling.py+++ b/posthog/temporal/data_imports/sources/common/http/sampling.py@@ -33,7 +33,6 @@ import timeimport uuidimport loggingimport threading-from dataclasses import dataclass, fieldfrom typing import TYPE_CHECKING, Anyfrom urllib.parse import parse_qsl, urlencode@@ -47,6 +46,12 @@ from posthog.temporal.data_imports.sources.common.http.url_utils import (redact_literal_values,scrub_url,)+from posthog.temporal.data_imports.sources.common.sample_scrub import (+ CaptureConfig,+ CaptureRule,+ scrub_string as _scrub_string,+ scrub_value as _scrub_value,+)if TYPE_CHECKING:from requests import PreparedRequest, Response@@ -60,85 +65,14 @@ CAPTURE_COUNTER_KEY_PREFIX = "data_imports:http_sample_capture:counter"S3_PREFIX = "warehouse-sources-http-samples"CONFIG_CACHE_TTL_SECONDS = 30MAX_CONFIG_TTL_SECONDS = 24 * 60 * 60-WILDCARD = "*"_REDACTED_HEADER = "REDACTED"_REDACTED_FORM_VALUE = "REDACTED"-_REDACTED_SCRUB_FAILURE = "<scrub_failed>"_AUTH_HEADER_NAMES: frozenset[str] = frozenset({"authorization", "x-api-key", "x-auth-token", "cookie", "set-cookie", "proxy-authorization"})--@dataclass(frozen=True)-class CaptureRule:- source_type: str = WILDCARD- response_code: str = WILDCARD- team_id: str = WILDCARD- schema_id: str = WILDCARD- limit: int = 0-- def matches(self, *, source_type: str, status_code: int | None, team_id: int, schema_id: str) -> bool:- if self.source_type != WILDCARD and self.source_type != source_type:- return False- if self.team_id != WILDCARD and self.team_id != str(team_id):- return False- if self.schema_id != WILDCARD and self.schema_id != str(schema_id):- return False- return _matches_status(self.response_code, status_code)-- @classmethod- def from_dict(cls, raw: dict[str, Any]) -> CaptureRule:- return cls(- source_type=str(raw.get("source_type") or WILDCARD),- response_code=str(raw.get("response_code") or WILDCARD),- team_id=str(raw.get("team_id") or WILDCARD),- schema_id=str(raw.get("schema_id") or WILDCARD),- limit=int(raw.get("limit") or 0),- )-- def to_dict(self) -> dict[str, Any]:- return {- "source_type": self.source_type,- "response_code": self.response_code,- "team_id": self.team_id,- "schema_id": self.schema_id,- "limit": self.limit,- }---@dataclass(frozen=True)-class CaptureConfig:- capture_id: str- rules: tuple[CaptureRule, ...] = field(default_factory=tuple)-- @classmethod- def from_json(cls, raw: bytes | str) -> CaptureConfig | None:- try:- data = json.loads(raw)- except (TypeError, ValueError, json.JSONDecodeError):- logger.warning("Failed to decode capture config JSON")- return None-- capture_id = data.get("capture_id")- if not capture_id:- return None- rules_raw = data.get("rules") or []- rules = tuple(CaptureRule.from_dict(r) for r in rules_raw if isinstance(r, dict))- return cls(capture_id=str(capture_id), rules=rules)-- def to_json(self) -> str:- return json.dumps({"capture_id": self.capture_id, "rules": [r.to_dict() for r in self.rules]})---def _matches_status(rule_value: str, status_code: int | None) -> bool:- if rule_value == WILDCARD:- return True- if status_code is None:- return False- if rule_value.endswith("xx") and len(rule_value) == 3 and rule_value[0].isdigit():- return str(status_code).startswith(rule_value[0])- return rule_value == str(status_code)+__all__ = ["CaptureConfig", "CaptureRule", "maybe_capture"]# In-process cache of the parsed Redis config. Thread-safe because the@@ -397,46 +331,3 @@ def _try_form_urlencoded(text: str) -> str | None:for name, value in pairs]return urlencode(scrubbed, doseq=False)---def _scrub_value(value: Any) -> Any:- """Walk a JSON-shaped value, scrubbing string leaves but preserving keys."""- if isinstance(value, dict):- return {k: _scrub_value(v) for k, v in value.items()}- if isinstance(value, list):- return [_scrub_value(item) for item in value]- if isinstance(value, str):- return _scrub_string(value)- return value---# scrubadub's default Scrubber is constructed lazily; the import is heavy.-_scrubber_lock = threading.Lock()-_scrubber: Any | None = None---def _get_scrubber() -> Any:- global _scrubber- if _scrubber is not None:- return _scrubber- with _scrubber_lock:- if _scrubber is None:- import scrubadub-- _scrubber = scrubadub.Scrubber()- return _scrubber---def _scrub_string(value: str) -> str:- if not value:- return value- try:- return _get_scrubber().clean(value)- except Exception:- # Fail closed: a scrubadub failure on a value we couldn't otherwise- # categorise must not leak the raw, potentially sensitive content- # into the captured sample. Replace with a placeholder so the- # surrounding structure (header dict, body shape) is preserved- # for fixture use, but the unredacted value never lands in S3.- logger.debug("scrubadub failed; replacing value with placeholder", exc_info=True)- return _REDACTED_SCRUB_FAILUREdiff --git a/posthog/temporal/data_imports/sources/common/job_context.py b/posthog/temporal/data_imports/sources/common/job_context.pynew file mode 100644index 000000000000..7d74b2cbe96e--- /dev/null+++ b/posthog/temporal/data_imports/sources/common/job_context.py@@ -0,0 +1,150 @@+"""Per-job context for warehouse-source telemetry.++The activity that runs a warehouse-source sync sets a `JobContext` once at+its entry point. The tracked transports (HTTP and gRPC) read it on every+outbound call to attach `team_id`, `source_type`, `external_data_schema_id`,+`external_data_source_id`, and `external_data_job_id` to logs, metrics and+sample-capture decisions.++Stored in a `contextvars.ContextVar` so it propagates across the source+generator's thread-pool boundary — see `pipelines/pipeline/pipeline.py`'s+`copy_context()` snapshot, which already preserves contextvars when calls+hop into the executor.++This module is transport-neutral: both `common/http` and `common/grpc`+import from here. `common/http/context.py` re-exports these names for+backwards compatibility.+"""++from __future__ import annotations++import contextvars+import dataclasses+from collections.abc import Iterator+from contextlib import contextmanager+from typing import TYPE_CHECKING++from structlog.contextvars import bind_contextvars, unbind_contextvars++if TYPE_CHECKING:+ import uuid++[email protected](frozen=True)+class JobContext:+ team_id: int+ source_type: str+ external_data_source_id: str+ external_data_schema_id: str+ external_data_job_id: str++ def as_log_fields(self) -> dict[str, int | str]:+ return {+ "team_id": self.team_id,+ "source_type": self.source_type,+ "external_data_source_id": self.external_data_source_id,+ "external_data_schema_id": self.external_data_schema_id,+ "external_data_job_id": self.external_data_job_id,+ }+++_current_job_context: contextvars.ContextVar[JobContext | None] = contextvars.ContextVar(+ "data_imports_job_context", default=None+)+++_BOUND_LOG_FIELD_NAMES: tuple[str, ...] = (+ "source_type",+ "external_data_source_id",+ "external_data_schema_id",+ "external_data_job_id",+)+++def current_job_context() -> JobContext | None:+ return _current_job_context.get()+++def _make_context(+ *,+ team_id: int,+ source_type: str,+ external_data_source_id: str | uuid.UUID,+ external_data_schema_id: str | uuid.UUID,+ external_data_job_id: str,+) -> JobContext:+ return JobContext(+ team_id=team_id,+ source_type=source_type,+ external_data_source_id=str(external_data_source_id),+ external_data_schema_id=str(external_data_schema_id),+ external_data_job_id=external_data_job_id,+ )+++def bind_job_context(+ *,+ team_id: int,+ source_type: str,+ external_data_source_id: str | uuid.UUID,+ external_data_schema_id: str | uuid.UUID,+ external_data_job_id: str,+) -> JobContext:+ """Set the current `JobContext` and bind matching structlog contextvars.++ Mirrors the existing pattern in `import_data_activity_sync` where+ `bind_contextvars(team_id=...)` is called without an explicit unbind —+ each activity invocation rebinds before doing work. The contextvar is+ per-task / per-thread, so concurrent activities don't leak.+ """+ ctx = _make_context(+ team_id=team_id,+ source_type=source_type,+ external_data_source_id=external_data_source_id,+ external_data_schema_id=external_data_schema_id,+ external_data_job_id=external_data_job_id,+ )+ _current_job_context.set(ctx)+ bind_contextvars(+ source_type=ctx.source_type,+ external_data_source_id=ctx.external_data_source_id,+ external_data_schema_id=ctx.external_data_schema_id,+ external_data_job_id=ctx.external_data_job_id,+ )+ return ctx+++@contextmanager+def scoped_job_context(+ *,+ team_id: int,+ source_type: str,+ external_data_source_id: str | uuid.UUID,+ external_data_schema_id: str | uuid.UUID,+ external_data_job_id: str,+) -> Iterator[JobContext]:+ """Context-manager variant for tests / synthetic call sites.++ Resets the contextvar and unbinds structlog contextvars on exit so+ test isolation isn't dependent on subsequent activities overwriting+ state.+ """+ ctx = _make_context(+ team_id=team_id,+ source_type=source_type,+ external_data_source_id=external_data_source_id,+ external_data_schema_id=external_data_schema_id,+ external_data_job_id=external_data_job_id,+ )+ token = _current_job_context.set(ctx)+ bind_contextvars(+ source_type=ctx.source_type,+ external_data_source_id=ctx.external_data_source_id,+ external_data_schema_id=ctx.external_data_schema_id,+ external_data_job_id=ctx.external_data_job_id,+ )+ try:+ yield ctx+ finally:+ _current_job_context.reset(token)+ unbind_contextvars(*_BOUND_LOG_FIELD_NAMES)diff --git a/posthog/temporal/data_imports/sources/common/sample_scrub.py b/posthog/temporal/data_imports/sources/common/sample_scrub.pynew file mode 100644index 000000000000..b5affeac20fc--- /dev/null+++ b/posthog/temporal/data_imports/sources/common/sample_scrub.py@@ -0,0 +1,171 @@+"""Transport-neutral sample-capture primitives.++Both the HTTP (`common/http/sampling.py`) and gRPC (`common/grpc/sampling.py`)+sample-capture pipelines share:++- the `CaptureRule` / `CaptureConfig` data model and its JSON (de)serialization,+- the status-class / status-code matching used to decide whether a rule fires,+- the scrubadub-based value scrubbing that anonymizes captured payloads.++Each transport keeps its own Redis key, S3 prefix, in-process config cache and+payload builder local — only the pieces above are shared here.+"""++from __future__ import annotations++import json+import logging+import threading+from dataclasses import dataclass, field+from typing import Any++logger = logging.getLogger(__name__)++WILDCARD = "*"+REDACTED_SCRUB_FAILURE = "<scrub_failed>"++# Auth-bearing field/key names redacted wholesale (by key) in captured samples,+# across transports. Deliberately curated to unambiguous secret-bearing names —+# generic, overloaded tokens like `code`, `key`, `auth`, or `token` are excluded+# because they collide with non-secret protobuf fields (e.g. `error.code`,+# `page_token`) and would make samples useless without protecting anything.+REDACT_FIELD_NAMES: frozenset[str] = frozenset(+ {+ "developer_token",+ "access_token",+ "refresh_token",+ "id_token",+ "subject_token",+ "actor_token",+ "client_secret",+ "client_assertion",+ "private_key",+ "private_key_id",+ "api_key",+ "apikey",+ "password",+ "authorization",+ }+)+++@dataclass(frozen=True)+class CaptureRule:+ source_type: str = WILDCARD+ response_code: str = WILDCARD+ team_id: str = WILDCARD+ schema_id: str = WILDCARD+ limit: int = 0++ def matches_dimensions(self, *, source_type: str, team_id: int, schema_id: str) -> bool:+ """Match the non-status dimensions (source/team/schema) against this rule."""+ if self.source_type != WILDCARD and self.source_type != source_type:+ return False+ if self.team_id != WILDCARD and self.team_id != str(team_id):+ return False+ if self.schema_id != WILDCARD and self.schema_id != str(schema_id):+ return False+ return True++ def matches(self, *, source_type: str, status_code: int | None, team_id: int, schema_id: str) -> bool:+ """HTTP-style match: dimensions + numeric HTTP status (incl. `2xx` classes)."""+ if not self.matches_dimensions(source_type=source_type, team_id=team_id, schema_id=schema_id):+ return False+ return matches_http_status(self.response_code, status_code)++ @classmethod+ def from_dict(cls, raw: dict[str, Any]) -> CaptureRule:+ return cls(+ source_type=str(raw.get("source_type") or WILDCARD),+ response_code=str(raw.get("response_code") or WILDCARD),+ team_id=str(raw.get("team_id") or WILDCARD),+ schema_id=str(raw.get("schema_id") or WILDCARD),+ limit=int(raw.get("limit") or 0),+ )++ def to_dict(self) -> dict[str, Any]:+ return {+ "source_type": self.source_type,+ "response_code": self.response_code,+ "team_id": self.team_id,+ "schema_id": self.schema_id,+ "limit": self.limit,+ }+++@dataclass(frozen=True)+class CaptureConfig:+ capture_id: str+ rules: tuple[CaptureRule, ...] = field(default_factory=tuple)++ @classmethod+ def from_json(cls, raw: bytes | str) -> CaptureConfig | None:+ try:+ data = json.loads(raw)+ except (TypeError, ValueError, json.JSONDecodeError):+ logger.warning("Failed to decode capture config JSON")+ return None++ capture_id = data.get("capture_id")+ if not capture_id:+ return None+ rules_raw = data.get("rules") or []+ rules = tuple(CaptureRule.from_dict(r) for r in rules_raw if isinstance(r, dict))+ return cls(capture_id=str(capture_id), rules=rules)++ def to_json(self) -> str:+ return json.dumps({"capture_id": self.capture_id, "rules": [r.to_dict() for r in self.rules]})+++def matches_http_status(rule_value: str, status_code: int | None) -> bool:+ """Match a numeric HTTP status against a rule value (`*`, `200`, or `2xx`)."""+ if rule_value == WILDCARD:+ return True+ if status_code is None:+ return False+ if rule_value.endswith("xx") and len(rule_value) == 3 and rule_value[0].isdigit():+ return str(status_code).startswith(rule_value[0])+ return rule_value == str(status_code)+++# scrubadub's default Scrubber is constructed lazily; the import is heavy.+_scrubber_lock = threading.Lock()+_scrubber: Any | None = None+++def get_scrubber() -> Any:+ global _scrubber+ if _scrubber is not None:+ return _scrubber+ with _scrubber_lock:+ if _scrubber is None:+ import scrubadub++ _scrubber = scrubadub.Scrubber()+ return _scrubber+++def scrub_string(value: str) -> str:+ if not value:+ return value+ try:+ return get_scrubber().clean(value)+ except Exception:+ # Fail closed: a scrubadub failure on a value we couldn't otherwise+ # categorise must not leak the raw, potentially sensitive content+ # into the captured sample. Replace with a placeholder so the+ # surrounding structure (header dict, body shape) is preserved+ # for fixture use, but the unredacted value never lands in S3.+ logger.debug("scrubadub failed; replacing value with placeholder", exc_info=True)+ return REDACTED_SCRUB_FAILURE+++def scrub_value(value: Any) -> Any:+ """Walk a JSON-shaped value, scrubbing string leaves but preserving keys."""+ if isinstance(value, dict):+ return {k: scrub_value(v) for k, v in value.items()}+ if isinstance(value, list):+ return [scrub_value(item) for item in value]+ if isinstance(value, str):+ return scrub_string(value)+ return valuediff --git a/posthog/temporal/data_imports/sources/common/test/test_grpc_metrics.py b/posthog/temporal/data_imports/sources/common/test/test_grpc_metrics.pynew file mode 100644index 000000000000..326dcff70ab0--- /dev/null+++ b/posthog/temporal/data_imports/sources/common/test/test_grpc_metrics.py@@ -0,0 +1,155 @@+import pytest+from unittest.mock import patch++import grpc++from posthog.temporal.data_imports.sources.common.grpc.metrics import (+ _NullCounter,+ _NullHistogram,+ _reset_cache_for_tests,+ get_grpc_latency_histogram,+ get_grpc_requests_counter,+ get_grpc_response_bytes_histogram,+ status_class,+)++[email protected](autouse=True)+def _reset_instrument_cache():+ """The instrument cache is process-global; clear it between tests."""+ _reset_cache_for_tests()+ yield+ _reset_cache_for_tests()+++ "code,expected",+ [+ (None, "error"),+ (grpc.StatusCode.OK, "ok"),+ (grpc.StatusCode.RESOURCE_EXHAUSTED, "resource_exhausted"),+ (grpc.StatusCode.INVALID_ARGUMENT, "client_error"),+ (grpc.StatusCode.NOT_FOUND, "client_error"),+ (grpc.StatusCode.ALREADY_EXISTS, "client_error"),+ (grpc.StatusCode.PERMISSION_DENIED, "client_error"),+ (grpc.StatusCode.UNAUTHENTICATED, "client_error"),+ (grpc.StatusCode.FAILED_PRECONDITION, "client_error"),+ (grpc.StatusCode.OUT_OF_RANGE, "client_error"),+ (grpc.StatusCode.DEADLINE_EXCEEDED, "unavailable"),+ (grpc.StatusCode.UNAVAILABLE, "unavailable"),+ (grpc.StatusCode.ABORTED, "unavailable"),+ (grpc.StatusCode.CANCELLED, "server_error"),+ (grpc.StatusCode.UNKNOWN, "server_error"),+ (grpc.StatusCode.UNIMPLEMENTED, "server_error"),+ (grpc.StatusCode.INTERNAL, "server_error"),+ (grpc.StatusCode.DATA_LOSS, "server_error"),+ ],+)+def test_status_class(code, expected: str):+ assert status_class(code) == expected+++def test_status_class_covers_every_code():+ """Every grpc.StatusCode must map to a known low-cardinality bucket."""+ valid = {"ok", "client_error", "resource_exhausted", "unavailable", "server_error", "error"}+ for code in grpc.StatusCode:+ assert status_class(code) in valid+++def test_null_counter_is_no_op():+ c = _NullCounter()+ c.add(1)+ c.add(0, {"method": "/x/Y"})+++def test_null_histogram_is_no_op():+ h = _NullHistogram()+ h.record(0)+ h.record(123, {"method": "/x/Y"})+++def test_get_counter_outside_workflow_returns_null():+ counter = get_grpc_requests_counter(team_id=1, source_type="google_ads")+ counter.add(1, {"method": "/x/Y", "status_class": "ok"})+++def test_get_histograms_outside_workflow_return_null():+ latency = get_grpc_latency_histogram(team_id=1, source_type="google_ads")+ bytes_ = get_grpc_response_bytes_histogram(team_id=1, source_type="google_ads")+ latency.record(123)+ bytes_.record(456)+++def test_meter_attributes_include_team_and_source():+ captured: list[dict] = []++ class FakeMeter:+ def with_additional_attributes(self, attrs):+ captured.append(attrs)+ return self++ def create_counter(self, name, desc):+ return object()++ with patch(+ "posthog.temporal.data_imports.sources.common.grpc.metrics._safe_metric_meter",+ return_value=FakeMeter(),+ ):+ get_grpc_requests_counter(team_id=42, source_type="google_ads")++ assert captured == [{"team_id": "42", "source_type": "google_ads"}]+++def test_get_counter_caches_per_team_and_source():+ creates: list[tuple[str, str]] = []++ class FakeMeter:+ def with_additional_attributes(self, attrs):+ return self++ def create_counter(self, name, desc):+ creates.append((name, desc))+ return object()++ with patch(+ "posthog.temporal.data_imports.sources.common.grpc.metrics._safe_metric_meter",+ return_value=FakeMeter(),+ ):+ first = get_grpc_requests_counter(team_id=42, source_type="google_ads")+ second = get_grpc_requests_counter(team_id=42, source_type="google_ads")+ third = get_grpc_requests_counter(team_id=42, source_type="bigquery")++ assert first is second+ assert first is not third+ assert len(creates) == 2+++def test_get_histogram_caches_per_team_and_source():+ creates: list[tuple[str, str]] = []++ class FakeMeter:+ def with_additional_attributes(self, attrs):+ return self++ def create_histogram(self, name, desc, unit):+ creates.append((name, desc))+ return object()++ with patch(+ "posthog.temporal.data_imports.sources.common.grpc.metrics._safe_metric_meter",+ return_value=FakeMeter(),+ ):+ a = get_grpc_latency_histogram(team_id=1, source_type="google_ads")+ b = get_grpc_latency_histogram(team_id=1, source_type="google_ads")+ c = get_grpc_response_bytes_histogram(team_id=1, source_type="google_ads")+ d = get_grpc_response_bytes_histogram(team_id=1, source_type="google_ads")++ assert a is b+ assert c is d+ assert len(creates) == 2+++def test_null_recorders_are_also_cached():+ first = get_grpc_requests_counter(team_id=1, source_type="google_ads")+ second = get_grpc_requests_counter(team_id=1, source_type="google_ads")+ assert first is seconddiff --git a/posthog/temporal/data_imports/sources/common/test/test_grpc_observer.py b/posthog/temporal/data_imports/sources/common/test/test_grpc_observer.pynew file mode 100644index 000000000000..082fe1fb526c--- /dev/null+++ b/posthog/temporal/data_imports/sources/common/test/test_grpc_observer.py@@ -0,0 +1,175 @@+import logging++import pytest+from unittest.mock import patch++import grpc++from posthog.temporal.data_imports.sources.common.grpc import observer+from posthog.temporal.data_imports.sources.common.grpc.observer import record_stream, record_unary+from posthog.temporal.data_imports.sources.common.job_context import scoped_job_context+++class _FakeMessage:+ def __init__(self, byte_size: int):+ self._byte_size = byte_size++ def ByteSize(self) -> int:+ return self._byte_size+++def _ctx():+ return scoped_job_context(+ team_id=99,+ source_type="google_ads",+ external_data_source_id="src",+ external_data_schema_id="schema",+ external_data_job_id="job",+ )+++def test_record_unary_emits_debug_log_on_ok(caplog):+ with _ctx(), patch.object(observer, "_emit_metrics"), patch.object(observer, "maybe_capture"):+ with caplog.at_level(logging.DEBUG, logger="posthog.temporal.data_imports.sources.common.grpc.observer"):+ record_unary(+ method="/svc/M",+ host="h",+ request=_FakeMessage(1),+ response=_FakeMessage(2),+ code=grpc.StatusCode.OK,+ exception=None,+ started_at_monotonic=0.0,+ )+ levels = {r.levelname for r in caplog.records}+ assert "WARNING" not in levels+++def test_record_unary_emits_warning_on_error():+ captured: list[tuple] = []++ class FakeLogger:+ def warning(self, *args, **kwargs):+ captured.append(("warning", args, kwargs))++ def debug(self, *args, **kwargs):+ captured.append(("debug", args, kwargs))++ with (+ _ctx(),+ patch.object(observer, "logger", FakeLogger()),+ patch.object(observer, "_emit_metrics"),+ patch.object(observer, "maybe_capture"),+ ):+ record_unary(+ method="/svc/M",+ host="h",+ request=_FakeMessage(1),+ response=None,+ code=grpc.StatusCode.UNAVAILABLE,+ exception=_FakeError(),+ started_at_monotonic=0.0,+ )++ assert captured and captured[0][0] == "warning"+++class _FakeError(grpc.RpcError):+ pass+++def test_observer_swallows_metric_failures():+ with (+ _ctx(),+ patch.object(observer, "maybe_capture"),+ patch(+ "posthog.temporal.data_imports.sources.common.grpc.observer.get_grpc_requests_counter",+ side_effect=RuntimeError("metrics down"),+ ),+ ):+ # Must not raise.+ record_unary(+ method="/svc/M",+ host="h",+ request=_FakeMessage(1),+ response=_FakeMessage(2),+ code=grpc.StatusCode.OK,+ exception=None,+ started_at_monotonic=0.0,+ )+++def test_observer_swallows_sampling_failures():+ with (+ _ctx(),+ patch.object(observer, "_emit_metrics"),+ patch.object(observer, "maybe_capture", side_effect=RuntimeError("s3 down")),+ ):+ record_stream(+ method="/svc/M",+ host="h",+ request=_FakeMessage(1),+ retained_responses=[_FakeMessage(2)],+ response_bytes=2,+ message_count=1,+ code=grpc.StatusCode.OK,+ exception=None,+ started_at_monotonic=0.0,+ )+++def test_record_unary_calls_sample_capture_with_response_messages():+ with _ctx(), patch.object(observer, "_emit_metrics"), patch.object(observer, "maybe_capture") as capture:+ response = _FakeMessage(2)+ record_unary(+ method="/svc/M",+ host="h",+ request=_FakeMessage(1),+ response=response,+ code=grpc.StatusCode.OK,+ exception=None,+ started_at_monotonic=0.0,+ )+ kwargs = capture.call_args.kwargs+ assert kwargs["response_messages"] == [response]+ assert kwargs["record"].status_class == "ok"+ assert kwargs["record"].status_code_num == 0+++def test_no_metrics_or_capture_without_job_context():+ """Outside a bound JobContext, metrics + capture are skipped (no crash)."""+ with patch.object(observer, "_emit_metrics") as metrics, patch.object(observer, "maybe_capture") as capture:+ record_unary(+ method="/svc/M",+ host="h",+ request=_FakeMessage(1),+ response=_FakeMessage(2),+ code=grpc.StatusCode.OK,+ exception=None,+ started_at_monotonic=0.0,+ )+ # _emit_metrics is always invoked but no-ops on None ctx; capture is gated on ctx.+ metrics.assert_called_once()+ capture.assert_not_called()+++ "code,expected_num",+ [+ (grpc.StatusCode.OK, 0),+ (grpc.StatusCode.UNAVAILABLE, 14),+ (grpc.StatusCode.RESOURCE_EXHAUSTED, 8),+ (None, None),+ ],+)+def test_status_code_num_extraction(code, expected_num):+ with _ctx(), patch.object(observer, "_emit_metrics"), patch.object(observer, "maybe_capture") as capture:+ record_unary(+ method="/svc/M",+ host="h",+ request=_FakeMessage(1),+ response=_FakeMessage(2) if code is not None else None,+ code=code,+ exception=None if code is not None else _FakeError(),+ started_at_monotonic=0.0,+ )+ assert capture.call_args.kwargs["record"].status_code_num == expected_numdiff --git a/posthog/temporal/data_imports/sources/common/test/test_grpc_sampling.py b/posthog/temporal/data_imports/sources/common/test/test_grpc_sampling.pynew file mode 100644index 000000000000..367a01971abf--- /dev/null+++ b/posthog/temporal/data_imports/sources/common/test/test_grpc_sampling.py@@ -0,0 +1,271 @@+import json++import pytest+from unittest.mock import MagicMock, patch++from google.protobuf.struct_pb2 import Struct++from posthog.temporal.data_imports.sources.common.grpc import sampling+from posthog.temporal.data_imports.sources.common.grpc.observer import GrpcRequestRecord+from posthog.temporal.data_imports.sources.common.grpc.proto_utils import message_byte_size, message_to_scrubbed_dict+from posthog.temporal.data_imports.sources.common.grpc.sampling import (+ CAPTURE_CONFIG_REDIS_KEY,+ S3_PREFIX,+ _build_sample_payload,+ _first_match,+ _matches_grpc_status,+ maybe_capture,+)+from posthog.temporal.data_imports.sources.common.job_context import JobContext+from posthog.temporal.data_imports.sources.common.sample_scrub import CaptureConfig, CaptureRule++[email protected](autouse=True)+def _reset_caches():+ sampling._reset_cache_for_tests()+ yield+ sampling._reset_cache_for_tests()+++def _ctx(team_id: int = 99, source_type: str = "google_ads", schema_id: str = "schema-uuid") -> JobContext:+ return JobContext(+ team_id=team_id,+ source_type=source_type,+ external_data_source_id="src-uuid",+ external_data_schema_id=schema_id,+ external_data_job_id="run-id",+ )+++def _record(+ *,+ method: str = "/svc/Search",+ status_class: str = "ok",+ status_code_num: int | None = 0,+ message_count: int | None = 1,+) -> GrpcRequestRecord:+ return GrpcRequestRecord(+ method=method,+ host="googleads.googleapis.com",+ request_bytes=10,+ response_bytes=20,+ status_class=status_class,+ status_code_num=status_code_num,+ latency_ms=42,+ message_count=message_count,+ error_class=None,+ )+++def _struct(data: dict) -> Struct:+ s = Struct()+ s.update(data)+ return s+++# ---------------------------------------------------------------------------+# proto helpers+# ---------------------------------------------------------------------------+++def test_message_byte_size_of_proto():+ msg = _struct({"a": "b"})+ assert message_byte_size(msg) == msg.ByteSize()+ assert message_byte_size(msg) > 0+++def test_message_byte_size_of_non_message_is_zero():+ assert message_byte_size(object()) == 0+ assert message_byte_size(None) == 0+ assert message_byte_size({"not": "a message"}) == 0+++def test_message_to_scrubbed_dict_redacts_auth_keys():+ msg = _struct({"developer_token": "super-secret", "refresh_token": "rt", "name": "campaign"})+ result = message_to_scrubbed_dict(msg)+ assert result["developer_token"] == "REDACTED"+ assert result["refresh_token"] == "REDACTED"+ assert "super-secret" not in json.dumps(result)+ assert "rt" not in [result["refresh_token"]]+++def test_message_to_scrubbed_dict_of_plain_dict():+ # Non-proto value (gapic hadn't coerced a dict request yet).+ result = message_to_scrubbed_dict({"client_secret": "x", "q": "value"})+ assert result["client_secret"] == "REDACTED"+++def test_message_to_scrubbed_dict_redacts_bytes_fields():+ """Bytes fields (e.g. BigQuery's serialized Arrow row batches) must not be+ base64-serialized into a sample — they carry raw table data scrubadub can't see."""+ from google.cloud.bigquery_storage_v1.types import ReadRowsResponse++ msg = ReadRowsResponse()+ msg.arrow_record_batch.serialized_record_batch = b"SECRET_CUSTOMER_ROWS"+ raw = type(msg).pb(msg)++ result = message_to_scrubbed_dict(raw)+ serialized = json.dumps(result)+ assert "SECRET_CUSTOMER_ROWS" not in serialized+ # base64 of the secret must not leak either.+ assert "U0VDUkVU" not in serialized+ assert result["arrow_record_batch"]["serialized_record_batch"] == "<bytes:20>"+++def test_message_to_scrubbed_dict_does_not_redact_proto_code_field():+ """`code` is a generic protobuf field name (e.g. error codes) — it must stay+ readable; only curated auth keys are redacted."""+ result = message_to_scrubbed_dict({"code": "INVALID_ARGUMENT", "developer_token": "x"})+ assert result["code"] == "INVALID_ARGUMENT"+ assert result["developer_token"] == "REDACTED"+++# ---------------------------------------------------------------------------+# status matching+# ---------------------------------------------------------------------------+++ "rule_value,status_class,code_num,expected",+ [+ ("*", "ok", 0, True),+ ("ok", "ok", 0, True),+ ("ok", "unavailable", 14, False),+ ("unavailable", "unavailable", 14, True),+ ("resource_exhausted", "resource_exhausted", 8, True),+ ("14", "unavailable", 14, True),+ ("8", "unavailable", 14, False),+ ("server_error", "ok", 0, False),+ ],+)+def test_matches_grpc_status(rule_value, status_class, code_num, expected):+ assert _matches_grpc_status(rule_value, status_class, code_num) is expected+++def test_first_match_dimensions_and_status():+ rules = (+ CaptureRule(source_type="bigquery", response_code="*", limit=5),+ CaptureRule(source_type="google_ads", response_code="unavailable", limit=5),+ CaptureRule(source_type="google_ads", response_code="*", limit=5),+ )+ match = _first_match(+ rules, source_type="google_ads", status_class="ok", status_code_num=0, team_id=99, schema_id="s"+ )+ assert match is not None+ # First two don't match (wrong source / wrong status); index 2 wins.+ assert match[0] == 2+++# ---------------------------------------------------------------------------+# config cache (separate from HTTP)+# ---------------------------------------------------------------------------+++def test_load_config_uses_grpc_redis_key():+ fake_redis = MagicMock()+ fake_redis.get.return_value = json.dumps({"capture_id": "x", "rules": []}).encode()+ with patch("posthog.temporal.data_imports.sources.common.grpc.sampling.get_client", return_value=fake_redis):+ sampling._load_config()+ fake_redis.get.assert_called_once_with(CAPTURE_CONFIG_REDIS_KEY)+++def test_is_capture_armed_reflects_config_presence():+ fake_redis = MagicMock()+ fake_redis.get.return_value = json.dumps({"capture_id": "x", "rules": []}).encode()+ with patch("posthog.temporal.data_imports.sources.common.grpc.sampling.get_client", return_value=fake_redis):+ assert sampling.is_capture_armed() is True++ sampling._reset_cache_for_tests()+ fake_redis.get.return_value = None+ with patch("posthog.temporal.data_imports.sources.common.grpc.sampling.get_client", return_value=fake_redis):+ assert sampling.is_capture_armed() is False+++ "limit,sequence,expected",+ [+ (0, [1], [False]),+ (2, [1, 2, 3], [True, True, False]),+ ],+)+def test_try_reserve_slot_enforces_limit(limit, sequence, expected):+ fake_redis = MagicMock()+ fake_redis.incr.side_effect = sequence+ fake_redis.ttl.return_value = 600+ with patch("posthog.temporal.data_imports.sources.common.grpc.sampling.get_client", return_value=fake_redis):+ results = [sampling._try_reserve_slot("cap", 0, limit) for _ in sequence]+ assert results == expected+++# ---------------------------------------------------------------------------+# payload + S3 layout+# ---------------------------------------------------------------------------+++def test_build_payload_scrubs_and_marks_truncation():+ request = _struct({"developer_token": "secret", "query": "SELECT 1"})+ responses = [_struct({"row": "1"}), _struct({"row": "2"})]+ record = _record(message_count=50) # more produced than retained++ payload = json.loads(_build_sample_payload(request=request, response_messages=responses, record=record, ctx=_ctx()))++ assert payload["request"]["message"]["developer_token"] == "REDACTED"+ assert payload["request"]["method"] == "/svc/Search"+ assert payload["response"]["status_class"] == "ok"+ assert payload["response"]["truncated"] is True+ assert payload["context"]["team_id"] == 99+ assert "secret" not in json.dumps(payload)+++def test_build_payload_drops_bodies_over_size_cap():+ big = _struct({"blob": "x" * (sampling.MAX_SAMPLE_BYTES)})+ record = _record(message_count=1)+ payload = json.loads(_build_sample_payload(request=_struct({}), response_messages=[big], record=record, ctx=_ctx()))+ assert payload["response"]["messages"] == []+ assert payload["response"]["dropped_for_size"] is True+++def test_maybe_capture_writes_matching_sample_to_s3():+ config = CaptureConfig(+ capture_id="cap123", rules=(CaptureRule(source_type="google_ads", response_code="ok", limit=10),)+ )+ fake_redis = MagicMock()+ fake_redis.get.return_value = config.to_json().encode()+ fake_redis.incr.side_effect = [1, 1] # reserve slot, then sequence+ fake_redis.ttl.return_value = 600++ with (+ patch("posthog.temporal.data_imports.sources.common.grpc.sampling.get_client", return_value=fake_redis),+ patch("posthog.temporal.data_imports.sources.common.grpc.sampling.object_storage.write") as write,+ ):+ maybe_capture(+ request=_struct({"q": "x"}), response_messages=[_struct({"r": "1"})], record=_record(), ctx=_ctx()+ )++ assert write.called+ key = write.call_args.args[0]+ assert key.startswith(f"{S3_PREFIX}/cap123/google_ads/")+ assert key.endswith(".json")+++def test_maybe_capture_noop_when_no_config():+ fake_redis = MagicMock()+ fake_redis.get.return_value = None+ with (+ patch("posthog.temporal.data_imports.sources.common.grpc.sampling.get_client", return_value=fake_redis),+ patch("posthog.temporal.data_imports.sources.common.grpc.sampling.object_storage.write") as write,+ ):+ maybe_capture(request=_struct({}), response_messages=[], record=_record(), ctx=_ctx())+ write.assert_not_called()+++def test_maybe_capture_noop_when_no_rule_matches():+ config = CaptureConfig(capture_id="cap", rules=(CaptureRule(source_type="bigquery", response_code="*", limit=10),))+ fake_redis = MagicMock()+ fake_redis.get.return_value = config.to_json().encode()+ with (+ patch("posthog.temporal.data_imports.sources.common.grpc.sampling.get_client", return_value=fake_redis),+ patch("posthog.temporal.data_imports.sources.common.grpc.sampling.object_storage.write") as write,+ ):+ maybe_capture(request=_struct({}), response_messages=[], record=_record(), ctx=_ctx())+ write.assert_not_called()diff --git a/posthog/temporal/data_imports/sources/common/test/test_grpc_transport.py b/posthog/temporal/data_imports/sources/common/test/test_grpc_transport.pynew file mode 100644index 000000000000..fc090cda7236--- /dev/null+++ b/posthog/temporal/data_imports/sources/common/test/test_grpc_transport.py@@ -0,0 +1,308 @@+from types import SimpleNamespace+from typing import Any++import pytest+from unittest.mock import patch++import grpc++from posthog.temporal.data_imports.sources.common.grpc import transport+from posthog.temporal.data_imports.sources.common.grpc.transport import (+ TrackedUnaryStreamClientInterceptor,+ TrackedUnaryUnaryClientInterceptor,+ make_tracked_channel,+ tracked_interceptors,+)++HOST = "googleads.googleapis.com"+METHOD = "/google.ads.googleads.v23.services.GoogleAdsService/Search"+++class _FakeMessage:+ def __init__(self, byte_size: int):+ self._byte_size = byte_size++ def ByteSize(self) -> int:+ return self._byte_size+++class _FakeUnaryOutcome:+ """Mimics grpc's `_UnaryOutcome`: resolved future with code/result/exception."""++ def __init__(self, response: Any, code: grpc.StatusCode = grpc.StatusCode.OK):+ self._response = response+ self._code = code++ def code(self) -> grpc.StatusCode:+ return self._code++ def exception(self) -> BaseException | None:+ return None++ def result(self) -> Any:+ return self._response+++class _FakeRpcError(grpc.RpcError):+ def __init__(self, code: grpc.StatusCode):+ self._code = code++ def code(self) -> grpc.StatusCode:+ return self._code+++def _call_details(method: str = METHOD) -> SimpleNamespace:+ return SimpleNamespace(method=method)+++# ---------------------------------------------------------------------------+# Unary-unary+# ---------------------------------------------------------------------------+++def test_unary_success_records_and_returns_outcome_unchanged():+ request = _FakeMessage(11)+ response = _FakeMessage(22)+ outcome = _FakeUnaryOutcome(response, grpc.StatusCode.OK)++ interceptor = TrackedUnaryUnaryClientInterceptor(HOST)+ with patch.object(transport, "record_unary") as record:+ result = interceptor.intercept_unary_unary(lambda d, r: outcome, _call_details(), request)++ assert result is outcome+ kwargs = record.call_args.kwargs+ assert kwargs["method"] == METHOD+ assert kwargs["host"] == HOST+ assert kwargs["request"] is request+ assert kwargs["response"] is response+ assert kwargs["code"] == grpc.StatusCode.OK+ assert kwargs["exception"] is None+++def test_unary_error_records_error_and_returns_outcome_unchanged():+ request = _FakeMessage(11)+ error = _FakeRpcError(grpc.StatusCode.UNAVAILABLE)++ interceptor = TrackedUnaryUnaryClientInterceptor(HOST)+ with patch.object(transport, "record_unary") as record:+ result = interceptor.intercept_unary_unary(lambda d, r: error, _call_details(), request)++ # The raw RpcError is returned so the SDK's `.result()` still raises.+ assert result is error+ kwargs = record.call_args.kwargs+ assert kwargs["code"] == grpc.StatusCode.UNAVAILABLE+ assert kwargs["response"] is None+ assert kwargs["exception"] is error+++def test_unary_observer_failure_does_not_mask_outcome():+ outcome = _FakeUnaryOutcome(_FakeMessage(1))+ interceptor = TrackedUnaryUnaryClientInterceptor(HOST)+ with patch.object(transport, "record_unary", side_effect=RuntimeError("telemetry boom")):+ result = interceptor.intercept_unary_unary(lambda d, r: outcome, _call_details(), _FakeMessage(1))+ assert result is outcome+++# ---------------------------------------------------------------------------+# Unary-stream+# ---------------------------------------------------------------------------+++def test_stream_success_sizes_counts_and_records_once():+ messages = [_FakeMessage(10), _FakeMessage(20), _FakeMessage(30)]+ interceptor = TrackedUnaryStreamClientInterceptor(HOST)++ with (+ patch.object(transport, "record_stream") as record,+ patch.object(transport, "is_capture_armed", return_value=False),+ ):+ wrapper = interceptor.intercept_unary_stream(lambda d, r: iter(messages), _call_details(), _FakeMessage(5))+ collected = list(wrapper)++ assert collected == messages+ assert record.call_count == 1+ kwargs = record.call_args.kwargs+ assert kwargs["code"] == grpc.StatusCode.OK+ assert kwargs["message_count"] == 3+ assert kwargs["response_bytes"] == 60+ assert kwargs["exception"] is None+ assert kwargs["retained_responses"] == [] # capture disarmed → nothing retained+++def test_stream_is_lazy_and_does_not_buffer():+ produced: list[int] = []++ def gen():+ for i in range(3):+ produced.append(i)+ yield _FakeMessage(1)++ interceptor = TrackedUnaryStreamClientInterceptor(HOST)+ with patch.object(transport, "record_stream"), patch.object(transport, "is_capture_armed", return_value=False):+ wrapper = interceptor.intercept_unary_stream(lambda d, r: gen(), _call_details(), _FakeMessage(0))+ it = iter(wrapper)+ next(it)+ # Only the first element should have been produced so far.+ assert produced == [0]+ next(it)+ assert produced == [0, 1]+++def test_stream_error_mid_iteration_records_and_reraises():+ error = _FakeRpcError(grpc.StatusCode.RESOURCE_EXHAUSTED)++ def gen():+ yield _FakeMessage(10)+ yield _FakeMessage(20)+ raise error++ interceptor = TrackedUnaryStreamClientInterceptor(HOST)+ with (+ patch.object(transport, "record_stream") as record,+ patch.object(transport, "is_capture_armed", return_value=False),+ ):+ wrapper = interceptor.intercept_unary_stream(lambda d, r: gen(), _call_details(), _FakeMessage(0))+ it = iter(wrapper)+ next(it)+ next(it)+ with pytest.raises(grpc.RpcError):+ next(it)++ assert record.call_count == 1+ kwargs = record.call_args.kwargs+ assert kwargs["code"] == grpc.StatusCode.RESOURCE_EXHAUSTED+ assert kwargs["exception"] is error+ assert kwargs["message_count"] == 2+ assert kwargs["response_bytes"] == 30+++def test_stream_retains_head_only_when_capture_armed():+ messages = [_FakeMessage(1) for _ in range(10)]+ interceptor = TrackedUnaryStreamClientInterceptor(HOST)++ with (+ patch.object(transport, "record_stream") as record,+ patch.object(transport, "is_capture_armed", return_value=True),+ ):+ wrapper = interceptor.intercept_unary_stream(lambda d, r: iter(messages), _call_details(), _FakeMessage(0))+ list(wrapper)++ retained = record.call_args.kwargs["retained_responses"]+ # MAX_CAPTURED_RESPONSE_MESSAGES head only, not all 10.+ assert 0 < len(retained) <= 3+ assert record.call_args.kwargs["message_count"] == 10+++def test_stream_observer_failure_does_not_break_iteration():+ messages = [_FakeMessage(1)]+ interceptor = TrackedUnaryStreamClientInterceptor(HOST)+ with (+ patch.object(transport, "record_stream", side_effect=RuntimeError("boom")),+ patch.object(transport, "is_capture_armed", return_value=False),+ ):+ wrapper = interceptor.intercept_unary_stream(lambda d, r: iter(messages), _call_details(), _FakeMessage(0))+ assert list(wrapper) == messages+++def test_stream_wrapper_delegates_unknown_attributes():+ sentinel = object()++ class _CallLike:+ def __iter__(self):+ return iter([])++ def cancel(self):+ return sentinel++ interceptor = TrackedUnaryStreamClientInterceptor(HOST)+ with patch.object(transport, "is_capture_armed", return_value=False):+ wrapper = interceptor.intercept_unary_stream(lambda d, r: _CallLike(), _call_details(), _FakeMessage(0))+ assert wrapper.cancel() is sentinel+++def test_stream_close_records_partial_stream_when_consumer_stops_early():+ messages = [_FakeMessage(10), _FakeMessage(20), _FakeMessage(30)]+ interceptor = TrackedUnaryStreamClientInterceptor(HOST)++ with (+ patch.object(transport, "record_stream") as record,+ patch.object(transport, "is_capture_armed", return_value=False),+ ):+ wrapper = interceptor.intercept_unary_stream(lambda d, r: iter(messages), _call_details(), _FakeMessage(0))+ it = iter(wrapper)+ next(it) # consume one message, then bail out early+ wrapper.close()++ assert record.call_count == 1+ kwargs = record.call_args.kwargs+ assert kwargs["code"] is None+ assert kwargs["exception"] is None+ assert kwargs["message_count"] == 1+ assert kwargs["response_bytes"] == 10+++def test_stream_close_after_completion_does_not_double_record():+ messages = [_FakeMessage(10)]+ interceptor = TrackedUnaryStreamClientInterceptor(HOST)++ with (+ patch.object(transport, "record_stream") as record,+ patch.object(transport, "is_capture_armed", return_value=False),+ ):+ wrapper = interceptor.intercept_unary_stream(lambda d, r: iter(messages), _call_details(), _FakeMessage(0))+ list(wrapper) # drains to StopIteration → records once+ wrapper.close() # idempotent: guarded by _recorded++ assert record.call_count == 1+ assert record.call_args.kwargs["code"] == grpc.StatusCode.OK+++def test_stream_close_delegates_to_inner_iterator():+ closed = []++ class _ClosableCall:+ def __iter__(self):+ return iter([])++ def close(self):+ closed.append(True)++ interceptor = TrackedUnaryStreamClientInterceptor(HOST)+ with (+ patch.object(transport, "record_stream"),+ patch.object(transport, "is_capture_armed", return_value=False),+ ):+ wrapper = interceptor.intercept_unary_stream(lambda d, r: _ClosableCall(), _call_details(), _FakeMessage(0))+ wrapper.close()++ assert closed == [True]+++# ---------------------------------------------------------------------------+# Factories+# ---------------------------------------------------------------------------+++def test_tracked_interceptors_returns_both_kinds():+ interceptors = tracked_interceptors(HOST)+ assert len(interceptors) == 2+ assert any(isinstance(i, grpc.UnaryUnaryClientInterceptor) for i in interceptors)+ assert any(isinstance(i, grpc.UnaryStreamClientInterceptor) for i in interceptors)+++def test_make_tracked_channel_wraps_with_interceptors():+ base = grpc.insecure_channel("localhost:50051")+ captured: dict[str, Any] = {}++ def fake_intercept(channel, *interceptors):+ captured["channel"] = channel+ captured["interceptors"] = interceptors+ return "intercepted"++ with patch("grpc.intercept_channel", side_effect=fake_intercept):+ result = make_tracked_channel(base, host=HOST)++ assert result == "intercepted"+ assert captured["channel"] is base+ assert len(captured["interceptors"]) == 2+ base.close()diff --git a/posthog/temporal/data_imports/sources/common/test/test_http_sampling.py b/posthog/temporal/data_imports/sources/common/test/test_http_sampling.pyindex b3c54295ba68..0ccf6893e365 100644--- a/posthog/temporal/data_imports/sources/common/test/test_http_sampling.py+++ b/posthog/temporal/data_imports/sources/common/test/test_http_sampling.py@@ -449,7 +449,7 @@ def test_scrub_body_handles_none():def test_scrub_string_fails_closed_when_scrubadub_fails():"""A scrubadub crash must NOT leak the raw value — replace with a placeholder."""with patch(- "posthog.temporal.data_imports.sources.common.http.sampling._get_scrubber",+ "posthog.temporal.data_imports.sources.common.sample_scrub.get_scrubber",side_effect=RuntimeError("scrubadub broken"),):result = sampling._scrub_string("super-secret-token-123")diff --git a/posthog/temporal/data_imports/sources/common/test/test_job_context.py b/posthog/temporal/data_imports/sources/common/test/test_job_context.pynew file mode 100644index 000000000000..3036256b77e1--- /dev/null+++ b/posthog/temporal/data_imports/sources/common/test/test_job_context.py@@ -0,0 +1,48 @@+from posthog.temporal.data_imports.sources.common import job_context+from posthog.temporal.data_imports.sources.common.http import context as http_context+from posthog.temporal.data_imports.sources.common.job_context import (+ bind_job_context,+ current_job_context,+ scoped_job_context,+)+++def test_http_context_shim_reexports_neutral_module():+ """The HTTP context module must re-export the neutral objects unchanged."""+ assert http_context.JobContext is job_context.JobContext+ assert http_context.bind_job_context is job_context.bind_job_context+ assert http_context.scoped_job_context is job_context.scoped_job_context+ assert http_context.current_job_context is job_context.current_job_context+ # Private names a few HTTP tests reach into.+ assert http_context._current_job_context is job_context._current_job_context+ assert http_context._BOUND_LOG_FIELD_NAMES is job_context._BOUND_LOG_FIELD_NAMES+++def test_scoped_job_context_sets_and_resets():+ assert current_job_context() is None+ with scoped_job_context(+ team_id=1,+ source_type="google_ads",+ external_data_source_id="s",+ external_data_schema_id="sc",+ external_data_job_id="j",+ ) as ctx:+ assert current_job_context() is ctx+ assert ctx.team_id == 1+ assert ctx.source_type == "google_ads"+ assert current_job_context() is None+++def test_bind_job_context_coerces_uuid_like_ids_to_str():+ import uuid++ source_id = uuid.uuid4()+ ctx = bind_job_context(+ team_id=7,+ source_type="bigquery",+ external_data_source_id=source_id,+ external_data_schema_id="sc",+ external_data_job_id="j",+ )+ assert ctx.external_data_source_id == str(source_id)+ assert current_job_context() is ctxdiff --git a/posthog/temporal/data_imports/sources/google_ads/google_ads.py b/posthog/temporal/data_imports/sources/google_ads/google_ads.pyindex c7d0eecc52ff..beb994f72955 100644--- a/posthog/temporal/data_imports/sources/google_ads/google_ads.py+++ b/posthog/temporal/data_imports/sources/google_ads/google_ads.py@@ -21,6 +21,7 @@ from posthog.temporal.data_imports.naming_convention import NamingConventionfrom posthog.temporal.data_imports.pipelines.helpers import incremental_type_to_initial_valuefrom posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponsefrom posthog.temporal.data_imports.sources.common import config+from posthog.temporal.data_imports.sources.common.grpc import tracked_interceptorsfrom posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom posthog.temporal.data_imports.sources.common.sql import Column, Tablefrom posthog.temporal.data_imports.sources.generated_configs import GoogleAdsSourceConfig@@ -28,6 +29,10 @@ from posthog.temporal.data_imports.sources.google_ads.schemas import FIELD_ALIASfrom products.data_warehouse.backend.types import IncrementalFieldType+# Host used to label the tracked gRPC transport's logs/metrics. Matches+# `GoogleAdsServiceClient.DEFAULT_ENDPOINT`.+GOOGLE_ADS_HOST = "googleads.googleapis.com"+@dataclasses.dataclassclass GoogleAdsResumeConfig:@@ -307,7 +312,7 @@ def get_schemas(config: GoogleAdsSourceConfigUnion, team_id: int) -> TableSchemaOnly selectable fields are, well, selected."""client = google_ads_client(config, team_id)- gaf_service = client.get_service("GoogleAdsFieldService")+ gaf_service = client.get_service("GoogleAdsFieldService", interceptors=tracked_interceptors(GOOGLE_ADS_HOST))fields_query = gaf_service.search_google_ads_fields(query=f"select name, data_type, is_repeated, type_url where selectable = true")@@ -426,7 +431,9 @@ def google_ads_source(query += f" {'AND' if 'WHERE' in query else 'WHERE'} {table.extra_where}"client = google_ads_client(config, team_id)- service: GoogleAdsServiceClient = client.get_service("GoogleAdsService", version="v23")+ service: GoogleAdsServiceClient = client.get_service(+ "GoogleAdsService", version="v23", interceptors=tracked_interceptors(GOOGLE_ADS_HOST)+ )customer_id = clean_customer_id(config.customer_id)yield from _search_as_arrow_tables(diff --git a/posthog/temporal/data_imports/workflow_activities/import_data_sync.py b/posthog/temporal/data_imports/workflow_activities/import_data_sync.pyindex 9400a3df0ed7..84a66891e8dd 100644--- a/posthog/temporal/data_imports/workflow_activities/import_data_sync.py+++ b/posthog/temporal/data_imports/workflow_activities/import_data_sync.py@@ -26,7 +26,7 @@ from posthog.temporal.data_imports.pipelines.pipeline_sync import PipelineInputsfrom posthog.temporal.data_imports.row_tracking import setup_row_trackingfrom posthog.temporal.data_imports.sources import SourceRegistryfrom posthog.temporal.data_imports.sources.common.base import ResumableSource, SimpleSource-from posthog.temporal.data_imports.sources.common.http import bind_job_context+from posthog.temporal.data_imports.sources.common.job_context import bind_job_contextfrom posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom posthog.temporal.data_imports.sources.postgres.exceptions import CDCHandledExternally