: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(devex): scaffold working dummy product in bootstrap and validate in CI (#57959)
Julian Bezdb2aaef0f3a0
diff --git a/.github/scripts/check-idor-model-coverage.py b/.github/scripts/check-idor-model-coverage.pyindex bc6c82eb6421..be76c16cdc3e 100644--- a/.github/scripts/check-idor-model-coverage.py+++ b/.github/scripts/check-idor-model-coverage.py@@ -124,6 +124,8 @@ def get_scoped_models() -> tuple[dict[str, set[str]], set[str], set[str], set[st"InsightCachingState","InstanceSetting","Schedule",+ # --- Auto-scoped via ProductTeamModel (TeamScopedManager handles filtering) ---+ "SplineReticulator", # CI scaffold (hogli product:bootstrap)# --- Accessed via parent FK (no direct team-scoped lookup needed) ---"AlertSubscription","Approval",diff --git a/.github/workflows/ci-backend.yml b/.github/workflows/ci-backend.ymlindex ace858f45cad..8d09e55af909 100644--- a/.github/workflows/ci-backend.yml+++ b/.github/workflows/ci-backend.yml@@ -530,6 +530,9 @@ jobs:- name: Install Python dependenciesrun: UV_PROJECT_ENVIRONMENT=$pythonLocation uv sync --frozen --dev+ - name: Bootstrap scaffold product+ run: ./bin/hogli product:bootstrap spline_reticulator --non-interactive+- name: Lint product structurerun: ./bin/hogli product:lint --alldiff --git a/tools/hogli-commands/hogli_commands/product/cli.py b/tools/hogli-commands/hogli_commands/product/cli.pyindex 925230a33db8..ec5af9d1d148 100644--- a/tools/hogli-commands/hogli_commands/product/cli.py+++ b/tools/hogli-commands/hogli_commands/product/cli.py@@ -13,8 +13,9 @@ from .scaffold import bootstrap_product@click.argument("name")@click.option("--dry-run", is_flag=True, help="Show what would be created without creating")@click.option("--force", is_flag=True, help="Overwrite existing files")-def cmd_bootstrap(name: str, dry_run: bool, force: bool) -> None:- bootstrap_product(name, dry_run, force)[email protected]("--non-interactive", is_flag=True, help="Skip prompts, use defaults (for CI)")+def cmd_bootstrap(name: str, dry_run: bool, force: bool, non_interactive: bool) -> None:+ bootstrap_product(name, dry_run, force, non_interactive=non_interactive)@click.command(name="product:lint", help="Check product structure for misplaced files")diff --git a/tools/hogli-commands/hogli_commands/product/scaffold.py b/tools/hogli-commands/hogli_commands/product/scaffold.pyindex 9e0901b58880..4dc2a228a6e4 100644--- a/tools/hogli-commands/hogli_commands/product/scaffold.py+++ b/tools/hogli-commands/hogli_commands/product/scaffold.py@@ -148,7 +148,7 @@ def _write_product_yaml(product_dir: Path, display_name: str, owners: list[str],click.echo(f"\n Created product.yaml (name={display_name!r}, owners={owners})")-def bootstrap_product(name: str, dry_run: bool, force: bool) -> None:+def bootstrap_product(name: str, dry_run: bool, force: bool, *, non_interactive: bool = False) -> None:if not _VALID_PRODUCT_NAME_RE.match(name):raise click.ClickException(f"Invalid product name '{name}' — must be lowercase, start with a letter, and contain only [a-z0-9_]."@@ -209,6 +209,8 @@ def bootstrap_product(name: str, dry_run: bool, force: bool) -> None:# product.yaml — canonical metadataif dry_run:_write_product_yaml(product_dir, _default_display_name(name), ["team-CHANGEME"], dry_run=True)+ elif non_interactive:+ _write_product_yaml(product_dir, _default_display_name(name), ["team-devex"], dry_run=False)else:display_name = click.prompt(" Display name", default=_default_display_name(name), show_default=True)owner = click.prompt(@@ -227,6 +229,8 @@ def bootstrap_product(name: str, dry_run: bool, force: bool) -> None:if dry_run:_add_to_db_routing(name, name, dry_run=True)+ elif non_interactive:+ _add_to_db_routing(name, name, dry_run=False)else:click.echo("\n Products get their own database by default — this isolates locks, "diff --git a/tools/hogli-commands/hogli_commands/product_structure.yaml b/tools/hogli-commands/hogli_commands/product_structure.yamlindex 9375d10eaa95..fcb00e8e7e8c 100644--- a/tools/hogli-commands/hogli_commands/product_structure.yaml+++ b/tools/hogli-commands/hogli_commands/product_structure.yaml@@ -105,17 +105,36 @@ backend_files:required: truecan_be_folder: truetemplate: |- """Django models for {product}."""+ """+ Django models for {product}.++ Keep models thin — business logic belongs in logic/.+ Use types from facade/enums.py where applicable.+ Avoid ForeignKeys to models outside this app; if needed,+ disallow reverse relations with related_name='+'.+ """++ import uuid+from django.db import models- from posthog.models.utils import UUIDModel+ from posthog.models.scoping.product_mixin import ProductTeamModel++ from .facade.enums import SplineStatus- # Define your models here- # Important:- # - Keep models thin, no business logic, use logic.py instead- # - Use types from facade/contracts.py or facade/enums.py where applicable- # - Do not use ForeignKeys to models outside this app unless allowed, as you will make implicit dependencies.- # - If you make a ForeignKey to a common model, disallow reverse relations with related_name='+'++ class SplineReticulator(ProductTeamModel):+ id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)+ name = models.CharField(max_length=255)+ status = models.CharField(+ max_length=32,+ choices=[(s.value, s.value) for s in SplineStatus],+ default=SplineStatus.PENDING,+ )+ created_at = models.DateTimeField(auto_now_add=True)++ def __str__(self) -> str:+ return self.namelogic/:# Scaffolded as a package because business logic tends to grow fast and@@ -126,15 +145,20 @@ backend_files:__init__.py:required: falsetemplate: |- """- Business logic for {product}.+ """Business logic for {product}."""- Validation, calculations, business rules, ORM queries.- Called by facade/api.py.+ from __future__ import annotations- Split into submodules (e.g. logic/queries.py, logic/rules.py)- as this grows.- """+ from ..facade.enums import SplineStatus+ from ..models import SplineReticulator+++ def create_spline_reticulator(*, team_id: int, name: str) -> SplineReticulator:+ return SplineReticulator.objects.create(team_id=team_id, name=name, status=SplineStatus.PENDING)+++ def list_spline_reticulators() -> list[SplineReticulator]:+ return list(SplineReticulator.objects.all())tasks/:__init__.py:@@ -170,28 +194,35 @@ backend_files:"""Facade for {product}.- This is the ONLY module other products are allowed to import.-- Responsibilities:- - Accept frozen dataclasses as input parameters- - Call business logic (logic.py)- - Convert Django models to frozen dataclasses before returning- - Enforce transactions where needed- - Remain thin and stable-- Do NOT:- - Implement business logic here (use logic.py)- - Import DRF, serializers, or HTTP concerns- - Return ORM instances or QuerySets+ The ONLY module other products are allowed to import.+ Accept frozen dataclasses, call logic/, return frozen+ dataclasses. Never return ORM instances or import DRF."""+ from __future__ import annotations++ from .. import logic+ from ..models import SplineReticulatorfrom . import contracts+ from .enums import SplineStatus+- # --- Converters (model -> frozen dataclass) ---- #- # These look repetitive when fields align 1:1. The value is having ONE place- # where "internal" becomes "external contract". When models and contracts drift,- # the mapper absorbs the change instead of it leaking everywhere.+ def _to_dto(obj: SplineReticulator) -> contracts.SplineReticulatorDTO:+ return contracts.SplineReticulatorDTO(+ id=obj.id,+ name=obj.name,+ status=SplineStatus(obj.status),+ created_at=obj.created_at,+ )+++ def create(input: contracts.CreateSplineReticulatorInput) -> contracts.SplineReticulatorDTO:+ obj = logic.create_spline_reticulator(team_id=input.team_id, name=input.name)+ return _to_dto(obj)+++ def list_all() -> list[contracts.SplineReticulatorDTO]:+ return [_to_dto(obj) for obj in logic.list_spline_reticulators()]contracts.py:required: true@@ -199,36 +230,48 @@ backend_files:"""Contract types for {product}.- Stable, framework-free frozen dataclasses that define what this- product exposes to the rest of the codebase.-- Characteristics:- - No Django imports- - Immutable (frozen=True)- - Used by facade as inputs/outputs-- Do NOT depend on Django models, DRF serializers, or request objects.+ Frozen dataclasses that define what this product exposes.+ No Django imports. Used by facade as inputs/outputs."""+from dataclasses import dataclass+ from datetime import datetime+ from uuid import UUID++ from .enums import SplineStatus+++ @dataclass(frozen=True)+ class SplineReticulatorDTO:+ id: UUID+ name: str+ status: SplineStatus+ created_at: datetime+++ @dataclass(frozen=True)+ class CreateSplineReticulatorInput:+ team_id: int+ name: strenums.py:required: falsetemplate: |"""- Exported enums and constants for {product}.+ Exported enums for {product}.- Small products can keep enums in contracts.py instead. Split- into this file when contracts.py gets crowded.-- Rule: if an enum appears in a contract dataclass field, it- belongs here (or in contracts.py). Shared types that other- products need to interpret contract objects also belong here.-- Internal-only constants (DB magic values, feature flags, etc.)- should stay in the implementation (logic.py, models.py).+ If an enum appears in a contract dataclass field, it belongs here.+ Internal-only constants (DB magic values, feature flags) stay in+ the implementation (logic.py, models.py)."""+from enum import StrEnum++ class SplineStatus(StrEnum):+ PENDING = "pending"+ RETICULATED = "reticulated"+presentation/:__init__.py:required: true@@ -237,15 +280,21 @@ backend_files:serializers.py:required: truetemplate: |- """- DRF serializers for {product}.+ """DRF serializers for {product}."""- Converts frozen dataclasses to/from JSON. Can be auto-generated from- dataclasses using DataclassSerializer.- """+ from rest_framework import serializersfrom rest_framework_dataclasses.serializers import DataclassSerializer- # from ..facade.contracts import ...+ from ..facade.contracts import SplineReticulatorDTO+++ class SplineReticulatorSerializer(DataclassSerializer):+ class Meta:+ dataclass = SplineReticulatorDTO+++ class CreateSplineReticulatorSerializer(serializers.Serializer):+ name = serializers.CharField(max_length=255, help_text="Name of the spline to reticulate.")views.py:required: true@@ -253,29 +302,50 @@ backend_files:"""DRF views for {product}.- Responsibilities:- - Validate incoming JSON (via serializers)- - Convert JSON to frozen dataclasses- - Call facade methods (facade/api.py)- - Convert frozen dataclasses to JSON responses-- No business logic here - that belongs in logic.py via the facade.+ Validate JSON via serializers, call facade methods,+ return serialized responses. No business logic here."""- from rest_framework import viewsets++ from drf_spectacular.utils import extend_schema+ from rest_framework import status, viewsets+ from rest_framework.request import Request+ from rest_framework.response import Responsefrom posthog.api.routing import TeamAndOrgViewSetMixin- # from ..facade import api+ from ..facade import api, contracts+ from .serializers import CreateSplineReticulatorSerializer, SplineReticulatorSerializer+++ class SplineReticulatorViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):+ scope_object = "INTERNAL"++ @extend_schema(responses={{200: SplineReticulatorSerializer(many=True)}})+ def list(self, request: Request, **kwargs) -> Response:+ items = api.list_all()+ return Response(SplineReticulatorSerializer(items, many=True).data)++ @extend_schema(request=CreateSplineReticulatorSerializer, responses={{201: SplineReticulatorSerializer}})+ def create(self, request: Request, **kwargs) -> Response:+ serializer = CreateSplineReticulatorSerializer(data=request.data)+ serializer.is_valid(raise_exception=True)+ dto = api.create(contracts.CreateSplineReticulatorInput(+ team_id=self.team_id,+ **serializer.validated_data,+ ))+ return Response(SplineReticulatorSerializer(dto).data, status=status.HTTP_201_CREATED)urls.py:required: truetemplate: |"""URL routes for {product}."""+from rest_framework.routers import DefaultRouter- # from .views import ...+ from .views import SplineReticulatorViewSetrouter = DefaultRouter()+ router.register(r"spline_reticulators", SplineReticulatorViewSet, basename="spline_reticulators")urlpatterns = router.urlstests/:@@ -283,6 +353,23 @@ backend_files:required: truetemplate: ''+ conftest.py:+ required: false+ template: |+ import pytest++ from posthog.models.scoping import team_scope+++ @pytest.fixture(autouse=True)+ def _set_team_scope(request):+ if request.node.get_closest_marker("django_db") is None:+ yield+ return+ team = request.getfixturevalue("team")+ with team_scope(team.id):+ yield+test_models.py:required: falsetemplate: ''@@ -293,7 +380,28 @@ backend_files:test_api.py:required: false- template: ''+ template: |+ from uuid import UUID++ import pytest++ from products.{product}.backend.facade import api+ from products.{product}.backend.facade.contracts import CreateSplineReticulatorInput+ from products.{product}.backend.facade.enums import SplineStatus+++ @pytest.mark.django_db+ class TestSplineReticulatorAPI:+ def test_create_and_list(self, team):+ dto = api.create(CreateSplineReticulatorInput(team_id=team.id, name="test-spline"))++ assert isinstance(dto.id, UUID)+ assert dto.name == "test-spline"+ assert dto.status == SplineStatus.PENDING++ all_items = api.list_all()+ assert len(all_items) == 1+ assert all_items[0].id == dto.idtest_presentation.py:required: false