:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(hogql): defer warehouse foreign-key joins off the query hot path (#85519)
Frank Hamand433815a3a647
diff --git a/posthog/hogql/database/database.py b/posthog/hogql/database/database.pyindex 4231558e9796..baedbc74cc15 100644--- a/posthog/hogql/database/database.py+++ b/posthog/hogql/database/database.py@@ -593,6 +593,21 @@ class Database(BaseModel):# keyed by HogQL DataWarehouseTable.table_id (str(Django table UUID))._data_warehouse_sync_warnings: dict[str, list[DataWarehouseSyncWarning]] = {}+ # Deferred Postgres foreign-key wiring. On teams with many warehouse tables, wiring foreign-key+ # lazy joins for every table dominates database construction, yet a query that touches no+ # warehouse table never needs them. The work is stashed here and built the first time a+ # warehouse table is accessed (see get_table / _ensure_foreign_keys_built).+ _deferred_foreign_key_tables: list[Any] = []+ _foreign_keys_built: bool = True+ _foreign_keys_building: bool = False+ # Lowercased, because Snowflake nodes resolve case-insensitively and a query may name a table with+ # casing that differs from the canonical catalog name.+ _foreign_key_trigger_names: Optional[set[str]] = None+ # ids of the ExpressionField objects saved expressions added at build time. The deferred build+ # lets a foreign key replace only these (see _ensure_foreign_keys_built), never the id/timestamp+ # mappings event modifiers write, which the eager path preserved.+ _deferred_overridable_expression_field_ids: set[int] = set()+_timezone: str | None_week_start_day: WeekStartDay | None@@ -617,6 +632,11 @@ class Database(BaseModel):self._direct_connection_metadata = Noneself._direct_access_warehouse_table_names = set()self._data_warehouse_sync_warnings = {}+ self._deferred_foreign_key_tables = []+ self._foreign_keys_built = True+ self._foreign_keys_building = False+ self._foreign_key_trigger_names = None+ self._deferred_overridable_expression_field_ids = set()self._serialization_errors: dict[str, str] = {} # table_key -> error_messageself.user_access_control: Optional[UserAccessControl] = None@@ -654,7 +674,7 @@ class Database(BaseModel):def get_table(self, table_name: str | list[str]) -> Table:try:- return cast(Table, self.get_table_node(table_name).get())+ table = cast(Table, self.get_table_node(table_name).get())except ResolutionError as e:if isinstance(table_name, list):table_name = ".".join(table_name)@@ -664,6 +684,53 @@ class Database(BaseModel):suffix = f" Did you mean: {', '.join(suggestions)}?" if suggestions else ""raise QueryError(f"Unknown table `{table_name}`.{suffix}") from e+ # First access to any warehouse table wires the deferred foreign-key joins for the whole graph.+ if not self._foreign_keys_built and self._should_build_foreign_keys_for(table_name):+ self._ensure_foreign_keys_built()++ return table++ def _should_build_foreign_keys_for(self, table_name: str | list[str]) -> bool:+ trigger_names = self._foreign_key_trigger_names+ if not trigger_names:+ return False+ name = ".".join(str(part) for part in table_name) if isinstance(table_name, list) else table_name+ # Fold case so a Snowflake reference that resolved through the case-insensitive fallback still+ # arms the build. Over-triggering only costs the build we deferred; under-triggering would drop+ # foreign-key fields the eager path had.+ return name.lower() in trigger_names++ def _ensure_foreign_keys_built(self) -> None:+ """Wire the deferred Postgres foreign-key lazy joins, at most once.++ The full graph is built in a single pass (not just the accessed table) so reverse joins and+ field precedence match the eager path exactly. Resolving a foreign-key target re-enters+ get_table, so `_foreign_keys_building` guards that recursion rather than the built flag — the+ work stays pending until the pass finishes, so a mid-pass failure doesn't leave a half-wired+ graph behind. Callers that swallow resolution errors retry on their next access instead.+ Saved expressions were applied at build time (before this runs), so foreign keys are allowed+ to replace a colliding saved-expression field — preserving the eager "saved expressions never+ shadow a join field" invariant. Only fields saved expressions created are overridable; the+ id/timestamp mappings event modifiers write stay put, as they did in the eager order.+ """+ if self._foreign_keys_built or self._foreign_keys_building:+ return+ self._foreign_keys_building = True+ try:+ with tracer.start_as_current_span("warehouse_foreign_keys"):+ for hogql_table, warehouse_table_model in self._deferred_foreign_key_tables:+ add_postgres_foreign_key_lazy_joins(+ hogql_table=hogql_table,+ warehouse_table=warehouse_table_model,+ database=self,+ schemas=_get_active_external_data_schemas(warehouse_table_model),+ overridable_expression_field_ids=self._deferred_overridable_expression_field_ids,+ )+ finally:+ self._foreign_keys_building = False+ self._foreign_keys_built = True+ self._deferred_foreign_key_tables = []+def _suggest_table_names(self, name: str, *, limit: int = 3) -> list[str]:"""Return up to `limit` close matches for a mistyped table name.@@ -2142,14 +2209,10 @@ class Database(BaseModel):database._add_views(views)if build_postgres_foreign_keys:- with timings.measure("warehouse_foreign_keys", emit_span=True):- for hogql_table, warehouse_table_model in warehouse_tables_to_process:- add_postgres_foreign_key_lazy_joins(- hogql_table=hogql_table,- warehouse_table=warehouse_table_model,- database=database,- schemas=_get_active_external_data_schemas(warehouse_table_model),- )+ # Stash the work now; _ensure_foreign_keys_built wires it on first warehouse-table access.+ # Arming (below, after apply_schema_scope) is deliberately deferred so build-time+ # get_table calls — e.g. saved expressions — don't trigger the build prematurely.+ database._deferred_foreign_key_tables = warehouse_tables_to_processwith timings.measure("data_warehouse_joins", emit_span=True):for join in sources.data_warehouse_joins:@@ -2278,16 +2341,34 @@ class Database(BaseModel):# off chance duplicates exist.if saved_expression.field_name in expression_table.fields:continue- expression_table.fields[saved_expression.field_name] = ExpressionField(+ saved_expression_field = ExpressionField(name=saved_expression.field_name,expr=parse_expr(saved_expression.expression),isolate_scope=True,)+ expression_table.fields[saved_expression.field_name] = saved_expression_field+ # A deferred foreign key may replace this saved-expression field (eager order wired+ # foreign keys first); track it so only these fields, not event-modifier mappings, are+ # overridable when the deferred build runs.+ database._deferred_overridable_expression_field_ids.add(id(saved_expression_field))except Exception as e:capture_exception(e)database.apply_schema_scope()+ # Arm the deferred foreign-key build only once the schema scope is final, so the trigger set+ # reflects the tables that actually survive pruning. Until now _foreign_keys_built stayed+ # True, keeping build-time get_table calls from wiring foreign keys eagerly.+ if build_postgres_foreign_keys and database._deferred_foreign_key_tables:+ trigger_names = (+ set(database._warehouse_table_names)+ | set(database._warehouse_self_managed_table_names)+ | set(database._direct_access_warehouse_table_names)+ | _foreign_key_join_entry_points(database, sources.data_warehouse_joins)+ )+ database._foreign_key_trigger_names = {name.lower() for name in trigger_names}+ database._foreign_keys_built = False+return database@@ -2609,6 +2690,31 @@ def _get_active_external_data_schemas(warehouse_table: DataWarehouseTable) -> lireturn list(ExternalDataSchema.objects.filter(_not_deleted_q(), table_id=warehouse_table.id))+def _foreign_key_join_entry_points(database: Database, joins: Sequence[DataWarehouseJoin]) -> set[str]:+ """Extra table names that must arm the deferred foreign-key build.++ A data warehouse join holds its joining table as a `Table` object, so resolving+ `persons.orders.customer` reaches `orders` without ever calling `get_table` on it. Arming on the+ join's source table keeps the foreign-key fields behind such a join present.+ """+ deferred_tables = {id(hogql_table) for hogql_table, _ in database._deferred_foreign_key_tables}+ entry_points: set[str] = set()+ for join in joins:+ if not database.has_table(join.joining_table_name):+ continue+ try:+ joining_table = database.get_table(join.joining_table_name)+ except QueryError:+ continue+ if id(joining_table) not in deferred_tables:+ continue+ entry_points.add(join.source_table_name)+ # A join from `persons` is mirrored onto `events` and the person virtual table.+ if join.source_table_name == "persons":+ entry_points.add("events")+ return entry_points++def _strip_external_source_prefix(source: ExternalDataSource, table_name: str) -> str:source_type = source.source_type.lower()raw_prefix = (source.prefix or "").lower()diff --git a/posthog/hogql/database/postgres_utils.py b/posthog/hogql/database/postgres_utils.pyindex 6c0f605f970a..b774420ebc69 100644--- a/posthog/hogql/database/postgres_utils.py+++ b/posthog/hogql/database/postgres_utils.py@@ -6,7 +6,7 @@ from typing import TYPE_CHECKING, Any, Protocolfrom posthog.hogql.database.direct_sql_table import DirectSQLTablefrom posthog.hogql.database.lazy_join_tags import FOREIGN_KEY-from posthog.hogql.database.models import LazyJoin, Table+from posthog.hogql.database.models import ExpressionField, FieldOrTable, LazyJoin, Tablefrom posthog.hogql.database.utils import get_join_field_chainfrom posthog.exceptions_capture import capture_exception@@ -28,11 +28,36 @@ class WarehouseForeignKey:target_column: str+def _existing_field_blocks_join(+ existing: FieldOrTable | None, overridable_expression_field_ids: set[int] | None+) -> bool:+ """Whether an already-present field stops us from adding a foreign-key join under this name.++ Any existing field blocks by default. The one exception is the deferred build path: it passes the+ ids of the ExpressionField objects that *saved expressions* created (`overridable_expression_field_ids`).+ Because saved expressions are applied before foreign keys there (the reverse of the eager order), a+ saved expression is allowed to be replaced by a foreign key — preserving the eager invariant that a+ saved expression never shadows a join field. Other ExpressionField values (e.g. the id/timestamp+ mappings event modifiers write at build time) are not in the set and keep blocking, matching the+ eager path where those mappings won over foreign keys.+ """+ if existing is None:+ return False+ if (+ overridable_expression_field_ids is not None+ and isinstance(existing, ExpressionField)+ and id(existing) in overridable_expression_field_ids+ ):+ return False+ return True++def add_postgres_foreign_key_lazy_joins(hogql_table: Table,warehouse_table: DataWarehouseTable,database: DatabaseTableLookup,schemas: Sequence[ExternalDataSchema],+ overridable_expression_field_ids: set[int] | None = None,) -> None:foreign_keys = _get_foreign_keys_from_schemas(schemas)@@ -44,6 +69,7 @@ def add_postgres_foreign_key_lazy_joins(column=foreign_key.column,target_table=foreign_key.target_table,target_column=foreign_key.target_column,+ overridable_expression_field_ids=overridable_expression_field_ids,)if foreign_keys:@@ -62,7 +88,7 @@ def add_postgres_foreign_key_lazy_joins(continuefield_name = column_name[:-3]- if hogql_table.fields.get(field_name):+ if _existing_field_blocks_join(hogql_table.fields.get(field_name), overridable_expression_field_ids):continueinferred_foreign_key = _find_inferred_foreign_key(@@ -83,6 +109,7 @@ def add_postgres_foreign_key_lazy_joins(column=inferred_foreign_key.column,target_table=inferred_foreign_key.target_table,target_column=inferred_foreign_key.target_column,+ overridable_expression_field_ids=overridable_expression_field_ids,)@@ -128,6 +155,7 @@ def _add_foreign_key_lazy_join(column: str,target_table: str,target_column: str,+ overridable_expression_field_ids: set[int] | None = None,) -> None:if not column or not target_table or not target_column:return@@ -143,7 +171,7 @@ def _add_foreign_key_lazy_join(returnfield_name = column[:-3] if column.endswith("_id") and len(column) > 3 else column- if hogql_table.fields.get(field_name):+ if _existing_field_blocks_join(hogql_table.fields.get(field_name), overridable_expression_field_ids):returnresolved_target = _resolve_target_table(@@ -171,7 +199,7 @@ def _add_foreign_key_lazy_join(returnreverse_field_name = _reverse_foreign_key_field_name(source_table_name, target_table_name)- if target_hogql_table.fields.get(reverse_field_name) is not None:+ if _existing_field_blocks_join(target_hogql_table.fields.get(reverse_field_name), overridable_expression_field_ids):returntarget_hogql_table.fields[reverse_field_name] = LazyJoin(diff --git a/posthog/hogql/database/test/test_database.py b/posthog/hogql/database/test/test_database.pyindex 186198f67f3e..caa60efd92de 100644--- a/posthog/hogql/database/test/test_database.py+++ b/posthog/hogql/database/test/test_database.py@@ -67,10 +67,12 @@ from posthog.hogql.test.utils import pretty_print_in_testsfrom posthog.constants import AvailableFeaturefrom posthog.models.group_type_mapping import invalidate_group_types_cachefrom posthog.models.organization import Organization, OrganizationMembership+from posthog.models.scoping import team_scopefrom posthog.models.team.team import Teamfrom posthog.test.test_utils import create_group_type_mapping_without_created_atfrom products.data_modeling.backend.facade.models import DataWarehouseSavedQuery+from products.data_tools.backend.models.expression import DataWarehouseExpressionfrom products.data_tools.backend.models.join import DataWarehouseJoinfrom products.warehouse_sources.backend.facade.models import (DataWarehouseCredential,@@ -1182,6 +1184,71 @@ class TestDatabase(BaseTest, QueryMatchingTest):assert isinstance(resolved_field, DatabaseField)assert resolved_field.name == "N_NAME"+ @patch("posthog.hogql.query.sync_execute", return_value=([], []))+ def test_deferred_foreign_keys_wire_for_snowflake_table_named_in_another_case(self, patch_execute):+ source = ExternalDataSource.objects.create(+ team=self.team,+ source_id="snowflake_fk_source",+ source_type=ExternalDataSourceType.SNOWFLAKE,+ access_method=ExternalDataSource.AccessMethod.DIRECT,+ job_inputs={"database": "DB", "schema": ""},+ )+ customer_table = DataWarehouseTable.objects.create(+ name="TPCH_SF1.CUSTOMER",+ format="Parquet",+ team=self.team,+ external_data_source=source,+ external_data_source_id=source.id,+ url_pattern="s3://test/*",+ options={+ "direct_snowflake_catalog": "DB",+ "direct_snowflake_schema": "TPCH_SF1",+ "direct_snowflake_table": "CUSTOMER",+ },+ columns={"C_CUSTKEY": {"clickhouse": "Int64", "hogql": "integer"}},+ )+ orders_table = DataWarehouseTable.objects.create(+ name="TPCH_SF1.ORDERS",+ format="Parquet",+ team=self.team,+ external_data_source=source,+ external_data_source_id=source.id,+ url_pattern="s3://test/*",+ options={+ "direct_snowflake_catalog": "DB",+ "direct_snowflake_schema": "TPCH_SF1",+ "direct_snowflake_table": "ORDERS",+ },+ columns={+ "O_ORDERKEY": {"clickhouse": "Int64", "hogql": "integer"},+ # Quoted lowercase column, so the join field it produces ("customer") doesn't collide+ # with the column name and the foreign key actually wires.+ "customer_id": {"clickhouse": "Int64", "hogql": "integer"},+ },+ )+ ExternalDataSchema.objects.create(name="TPCH_SF1.CUSTOMER", team=self.team, source=source, table=customer_table)+ ExternalDataSchema.objects.create(+ name="TPCH_SF1.ORDERS",+ team=self.team,+ source=source,+ table=orders_table,+ sync_type_config={+ "schema_metadata": {+ "foreign_keys": [+ {"column": "customer_id", "target_table": "CUSTOMER", "target_column": "C_CUSTKEY"}+ ]+ }+ },+ )++ sources = Database._fetch_sources(team=self.team, connection_id=str(source.id))+ database = Database._build_from_sources(sources)++ # Snowflake folds unquoted names, so a lowercase reference resolves to the canonical table —+ # and must still arm the deferred foreign-key build for the whole graph.+ orders = database.get_table("tpch_sf1.orders")+ assert isinstance(orders.fields.get("customer"), LazyJoin)+@patch("posthog.hogql.query.sync_execute", return_value=([], []))def test_build_from_sources_keeps_non_snowflake_tables_case_sensitive(self, patch_execute):# The case-insensitive fallback is opt-in per node, so a non-Snowflake direct table must NOT@@ -2827,6 +2894,224 @@ class TestDatabase(BaseTest, QueryMatchingTest):assert isinstance(activitylog.fields.get("team"), LazyJoin)assert isinstance(team.fields.get("posthog_activitylogs"), LazyJoin)+ def test_postgres_foreign_keys_are_deferred_until_a_warehouse_table_is_accessed(self):+ credentials = DataWarehouseCredential.objects.create(+ access_key="test_key", access_secret="test_secret", team=self.team+ )+ source = ExternalDataSource.objects.create(+ team=self.team,+ source_id="source_id",+ source_type=ExternalDataSourceType.POSTGRES,+ access_method=ExternalDataSource.AccessMethod.WAREHOUSE,+ prefix="ph3",+ )+ team_table = DataWarehouseTable.objects.create(+ name="posthog_team",+ format="Parquet",+ team=self.team,+ credential=credentials,+ external_data_source=source,+ url_pattern="s3://test/*",+ columns={"id": {"hogql": "integer", "clickhouse": "Int64", "schema_valid": True}},+ )+ activitylog_table = DataWarehouseTable.objects.create(+ name="posthog_activitylog",+ format="Parquet",+ team=self.team,+ credential=credentials,+ external_data_source=source,+ url_pattern="s3://test/*",+ columns={+ "id": {"hogql": "integer", "clickhouse": "Int64", "schema_valid": True},+ "team_id": {"hogql": "integer", "clickhouse": "Int64", "schema_valid": True},+ },+ )+ ExternalDataSchema.objects.create(name="posthog_team", team=self.team, source=source, table=team_table)+ ExternalDataSchema.objects.create(+ name="posthog_activitylog",+ team=self.team,+ source=source,+ table=activitylog_table,+ sync_type_config={+ "schema_metadata": {+ "foreign_keys": [{"column": "team_id", "target_table": "posthog_team", "target_column": "id"}]+ }+ },+ )++ database = Database.create_for(team=self.team)++ # Reading through the tree directly does not resolve via get_table, so it never arms the build.+ activitylog_before = database.get_table_node("postgres.ph3.posthog_activitylog").get()+ assert isinstance(activitylog_before, Table)+ assert activitylog_before.fields.get("team") is None++ # Accessing a core (non-warehouse) table must not pay for warehouse foreign keys.+ database.get_table("events")+ activitylog_after_events = database.get_table_node("postgres.ph3.posthog_activitylog").get()+ assert isinstance(activitylog_after_events, Table)+ assert activitylog_after_events.fields.get("team") is None++ # The first warehouse-table access wires the whole graph — forward and reverse joins.+ activitylog = database.get_table("postgres.ph3.posthog_activitylog")+ assert isinstance(activitylog.fields.get("team"), LazyJoin)+ assert isinstance(database.get_table("postgres.ph3.posthog_team").fields.get("posthog_activitylogs"), LazyJoin)++ def test_deferred_foreign_keys_do_not_replace_event_modifier_field_mappings(self):+ credentials = DataWarehouseCredential.objects.create(+ access_key="test_key", access_secret="test_secret", team=self.team+ )+ source = ExternalDataSource.objects.create(+ team=self.team,+ source_id="source_id",+ source_type=ExternalDataSourceType.POSTGRES,+ access_method=ExternalDataSource.AccessMethod.WAREHOUSE,+ prefix="ph3",+ )+ team_table = DataWarehouseTable.objects.create(+ name="posthog_team",+ format="Parquet",+ team=self.team,+ credential=credentials,+ external_data_source=source,+ url_pattern="s3://test/*",+ columns={"id": {"hogql": "integer", "clickhouse": "Int64", "schema_valid": True}},+ )+ activitylog_table = DataWarehouseTable.objects.create(+ name="posthog_activitylog",+ format="Parquet",+ team=self.team,+ credential=credentials,+ external_data_source=source,+ url_pattern="s3://test/*",+ columns={+ "id": {"hogql": "integer", "clickhouse": "Int64", "schema_valid": True},+ "row_id": {"hogql": "integer", "clickhouse": "Int64", "schema_valid": True},+ "team_id": {"hogql": "integer", "clickhouse": "Int64", "schema_valid": True},+ "timestamp": {"hogql": "datetime", "clickhouse": "DateTime64(6, 'UTC')", "schema_valid": True},+ },+ )+ ExternalDataSchema.objects.create(name="posthog_team", team=self.team, source=source, table=team_table)+ # A foreign key on `id` collides with the event-modifier `id` mapping; the `team_id` one does not.+ ExternalDataSchema.objects.create(+ name="posthog_activitylog",+ team=self.team,+ source=source,+ table=activitylog_table,+ sync_type_config={+ "schema_metadata": {+ "foreign_keys": [+ {"column": "id", "target_table": "posthog_team", "target_column": "id"},+ {"column": "team_id", "target_table": "posthog_team", "target_column": "id"},+ ]+ }+ },+ )++ modifiers = create_default_modifiers_for_team(+ self.team,+ modifiers=HogQLQueryModifiers(+ dataWarehouseEventsModifiers=[+ DataWarehouseEventsModifier(+ table_name="postgres.ph3.posthog_activitylog",+ id_field="row_id",+ timestamp_field="timestamp",+ distinct_id_field="distinct_id",+ )+ ],+ ),+ )++ database = Database.create_for(team=self.team, modifiers=modifiers)+ activitylog = database.get_table("postgres.ph3.posthog_activitylog")++ # The modifier's `id` mapping wins over the colliding foreign key, as it did in the eager path.+ assert isinstance(activitylog.fields.get("id"), ExpressionField)+ # The non-colliding foreign key still wired, proving the deferred build actually ran.+ assert isinstance(activitylog.fields.get("team"), LazyJoin)++ def _postgres_warehouse_source_with_foreign_key(self, *, foreign_keys: list[dict[str, str]]) -> None:+ credentials = DataWarehouseCredential.objects.create(+ access_key="test_key", access_secret="test_secret", team=self.team+ )+ source = ExternalDataSource.objects.create(+ team=self.team,+ source_id="source_id",+ source_type=ExternalDataSourceType.POSTGRES,+ access_method=ExternalDataSource.AccessMethod.WAREHOUSE,+ prefix="ph3",+ )+ team_table = DataWarehouseTable.objects.create(+ name="posthog_team",+ format="Parquet",+ team=self.team,+ credential=credentials,+ external_data_source=source,+ url_pattern="s3://test/*",+ columns={"id": {"hogql": "integer", "clickhouse": "Int64", "schema_valid": True}},+ )+ activitylog_table = DataWarehouseTable.objects.create(+ name="posthog_activitylog",+ format="Parquet",+ team=self.team,+ credential=credentials,+ external_data_source=source,+ url_pattern="s3://test/*",+ columns={+ "id": {"hogql": "integer", "clickhouse": "Int64", "schema_valid": True},+ "team_id": {"hogql": "integer", "clickhouse": "Int64", "schema_valid": True},+ },+ )+ ExternalDataSchema.objects.create(name="posthog_team", team=self.team, source=source, table=team_table)+ ExternalDataSchema.objects.create(+ name="posthog_activitylog",+ team=self.team,+ source=source,+ table=activitylog_table,+ sync_type_config={"schema_metadata": {"foreign_keys": foreign_keys}},+ )++ def test_deferred_foreign_keys_wire_for_a_table_reached_through_a_data_warehouse_join(self):+ self._postgres_warehouse_source_with_foreign_key(+ foreign_keys=[{"column": "team_id", "target_table": "posthog_team", "target_column": "id"}]+ )+ DataWarehouseJoin.objects.create(+ team=self.team,+ source_table_name="events",+ source_table_key="event",+ joining_table_name="postgres.ph3.posthog_activitylog",+ joining_table_key="id",+ field_name="activitylog",+ )++ database = Database.create_for(team=self.team)++ # The join holds the warehouse table as an object, so resolving through it never calls+ # get_table on the warehouse name. Accessing the join's source table has to arm the build.+ join_field = database.get_table("events").fields["activitylog"]+ assert isinstance(join_field, LazyJoin)+ joined = join_field.resolve_table(HogQLContext(team_id=self.team.pk, database=database))+ assert isinstance(joined.fields.get("team"), LazyJoin)++ def test_deferred_foreign_keys_replace_a_colliding_saved_expression(self):+ self._postgres_warehouse_source_with_foreign_key(+ foreign_keys=[{"column": "team_id", "target_table": "posthog_team", "target_column": "id"}]+ )+ with team_scope(self.team.id, canonical=True):+ DataWarehouseExpression.objects.create(+ team=self.team,+ table_name="postgres.ph3.posthog_activitylog",+ field_name="team",+ expression="team_id",+ )++ database = Database.create_for(team=self.team)++ # The eager path wired foreign keys first, so the expression was skipped as a shadowing name.+ # Deferring flips the order, so the join still has to reclaim the field.+ activitylog = database.get_table("postgres.ph3.posthog_activitylog")+ assert isinstance(activitylog.fields.get("team"), LazyJoin)+def test_serialize_direct_postgres_skips_foreign_key_join_when_target_table_is_missing(self):credentials = DataWarehouseCredential.objects.create(access_key="test_key", access_secret="test_secret", team=self.team