: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(devex): tell schema authors when the api ratchet flags a builder they only exposed (#105016)
Julian Bezbf041756ae0d
diff --git a/.github/workflows/ci-python.yml b/.github/workflows/ci-python.ymlindex 1f7cee0ea140..d88c02f3a302 100644--- a/.github/workflows/ci-python.yml+++ b/.github/workflows/ci-python.yml@@ -508,6 +508,10 @@ jobs:- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2with:persist-credentials: false+ # So `HEAD^1` (the pull request's base commit) resolves below, letting+ # the ratchet tell a builder a schema change merely exposed apart from+ # one this branch actually added.+ fetch-depth: 2- name: Set up Pythonuses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0@@ -522,6 +526,8 @@ jobs:# Skip on unrebased branches: the command may not be registered yet.- name: Ratchet product paths in lib/api.ts+ env:+ API_RATCHET_BASE: HEAD^1run: |if [ ! -f tools/hogli-commands/hogli_commands/api_ratchet.py ]; thenecho "hogli lint:api-ratchet not present on this branch yet — skipping (rebase to pick it up)"diff --git a/tools/hogli-commands/hogli_commands/api_ratchet.py b/tools/hogli-commands/hogli_commands/api_ratchet.pyindex 66734308911d..aa294d97ab5b 100644--- a/tools/hogli-commands/hogli_commands/api_ratchet.py+++ b/tools/hogli-commands/hogli_commands/api_ratchet.py@@ -19,6 +19,19 @@ Existing redundancy is grandfathered in a baseline file. The command fails onlyon a redundant method that is not in the baseline, which is the case that wouldadd new debt. A shrinking baseline is the migration's progress metric.+A pull request that only adds OpenAPI schema for an endpoint makes an existing,+untouched path method redundant for the first time. The route did not change,+only whether a generated client now covers it. Telling that author to "use the+generated client instead" blames the schema work for debt it did not add, and the+cheapest way out would be dropping the schema annotation. Setting the+``API_RATCHET_BASE`` environment variable to a git ref (CI passes ``HEAD^1``, the+pull request's base commit) separates the two cases. A redundant method that is+not in the baseline but already built the same route on that ref is "exposed": the+check still fails, so the baseline and the semgrep rules stay exact, but it names+the one command that records it (``--update-baseline --write-semgrep``) and tells+the author to keep the schema change. Unset, or when the ref cannot be read+(shallow clone, bad ref), every new entry gets the ordinary message.+hogli lint:api-ratchet # check against the baselinehogli lint:api-ratchet --prune-baseline # drop stale entries, never add onehogli lint:api-ratchet --update-baseline # rewrite the baseline, new debt included@@ -34,8 +47,10 @@ are normalized onto ``projects`` before comparison.from __future__ import annotations+import osimport reimport json+import subprocessfrom collections.abc import Iterablefrom dataclasses import dataclassfrom functools import lru_cache@@ -65,6 +80,9 @@ PLUMBING_TEMPLATES: Final = frozenset({("projects",), ("projects", "{}"), ("orga# Sits next to the file it ratchets, so the person adding a path method sees it.BASELINE: Final = Path("frontend/src/lib/api-ratchet-baseline.txt")+# CI passes this as `HEAD^1`, the pull request's base commit.+API_RATCHET_BASE_ENV: Final = "API_RATCHET_BASE"+SEMGREP_RULE: Final = Path(".semgrep/rules/devex/prefer-codegen-api-namespaced.yaml")SEMGREP_BEGIN: Final = " # --- generated by `hogli lint:api-ratchet --write-semgrep` ---"SEMGREP_END: Final = " # --- end generated ---"@@ -807,6 +825,23 @@ def _argument_segments_after(text: str, offset: int) -> tuple[str, ...]:return tuple(segments)+def _method_route_entries(source: str) -> frozenset[str]:+ """Every (method, normalized route) pair ``source`` builds, in baseline-entry form.++ Parsed with the same ``ApiRequestResolver`` used for the current api.ts. This+ reads a *different* version of the file (the base ref's), so it does not care+ whether a route was redundant there - only whether the method already built it,+ to compare against ``RedundantMethod.entry`` on the current side.+ """+ resolver = ApiRequestResolver(source)+ entries: set[str] = set()+ for name in resolver.method_names():+ for template in resolver.templates(name):+ normalized = normalize_template(template)+ entries.add(f"{name} {'/'.join(normalized)}")+ return frozenset(entries)++class Ratchet:"""The report: which path methods are redundant, and which namespaces use them."""@@ -1075,7 +1110,7 @@ def semgrep_drift(repo_root: Path, ratchet: Ratchet) -> str | None:return None if committed == render_semgrep_rules(ratchet) else "the committed rules are out of date"-def _report_json(ratchet: Ratchet, new: set[str], stale: set[str]) -> str:+def _report_json(ratchet: Ratchet, new: set[str], stale: set[str], exposed: set[str]) -> str:return json.dumps({"redundant": [@@ -1085,11 +1120,52 @@ def _report_json(ratchet: Ratchet, new: set[str], stale: set[str]) -> str:"namespaces": {ns: sorted(products) for ns, products in sorted(ratchet.namespaces().items())},"new": sorted(new),"stale": sorted(stale),+ "exposed": sorted(exposed),},indent=2,)+def _exposed_message(ratchet: Ratchet, exposed: set[str]) -> str:+ """The failure for builders a schema change exposed, with the one command that records them."""+ lines = [f"\n❌ {len(exposed)} builder(s) already existed and only gained a generated twin in this change."]+ lines.append(" Not your debt, so keep the schema change:")+ for entry in sorted(ratchet.redundant, key=lambda item: item.entry):+ if entry.entry in exposed:+ lines.append(f" {entry.name} -> /api/{'/'.join(entry.template)}")+ lines.append(" Run: hogli lint:api-ratchet --update-baseline --write-semgrep, then commit the result.")+ return "\n".join(lines)+++def _read_base_api_ts(repo_root: Path, ref: str) -> str | None:+ """The base ref's api.ts contents, or ``None`` if git can't produce them.++ Covers a shallow checkout that never fetched the ref, a bad ref name, and a repo+ where the file didn't exist yet at that commit — each comes back as a failed+ ``git show`` rather than a partial read.+ """+ result = subprocess.run(+ ["git", "show", f"{ref}:{API_TS.as_posix()}"], cwd=repo_root, capture_output=True, text=True+ )+ return result.stdout if result.returncode == 0 else None+++def _base_entries(repo_root: Path) -> frozenset[str] | None:+ """The method and route entries the ``API_RATCHET_BASE_ENV`` ref builds, or ``None``.++ ``None`` when the variable is unset, or with a warning when git cannot read the ref;+ either way every new entry then gets the ordinary message.+ """+ ref = os.environ.get(API_RATCHET_BASE_ENV)+ if not ref:+ return None+ base_source = _read_base_api_ts(repo_root, ref)+ if base_source is None:+ click.echo(f"⚠️ {API_RATCHET_BASE_ENV}={ref} could not be read (shallow clone or unknown ref).", err=True)+ return None+ return _method_route_entries(base_source)++@click.command(name="lint:api-ratchet",help="Block new frontend/src/lib/api.ts path methods that a generated client already covers.",@@ -1139,13 +1215,18 @@ def cmd_lint_api_ratchet(click.echo(f"Baseline rewritten: {len(redundant)} redundant path method(s).")if new:click.echo(- f"⚠️ This grew the baseline by {len(new)} entry/entries, which grandfathers new debt.\n"- " Migrate the call sites instead, or say in the pull request why the entry has to stay."+ f"⚠️ This grew the baseline by {len(new)} entry/entries.\n"+ " If this change added them, migrate the call sites instead, or say in the pull request why\n"+ " they have to stay. If they existed before and a schema change only exposed them, that is expected.")return+ base_entries = _base_entries(repo_root)+ exposed = {entry for entry in new if base_entries is not None and entry in base_entries}+ added = new - exposed+if as_json:- click.echo(_report_json(ratchet, new, stale))+ click.echo(_report_json(ratchet, new, stale, exposed))raise SystemExit(1 if new else 0)drift = semgrep_drift(repo_root, ratchet)@@ -1156,10 +1237,12 @@ def cmd_lint_api_ratchet(for stale_entry in sorted(stale):click.echo(f" {stale_entry}")click.echo(" Run: hogli lint:api-ratchet --prune-baseline")- if new:- click.echo(f"\n❌ {len(new)} path method(s) duplicate a generated client:")+ if exposed:+ click.echo(_exposed_message(ratchet, exposed))+ if added:+ click.echo(f"\n❌ {len(added)} path method(s) duplicate a generated client:")for redundant_method in sorted(ratchet.redundant, key=lambda item: item.entry):- if redundant_method.entry not in new:+ if redundant_method.entry not in added:continueclick.echo(f" {redundant_method.name} -> /api/{'/'.join(redundant_method.template)}"@@ -1171,6 +1254,7 @@ def cmd_lint_api_ratchet("if it is not, annotate the viewset and run `hogli build:openapi` before migrating.\n""Agents: invoke the `adopting-generated-api-types` skill.")+ if new:raise SystemExit(1)if drift is not None:click.echo(f"\n❌ {SEMGREP_RULE} is stale: {drift}.\n Run: hogli lint:api-ratchet --write-semgrep")diff --git a/tools/hogli-commands/hogli_commands/tests/test_api_ratchet.py b/tools/hogli-commands/hogli_commands/tests/test_api_ratchet.pyindex 68e0d6923902..f932b69692e5 100644--- a/tools/hogli-commands/hogli_commands/tests/test_api_ratchet.py+++ b/tools/hogli-commands/hogli_commands/tests/test_api_ratchet.py@@ -1,5 +1,6 @@from __future__ import annotations+import jsonfrom pathlib import Pathimport pytest@@ -221,6 +222,13 @@ def _baseline_lines(*names: str) -> str:return "".join(f"{name} {_FIXTURE_ROUTES[name]}\n" for name in names)+# A base ref where `hogFlows` never existed.+API_TS_FIXTURE_WITHOUT_HOGFLOWS = API_TS_FIXTURE.replace(+ " public hogFlows(): ApiRequest {\n return this.environmentsDetail().addPathComponent('hog_flows')\n }\n\n",+ "",+)++class TestApiRequestResolver:@parameterized.expand([@@ -406,12 +414,12 @@ class TestBaselineFixModes:assert read_baseline(tmp_path) == {"hogFlows projects/{}/hog_flows"}assert runner.invoke(cmd_lint_api_ratchet, []).exit_code == 1- def test_update_warns_that_it_grandfathers_new_debt(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ def test_update_warns_when_it_grows_the_baseline(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:_write_repo(tmp_path, baseline=_baseline_lines("hogFlows"))monkeypatch.setattr(api_ratchet, "REPO_ROOT", tmp_path)result = runner.invoke(cmd_lint_api_ratchet, ["--update-baseline"])assert result.exit_code == 0- assert "grandfathers new debt" in result.output+ assert "grew the baseline" in result.outputassert runner.invoke(cmd_lint_api_ratchet, []).exit_code == 0@@ -612,3 +620,73 @@ class TestCommand:"propertyDefinitions projects/{}/property_definitions","organizationMembers organizations/{}/members",}+++class TestExposedBuilders:+ def _run(self, monkeypatch: pytest.MonkeyPatch, root: Path, base_source: str | None) -> Result:+ monkeypatch.setattr(api_ratchet, "REPO_ROOT", root)+ if base_source is None:+ monkeypatch.delenv(api_ratchet.API_RATCHET_BASE_ENV, raising=False)+ else:+ monkeypatch.setenv(api_ratchet.API_RATCHET_BASE_ENV, "HEAD^1")+ monkeypatch.setattr(api_ratchet, "_read_base_api_ts", lambda repo_root, ref: base_source)+ return runner.invoke(cmd_lint_api_ratchet, [])++ def test_a_builder_the_base_already_had_fails_with_the_command_that_records_it(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ _write_repo(+ tmp_path,+ baseline=_baseline_lines("signalReport", "signalReports", "propertyDefinitions", "organizationMembers"),+ )++ result = self._run(monkeypatch, tmp_path, API_TS_FIXTURE)++ assert result.exit_code == 1+ assert "hogFlows" in result.output+ assert "already existed" in result.output+ assert "--update-baseline --write-semgrep" in result.output+ assert "duplicate a generated client" not in result.output+ # The named command is the whole fix.+ assert runner.invoke(cmd_lint_api_ratchet, ["--update-baseline", "--write-semgrep"]).exit_code == 0+ assert self._run(monkeypatch, tmp_path, API_TS_FIXTURE).exit_code == 0++ def test_a_builder_missing_from_the_base_is_still_new_debt(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ _write_repo(+ tmp_path,+ baseline=_baseline_lines("signalReport", "signalReports", "propertyDefinitions", "organizationMembers"),+ )+ result = self._run(monkeypatch, tmp_path, API_TS_FIXTURE_WITHOUT_HOGFLOWS)+ assert result.exit_code == 1+ assert "duplicate a generated client" in result.output+ assert "already existed" not in result.output++ def test_without_the_env_var_the_check_stays_strict(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ _write_repo(+ tmp_path,+ baseline=_baseline_lines("signalReport", "signalReports", "propertyDefinitions", "organizationMembers"),+ )+ result = self._run(monkeypatch, tmp_path, None)+ assert result.exit_code == 1+ assert "duplicate a generated client" in result.output+ assert "already existed" not in result.output++ def test_an_unreadable_base_ref_falls_back_to_strict_with_a_warning(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ _write_repo(+ tmp_path,+ baseline=_baseline_lines("signalReport", "signalReports", "propertyDefinitions", "organizationMembers"),+ )+ monkeypatch.setattr(api_ratchet, "REPO_ROOT", tmp_path)+ monkeypatch.setenv(api_ratchet.API_RATCHET_BASE_ENV, "HEAD^1")+ monkeypatch.setattr(api_ratchet, "_read_base_api_ts", lambda repo_root, ref: None)+ result = runner.invoke(cmd_lint_api_ratchet, [])+ assert result.exit_code == 1+ assert "could not be read" in result.output+ assert "hogFlows" in result.output+ # The warning must not corrupt the machine-readable report.+ report = json.loads(CliRunner(mix_stderr=False).invoke(cmd_lint_api_ratchet, ["--json"]).stdout)+ assert report["exposed"] == []