: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 1 missing table to the RentCast source (#118410)
Tom Owers5b9144879e78
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.mdindex bd6ff0384088..ae46cb8e375b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md@@ -10110,7 +10110,7 @@ Today (3): `properties`, `rental_listings`, `sale_listings`Diffed against: <https://developers.rentcast.io/sitemap.xml>-- [ ] `/v1/markets (market statistics)` — zip-level rental and sale market aggregates plus history - the only aggregate dataset RentCast publishes and the natural join target for the listings already synced (high)+- [x] `/v1/markets (market statistics)` — zip-level rental and sale market aggregates plus history - the only aggregate dataset RentCast publishes and the natural join target for the listings already synced (high)Note: The remaining uncovered endpoints - /v1/avm/value (value estimate) and /v1/avm/rent/long-term (rent estimate) - are per-address computations that require an address or lat/long on every call, so they do not map to a syncable table; they are deliberately excluded rather than overlooked. Static 3-table source, no dynamic discovery in products/warehouse_sources/backend/temporal/data_imports/sources/rentcast.diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/rentcast.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/rentcast.pyindex 3fb7086edaf0..5a164111a8b9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/rentcast.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/rentcast.py@@ -7,3 +7,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass RentCastSourceConfig(config.Config):api_key: str+ zip_codes: str | None = Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/rentcast/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/rentcast/canonical_descriptions.pyindex ee2de393a9c1..f619edab0af4 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/rentcast/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/rentcast/canonical_descriptions.py@@ -76,4 +76,14 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"daysOnMarket": "The number of days the property has been on the market.",},},+ "markets": {+ "description": "Aggregate sale and rental market statistics and monthly historical trends for one US ZIP code.",+ "docs_url": "https://developers.rentcast.io/reference/market-data-schema",+ "columns": {+ "id": "The ZIP code id, as a 5-digit number.",+ "zipCode": "The ZIP code name, as a 5-digit number.",+ "saleData": "Aggregate sale market statistics and property price trends for this ZIP code, including breakdowns by property type and bedrooms and monthly history. Absent when no sale statistics are available.",+ "rentalData": "Aggregate rental market statistics and rent trends for this ZIP code, including breakdowns by property type and bedrooms and monthly history. Absent when no rental statistics are available.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/rentcast/rentcast.py b/products/warehouse_sources/backend/temporal/data_imports/sources/rentcast/rentcast.pyindex d77b72da6685..10e0aaa84a4e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/rentcast/rentcast.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/rentcast/rentcast.py@@ -1,4 +1,6 @@+import reimport dataclasses+from collections.abc import Iterator, Sequencefrom typing import Any, Optionalfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session@@ -6,13 +8,23 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resRESTAPIConfig,rest_api_resource,)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import APIKeyAuth+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.config_setup import (+ create_response_hooks,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (OffsetPaginator,+ SinglePagePaginator,)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import RESTClient+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import ResponseActionfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse-from products.warehouse_sources.backend.temporal.data_imports.sources.rentcast.settings import RENTCAST_ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.rentcast.settings import (+ MARKETS_ENDPOINT,+ RENTCAST_ENDPOINTS,+)RENTCAST_BASE_URL = "https://api.rentcast.io/v1"# The list endpoints accept a `limit` between 1 and 500; the largest page minimises round trips@@ -21,13 +33,88 @@ PAGE_SIZE = 500# Cheap endpoint used to confirm an API key is genuine. The key is account-wide, so one probe# validates access to every list endpoint. A `limit` of 1 keeps the billed request small.DEFAULT_PROBE_PATH = "/properties"+# One `/markets` call returns one small aggregate object, so a short read timeout is enough.+MARKETS_REQUEST_TIMEOUT = (10, 60)+# RentCast answers 404 when it has no market statistics for a ZIP code. That ZIP code gets no row+# and the sync continues with the next one.+MARKETS_RESPONSE_ACTIONS: list[ResponseAction] = [{"status_code": 404, "action": "ignore"}]+ZIP_CODE_SEPARATOR = re.compile(r"[,\s]+")+ZIP_CODE_PATTERN = re.compile(r"^\d{5}$")+MISSING_ZIP_CODES_ERROR = "The RentCast markets table needs at least one ZIP code"+INVALID_ZIP_CODES_ERROR = "RentCast ZIP codes must be 5-digit US ZIP codes"[email protected] # nosemgrep: prefer-frozen-dataclasses -- pre-existing; new field shifts the backlog finding into diffclass RentCastResumeConfig:# Offset of the next page to fetch. Offset pagination is deterministic, so a crashed# full-refresh sync resumes from the page after the last one yielded; merge dedupes on `id`.offset: int = 0+ # For `markets`, the next ZIP code to fetch. Tracked by value rather than position so that editing+ # the configured ZIP code list between runs never skips or repeats ZIP codes.+ next_zip_code: Optional[str] = None+++def parse_zip_codes(value: Optional[str]) -> list[str]:+ zip_codes = list(dict.fromkeys(part for part in ZIP_CODE_SEPARATOR.split(value or "") if part))+ invalid = [zip_code for zip_code in zip_codes if not ZIP_CODE_PATTERN.match(zip_code)]+ if invalid:+ raise ValueError(f"{INVALID_ZIP_CODES_ERROR}. Check these values: {', '.join(invalid)}")+ return zip_codes+++def _market_pages(+ api_key: str,+ zip_codes: Sequence[str],+ resumable_source_manager: ResumableSourceManager[RentCastResumeConfig],+) -> Iterator[list[Any]]:+ client = RESTClient(+ base_url=RENTCAST_BASE_URL,+ headers={"Accept": "application/json"},+ auth=APIKeyAuth(api_key=api_key, name="X-Api-Key", location="header"),+ request_timeout=MARKETS_REQUEST_TIMEOUT,+ )+ hooks = create_response_hooks(MARKETS_RESPONSE_ACTIONS)++ start = 0+ if resumable_source_manager.can_resume():+ resume = resumable_source_manager.load_state()+ if resume is not None and resume.next_zip_code in zip_codes:+ start = zip_codes.index(resume.next_zip_code)++ for index in range(start, len(zip_codes)):+ rows = [+ row+ for page in client.paginate(+ "/markets",+ params={"zipCode": zip_codes[index]},+ paginator=SinglePagePaginator(),+ hooks=hooks,+ )+ for row in page+ ]+ if index + 1 < len(zip_codes):+ resumable_source_manager.save_state(RentCastResumeConfig(next_zip_code=zip_codes[index + 1]))+ if rows:+ yield rows+ resumable_source_manager.safe_point()+++def _markets_source(+ api_key: str,+ zip_codes_setting: Optional[str],+ resumable_source_manager: ResumableSourceManager[RentCastResumeConfig],+) -> SourceResponse:+ zip_codes = parse_zip_codes(zip_codes_setting)+ if not zip_codes:+ raise ValueError(f"{MISSING_ZIP_CODES_ERROR}. Add a comma-separated list of ZIP codes to the source settings.")++ return SourceResponse(+ name=MARKETS_ENDPOINT,+ items=lambda: _market_pages(api_key, zip_codes, resumable_source_manager),+ primary_keys=RENTCAST_ENDPOINTS[MARKETS_ENDPOINT].primary_keys,+ partition_count=1,+ partition_size=1,+ )def rentcast_source(@@ -37,7 +124,11 @@ def rentcast_source(job_id: str,resumable_source_manager: ResumableSourceManager[RentCastResumeConfig],db_incremental_field_last_value: Optional[Any] = None,+ zip_codes: Optional[str] = None,) -> SourceResponse:+ if endpoint == MARKETS_ENDPOINT:+ return _markets_source(api_key, zip_codes, resumable_source_manager)+config = RENTCAST_ENDPOINTS[endpoint]rest_config: RESTAPIConfig = {diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/rentcast/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/rentcast/settings.pyindex c705ddf17e04..857333b655df 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/rentcast/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/rentcast/settings.py@@ -16,15 +16,20 @@ class RentCastEndpointConfig:# updated-since cursor (listing search only filters by `daysOld`, days since first listed, which# isn't a last-modified timestamp), so there is no incremental cursor to advance safely.#-# Only endpoints that return a record list via limit/offset pagination without a mandatory parent-# id are included. RentCast is a property-lookup API, so these search endpoints accept optional-# geographic filters (city/state/zipCode/lat-long) and fall back to a broad default area when none-# is supplied. The single-object market-statistics endpoint (`/markets`) requires a `zipCode` and-# is intentionally omitted.+# The search endpoints return a record list via limit/offset pagination. RentCast is a+# property-lookup API, so they accept optional geographic filters (city/state/zipCode/lat-long) and+# fall back to a broad default area when none is supplied.+#+# `/markets` returns one aggregate object per call and requires a `zipCode`, so the `markets` table+# makes one request per ZIP code the user lists in the source settings. The response `id` is the ZIP+# code itself.+MARKETS_ENDPOINT = "markets"+RENTCAST_ENDPOINTS: dict[str, RentCastEndpointConfig] = {"properties": RentCastEndpointConfig(name="properties", path="/properties"),"sale_listings": RentCastEndpointConfig(name="sale_listings", path="/listings/sale"),"rental_listings": RentCastEndpointConfig(name="rental_listings", path="/listings/rental/long-term"),+ MARKETS_ENDPOINT: RentCastEndpointConfig(name=MARKETS_ENDPOINT, path="/markets"),}ENDPOINTS = tuple(RENTCAST_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/rentcast/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/rentcast/source.pyindex 8d100c93a948..dfe9782995ea 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/rentcast/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/rentcast/source.py@@ -23,13 +23,17 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_RentCastSourceConfig,)from products.warehouse_sources.backend.temporal.data_imports.sources.rentcast.rentcast import (+ INVALID_ZIP_CODES_ERROR,+ MISSING_ZIP_CODES_ERROR,RentCastResumeConfig,+ parse_zip_codes,rentcast_source,validate_credentials as _validate_rentcast_credentials,)from products.warehouse_sources.backend.temporal.data_imports.sources.rentcast.settings import (ENDPOINTS,INCREMENTAL_FIELDS,+ MARKETS_ENDPOINT,RENTCAST_ENDPOINTS,)from products.warehouse_sources.backend.types import ExternalDataSourceType@@ -57,7 +61,9 @@ class RentCastSource(ResumableSource[RentCastSourceConfig, RentCastResumeConfig]releaseStatus=ReleaseStatus.ALPHA,caption="""Enter your RentCast API key to pull US real estate data into the PostHog Data warehouse.-You can create an API key under **API dashboard** in [RentCast](https://app.rentcast.io/app/api). The key grants read access to property records and active sale and rental listings.+You can create an API key under **API dashboard** in [RentCast](https://app.rentcast.io/app/api). The key grants read access to property records, active sale and rental listings, and market statistics.++To sync the **markets** table, enter the ZIP codes you want market statistics for. Each ZIP code uses one RentCast API request per sync.""",iconPath="/static/services/rentcast.png",docsUrl="https://posthog.com/docs/cdp/sources/rentcast",@@ -72,6 +78,15 @@ You can create an API key under **API dashboard** in [RentCast](https://app.rentplaceholder="",secret=True,),+ SourceFieldInputConfig(+ name="zip_codes",+ label="ZIP codes for market statistics",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="29611, 78701",+ caption="A comma-separated list of 5-digit US ZIP codes. Only the markets table uses it.",+ secret=False,+ ),],),)@@ -87,6 +102,8 @@ You can create an API key under **API dashboard** in [RentCast](https://app.rentreturn {"401 Client Error: Unauthorized for url: https://api.rentcast.io": "Your RentCast API key is invalid or has been revoked. Generate a new key in the RentCast API dashboard, then reconnect.","403 Client Error: Forbidden for url: https://api.rentcast.io": "Your RentCast API key does not have access to this data. Check the key's plan and permissions, then reconnect.",+ MISSING_ZIP_CODES_ERROR: "Add one or more ZIP codes to the RentCast source settings to sync the markets table.",+ INVALID_ZIP_CODES_ERROR: "Correct the ZIP codes in the RentCast source settings. Each one must be a 5-digit US ZIP code.",}def get_schemas(@@ -100,7 +117,17 @@ You can create an API key under **API dashboard** in [RentCast](https://app.rent) -> list[SourceSchema]:# Every endpoint is full refresh only — RentCast's list endpoints expose no reliably# ordered server-side timestamp filter, so there is no incremental cursor to advance.- return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)+ # `markets` needs ZIP codes to sync, so it stays off by default until some are configured.+ try:+ has_zip_codes = bool(parse_zip_codes(config.zip_codes))+ except ValueError:+ has_zip_codes = False+ return build_endpoint_schemas(+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ names,+ should_sync_default={MARKETS_ENDPOINT: has_zip_codes},+ )def validate_credentials(self,@@ -109,6 +136,10 @@ You can create an API key under **API dashboard** in [RentCast](https://app.rentschema_name: Optional[str] = None,api_version: str | None = None,) -> tuple[bool, str | None]:+ try:+ parse_zip_codes(config.zip_codes)+ except ValueError as error:+ return False, str(error)# The API key is account-wide, so a single probe validates access to every schema.return _validate_rentcast_credentials(config.api_key)@@ -131,4 +162,5 @@ You can create an API key under **API dashboard** in [RentCast](https://app.rentjob_id=inputs.job_id,resumable_source_manager=resumable_source_manager,db_incremental_field_last_value=None, # every RentCast endpoint is full refresh+ zip_codes=config.zip_codes,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/rentcast/tests/test_rentcast.py b/products/warehouse_sources/backend/temporal/data_imports/sources/rentcast/tests/test_rentcast.pyindex 07e575ac5328..9c8aef63389e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/rentcast/tests/test_rentcast.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/rentcast/tests/test_rentcast.py@@ -15,6 +15,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_RentCastSourceConfig,)from products.warehouse_sources.backend.temporal.data_imports.sources.rentcast.rentcast import (+ INVALID_ZIP_CODES_ERROR,+ MISSING_ZIP_CODES_ERROR,PAGE_SIZE,RentCastResumeConfig,validate_credentials,@@ -26,8 +28,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.rentcast.sfrom products.warehouse_sources.backend.temporal.data_imports.sources.rentcast.source import RentCastSource-def _driver() -> SourceDriver:- return SourceDriver(RentCastSource(), RentCastSourceConfig(api_key="rc-key"))+def _driver(zip_codes: str | None = "10001") -> SourceDriver:+ return SourceDriver(RentCastSource(), RentCastSourceConfig(api_key="rc-key", zip_codes=zip_codes))def _page(body: Any) -> ScriptedResponse:@@ -39,6 +41,10 @@ def _full_page(start_id: int) -> list[dict]:return [{"id": start_id + i} for i in range(PAGE_SIZE)]+def _market(zip_code: str) -> dict[str, Any]:+ return {"id": zip_code, "zipCode": zip_code, "rentalData": {"averageRent": 1850, "history": {}}}++class TestPagination:def test_paginates_and_progresses_offset(self) -> None:result = _driver().run("properties", [_page(_full_page(0)), _page([{"id": 999}])])@@ -66,6 +72,86 @@ class TestPagination:assert "Unexpected 200 response body shape" in str(result.raised)+class TestMarkets:+ def test_requests_each_zip_code_and_skips_zip_codes_without_data(self) -> None:+ result = _driver(zip_codes=" 10001, 20002\n10001 30003 ").run(+ "markets",+ [+ _page(_market("10001")),+ ScriptedResponse(status=404, json={"status": 404, "error": "resource/not-found"}),+ _page(_market("30003")),+ ],+ )++ assert result.raised is None+ assert result.paths == ["/v1/markets"] * 3+ assert result.params("zipCode") == ["10001", "20002", "30003"]+ assert [row["id"] for row in result.rows] == ["10001", "30003"]+ assert result.rows[0]["rentalData"] == {"averageRent": 1850, "history": {}}+ assert result.saved_states == [+ RentCastResumeConfig(next_zip_code="20002"),+ RentCastResumeConfig(next_zip_code="30003"),+ ]+ assert result.committed_states[-1] == RentCastResumeConfig(next_zip_code="30003")++ def test_resumes_from_saved_zip_code_position(self) -> None:+ result = _driver(zip_codes="10001,20002,30003").run(+ "markets", [_page(_market("30003"))], resume_state=RentCastResumeConfig(next_zip_code="30003")+ )++ assert result.params("zipCode") == ["30003"]+ assert [row["id"] for row in result.rows] == ["30003"]++ def test_resume_follows_the_zip_code_when_the_list_was_edited(self) -> None:+ result = _driver(zip_codes="40004,30003").run(+ "markets", [_page(_market("30003"))], resume_state=RentCastResumeConfig(next_zip_code="30003")+ )++ assert result.params("zipCode") == ["30003"]++ def test_resume_restarts_when_the_saved_zip_code_was_removed(self) -> None:+ result = _driver(zip_codes="10001,20002").run(+ "markets",+ [_page(_market("10001")), _page(_market("20002"))],+ resume_state=RentCastResumeConfig(next_zip_code="30003"),+ )++ assert result.params("zipCode") == ["10001", "20002"]++ @parameterized.expand(+ [+ ("not_set", None, MISSING_ZIP_CODES_ERROR),+ ("empty", "", MISSING_ZIP_CODES_ERROR),+ ("only_separators", " , ,", MISSING_ZIP_CODES_ERROR),+ ("too_short", "10001, 2002", INVALID_ZIP_CODES_ERROR),+ ("zip_plus_four", "10001-1234", INVALID_ZIP_CODES_ERROR),+ ("not_digits", "abcde", INVALID_ZIP_CODES_ERROR),+ ]+ )+ def test_bad_zip_codes_fail_before_any_request_with_a_non_retryable_error(+ self, _name: str, zip_codes: str | None, expected_error: str+ ) -> None:+ result = _driver(zip_codes=zip_codes).run("markets", [])++ assert isinstance(result.raised, ValueError)+ assert expected_error in str(result.raised)+ assert result.requests == []+ assert any(key in str(result.raised) for key in RentCastSource().get_non_retryable_errors())++ def test_bad_zip_codes_do_not_block_other_tables(self) -> None:+ result = _driver(zip_codes="abcde").run("properties", [_page([{"id": 1}])])++ assert result.raised is None+ assert result.rows == [{"id": 1}]++ @parameterized.expand([(401,), (403,)])+ def test_auth_failures_map_to_non_retryable_errors(self, status: int) -> None:+ result = _driver().run("markets", always(ScriptedResponse(status=status, json={"status": status})))++ assert result.raised is not None+ assert any(key in str(result.raised) for key in RentCastSource().get_non_retryable_errors())++class TestValidateCredentials:@parameterized.expand([diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/rentcast/tests/test_rentcast_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/rentcast/tests/test_rentcast_source.pyindex ebec2650dc50..569cd13fdc41 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/rentcast/tests/test_rentcast_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/rentcast/tests/test_rentcast_source.py@@ -55,6 +55,32 @@ class TestRentCastSource:assert result == expectedassert network.requests_log[0].headers["x-api-key"] == "rc-key"+ @parameterized.expand(+ [+ ("not_set", None, False),+ ("empty", "", False),+ ("malformed", "1234", False),+ ("configured", "10001, 20002", True),+ ]+ )+ def test_markets_is_enabled_by_default_only_with_zip_codes(+ self, _name: str, zip_codes: str | None, expected: bool+ ) -> None:+ config = RentCastSourceConfig(api_key="rc-key", zip_codes=zip_codes)+ schemas = {schema.name: schema for schema in self.source.get_schemas(config, self.team_id)}++ assert schemas["markets"].should_sync_default is expected+ assert schemas["properties"].should_sync_default is True++ def test_validate_credentials_rejects_bad_zip_codes_without_a_request(self) -> None:+ config = RentCastSourceConfig(api_key="rc-key", zip_codes="10001, 1234")+ with scripted_network(always(ScriptedResponse(status=200, json=[]))) as network:+ valid, message = self.source.validate_credentials(config, self.team_id)++ assert valid is False+ assert message is not None and "1234" in message+ assert network.requests_log == []+def test_source_for_pipeline_plumbs_arguments(self) -> None:result = SourceDriver(self.source, self.config).run("properties",