Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-catalog): relationship proposals promoting to warehouse joins (#69536)

Thiago Salvatore4f77bdcb3daf
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yaml
index 270db163613d..387808a5afa4 100644
--- a/.semgrep/rules/security/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml
@@ -197,6 +197,7 @@ rules:
|MessageRecipientPreference
|MessageTemplate
|Metric
+ |RelationshipProposal
|MCPAnalyticsSubmission
|MCPIntentClusterSnapshot
|MCPIntentEmbeddingCache
@@ -494,6 +495,7 @@ rules:
|MessageRecipientPreference
|MessageTemplate
|Metric
+ |RelationshipProposal
|MCPIntentClusterSnapshot
|MCPIntentEmbeddingCache
|MCPSession
diff --git a/products/data_catalog/backend/facade/api.py b/products/data_catalog/backend/facade/api.py
index 9807d9ed94cc..3ab47267ec7d 100644
--- a/products/data_catalog/backend/facade/api.py
+++ b/products/data_catalog/backend/facade/api.py
@@ -23,12 +23,15 @@ from ..logic.metrics import (
update_metric,
upsert_metric,
)
+from ..logic.relationships import accept_proposal, propose_relationship, reject_proposal, relationships_for_team
from ..logic.validation import validate_metric_definition
-from .models import Metric, TableCertification
+from .models import Metric, RelationshipProposal, TableCertification
__all__ = [
"Metric",
+ "RelationshipProposal",
"TableCertification",
+ "accept_proposal",
"approve_metric",
"certifications_for_team",
"certify",
@@ -36,7 +39,10 @@ __all__ = [
"deprecate",
"metrics_for_team",
"propose_certification",
+ "propose_relationship",
"refresh_metric_from_insight",
+ "reject_proposal",
+ "relationships_for_team",
"revoke_certification",
"run_metric",
"soft_delete_metric",
diff --git a/products/data_catalog/backend/facade/enums.py b/products/data_catalog/backend/facade/enums.py
index 8db29736062d..c0c8bb47d4f0 100644
--- a/products/data_catalog/backend/facade/enums.py
+++ b/products/data_catalog/backend/facade/enums.py
@@ -40,3 +40,11 @@ class CertificationStatus(StrEnum):
PROPOSED = "proposed"
CERTIFIED = "certified"
DEPRECATED = "deprecated"
+
+
+class RelationshipStatus(StrEnum):
+ """Review state of a proposed join between two warehouse tables."""
+
+ PROPOSED = "proposed"
+ ACCEPTED = "accepted"
+ REJECTED = "rejected"
diff --git a/products/data_catalog/backend/facade/models.py b/products/data_catalog/backend/facade/models.py
index c2fc05730787..7ba34d64d3a2 100644
--- a/products/data_catalog/backend/facade/models.py
+++ b/products/data_catalog/backend/facade/models.py
@@ -5,6 +5,6 @@ own presentation layer are allowed to reach the ORM classes, keeping direct mode
the isolation boundary.
"""
-from ..models import Metric, TableCertification
+from ..models import Metric, RelationshipProposal, TableCertification
-__all__ = ["Metric", "TableCertification"]
+__all__ = ["Metric", "RelationshipProposal", "TableCertification"]
diff --git a/products/data_catalog/backend/logic/relationships.py b/products/data_catalog/backend/logic/relationships.py
new file mode 100644
index 000000000000..07117b26b8a4
--- /dev/null
+++ b/products/data_catalog/backend/logic/relationships.py
@@ -0,0 +1,290 @@
+"""Relationship proposal lifecycle -- promote a reviewed join into a real DataWarehouseJoin.
+
+Proposals are deduped undirected (a->b and b->a share a fingerprint), so a rejection blocks the pair
+in both orientations forever. Accepting re-validates the join keys and runs a live probe (a blessed
+join is a demonstrated-working join) before creating exactly one join under a row lock.
+"""
+
+import json
+import hashlib
+from typing import Optional
+
+from django.db import (
+ IntegrityError,
+ connection as db_connection,
+ transaction,
+)
+from django.db.models import QuerySet
+from django.utils import timezone
+
+from rest_framework.exceptions import ValidationError
+
+from posthog.hogql import ast
+from posthog.hogql.context import HogQLContext
+from posthog.hogql.database.database import Database
+from posthog.hogql.database.lazy_join_tags import DATA_WAREHOUSE, DATA_WAREHOUSE_EXPERIMENTS
+from posthog.hogql.database.models import LazyJoin
+from posthog.hogql.database.utils import get_join_field_chain
+from posthog.hogql.database.warehouse_join_resolvers import data_warehouse_resolver_params
+from posthog.hogql.errors import (
+ ExposedHogQLError,
+ SyntaxError as HogQLSyntaxError,
+)
+from posthog.hogql.parser import parse_expr, parse_select
+from posthog.hogql.query import execute_hogql_query
+
+from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
+from posthog.event_usage import report_user_action
+from posthog.exceptions_capture import capture_exception
+from posthog.models import Team, User
+
+from products.data_tools.backend.facade.models import DataWarehouseJoin
+
+from ..facade.enums import RelationshipStatus
+from ..models import RelationshipProposal
+from .exceptions import CatalogConflict
+
+
+def _fingerprint(source_name: str, source_key: str, joining_name: str, joining_key: str) -> str:
+ endpoints = sorted(
+ [
+ [source_name, _canonicalize_join_key(source_key)],
+ [joining_name, _canonicalize_join_key(joining_key)],
+ ]
+ )
+ return hashlib.sha256(json.dumps(endpoints, sort_keys=True).encode()).hexdigest()
+
+
+def _canonicalize_join_key(key: str) -> str:
+ try:
+ return parse_expr(key).to_hogql()
+ except HogQLSyntaxError as error:
+ raise ValidationError({"keys": f"Invalid HogQL join key: {error}"}) from error
+
+
+def _capture(user: Optional[User], team: Team, event: str, proposal: RelationshipProposal) -> None:
+ if user is None:
+ return
+ report_user_action(
+ user=user,
+ event=event,
+ team=team,
+ properties={
+ "proposal_id": str(proposal.id),
+ "status": proposal.status,
+ "source_table": proposal.source_table_name,
+ "joining_table": proposal.joining_table_name,
+ },
+ )
+
+
+def _validate_tables_exist(team: Team, user: Optional[User], *table_names: str) -> None:
+ database = Database.create_for(team_id=team.id, user=user)
+ for name in table_names:
+ if not database.has_table(name):
+ raise ValidationError({"table": f"Table '{name}' not found. Check system.information_schema.tables."})
+
+
+def propose_relationship(
+ *,
+ team: Team,
+ user: Optional[User],
+ source_table_name: str,
+ source_table_key: str,
+ joining_table_name: str,
+ joining_table_key: str,
+ field_name: str,
+ configuration: Optional[dict] = None,
+ confidence: Optional[float] = None,
+ reasoning: str = "",
+ evidence: Optional[dict] = None,
+) -> RelationshipProposal:
+ # Propose-time existence check so hallucinated/typo'd tables never reach the review queue.
+ _validate_tables_exist(team, user, source_table_name, joining_table_name)
+
+ fingerprint = _fingerprint(source_table_name, source_table_key, joining_table_name, joining_table_key)
+ existing = RelationshipProposal.objects.for_team(team.id).filter(undirected_fingerprint=fingerprint).first()
+ if existing is not None:
+ raise CatalogConflict(
+ detail={
+ "error": f"A proposal for this join pair already exists (status: {existing.status}).",
+ "proposal_id": str(existing.id),
+ }
+ )
+
+ try:
+ proposal = RelationshipProposal.objects.for_team(team.id).create(
+ team=team,
+ source_table_name=source_table_name,
+ source_table_key=source_table_key,
+ joining_table_name=joining_table_name,
+ joining_table_key=joining_table_key,
+ field_name=field_name,
+ configuration=configuration or {},
+ confidence=confidence,
+ reasoning=reasoning,
+ evidence=evidence or {},
+ undirected_fingerprint=fingerprint,
+ created_by=user,
+ )
+ except IntegrityError:
+ # A concurrent reverse-orientation proposal won the fingerprint (the DB constraint kills the
+ # race the logic check alone cannot).
+ existing = RelationshipProposal.objects.for_team(team.id).filter(undirected_fingerprint=fingerprint).first()
+ raise CatalogConflict(
+ detail={
+ "error": "A proposal for this join pair already exists.",
+ "proposal_id": str(existing.id) if existing else None,
+ }
+ )
+
+ _capture(user, team, "data catalog relationship proposed", proposal)
+ return proposal
+
+
+def accept_proposal(proposal: RelationshipProposal, user: Optional[User]) -> RelationshipProposal:
+ with transaction.atomic():
+ # Serialize concurrent accepts of this proposal.
+ proposal = RelationshipProposal.objects.for_team(proposal.team_id).select_for_update().get(pk=proposal.pk)
+ if proposal.status == RelationshipStatus.ACCEPTED and proposal.created_join_id:
+ return proposal
+ if proposal.status == RelationshipStatus.REJECTED:
+ raise ValidationError({"status": "This proposal was rejected and cannot be accepted."})
+
+ _acquire_accessor_lock(proposal)
+ existing_join = _get_exact_existing_join(proposal)
+ _probe_join(proposal, user, existing_join=existing_join)
+ join = existing_join or _create_join(proposal, user)
+
+ proposal.status = RelationshipStatus.ACCEPTED
+ proposal.reviewed_by = user
+ proposal.reviewed_at = timezone.now()
+ proposal.created_join = join
+ proposal.save()
+
+ _capture(user, proposal.team, "data catalog relationship accepted", proposal)
+ return proposal
+
+
+def _probe_join(
+ proposal: RelationshipProposal, user: Optional[User], *, existing_join: Optional[DataWarehouseJoin]
+) -> None:
+ """Prove the join works by running SELECT {joined_field} FROM {source} LIMIT 10 through it."""
+ database = Database.create_for(team_id=proposal.team_id, user=user)
+ from_field = get_join_field_chain(proposal.source_table_key)
+ to_field = get_join_field_chain(proposal.joining_table_key)
+ if from_field is None or to_field is None:
+ raise ValidationError({"keys": "Join keys must be field expressions."})
+
+ try:
+ source_table = database.get_table(proposal.source_table_name)
+ joining_table = database.get_table(proposal.joining_table_name)
+ existing_field = source_table.fields.get(proposal.field_name)
+ if existing_field is not None and existing_join is None:
+ raise ValidationError(
+ {"field_name": f"'{proposal.field_name}' is already a field on '{proposal.source_table_name}'."}
+ )
+ # Mirror the resolver selection Database uses when it materializes the real join, so the
+ # probe exercises the same code path -- otherwise an experiments-optimized join is probed with
+ # the plain equality resolver and an invalid experiments_timestamp_key survives review.
+ configuration = proposal.configuration if isinstance(proposal.configuration, dict) else {}
+ use_experiments = bool(proposal.joining_table_name == "events" and configuration.get("experiments_optimized"))
+ source_table.fields["_catalog_probe"] = LazyJoin(
+ from_field=from_field,
+ to_field=to_field,
+ join_table=joining_table,
+ resolver=DATA_WAREHOUSE_EXPERIMENTS if use_experiments else DATA_WAREHOUSE,
+ resolver_params=data_warehouse_resolver_params(
+ source_table_key=proposal.source_table_key,
+ joining_table_key=proposal.joining_table_key,
+ joining_table_name=proposal.joining_table_name,
+ configuration=proposal.configuration,
+ override_join_type="INNER JOIN",
+ ),
+ )
+ validation_query = parse_select(
+ "SELECT {to_field} FROM {source_table_name} LIMIT 10",
+ placeholders={
+ "to_field": ast.Field(chain=["_catalog_probe", *to_field]),
+ "source_table_name": parse_expr(proposal.source_table_name),
+ },
+ )
+ tag_queries(product=Product.WAREHOUSE, feature=Feature.QUERY)
+ execute_hogql_query(
+ query=validation_query, team=proposal.team, context=HogQLContext(database=database, user=user)
+ )
+ except ValidationError:
+ raise
+ except ExposedHogQLError as e:
+ raise ValidationError({"join": f"The join does not work: {e}"})
+ except Exception as e:
+ capture_exception(e)
+ raise ValidationError({"join": "The join could not be validated against the data."})
+
+
+def _acquire_accessor_lock(proposal: RelationshipProposal) -> None:
+ lock_key = f"data-catalog-relationship:{proposal.team_id}:{proposal.source_table_name}:{proposal.field_name}"
+ lock_id = int.from_bytes(hashlib.sha256(lock_key.encode()).digest()[:8], byteorder="big", signed=True)
+ with db_connection.cursor() as cursor:
+ cursor.execute("SELECT pg_advisory_xact_lock(%s)", [lock_id])
+
+
+def _get_exact_existing_join(proposal: RelationshipProposal) -> Optional[DataWarehouseJoin]:
+ joins = list(
+ DataWarehouseJoin.objects.filter(
+ team_id=proposal.team_id, source_table_name=proposal.source_table_name, field_name=proposal.field_name
+ ).exclude(deleted=True)
+ )
+ exact_matches = [
+ join
+ for join in joins
+ if join.source_table_key == proposal.source_table_key
+ and join.joining_table_name == proposal.joining_table_name
+ and join.joining_table_key == proposal.joining_table_key
+ and _normalize_configuration(join.configuration) == _normalize_configuration(proposal.configuration)
+ ]
+ if len(exact_matches) == len(joins):
+ return exact_matches[0] if exact_matches else None
+ if joins:
+ raise ValidationError(
+ {"field_name": f"'{proposal.field_name}' is already a join field on '{proposal.source_table_name}'."}
+ )
+ return None
+
+
+def _normalize_configuration(configuration: object) -> object:
+ return configuration if isinstance(configuration, dict) else {}
+
+
+def _create_join(proposal: RelationshipProposal, user: Optional[User]) -> DataWarehouseJoin:
+ return DataWarehouseJoin.objects.create(
+ team=proposal.team,
+ source_table_name=proposal.source_table_name,
+ source_table_key=proposal.source_table_key,
+ joining_table_name=proposal.joining_table_name,
+ joining_table_key=proposal.joining_table_key,
+ field_name=proposal.field_name,
+ configuration=proposal.configuration,
+ created_by=user,
+ )
+
+
+def reject_proposal(proposal: RelationshipProposal, user: Optional[User], reason: str = "") -> RelationshipProposal:
+ with transaction.atomic():
+ proposal = RelationshipProposal.objects.for_team(proposal.team_id).select_for_update().get(pk=proposal.pk)
+ if proposal.status == RelationshipStatus.REJECTED:
+ return proposal
+ if proposal.status != RelationshipStatus.PROPOSED:
+ raise ValidationError({"status": "Only proposed relationships can be rejected."})
+ proposal.status = RelationshipStatus.REJECTED
+ proposal.reviewed_by = user
+ proposal.reviewed_at = timezone.now()
+ proposal.rejection_reason = reason
+ proposal.save()
+
+ _capture(user, proposal.team, "data catalog relationship rejected", proposal)
+ return proposal
+
+
+def relationships_for_team(team: Team) -> QuerySet[RelationshipProposal]:
+ return RelationshipProposal.objects.for_team(team.id).order_by("-created_at")
diff --git a/products/data_catalog/backend/migrations/0003_relationshipproposal.py b/products/data_catalog/backend/migrations/0003_relationshipproposal.py
new file mode 100644
index 000000000000..6ac8d91424e2
--- /dev/null
+++ b/products/data_catalog/backend/migrations/0003_relationshipproposal.py
@@ -0,0 +1,177 @@
+# Generated by Django 5.2.14 on 2026-07-08 23:47
+
+import django.core.validators
+import django.db.models.deletion
+from django.conf import settings
+from django.db import migrations, models
+
+import posthog.models.utils
+
+import products.data_catalog.backend.facade.enums
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("data_catalog", "0002_tablecertification"),
+ ("data_tools", "0002_migrate_data_modeling_models"),
+ ("posthog", "1247_oauthaccesstoken_token_idx"),
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="RelationshipProposal",
+ fields=[
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True, null=True)),
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.models.utils.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ (
+ "source_table_name",
+ models.CharField(
+ help_text="Name of the table the join starts from.",
+ max_length=400,
+ ),
+ ),
+ (
+ "source_table_key",
+ models.CharField(
+ help_text="HogQL key expression on the source table.",
+ max_length=400,
+ ),
+ ),
+ (
+ "joining_table_name",
+ models.CharField(help_text="Name of the table being joined in.", max_length=400),
+ ),
+ (
+ "joining_table_key",
+ models.CharField(
+ help_text="HogQL key expression on the joining table.",
+ max_length=400,
+ ),
+ ),
+ (
+ "field_name",
+ models.CharField(
+ help_text="Accessor the join adds to the source table.",
+ max_length=400,
+ ),
+ ),
+ (
+ "configuration",
+ models.JSONField(
+ blank=True,
+ default=dict,
+ help_text="Extra join configuration (e.g. field mapping).",
+ ),
+ ),
+ (
+ "confidence",
+ models.FloatField(
+ blank=True,
+ help_text="Discovery confidence in this join, 0-1.",
+ null=True,
+ validators=[
+ django.core.validators.MinValueValidator(0),
+ django.core.validators.MaxValueValidator(1),
+ ],
+ ),
+ ),
+ (
+ "reasoning",
+ models.TextField(blank=True, help_text="Why this join is proposed."),
+ ),
+ (
+ "evidence",
+ models.JSONField(
+ blank=True,
+ default=dict,
+ help_text="Sampling evidence: match rates, sample values.",
+ ),
+ ),
+ (
+ "status",
+ models.CharField(
+ choices=[
+ ("proposed", "proposed"),
+ ("accepted", "accepted"),
+ ("rejected", "rejected"),
+ ],
+ default=products.data_catalog.backend.facade.enums.RelationshipStatus["PROPOSED"],
+ help_text="proposed, accepted (promoted to a real join), or rejected (never re-proposed).",
+ max_length=32,
+ ),
+ ),
+ ("reviewed_at", models.DateTimeField(blank=True, null=True)),
+ (
+ "rejection_reason",
+ models.TextField(blank=True, help_text="Why the proposal was rejected."),
+ ),
+ (
+ "undirected_fingerprint",
+ models.CharField(
+ help_text="sha256 of the sorted {(table, key), (table, key)} pair set -- one proposal per physical join pair.",
+ max_length=64,
+ ),
+ ),
+ (
+ "created_by",
+ models.ForeignKey(
+ blank=True,
+ db_constraint=False,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ (
+ "created_join",
+ models.ForeignKey(
+ blank=True,
+ db_constraint=False,
+ help_text="The join created when this proposal was accepted (promotion provenance).",
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to="data_tools.datawarehousejoin",
+ ),
+ ),
+ (
+ "reviewed_by",
+ models.ForeignKey(
+ blank=True,
+ db_constraint=False,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ to="posthog.team",
+ ),
+ ),
+ ],
+ options={
+ "indexes": [models.Index(fields=["team", "status"], name="data_catalo_team_id_1b11e5_idx")],
+ "constraints": [
+ models.UniqueConstraint(
+ fields=("team", "undirected_fingerprint"),
+ name="unique_relationship_fingerprint",
+ )
+ ],
+ },
+ ),
+ ]
diff --git a/products/data_catalog/backend/migrations/max_migration.txt b/products/data_catalog/backend/migrations/max_migration.txt
index d8565958bfee..b4cff360607d 100644
--- a/products/data_catalog/backend/migrations/max_migration.txt
+++ b/products/data_catalog/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0002_tablecertification
+0003_relationshipproposal
diff --git a/products/data_catalog/backend/models/__init__.py b/products/data_catalog/backend/models/__init__.py
index 2d794843d447..8d47b45a7a9b 100644
--- a/products/data_catalog/backend/models/__init__.py
+++ b/products/data_catalog/backend/models/__init__.py
@@ -1,4 +1,5 @@
from .certification import TableCertification
from .metric import METRIC_NAME_REGEX, Metric
+from .relationship_proposal import RelationshipProposal
-__all__ = ["METRIC_NAME_REGEX", "Metric", "TableCertification"]
+__all__ = ["METRIC_NAME_REGEX", "Metric", "RelationshipProposal", "TableCertification"]
diff --git a/products/data_catalog/backend/models/relationship_proposal.py b/products/data_catalog/backend/models/relationship_proposal.py
new file mode 100644
index 000000000000..a87261a5b61c
--- /dev/null
+++ b/products/data_catalog/backend/models/relationship_proposal.py
@@ -0,0 +1,81 @@
+from django.core.validators import MaxValueValidator, MinValueValidator
+from django.db import models
+
+from posthog.models.scoping.root_mixin import TeamScopedRootMixin
+from posthog.models.utils import CreatedMetaFields, UpdatedMetaFields, UUIDModel
+
+from ..facade.enums import RelationshipStatus
+
+
+class RelationshipProposal(TeamScopedRootMixin, CreatedMetaFields, UpdatedMetaFields, UUIDModel):
+ """A reviewed join fact between two warehouse tables.
+
+ Table identity is name-based, mirroring ``DataWarehouseJoin`` itself; keys are HogQL expressions
+ (casts included) so accept is a 1:1 field copy into a real join. Rejection is undirected and
+ persists forever, so discovery never re-proposes the pair in either orientation -- enforced by a
+ unique ``undirected_fingerprint``.
+ """
+
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False)
+ created_by = models.ForeignKey(
+ "posthog.User", on_delete=models.SET_NULL, null=True, blank=True, db_constraint=False
+ )
+
+ source_table_name = models.CharField(max_length=400, help_text="Name of the table the join starts from.")
+ source_table_key = models.CharField(max_length=400, help_text="HogQL key expression on the source table.")
+ joining_table_name = models.CharField(max_length=400, help_text="Name of the table being joined in.")
+ joining_table_key = models.CharField(max_length=400, help_text="HogQL key expression on the joining table.")
+ field_name = models.CharField(max_length=400, help_text="Accessor the join adds to the source table.")
+ configuration = models.JSONField(
+ default=dict, blank=True, help_text="Extra join configuration (e.g. field mapping)."
+ )
+
+ confidence = models.FloatField(
+ null=True,
+ blank=True,
+ validators=[MinValueValidator(0), MaxValueValidator(1)],
+ help_text="Discovery confidence in this join, 0-1.",
+ )
+ reasoning = models.TextField(blank=True, help_text="Why this join is proposed.")
+ evidence = models.JSONField(default=dict, blank=True, help_text="Sampling evidence: match rates, sample values.")
+
+ status = models.CharField(
+ max_length=32,
+ choices=[(s.value, s.value) for s in RelationshipStatus],
+ default=RelationshipStatus.PROPOSED,
+ help_text="proposed, accepted (promoted to a real join), or rejected (never re-proposed).",
+ )
+ reviewed_by = models.ForeignKey(
+ "posthog.User",
+ on_delete=models.SET_NULL,
+ null=True,
+ blank=True,
+ db_constraint=False,
+ related_name="+",
+ )
+ reviewed_at = models.DateTimeField(null=True, blank=True)
+ rejection_reason = models.TextField(blank=True, help_text="Why the proposal was rejected.")
+
+ created_join = models.ForeignKey(
+ "data_tools.DataWarehouseJoin",
+ on_delete=models.SET_NULL,
+ null=True,
+ blank=True,
+ db_constraint=False,
+ related_name="+",
+ help_text="The join created when this proposal was accepted (promotion provenance).",
+ )
+
+ undirected_fingerprint = models.CharField(
+ max_length=64,
+ help_text="sha256 of the sorted {(table, key), (table, key)} pair set -- one proposal per physical join pair.",
+ )
+
+ class Meta:
+ constraints = [
+ models.UniqueConstraint(fields=["team", "undirected_fingerprint"], name="unique_relationship_fingerprint"),
+ ]
+ indexes = [models.Index(fields=["team", "status"])]
+
+ def __str__(self) -> str:
+ return f"{self.source_table_name} -> {self.joining_table_name}"
diff --git a/products/data_catalog/backend/presentation/serializers.py b/products/data_catalog/backend/presentation/serializers.py
index 4b15be07f9c0..26b16f12c1be 100644
--- a/products/data_catalog/backend/presentation/serializers.py
+++ b/products/data_catalog/backend/presentation/serializers.py
@@ -14,7 +14,7 @@ from posthog.schema_enums import IntervalType
from ..facade import api
from ..facade.enums import CreatedSource
-from ..facade.models import Metric, TableCertification
+from ..facade.models import Metric, RelationshipProposal, TableCertification
@extend_schema_field(OpenApiTypes.OBJECT)
@@ -236,3 +236,64 @@ class CertificationCreateSerializer(serializers.Serializer):
table_name = serializers.CharField(required=False, help_text="Table name; 409 with candidates if ambiguous.")
view_name = serializers.CharField(required=False, help_text="View name; 409 with candidates if ambiguous.")
notes = serializers.CharField(required=False, allow_blank=True, help_text="Why this mark exists.")
+
+
+@extend_schema_serializer(component_name="DataCatalogRelationshipProposal")
+class RelationshipProposalSerializer(serializers.ModelSerializer):
+ status = serializers.CharField(
+ read_only=True, help_text="proposed, accepted (promoted to a real join), or rejected (never re-proposed)."
+ )
+ configuration = _FreeJSONField(required=False, help_text="Extra join configuration, e.g. a field mapping.")
+ evidence = _FreeJSONField(required=False, help_text="Sampling evidence: match rates, sample values.")
+ reviewed_by = UserBasicSerializer(
+ read_only=True, allow_null=True, help_text="User who accepted or rejected the proposal."
+ )
+
+ class Meta:
+ model = RelationshipProposal
+ fields = [
+ "id",
+ "source_table_name",
+ "source_table_key",
+ "joining_table_name",
+ "joining_table_key",
+ "field_name",
+ "configuration",
+ "confidence",
+ "reasoning",
+ "evidence",
+ "status",
+ "reviewed_by",
+ "reviewed_at",
+ "rejection_reason",
+ "created_join",
+ "created_by",
+ "created_at",
+ ]
+ read_only_fields = [
+ "id",
+ "status",
+ "reviewed_by",
+ "reviewed_at",
+ "rejection_reason",
+ "created_join",
+ "created_by",
+ "created_at",
+ ]
+ extra_kwargs = {
+ "source_table_name": {"help_text": "Name of the table the join starts from."},
+ "source_table_key": {"help_text": "HogQL key expression on the source table (casts allowed)."},
+ "joining_table_name": {"help_text": "Name of the table being joined in."},
+ "joining_table_key": {"help_text": "HogQL key expression on the joining table (casts allowed)."},
+ "field_name": {"help_text": "Accessor the join adds to the source table."},
+ "confidence": {"help_text": "Discovery confidence in this join, 0-1."},
+ "reasoning": {"help_text": "Why this join is proposed."},
+ }
+
+
+class RelationshipRejectSerializer(serializers.Serializer):
+ rejection_reason = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ help_text="Why the proposal is rejected. Persisted so it is never re-proposed.",
+ )
diff --git a/products/data_catalog/backend/presentation/views.py b/products/data_catalog/backend/presentation/views.py
index 82fca7c2be88..534accd12eb9 100644
--- a/products/data_catalog/backend/presentation/views.py
+++ b/products/data_catalog/backend/presentation/views.py
@@ -8,7 +8,8 @@ from typing import cast
from django.db.models import QuerySet
-from drf_spectacular.utils import OpenApiResponse, extend_schema
+from drf_spectacular.types import OpenApiTypes
+from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema
from rest_framework import mixins, status, viewsets
from rest_framework.decorators import action as drf_action
from rest_framework.exceptions import PermissionDenied, ValidationError
@@ -25,7 +26,7 @@ from posthog.rate_limit import ClickHouseBurstRateThrottle, ClickHouseSustainedR
from ..facade import api
from ..facade.enums import HOGQL_DEFINITION_KIND, INSIGHT_DEFINITION_KINDS, NODE_DEFINITION_KINDS
-from ..facade.models import Metric, TableCertification
+from ..facade.models import Metric, RelationshipProposal, TableCertification
from .serializers import (
CertificationCreateSerializer,
CertificationSerializer,
@@ -33,6 +34,8 @@ from .serializers import (
MetricRunRequestSerializer,
MetricRunResponseSerializer,
MetricSerializer,
+ RelationshipProposalSerializer,
+ RelationshipRejectSerializer,
)
# Kinds that execute a ClickHouse query through the trends/funnels pipeline (node kinds run as a
@@ -255,3 +258,78 @@ class CertificationViewSet(
"""Mark the target as deprecated (avoid this source)."""
cert = api.deprecate(self.get_object(), cast(User, request.user))
return Response(CertificationSerializer(cert).data)
+
+
+class RelationshipProposalViewSet(
+ TeamAndOrgViewSetMixin,
+ mixins.ListModelMixin,
+ mixins.RetrieveModelMixin,
+ mixins.CreateModelMixin,
+ viewsets.GenericViewSet,
+):
+ """Reviewed join facts. Accepting one promotes it to a real DataWarehouseJoin; rejections persist."""
+
+ scope_object = "data_catalog"
+ serializer_class = RelationshipProposalSerializer
+ queryset = RelationshipProposal.objects.unscoped()
+
+ def safely_get_queryset(self, queryset: QuerySet[RelationshipProposal]) -> QuerySet[RelationshipProposal]:
+ proposals = api.relationships_for_team(self.team)
+ status_filter = self.request.query_params.get("status")
+ return proposals.filter(status=status_filter) if status_filter else proposals
+
+ @extend_schema(
+ parameters=[OpenApiParameter("status", OpenApiTypes.STR, description="Filter by proposed/accepted/rejected.")]
+ )
+ def list(self, request: Request, *args, **kwargs) -> Response:
+ return super().list(request, *args, **kwargs)
+
+ def create(self, request: Request, *args, **kwargs) -> Response:
+ serializer = self.get_serializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ data = serializer.validated_data
+ proposal = api.propose_relationship(
+ team=self.team,
+ user=cast(User, request.user),
+ source_table_name=data["source_table_name"],
+ source_table_key=data["source_table_key"],
+ joining_table_name=data["joining_table_name"],
+ joining_table_key=data["joining_table_key"],
+ field_name=data["field_name"],
+ configuration=data.get("configuration"),
+ confidence=data.get("confidence"),
+ reasoning=data.get("reasoning", ""),
+ evidence=data.get("evidence"),
+ )
+ return Response(self.get_serializer(proposal).data, status=status.HTTP_201_CREATED)
+
+ @action(
+ detail=True,
+ methods=["POST"],
+ required_scopes=["data_catalog_approval:write", "data_catalog:read", "query:read", "warehouse_view:write"],
+ throttle_classes=[HogQLQueryThrottle],
+ request=None,
+ responses={200: RelationshipProposalSerializer},
+ )
+ def accept(self, request: Request, **kwargs) -> Response:
+ """Promote the proposal to a real warehouse join after re-validating and probing it."""
+ # required_scopes gates tokens, but session users carry no scopes and AccessControlPermission
+ # only checks the data_catalog resource. Enforce the resources this action actually touches
+ # explicitly: query (the ClickHouse acceptance probe) and warehouse_view (the join it creates).
+ if not self.user_access_control.check_access_level_for_resource("query", "viewer"):
+ raise PermissionDenied("You need query access to accept a relationship proposal.")
+ if not self.user_access_control.check_access_level_for_resource("warehouse_view", "editor"):
+ raise PermissionDenied("You need warehouse view edit access to accept a relationship proposal.")
+ proposal = api.accept_proposal(self.get_object(), cast(User, request.user))
+ return Response(self.get_serializer(proposal).data)
+
+ @extend_schema(request=RelationshipRejectSerializer, responses={200: RelationshipProposalSerializer})
+ @action(detail=True, methods=["POST"], required_scopes=["data_catalog_approval:write", "data_catalog:read"])
+ def reject(self, request: Request, **kwargs) -> Response:
+ """Reject the proposal. Persists forever so the pair is never re-proposed."""
+ body = RelationshipRejectSerializer(data=request.data)
+ body.is_valid(raise_exception=True)
+ proposal = api.reject_proposal(
+ self.get_object(), cast(User, request.user), body.validated_data.get("rejection_reason", "")
+ )
+ return Response(self.get_serializer(proposal).data)
diff --git a/products/data_catalog/backend/routes.py b/products/data_catalog/backend/routes.py
index 0025b81dd413..417a7c8fb849 100644
--- a/products/data_catalog/backend/routes.py
+++ b/products/data_catalog/backend/routes.py
@@ -1,6 +1,10 @@
from posthog.api.routing import RouterRegistry
-from products.data_catalog.backend.presentation.views import CertificationViewSet, MetricViewSet
+from products.data_catalog.backend.presentation.views import (
+ CertificationViewSet,
+ MetricViewSet,
+ RelationshipProposalViewSet,
+)
def register_routes(routers: RouterRegistry) -> None:
@@ -11,3 +15,9 @@ def register_routes(routers: RouterRegistry) -> None:
"environment_data_catalog_certifications",
["team_id"],
)
+ routers.projects.register(
+ r"data_catalog/relationship_proposals",
+ RelationshipProposalViewSet,
+ "environment_data_catalog_relationship_proposals",
+ ["team_id"],
+ )
diff --git a/products/data_catalog/backend/tests/test_relationships.py b/products/data_catalog/backend/tests/test_relationships.py
new file mode 100644
index 000000000000..39e3fe85a88f
--- /dev/null
+++ b/products/data_catalog/backend/tests/test_relationships.py
@@ -0,0 +1,329 @@
+from concurrent.futures import ThreadPoolExecutor
+from threading import Barrier
+from typing import Any
+
+from posthog.test.base import APIBaseTest, BaseTest, NonAtomicBaseTest
+from unittest.mock import patch
+
+from django.db import IntegrityError, close_old_connections, transaction
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+from rest_framework import status
+from rest_framework.exceptions import ValidationError
+
+from posthog.hogql.database.lazy_join_tags import DATA_WAREHOUSE_EXPERIMENTS
+from posthog.hogql.errors import QueryError
+
+from posthog.models.personal_api_key import PersonalAPIKey
+from posthog.models.utils import generate_random_token_personal, hash_key_value
+from posthog.rate_limit import HogQLQueryThrottle
+
+from products.data_catalog.backend.facade.enums import RelationshipStatus
+from products.data_catalog.backend.logic import relationships
+from products.data_catalog.backend.logic.exceptions import CatalogConflict
+from products.data_catalog.backend.logic.relationships import accept_proposal, propose_relationship, reject_proposal
+from products.data_catalog.backend.models import RelationshipProposal
+from products.data_catalog.backend.presentation.serializers import RelationshipProposalSerializer
+from products.data_tools.backend.facade.models import DataWarehouseJoin
+
+# events and persons always exist in the HogQL database, so propose-time existence checks pass.
+_JOIN: dict[str, Any] = {
+ "source_table_name": "events",
+ "source_table_key": "distinct_id",
+ "joining_table_name": "persons",
+ "joining_table_key": "id",
+ "field_name": "linked_person",
+}
+
+
+class TestRelationshipModel(BaseTest):
+ def test_undirected_fingerprint_is_unique(self) -> None:
+ RelationshipProposal.objects.for_team(self.team.id).create(
+ team=self.team, undirected_fingerprint="abc", **_JOIN
+ )
+ with self.assertRaises(IntegrityError), transaction.atomic():
+ RelationshipProposal.objects.for_team(self.team.id).create(
+ team=self.team, undirected_fingerprint="abc", **_JOIN
+ )
+
+
+class TestProposeRelationship(BaseTest):
+ def test_unknown_table_rejected(self) -> None:
+ with self.assertRaises(ValidationError):
+ propose_relationship(team=self.team, user=self.user, **{**_JOIN, "source_table_name": "made_up_table"})
+
+ def test_reverse_orientation_is_deduped(self) -> None:
+ propose_relationship(team=self.team, user=self.user, **_JOIN)
+ with self.assertRaises(CatalogConflict):
+ propose_relationship(
+ team=self.team,
+ user=self.user,
+ source_table_name="persons",
+ source_table_key="id",
+ joining_table_name="events",
+ joining_table_key="distinct_id",
+ field_name="linked_events",
+ )
+
+ def test_equivalent_key_formatting_is_deduped(self) -> None:
+ propose_relationship(team=self.team, user=self.user, **_JOIN)
+ with self.assertRaises(CatalogConflict):
+ propose_relationship(
+ team=self.team,
+ user=self.user,
+ **{**_JOIN, "source_table_key": " distinct_id ", "joining_table_key": " id "},
+ )
+
+
+class TestAcceptProposal(BaseTest):
+ def _propose(self) -> RelationshipProposal:
+ return propose_relationship(team=self.team, user=self.user, **_JOIN)
+
+ def test_accept_creates_one_join_and_is_idempotent(self) -> None:
+ proposal = self._propose()
+ with patch.object(relationships, "execute_hogql_query"): # mock the ClickHouse probe boundary
+ accepted = accept_proposal(proposal, self.user)
+ accept_proposal(proposal, self.user) # idempotent
+
+ assert accepted.status == RelationshipStatus.ACCEPTED
+ assert accepted.created_join_id is not None
+ assert DataWarehouseJoin.objects.filter(team_id=self.team.id, source_table_name="events").count() == 1
+
+ def test_broken_join_probe_rejects(self) -> None:
+ proposal = self._propose()
+ with patch.object(relationships, "execute_hogql_query", side_effect=QueryError("no such column")):
+ with self.assertRaises(ValidationError):
+ accept_proposal(proposal, self.user)
+ proposal.refresh_from_db()
+ assert proposal.status == RelationshipStatus.PROPOSED # not promoted
+
+ def test_field_name_collision_rejected(self) -> None:
+ DataWarehouseJoin.objects.create(
+ team=self.team,
+ source_table_name="events",
+ source_table_key="x",
+ joining_table_name="other",
+ joining_table_key="y",
+ field_name="linked_person",
+ )
+ proposal = self._propose()
+ with patch.object(relationships, "execute_hogql_query"):
+ with self.assertRaises(ValidationError):
+ accept_proposal(proposal, self.user)
+
+ def test_physical_field_name_collision_rejected(self) -> None:
+ proposal = propose_relationship(team=self.team, user=self.user, **{**_JOIN, "field_name": "timestamp"})
+ with patch.object(relationships, "execute_hogql_query"):
+ with self.assertRaises(ValidationError):
+ accept_proposal(proposal, self.user)
+
+ def test_builtin_lazy_field_name_collision_rejected(self) -> None:
+ proposal = propose_relationship(team=self.team, user=self.user, **{**_JOIN, "field_name": "group_0"})
+ with patch.object(relationships, "execute_hogql_query"):
+ with self.assertRaises(ValidationError):
+ accept_proposal(proposal, self.user)
+
+ def test_experiments_optimized_probe_uses_experiments_resolver(self) -> None:
+ # An experiments-optimized events join resolves through DATA_WAREHOUSE_EXPERIMENTS at query
+ # time; the probe must build it the same way so an invalid experiments_timestamp_key is caught
+ # during review instead of the plain equality resolver silently passing it.
+ proposal = propose_relationship(
+ team=self.team,
+ user=self.user,
+ source_table_name="persons",
+ source_table_key="id",
+ joining_table_name="events",
+ joining_table_key="person_id",
+ field_name="linked_events",
+ configuration={"experiments_optimized": True, "experiments_timestamp_key": "timestamp"},
+ )
+ captured: dict[str, str] = {}
+
+ def _capture(**kwargs: Any) -> None:
+ database = kwargs["context"].database
+ captured["resolver"] = database.get_table("persons").fields["_catalog_probe"].resolver
+
+ with patch.object(relationships, "execute_hogql_query", side_effect=_capture):
+ accept_proposal(proposal, self.user)
+
+ assert captured["resolver"] == DATA_WAREHOUSE_EXPERIMENTS
+
+ @parameterized.expand([("empty_dict", {}), ("null", None)])
+ def test_exact_existing_join_is_reused(self, _name: str, configuration: dict[str, Any] | None) -> None:
+ join = DataWarehouseJoin.objects.create(team=self.team, configuration=configuration, **_JOIN)
+ proposal = self._propose()
+ with patch.object(relationships, "execute_hogql_query"):
+ accepted = accept_proposal(proposal, self.user)
+
+ assert accepted.created_join_id == join.id
+ assert DataWarehouseJoin.objects.filter(team_id=self.team.id, field_name=_JOIN["field_name"]).count() == 1
+
+
+class TestRejectProposal(BaseTest):
+ def test_reject_persists_reason(self) -> None:
+ proposal = propose_relationship(team=self.team, user=self.user, **_JOIN)
+ rejected = reject_proposal(proposal, self.user, "wrong keys")
+ assert rejected.status == RelationshipStatus.REJECTED
+ assert rejected.rejection_reason == "wrong keys"
+
+ def test_accepted_proposal_cannot_be_rejected(self) -> None:
+ proposal = propose_relationship(team=self.team, user=self.user, **_JOIN)
+ with patch.object(relationships, "execute_hogql_query"):
+ accepted = accept_proposal(proposal, self.user)
+
+ with self.assertRaises(ValidationError):
+ reject_proposal(accepted, self.user, "changed my mind")
+
+ accepted.refresh_from_db()
+ assert accepted.status == RelationshipStatus.ACCEPTED
+ assert accepted.created_join_id is not None
+ assert DataWarehouseJoin.objects.filter(pk=accepted.created_join_id, deleted=False).exists()
+
+
+class TestRelationshipConcurrency(NonAtomicBaseTest):
+ CLASS_DATA_LEVEL_SETUP = False
+
+ def _run_concurrently(self, operations: list[str], proposal_ids: list[str]) -> list[str]:
+ barrier = Barrier(len(operations))
+
+ def run(operation: str, proposal_id: str) -> str:
+ close_old_connections()
+ try:
+ proposal = RelationshipProposal.objects.for_team(self.team.id).get(pk=proposal_id)
+ barrier.wait()
+ if operation == "accept":
+ accept_proposal(proposal, None)
+ else:
+ reject_proposal(proposal, None, "not valid")
+ return operation
+ except ValidationError:
+ return "validation_error"
+ finally:
+ close_old_connections()
+
+ with ThreadPoolExecutor(max_workers=len(operations)) as executor:
+ futures = [
+ executor.submit(run, operation, proposal_id)
+ for operation, proposal_id in zip(operations, proposal_ids, strict=True)
+ ]
+ return [future.result() for future in futures]
+
+ def test_concurrent_accept_and_reject_leave_consistent_state(self) -> None:
+ proposal = propose_relationship(team=self.team, user=self.user, **_JOIN)
+ with patch.object(relationships, "execute_hogql_query"):
+ results = self._run_concurrently(["accept", "reject"], [str(proposal.id), str(proposal.id)])
+
+ proposal.refresh_from_db()
+ assert results.count("validation_error") == 1
+ assert proposal.status in {RelationshipStatus.ACCEPTED, RelationshipStatus.REJECTED}
+ assert DataWarehouseJoin.objects.filter(team_id=self.team.id, field_name=_JOIN["field_name"]).count() == (
+ 1 if proposal.status == RelationshipStatus.ACCEPTED else 0
+ )
+
+ def test_concurrent_accepts_with_same_accessor_create_one_join(self) -> None:
+ first = propose_relationship(team=self.team, user=self.user, **_JOIN)
+ second = propose_relationship(
+ team=self.team,
+ user=self.user,
+ **{**_JOIN, "source_table_key": "uuid", "joining_table_key": "created_at"},
+ )
+ with patch.object(relationships, "execute_hogql_query"):
+ results = self._run_concurrently(["accept", "accept"], [str(first.id), str(second.id)])
+
+ assert results.count("accept") == 1
+ assert results.count("validation_error") == 1
+ assert DataWarehouseJoin.objects.filter(team_id=self.team.id, field_name=_JOIN["field_name"]).count() == 1
+
+
+class TestRelationshipProposalSerializer(SimpleTestCase):
+ @parameterized.expand([(0.0,), (1.0,)])
+ def test_confidence_boundaries_are_valid(self, confidence: float) -> None:
+ serializer = RelationshipProposalSerializer(data={**_JOIN, "confidence": confidence})
+ assert serializer.is_valid(), serializer.errors
+
+ @parameterized.expand([(-0.01,), (1.01,)])
+ def test_confidence_outside_range_is_invalid(self, confidence: float) -> None:
+ serializer = RelationshipProposalSerializer(data={**_JOIN, "confidence": confidence})
+ assert not serializer.is_valid()
+ assert "confidence" in serializer.errors
+
+
+class TestRelationshipAPI(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.url = f"/api/projects/{self.team.id}/data_catalog/relationship_proposals/"
+
+ def test_create_proposal(self) -> None:
+ response = self.client.post(self.url, _JOIN, format="json")
+ assert response.status_code == status.HTTP_201_CREATED, response.json()
+ assert response.json()["status"] == RelationshipStatus.PROPOSED
+
+ def test_create_proposal_rejects_invalid_confidence(self) -> None:
+ response = self.client.post(self.url, {**_JOIN, "confidence": 1.01}, format="json")
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+
+ def test_create_proposal_rejects_malformed_join_key(self) -> None:
+ response = self.client.post(self.url, {**_JOIN, "source_table_key": "("}, format="json")
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+
+ @parameterized.expand(
+ [
+ (
+ "without_approval_scope",
+ ["data_catalog:read", "data_catalog:write", "query:read"],
+ status.HTTP_403_FORBIDDEN,
+ ),
+ (
+ "without_query_scope",
+ ["data_catalog:read", "data_catalog:write", "data_catalog_approval:write", "warehouse_view:write"],
+ status.HTTP_403_FORBIDDEN,
+ ),
+ (
+ "without_warehouse_view_scope",
+ ["data_catalog:read", "data_catalog:write", "data_catalog_approval:write", "query:read"],
+ status.HTTP_403_FORBIDDEN,
+ ),
+ (
+ "with_all_scopes",
+ [
+ "data_catalog:read",
+ "data_catalog:write",
+ "data_catalog_approval:write",
+ "query:read",
+ "warehouse_view:write",
+ ],
+ status.HTTP_200_OK,
+ ),
+ ]
+ )
+ def test_accept_requires_approval_query_and_warehouse_view_scopes(
+ self, _name: str, scopes: list[str], expected_status: int
+ ) -> None:
+ proposal = propose_relationship(team=self.team, user=self.user, **_JOIN)
+ raw = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="k",
+ user=self.user,
+ secure_value=hash_key_value(raw),
+ scopes=scopes,
+ )
+ self.client.logout()
+ with patch.object(relationships, "execute_hogql_query"):
+ response = self.client.post(f"{self.url}{proposal.id}/accept/", HTTP_AUTHORIZATION=f"Bearer {raw}")
+ assert response.status_code == expected_status
+
+ def test_accept_uses_hogql_query_throttle(self) -> None:
+ proposal = propose_relationship(team=self.team, user=self.user, **_JOIN)
+ with (
+ patch.object(HogQLQueryThrottle, "allow_request", return_value=False),
+ patch.object(HogQLQueryThrottle, "wait", return_value=None),
+ ):
+ response = self.client.post(f"{self.url}{proposal.id}/accept/")
+ assert response.status_code == status.HTTP_429_TOO_MANY_REQUESTS
+
+ def test_reject_via_api(self) -> None:
+ proposal = propose_relationship(team=self.team, user=self.user, **_JOIN)
+ response = self.client.post(f"{self.url}{proposal.id}/reject/", {"rejection_reason": "nope"}, format="json")
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["status"] == RelationshipStatus.REJECTED
diff --git a/products/data_catalog/frontend/generated/api.schemas.ts b/products/data_catalog/frontend/generated/api.schemas.ts
index 983d9fff4eb8..3306380145ec 100644
--- a/products/data_catalog/frontend/generated/api.schemas.ts
+++ b/products/data_catalog/frontend/generated/api.schemas.ts
@@ -394,6 +394,78 @@ export interface DataCatalogMetricRunApi {
instructions: string | null
}
+export interface DataCatalogRelationshipProposalApi {
+ readonly id: string
+ /**
+ * Name of the table the join starts from.
+ * @maxLength 400
+ */
+ source_table_name: string
+ /**
+ * HogQL key expression on the source table (casts allowed).
+ * @maxLength 400
+ */
+ source_table_key: string
+ /**
+ * Name of the table being joined in.
+ * @maxLength 400
+ */
+ joining_table_name: string
+ /**
+ * HogQL key expression on the joining table (casts allowed).
+ * @maxLength 400
+ */
+ joining_table_key: string
+ /**
+ * Accessor the join adds to the source table.
+ * @maxLength 400
+ */
+ field_name: string
+ /** Extra join configuration, e.g. a field mapping. */
+ configuration?: unknown
+ /**
+ * Discovery confidence in this join, 0-1.
+ * @minimum 0
+ * @maximum 1
+ * @nullable
+ */
+ confidence?: number | null
+ /** Why this join is proposed. */
+ reasoning?: string
+ /** Sampling evidence: match rates, sample values. */
+ evidence?: unknown
+ /** proposed, accepted (promoted to a real join), or rejected (never re-proposed). */
+ readonly status: string
+ /** User who accepted or rejected the proposal. */
+ readonly reviewed_by: UserBasicApi | null
+ /** @nullable */
+ readonly reviewed_at: string | null
+ /** Why the proposal was rejected. */
+ readonly rejection_reason: string
+ /**
+ * The join created when this proposal was accepted (promotion provenance).
+ * @nullable
+ */
+ readonly created_join: string | null
+ /** @nullable */
+ readonly created_by: number | null
+ readonly created_at: string
+}
+
+export interface PaginatedDataCatalogRelationshipProposalListApi {
+ count: number
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: DataCatalogRelationshipProposalApi[]
+}
+
+export interface RelationshipRejectApi {
+ /** Why the proposal is rejected. Persisted so it is never re-proposed. */
+ rejection_reason?: string
+}
+
export type DataCatalogCertificationsListParams = {
/**
* Number of results to return per page.
@@ -442,3 +514,18 @@ export const DataCatalogMetricsRunCreateRefresh = {
ForceAsync: 'force_async',
ForceCache: 'force_cache',
} as const
+
+export type DataCatalogRelationshipProposalsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number
+ /**
+ * Filter by proposed/accepted/rejected.
+ */
+ status?: string
+}
diff --git a/products/data_catalog/frontend/generated/api.ts b/products/data_catalog/frontend/generated/api.ts
index 99cdb97c3e79..8cc2e72984e0 100644
--- a/products/data_catalog/frontend/generated/api.ts
+++ b/products/data_catalog/frontend/generated/api.ts
@@ -17,9 +17,13 @@ import type {
DataCatalogMetricRunRequestApi,
DataCatalogMetricsListParams,
DataCatalogMetricsRunCreateParams,
+ DataCatalogRelationshipProposalApi,
+ DataCatalogRelationshipProposalsListParams,
PaginatedDataCatalogCertificationListApi,
PaginatedDataCatalogMetricListApi,
+ PaginatedDataCatalogRelationshipProposalListApi,
PatchedDataCatalogMetricApi,
+ RelationshipRejectApi,
} from './api.schemas'
// https://stackoverflow.com/questions/49579094/typescript-conditional-types-filter-out-readonly-properties-pick-only-requir/49579497#49579497
@@ -368,3 +372,125 @@ export const dataCatalogMetricsRunCreate = async (
body: JSON.stringify(dataCatalogMetricRunRequestApi),
})
}
+
+export const getDataCatalogRelationshipProposalsListUrl = (
+ projectId: string,
+ params?: DataCatalogRelationshipProposalsListParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/data_catalog/relationship_proposals/?${stringifiedParams}`
+ : `/api/projects/${projectId}/data_catalog/relationship_proposals/`
+}
+
+/**
+ * Reviewed join facts. Accepting one promotes it to a real DataWarehouseJoin; rejections persist.
+ */
+export const dataCatalogRelationshipProposalsList = async (
+ projectId: string,
+ params?: DataCatalogRelationshipProposalsListParams,
+ options?: RequestInit
+): Promise<PaginatedDataCatalogRelationshipProposalListApi> => {
+ return apiMutator<PaginatedDataCatalogRelationshipProposalListApi>(
+ getDataCatalogRelationshipProposalsListUrl(projectId, params),
+ {
+ ...options,
+ method: 'GET',
+ }
+ )
+}
+
+export const getDataCatalogRelationshipProposalsCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/data_catalog/relationship_proposals/`
+}
+
+/**
+ * Reviewed join facts. Accepting one promotes it to a real DataWarehouseJoin; rejections persist.
+ */
+export const dataCatalogRelationshipProposalsCreate = async (
+ projectId: string,
+ dataCatalogRelationshipProposalApi: NonReadonly<DataCatalogRelationshipProposalApi>,
+ options?: RequestInit
+): Promise<DataCatalogRelationshipProposalApi> => {
+ return apiMutator<DataCatalogRelationshipProposalApi>(getDataCatalogRelationshipProposalsCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(dataCatalogRelationshipProposalApi),
+ })
+}
+
+export const getDataCatalogRelationshipProposalsRetrieveUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/data_catalog/relationship_proposals/${id}/`
+}
+
+/**
+ * Reviewed join facts. Accepting one promotes it to a real DataWarehouseJoin; rejections persist.
+ */
+export const dataCatalogRelationshipProposalsRetrieve = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<DataCatalogRelationshipProposalApi> => {
+ return apiMutator<DataCatalogRelationshipProposalApi>(
+ getDataCatalogRelationshipProposalsRetrieveUrl(projectId, id),
+ {
+ ...options,
+ method: 'GET',
+ }
+ )
+}
+
+export const getDataCatalogRelationshipProposalsAcceptCreateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/data_catalog/relationship_proposals/${id}/accept/`
+}
+
+/**
+ * Promote the proposal to a real warehouse join after re-validating and probing it.
+ */
+export const dataCatalogRelationshipProposalsAcceptCreate = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<DataCatalogRelationshipProposalApi> => {
+ return apiMutator<DataCatalogRelationshipProposalApi>(
+ getDataCatalogRelationshipProposalsAcceptCreateUrl(projectId, id),
+ {
+ ...options,
+ method: 'POST',
+ }
+ )
+}
+
+export const getDataCatalogRelationshipProposalsRejectCreateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/data_catalog/relationship_proposals/${id}/reject/`
+}
+
+/**
+ * Reject the proposal. Persists forever so the pair is never re-proposed.
+ */
+export const dataCatalogRelationshipProposalsRejectCreate = async (
+ projectId: string,
+ id: string,
+ relationshipRejectApi?: RelationshipRejectApi,
+ options?: RequestInit
+): Promise<DataCatalogRelationshipProposalApi> => {
+ return apiMutator<DataCatalogRelationshipProposalApi>(
+ getDataCatalogRelationshipProposalsRejectCreateUrl(projectId, id),
+ {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(relationshipRejectApi),
+ }
+ )
+}
diff --git a/products/data_catalog/frontend/generated/api.zod.ts b/products/data_catalog/frontend/generated/api.zod.ts
index 38b1b8222f84..f80a46c0e329 100644
--- a/products/data_catalog/frontend/generated/api.zod.ts
+++ b/products/data_catalog/frontend/generated/api.zod.ts
@@ -221,3 +221,61 @@ export const DataCatalogMetricsRunCreateBody = /* @__PURE__ */ zod
query_id: zod.string().optional().describe('Client-supplied id to correlate or cancel the run.'),
})
.describe('Optional run-time overrides. The whole body may be omitted; a metric runs by its URL name.')
+
+/**
+ * Reviewed join facts. Accepting one promotes it to a real DataWarehouseJoin; rejections persist.
+ */
+export const dataCatalogRelationshipProposalsCreateBodySourceTableNameMax = 400
+
+export const dataCatalogRelationshipProposalsCreateBodySourceTableKeyMax = 400
+
+export const dataCatalogRelationshipProposalsCreateBodyJoiningTableNameMax = 400
+
+export const dataCatalogRelationshipProposalsCreateBodyJoiningTableKeyMax = 400
+
+export const dataCatalogRelationshipProposalsCreateBodyFieldNameMax = 400
+
+export const dataCatalogRelationshipProposalsCreateBodyConfidenceMin = 0
+export const dataCatalogRelationshipProposalsCreateBodyConfidenceMax = 1
+
+export const DataCatalogRelationshipProposalsCreateBody = /* @__PURE__ */ zod.object({
+ source_table_name: zod
+ .string()
+ .max(dataCatalogRelationshipProposalsCreateBodySourceTableNameMax)
+ .describe('Name of the table the join starts from.'),
+ source_table_key: zod
+ .string()
+ .max(dataCatalogRelationshipProposalsCreateBodySourceTableKeyMax)
+ .describe('HogQL key expression on the source table (casts allowed).'),
+ joining_table_name: zod
+ .string()
+ .max(dataCatalogRelationshipProposalsCreateBodyJoiningTableNameMax)
+ .describe('Name of the table being joined in.'),
+ joining_table_key: zod
+ .string()
+ .max(dataCatalogRelationshipProposalsCreateBodyJoiningTableKeyMax)
+ .describe('HogQL key expression on the joining table (casts allowed).'),
+ field_name: zod
+ .string()
+ .max(dataCatalogRelationshipProposalsCreateBodyFieldNameMax)
+ .describe('Accessor the join adds to the source table.'),
+ configuration: zod.unknown().optional().describe('Extra join configuration, e.g. a field mapping.'),
+ confidence: zod
+ .number()
+ .min(dataCatalogRelationshipProposalsCreateBodyConfidenceMin)
+ .max(dataCatalogRelationshipProposalsCreateBodyConfidenceMax)
+ .nullish()
+ .describe('Discovery confidence in this join, 0-1.'),
+ reasoning: zod.string().optional().describe('Why this join is proposed.'),
+ evidence: zod.unknown().optional().describe('Sampling evidence: match rates, sample values.'),
+})
+
+/**
+ * Reject the proposal. Persists forever so the pair is never re-proposed.
+ */
+export const DataCatalogRelationshipProposalsRejectCreateBody = /* @__PURE__ */ zod.object({
+ rejection_reason: zod
+ .string()
+ .optional()
+ .describe('Why the proposal is rejected. Persisted so it is never re-proposed.'),
+})
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index f6a3f30d5720..a5df1fe393a7 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -16061,6 +16061,64 @@ export namespace Schemas {
query_id?: string;
}
+ export interface DataCatalogRelationshipProposal {
+ readonly id: string;
+ /**
+ * Name of the table the join starts from.
+ * @maxLength 400
+ */
+ source_table_name: string;
+ /**
+ * HogQL key expression on the source table (casts allowed).
+ * @maxLength 400
+ */
+ source_table_key: string;
+ /**
+ * Name of the table being joined in.
+ * @maxLength 400
+ */
+ joining_table_name: string;
+ /**
+ * HogQL key expression on the joining table (casts allowed).
+ * @maxLength 400
+ */
+ joining_table_key: string;
+ /**
+ * Accessor the join adds to the source table.
+ * @maxLength 400
+ */
+ field_name: string;
+ /** Extra join configuration, e.g. a field mapping. */
+ configuration?: unknown;
+ /**
+ * Discovery confidence in this join, 0-1.
+ * @minimum 0
+ * @maximum 1
+ * @nullable
+ */
+ confidence?: number | null;
+ /** Why this join is proposed. */
+ reasoning?: string;
+ /** Sampling evidence: match rates, sample values. */
+ evidence?: unknown;
+ /** proposed, accepted (promoted to a real join), or rejected (never re-proposed). */
+ readonly status: string;
+ /** User who accepted or rejected the proposal. */
+ readonly reviewed_by: UserBasic | null;
+ /** @nullable */
+ readonly reviewed_at: string | null;
+ /** Why the proposal was rejected. */
+ readonly rejection_reason: string;
+ /**
+ * The join created when this proposal was accepted (promotion provenance).
+ * @nullable
+ */
+ readonly created_join: string | null;
+ /** @nullable */
+ readonly created_by: number | null;
+ readonly created_at: string;
+ }
+
export interface DataColorTheme {
readonly id: number;
/** @maxLength 100 */
@@ -35644,6 +35702,15 @@ export namespace Schemas {
results: DataCatalogMetric[];
}
+ export interface PaginatedDataCatalogRelationshipProposalList {
+ count: number;
+ /** @nullable */
+ next?: string | null;
+ /** @nullable */
+ previous?: string | null;
+ results: DataCatalogRelationshipProposal[];
+ }
+
export interface PaginatedDataColorThemeList {
count: number;
/** @nullable */
@@ -52257,6 +52324,11 @@ export namespace Schemas {
recorded: boolean;
}
+ export interface RelationshipReject {
+ /** Why the proposal is rejected. Persisted so it is never re-proposed. */
+ rejection_reason?: string;
+ }
+
/**
* Request body for `remember`.
*/
@@ -69550,6 +69622,21 @@ export namespace Schemas {
ForceCache: 'force_cache',
} as const;
+ export type DataCatalogRelationshipProposalsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number;
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number;
+ /**
+ * Filter by proposed/accepted/rejected.
+ */
+ status?: string;
+ };
+
export type DataColorThemesListParams = {
/**
* Number of results to return per page.