: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
chore(ci): add advisory duplication lint for python and typescript (#93240)
Paul D'Ambra96d8d248d61f
diff --git a/.github/scripts/post-duplication-section.mjs b/.github/scripts/post-duplication-section.mjsnew file mode 100644index 000000000000..e80ed5d54b58--- /dev/null+++ b/.github/scripts/post-duplication-section.mjs@@ -0,0 +1,69 @@+#!/usr/bin/env node+// Posts the duplication section of the shared CI report for one language. The+// duplication check is advisory while the gate proves itself: this section+// informs review, it never fails the job. Findings JSON comes from+// `python3 bin/lint_duplication.py --report-dir .`.+//+// Usage: node post-duplication-section.mjs <python|typescript> <findings.json>+import fs from 'node:fs'++import { markdownCell } from '../../frontend/bin/ci-report/format.mjs'+import { postSection } from '../../frontend/bin/ci-report/update-ci-report.mjs'++const SECTION_IDS = { python: 'duplication-python', typescript: 'duplication-ts' }+const LANGUAGE_NAMES = { python: 'Python', typescript: 'TypeScript' }++const [language, reportPath] = process.argv.slice(2)+const sectionId = SECTION_IDS[language]+if (!sectionId || !reportPath) {+ console.error('Usage: post-duplication-section.mjs <python|typescript> <findings.json>')+ process.exit(1)+}+const statusPath = reportPath.replace(/duplication-findings-[^/]+\.json$/, 'duplication-scan-status.json')+// The lint writes this before the scans start, so a failed scan is+// distinguishable from an unrebased branch (which has no files at all).+// Check it first: a failed scan must replace any stale section from an+// earlier commit rather than leave it standing.+if (fs.existsSync(statusPath) && JSON.parse(fs.readFileSync(statusPath, 'utf8')).status === 'failed') {+ await postSection({+ id: sectionId,+ status: 'fail',+ summary: 'the duplication scan could not run',+ body: 'The duplication scan failed on this run (see the job log). Nothing here says whether this branch adds duplication.',+ })+ process.exit(0)+}+if (!fs.existsSync(reportPath)) {+ console.info(`No findings report at ${reportPath} — skipping (branch predates the check?)`)+ process.exit(0)+}++const findings = JSON.parse(fs.readFileSync(reportPath, 'utf8'))+const worst = findings.reduce((max, finding) => Math.max(max, finding.tokens), 0)+// The limits the linter enforces — quote them instead of hardcoding so a+// limits-only edit cannot leave the report text behind.+const limits = JSON.parse(fs.readFileSync(new URL('../../bin/lint-duplication.limits.json', import.meta.url), 'utf8'))+const summary =+ findings.length > 0+ ? `${findings.length} new duplicated block${findings.length === 1 ? '' : 's'} (worst ${worst} tokens)`+ : 'clean'++const lines = [+ `New ${LANGUAGE_NAMES[language]} code duplication introduced by this branch. Fails at ${limits.production}+ tokens in app code, or ${limits.test}+ tokens when both copies live in test files. Advisory while the gate proves itself: extract a shared helper instead of copying.`,+ '',+]+if (findings.length > 0) {+ lines.push('| First copy | Second copy | Lines | Tokens |', '| --- | --- | --- | --- |')+ for (const finding of findings) {+ lines.push(+ `| \`${markdownCell(finding.first_file)}:${finding.first_start}\` | \`${markdownCell(finding.second_file)}:${finding.second_start}\` | ${finding.lines} | ${finding.tokens} |`+ )+ }+}++await postSection({+ id: sectionId,+ status: findings.length > 0 ? 'warn' : 'ok',+ summary,+ body: lines.join('\n'),+})diff --git a/.github/workflows/ci-duplication.yml b/.github/workflows/ci-duplication.ymlnew file mode 100644index 000000000000..5492d2cc4211--- /dev/null+++ b/.github/workflows/ci-duplication.yml@@ -0,0 +1,87 @@+name: Duplication lint++on:+ pull_request:+ paths:+ - '**.py'+ - '**.ts'+ - '**.tsx'+ - '.github/workflows/ci-duplication.yml'+ - '.github/scripts/post-duplication-section.mjs'+ - 'bin/lint_duplication.py'+ - 'bin/lint-duplication.limits.json'+ workflow_dispatch:++concurrency:+ group: ${{ github.workflow }}-${{ github.head_ref || github.ref }}+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}++permissions:+ contents: read+ # The poster steps write sections of the shared CI report comment (mirrors ci-frontend.yml / ci-ai.yml).+ pull-requests: write++jobs:+ duplication:+ name: Duplication lint+ runs-on: depot-ubuntu-24.04+ timeout-minutes: 10+ # Advisory while the gate proves itself; promote to blocking once it+ # has run clean across open PRs for a while.+ continue-on-error: true+ steps:+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2+ - name: Fetch PR base for the clone baseline+ env:+ BASE_REF: ${{ github.event.pull_request.base.ref || 'master' }}+ # The clone baseline is the branch point, so both histories must reach it.+ # Master moves fast enough that a couple of days puts the fork point past+ # any small fixed depth; deepen until it resolves, with a cap.+ run: |+ for depth in 200 2000 20000; do+ git fetch --no-tags --depth=$depth origin "$BASE_REF:refs/remotes/origin/$BASE_REF"+ # The checked-out PR ref is shallow too; deepen its side as well+ # or merge-base never resolves.+ git fetch --no-tags --depth=$depth origin "$GITHUB_REF"+ if git merge-base "origin/$BASE_REF" HEAD > /dev/null 2>&1; then+ break+ fi+ done+ git merge-base "origin/$BASE_REF" HEAD || echo "merge-base unresolved at depth $depth; the lint falls back to the base tip"+ - uses: actions/setup-node@6044e13b5dc448c55e2357c09f80417699197238 # v6.2.0+ with:+ node-version-file: .nvmrc+ - name: Lint for new duplication+ env:+ BASE_REF: ${{ github.event.pull_request.base.ref || 'master' }}+ run: |+ if [ ! -f bin/lint_duplication.py ]; then+ echo "bin/lint_duplication.py not present on this branch; skipping"+ exit 0+ fi+ python3 bin/lint_duplication.py --base "origin/$BASE_REF" --report-dir .+ # always() so findings still reach the comment when the lint step fails.+ # Skipped on trunk-merge/** branches: merge-queue draft PRs are ephemeral and+ # unread, and each section write spends shared GITHUB_TOKEN budget.+ - name: Post CI report — duplication (Python)+ if: always() && github.event_name == 'pull_request' && !startsWith(github.head_ref, 'trunk-merge/')+ env:+ GITHUB_TOKEN: ${{ github.token }}+ run: |+ # The status file (written before the scans) lets the poster mark a failed+ # scan; the findings file is the success path. Either one is enough to post.+ if [ -f .github/scripts/post-duplication-section.mjs ] && { [ -f duplication-scan-status.json ] || [ -f duplication-findings-python.json ]; }; then+ node .github/scripts/post-duplication-section.mjs python duplication-findings-python.json+ else+ echo "Skipping the duplication report section: script or findings not on this branch"+ fi+ - name: Post CI report — duplication (TypeScript)+ if: always() && github.event_name == 'pull_request' && !startsWith(github.head_ref, 'trunk-merge/')+ env:+ GITHUB_TOKEN: ${{ github.token }}+ run: |+ if [ -f .github/scripts/post-duplication-section.mjs ] && { [ -f duplication-scan-status.json ] || [ -f duplication-findings-ts.json ]; }; then+ node .github/scripts/post-duplication-section.mjs typescript duplication-findings-ts.json+ else+ echo "Skipping the duplication report section: script or findings not on this branch"+ fidiff --git a/bin/lint-duplication.limits.json b/bin/lint-duplication.limits.jsonnew file mode 100644index 000000000000..5f9fb91cb679--- /dev/null+++ b/bin/lint-duplication.limits.json@@ -0,0 +1,4 @@+{+ "production": 70,+ "test": 150+}diff --git a/bin/lint_duplication.py b/bin/lint_duplication.pynew file mode 100644index 000000000000..dcbddf2e9f28--- /dev/null+++ b/bin/lint_duplication.py@@ -0,0 +1,309 @@+#!/usr/bin/env python3+# ruff: noqa: T201 allow print statements+"""Gate a branch on new code duplication in Python and TypeScript.++Runs jscpd over this tree and over a worktree of the branch point, and+diffs the two clone sets, so only duplication the branch introduces can+fail the gate. Existing duplication is grandfathered in. App code and+test code are held to different bars: a clone between two test files may+run longer before it fails, because repeated setup is idiomatic in tests.++With --report-dir, also writes one findings file per language for the CI+report comment (.github/scripts/post-duplication-section.mjs).+"""++import re+import sys+import json+import hashlib+import argparse+import tempfile+import subprocess+import collections+from dataclasses import dataclass+from pathlib import Path++JSCPD_VERSION = "5.1.1"++FORMATS = "python,typescript,tsx"++# Migrations and generated code duplicate by design; .depot/ is a vendored+# mirror of .github/actions/.+IGNORE = "**/migrations/**,**/generated/**,**/generated.*,.depot/**"++# jscpd scan floor. Anything smaller is never reported at all.+SCAN_MIN_LINES = 10+SCAN_MIN_TOKENS = 70++TEST_PATH = re.compile(+ r"(^|/)(test|tests|__tests__|__mocks__)/"+ r"|(^|/)test_[^/]*\.py$"+ r"|_test\.py$"+ r"|conftest\.py$"+ r"|\.test\.tsx?$"+ r"|\.spec\.tsx?$"+ r"|\.stories\.tsx?$"+)++LIMITS_PATH = Path(__file__).with_name("lint-duplication.limits.json")+SCAN_TIMEOUT_SECONDS = 240+++@dataclass(frozen=True, kw_only=True, slots=True)+class Limits:+ production: int+ test: int+++def load_limits() -> Limits:+ data = json.loads(LIMITS_PATH.read_text())+ return Limits(production=int(data["production"]), test=int(data["test"]))+++LIMITS = load_limits()+APP_MAX_NEW_CLONE_TOKENS = LIMITS.production+TEST_MAX_NEW_CLONE_TOKENS = LIMITS.test++LANGUAGES = ("python", "typescript")+++def is_test_file(path: str) -> bool:+ return bool(TEST_PATH.search(path))+++def clone_language(clone: dict) -> str:+ return "python" if clone.get("format") == "python" else "typescript"+++def find_gate_failures(clones: list[dict]) -> list[tuple[dict, bool]]:+ """Keep the new clones that fail the gate, worst first.++ A clone between two test files gets the looser bar; anything touching+ app code is held to the app bar.+ """+ failures = []+ for clone in clones:+ if not clone.get("isNew"):+ continue+ both_tests = is_test_file(clone["firstFile"]["name"]) and is_test_file(clone["secondFile"]["name"])+ bar = TEST_MAX_NEW_CLONE_TOKENS if both_tests else APP_MAX_NEW_CLONE_TOKENS+ if clone["tokens"] >= bar:+ failures.append((clone, both_tests))+ failures.sort(key=lambda item: -item[0]["tokens"])+ return failures+++def build_findings(failures: list[tuple[dict, bool]]) -> dict[str, list[dict]]:+ """Shape the failures as per-language findings for the CI report files."""+ findings: dict[str, list[dict]] = {language: [] for language in LANGUAGES}+ for clone, _ in failures:+ findings[clone_language(clone)].append(+ {+ "first_file": clone["firstFile"]["name"],+ "first_start": clone["firstFile"]["start"],+ "second_file": clone["secondFile"]["name"],+ "second_start": clone["secondFile"]["start"],+ "lines": clone["lines"],+ "tokens": clone["tokens"],+ }+ )+ return findings+++def run_jscpd(scan_root: Path, out_dir: Path) -> list[dict]:+ """Scan one tree with jscpd and return its clone list."""+ try:+ proc = subprocess.run(+ [+ "npx",+ "--yes",+ f"jscpd@{JSCPD_VERSION}",+ "--format",+ FORMATS,+ "--min-lines",+ str(SCAN_MIN_LINES),+ "--min-tokens",+ str(SCAN_MIN_TOKENS),+ "--skip-comments",+ "--reporters",+ "json",+ "--output",+ str(out_dir),+ "--ignore",+ IGNORE,+ ".",+ ],+ capture_output=True,+ text=True,+ # Two scans must finish inside the CI job's timeout-minutes, or the+ # job dies before the failure section can post.+ timeout=SCAN_TIMEOUT_SECONDS,+ cwd=scan_root,+ )+ except subprocess.TimeoutExpired:+ print(f"duplication lint could not run: jscpd exceeded {SCAN_TIMEOUT_SECONDS}s scanning {scan_root}")+ raise SystemExit(2) from None+ report_path = out_dir / "jscpd-report.json"+ if proc.returncode != 0 or not report_path.exists():+ print(proc.stdout[-3000:])+ print(proc.stderr[-3000:])+ print(f"duplication lint could not run: jscpd exited {proc.returncode} scanning {scan_root}")+ raise SystemExit(2)+ return json.loads(report_path.read_text())["duplicates"]+++def clone_key(clone: dict) -> tuple[frozenset, str]:+ """Pair key, insensitive to which side jscpd calls first and to where in+ the files the fragment sits.++ Keying on the fragment text (not the span) means edits elsewhere in the+ files do not re-flag an old clone as new; editing the duplicated block+ itself does, which is what the gate is for.+ """+ pair = frozenset((clone["firstFile"]["name"], clone["secondFile"]["name"]))+ return pair, hashlib.sha256(clone["fragment"].encode()).hexdigest()+++def mark_new_clones(current: list[dict], baseline: list[dict]) -> None:+ """Flag clones the baseline cannot account for, counting occurrences.++ A fragment already copied once between two files is grandfathered only+ for as many copies as the baseline holds: a third copy of the same+ fragment in the same file pair is new duplication and must be flagged.+ """+ available = collections.Counter(clone_key(clone) for clone in baseline)+ for clone in current:+ key = clone_key(clone)+ if available[key] > 0:+ available[key] -= 1+ clone["isNew"] = False+ else:+ clone["isNew"] = True+++def resolve_baseline(base: str, repo: Path) -> str:+ """Return the ref to compare clones against.++ The branch point, not the base tip: jscpd matches clones with their+ locations, so a file that moved on the base since the branch forked+ re-flags every old clone inside it as new. Comparing against the+ merge-base keeps pre-existing duplication out of the gate no matter+ how far behind the branch falls.+ """+ merge_base = subprocess.run(+ ["git", "merge-base", base, "HEAD"], capture_output=True, text=True, cwd=repo+ ).stdout.strip()+ if merge_base:+ return merge_base+ print(f"Could not resolve the merge-base with {base!r} (shallow history?). Falling back to {base!r}.")+ return base+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--base", default="origin/master", help="git ref to compare clones against")+ parser.add_argument("--path", default=".", help="repository root to scan")+ parser.add_argument(+ "--report-dir",+ default=None,+ help="write duplication-findings-<language>.json files for the CI report into this directory",+ )+ args = parser.parse_args()++ if args.report_dir:+ # Written before any check or scan so an early exit can never leave a+ # stale "ok": the CI report can then tell "the scan failed" from "the+ # branch predates the check" (no files at all).+ (Path(args.report_dir) / "duplication-scan-status.json").write_text(json.dumps({"status": "failed"}) + "\n")++ if subprocess.run(["git", "rev-parse", "--verify", "--quiet", args.base], capture_output=True).returncode != 0:+ print(f"Base ref {args.base!r} not found. Fetch it first, e.g.:")+ print(" git fetch --no-tags --depth=1 origin master:refs/remotes/origin/master")+ return 2++ repo = Path(args.path).resolve()+ if not repo.is_dir():+ print(f"Scan path {repo} does not exist.")+ return 2++ baseline = resolve_baseline(args.base, repo)+ print(f"Comparing clones against {baseline}")++ # jscpd's own --baseline-from-ref mismatches clones whose files moved on+ # the base since the branch forked, and some stable pairs it re-flags+ # with no visible cause. Scan both trees with identical flags and diff+ # the clone sets ourselves instead: a clone is new only when no clone in+ # the baseline pairs the same files over the same fragment. jscpd merges+ # repeated occurrences of one fragment into a single clone, so a repeat+ # copy inside an already-duplicated file pair is not detectable here;+ # new file pairs and edited blocks are.+ scan_failed = False+ with tempfile.TemporaryDirectory(prefix="jscpd-") as tmp:+ tmp_path = Path(tmp)+ baseline_worktree = tmp_path / "baseline-worktree"+ # Registrations from runs killed mid-scan point at paths that no+ # longer exist; drop them before adding a fresh one.+ subprocess.run(["git", "worktree", "prune"], capture_output=True, cwd=repo)+ add = subprocess.run(+ ["git", "worktree", "add", "--detach", str(baseline_worktree), baseline],+ capture_output=True,+ text=True,+ cwd=repo,+ )+ if add.returncode != 0:+ print(add.stderr[-2000:])+ print(f"duplication lint could not check out the baseline {baseline}")+ return 2+ try:+ current_clones = run_jscpd(repo, tmp_path / "current-report")+ baseline_clones = run_jscpd(baseline_worktree, tmp_path / "baseline-report")+ except SystemExit:+ scan_failed = True+ current_clones = []+ finally:+ subprocess.run(+ ["git", "worktree", "remove", "--force", str(baseline_worktree)], capture_output=True, cwd=repo+ )++ if scan_failed:+ return 2++ mark_new_clones(current_clones, baseline_clones)+ print(+ f"{len(current_clones)} clones in this tree, {sum(1 for c in current_clones if c['isNew'])} not in the baseline"+ )+ if args.report_dir:+ (Path(args.report_dir) / "duplication-scan-status.json").write_text(json.dumps({"status": "ok"}) + "\n")++ failures = find_gate_failures(current_clones)+ findings = build_findings(failures)++ if args.report_dir:+ report_names = {"python": "duplication-findings-python.json", "typescript": "duplication-findings-ts.json"}+ for language, language_findings in findings.items():+ (Path(args.report_dir) / report_names[language]).write_text(json.dumps(language_findings, indent=2) + "\n")++ if not failures:+ print("No new code duplication above the bars.")+ return 0++ print("This branch adds new code duplication:")+ for clone, both_tests in failures:+ first, second = clone["firstFile"], clone["secondFile"]+ side = "test" if both_tests else "app"+ print(+ f" [{clone_language(clone)}] {first['name']}:{first['start']}-{first['end']} <-> "+ f"{second['name']}:{second['start']}-{second['end']} "+ f"({clone['lines']} lines, {clone['tokens']} tokens, {side} code)"+ )+ print()+ print(+ f"New duplication fails at {APP_MAX_NEW_CLONE_TOKENS}+ tokens in app code, "+ f"or {TEST_MAX_NEW_CLONE_TOKENS}+ tokens when both copies live in test files."+ )+ print("Extract the repeated block into a shared helper instead of copying it.")+ return 1+++if __name__ == "__main__":+ sys.exit(main())diff --git a/bin/test/test_lint_duplication.py b/bin/test/test_lint_duplication.pynew file mode 100644index 000000000000..cf256d27d41d--- /dev/null+++ b/bin/test/test_lint_duplication.py@@ -0,0 +1,189 @@+#!/usr/bin/env python3++import unittest++from parameterized import parameterized++from bin.lint_duplication import (+ APP_MAX_NEW_CLONE_TOKENS,+ TEST_MAX_NEW_CLONE_TOKENS,+ build_findings,+ clone_key,+ clone_language,+ find_gate_failures,+ is_test_file,+ mark_new_clones,+)+++def make_clone(first: str, second: str, tokens: int, is_new: bool = True, fmt: str = "python") -> dict:+ return {+ "firstFile": {"name": first, "start": 1, "end": 10},+ "secondFile": {"name": second, "start": 1, "end": 10},+ "tokens": tokens,+ "lines": 10,+ "isNew": is_new,+ "format": fmt,+ "fragment": "x = 1\n" * 10,+ }+++class TestIsTestFile(unittest.TestCase):+ @parameterized.expand(+ [+ ("test_prefix", "posthog/api/test/test_team.py", True),+ ("tests_dir", "products/alerts/backend/tests/api/test_alert.py", True),+ ("test_suffix", "posthog/hogql/parser_python_test.py", True),+ ("conftest", "posthog/conftest.py", True),+ ("repo_test_utils", "posthog/test/utils.py", True),+ ("app_viewset", "posthog/api/team.py", False),+ ("testy_is_not_a_test_prefix", "posthog/testimony.py", False),+ ("jest_test_ts", "frontend/src/exporter/Exporter.test.ts", True),+ ("jest_test_tsx", "frontend/src/exporter/ExportedInsight/ExportedInsight.test.tsx", True),+ ("playwright_spec", "playwright/e2e/insight-sharing-password.spec.ts", True),+ ("storybook_story", "frontend/src/scenes/insights/Insight.stories.tsx", True),+ ("tests_underscore_dir", "frontend/src/__tests__/utils.ts", True),+ ("mocks_dir", "frontend/src/__mocks__/server.ts", True),+ ("app_component", "frontend/src/scenes/insights/Insight.tsx", False),+ ("app_logic", "frontend/src/scenes/insights/insightLogic.ts", False),+ ]+ )+ def test_classification(self, _name: str, path: str, expected: bool) -> None:+ self.assertEqual(is_test_file(path), expected)+++class TestFindGateFailures(unittest.TestCase):+ @parameterized.expand(+ [+ (+ "app_clone_at_bar_fails",+ make_clone("posthog/api/a.py", "posthog/api/b.py", APP_MAX_NEW_CLONE_TOKENS),+ True,+ ),+ (+ "test_clone_under_test_bar_passes",+ make_clone("posthog/api/test/test_a.py", "posthog/api/test/test_b.py", TEST_MAX_NEW_CLONE_TOKENS - 1),+ False,+ ),+ (+ "test_clone_at_test_bar_fails",+ make_clone("posthog/api/test/test_a.py", "posthog/api/test/test_b.py", TEST_MAX_NEW_CLONE_TOKENS),+ True,+ ),+ (+ "cross_boundary_uses_app_bar",+ make_clone("posthog/api/a.py", "posthog/api/test/test_b.py", APP_MAX_NEW_CLONE_TOKENS),+ True,+ ),+ (+ "pre_existing_clone_never_fails",+ make_clone("posthog/api/a.py", "posthog/api/b.py", 900, is_new=False),+ False,+ ),+ (+ "ts_app_clone_at_bar_fails",+ make_clone("frontend/src/a.ts", "frontend/src/b.ts", APP_MAX_NEW_CLONE_TOKENS, fmt="typescript"),+ True,+ ),+ (+ "ts_test_clone_under_test_bar_passes",+ make_clone("frontend/src/a.test.ts", "frontend/src/b.test.ts", TEST_MAX_NEW_CLONE_TOKENS - 1),+ False,+ ),+ ]+ )+ def test_gate(self, _name: str, clone: dict, expected_fails: bool) -> None:+ failures = find_gate_failures([clone])+ self.assertEqual(len(failures) == 1, expected_fails)++ def test_worst_first(self) -> None:+ small = make_clone("posthog/api/a.py", "posthog/api/b.py", 100)+ big = make_clone("posthog/api/c.py", "posthog/api/d.py", 900)+ failures = find_gate_failures([small, big])+ self.assertEqual([clone["tokens"] for clone, _ in failures], [900, 100])+++class TestBuildFindings(unittest.TestCase):+ def test_partition_by_language(self) -> None:+ py = make_clone("posthog/api/a.py", "posthog/api/b.py", 200)+ ts = make_clone("frontend/src/a.ts", "frontend/src/b.ts", 200, fmt="typescript")+ tsx = make_clone("frontend/src/a.tsx", "frontend/src/b.tsx", 200, fmt="tsx")+ findings = build_findings(find_gate_failures([py, ts, tsx]))+ self.assertEqual([f["first_file"] for f in findings["python"]], ["posthog/api/a.py"])+ self.assertEqual([f["first_file"] for f in findings["typescript"]], ["frontend/src/a.ts", "frontend/src/a.tsx"])++ def test_finding_fields(self) -> None:+ clone = make_clone("posthog/api/a.py", "posthog/api/test/test_a.py", 200)+ (finding,) = build_findings(find_gate_failures([clone]))["python"]+ self.assertEqual(+ finding,+ {+ "first_file": "posthog/api/a.py",+ "first_start": 1,+ "second_file": "posthog/api/test/test_a.py",+ "second_start": 1,+ "lines": 10,+ "tokens": 200,+ },+ )++ def test_clone_language_defaults_to_typescript_for_non_python(self) -> None:+ self.assertEqual(clone_language(make_clone("a.ts", "b.ts", 100, fmt="tsx")), "typescript")+ self.assertEqual(clone_language(make_clone("a.py", "b.py", 100)), "python")+++class TestCloneKey(unittest.TestCase):+ @parameterized.expand(+ [+ ("same_pair_same_key", None, None, True),+ ("swapped_sides_same_key", "swap", None, True),+ ("moved_in_file_same_key", "shift", None, True),+ ("edited_fragment_differs", None, "fragment", False),+ ("different_pair_differs", None, "rename", False),+ ]+ )+ def test_key(+ self, _name: str, first_mutation: str | None, second_mutation: str | None, expected_equal: bool+ ) -> None:+ first = make_clone("a.py", "b.py", 100)+ second = make_clone("a.py", "b.py", 100)+ if first_mutation == "swap":+ first["firstFile"], first["secondFile"] = first["secondFile"], first["firstFile"]+ if first_mutation == "shift":+ first["firstFile"]["start"] = 42+ first["secondFile"]["start"] = 99+ if second_mutation == "fragment":+ second["fragment"] = "y = 2\n" * 10+ if second_mutation == "rename":+ second["secondFile"]["name"] = "c.py"+ self.assertEqual(clone_key(first) == clone_key(second), expected_equal)+++class TestMarkNewClones(unittest.TestCase):+ @parameterized.expand(+ [+ ("no_baseline_all_new", 0, 2, [True, True]),+ ("baseline_covers_one_copy", 1, 2, [False, True]),+ ("baseline_covers_every_copy", 2, 2, [False, False]),+ ("baseline_has_spare_copies", 3, 1, [False]),+ ]+ )+ def test_grandfathers_only_as_many_copies_as_the_baseline_holds(+ self, _name: str, baseline_copies: int, current_copies: int, expected_is_new: list[bool]+ ) -> None:+ baseline = [make_clone("a.py", "b.py", 100) for _ in range(baseline_copies)]+ current = [make_clone("a.py", "b.py", 100, is_new=False) for _ in range(current_copies)]+ mark_new_clones(current, baseline)+ self.assertEqual([clone["isNew"] for clone in current], expected_is_new)++ def test_an_edited_fragment_is_new_even_when_the_pair_has_a_baseline_clone(self) -> None:+ baseline = [make_clone("a.py", "b.py", 100)]+ edited = make_clone("a.py", "b.py", 100)+ edited["fragment"] = "y = 2\n" * 10+ current = [make_clone("a.py", "b.py", 100), edited]+ mark_new_clones(current, baseline)+ self.assertEqual([clone["isNew"] for clone in current], [False, True])+++if __name__ == "__main__":+ unittest.main()diff --git a/frontend/bin/ci-report/update-ci-report.mjs b/frontend/bin/ci-report/update-ci-report.mjsindex 881144faa390..83a245d3318b 100644--- a/frontend/bin/ci-report/update-ci-report.mjs+++ b/frontend/bin/ci-report/update-ci-report.mjs@@ -17,6 +17,8 @@ export const SECTIONS = [{ id: 'trunk-lane', title: 'Trunk lane' },{ id: 'complexity-python', title: 'Complexity (Python)' },{ id: 'complexity-ts', title: 'Complexity (TypeScript)' },+ { id: 'duplication-python', title: 'Duplication (Python)' },+ { id: 'duplication-ts', title: 'Duplication (TypeScript)' },{ id: 'comment-density', title: 'Comment density' },{ id: 'bundle-size', title: 'Bundle size' },{ id: 'eager-graph', title: 'Eager graph' },diff --git a/hogli.yaml b/hogli.yamlindex eca53778e9f3..93943e8928db 100644--- a/hogli.yaml+++ b/hogli.yaml@@ -861,6 +861,9 @@ quality:lint:feature-flags:fix:cmd: node bin/lint-feature-flag-sorting.mjs --fixdescription: Auto-sort FEATURE_FLAGS in constants.tsx alphabetically+ lint:duplication:+ cmd: python3 bin/lint_duplication.py+ description: Gate the branch on new Python and TypeScript code duplication via jscpd (test files get a relaxed limit)lint:complexity:click: hogli_commands.complexity_lint:cmd_lint_complexitydescription: Check cyclomatic complexity of changed Python/TypeScript files (warn-only; test files get a relaxed limit)