: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): relax complexity lint to 15 for test files (#92762)
Paul D'Ambraaa01ac1f77c9
diff --git a/.github/scripts/post-complexity-section.mjs b/.github/scripts/post-complexity-section.mjsindex 3b65edac69bd..65e2e0d4aab8 100644--- a/.github/scripts/post-complexity-section.mjs+++ b/.github/scripts/post-complexity-section.mjs@@ -25,20 +25,24 @@ if (!fs.existsSync(reportPath)) {const findings = JSON.parse(fs.readFileSync(reportPath, 'utf8'))const maxComplexity = findings.reduce((max, finding) => Math.max(max, finding.complexity), 0)+// The limits the linters enforce — 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-complexity.limits.json', import.meta.url), 'utf8'))const summary =findings.length > 0- ? `${findings.length} function${findings.length === 1 ? '' : 's'} above 10 (max ${maxComplexity})`+ ? `${findings.length} function${findings.length === 1 ? '' : 's'} above the limit (max ${maxComplexity})`: 'clean'const lines = [- `Cyclomatic complexity above 10 in changed ${language} files. Warn only: worth simplifying when you next touch these functions.`,+ `Cyclomatic complexity above the limit in changed ${language} files (${limits.production} for production files, ${limits.test} for test files). Warn only: worth simplifying when you next touch these functions.`,'',]if (findings.length > 0) {- lines.push('| Function | Location | Complexity |', '| --- | --- | --- |')+ lines.push('| Function | Location | Complexity | Limit |', '| --- | --- | --- | --- |')for (const finding of [...findings].sort((a, b) => b.complexity - a.complexity)) {lines.push(- `| \`${markdownCell(finding.name)}\` | \`${markdownCell(finding.file)}:${finding.line}\` | ${finding.complexity} |`+ // `limit` is absent from findings written by linters that predate it.+ `| \`${markdownCell(finding.name)}\` | \`${markdownCell(finding.file)}:${finding.line}\` | ${finding.complexity} | ${finding.limit ?? '?'} |`)}}diff --git a/bin/lint-complexity.limits.json b/bin/lint-complexity.limits.jsonnew file mode 100644index 000000000000..b5eb4301668c--- /dev/null+++ b/bin/lint-complexity.limits.json@@ -0,0 +1,4 @@+{+ "production": 10,+ "test": 15+}diff --git a/bin/lint-complexity.mjs b/bin/lint-complexity.mjsindex 3128a5732e2f..50ab48fa9bdb 100644--- a/bin/lint-complexity.mjs+++ b/bin/lint-complexity.mjs@@ -9,12 +9,14 @@* Usage:* node bin/lint-complexity.mjs [--json] [--report <path>] <files...>*- * Findings above WARN_AT are warnings; the check never fails a job (advisory- * while the pre-existing backlog settles). `--json` emits the findings as- * JSON for `hogli lint:complexity`, which owns human-readable output.- * `--report <path>` writes the same JSON to a file while printing human- * output and annotations (used by CI to post the CI report section). A test- * binds the thresholds here to the Python side (test_complexity_lint.py).+ * Findings above a file's limit are warnings; the check never fails a job+ * (advisory while the pre-existing backlog settles). `--json` emits the+ * findings as JSON for `hogli lint:complexity`, which owns human-readable+ * output. `--report <path>` writes the same JSON to a file while printing+ * human output and annotations (used by CI to post the CI report section).+ * Both sides read their limits from bin/lint-complexity.limits.json so the+ * two implementations cannot drift; complexity_lint.py says why tests get+ * the relaxed bound.*/import { existsSync, readFileSync, writeFileSync } from 'fs'@@ -28,7 +30,15 @@ const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..')const require = createRequire(resolve(repoRoot, 'frontend', 'package.json'))const ts = require('typescript')-const WARN_AT = 10+const LIMITS = JSON.parse(readFileSync(resolve(repoRoot, 'bin', 'lint-complexity.limits.json'), 'utf8'))++// A test file: a *.test.* / *.spec.* file, or inside a __tests__/test/tests+// directory. Mirrors is_test_file in complexity_lint.py; keep the two in step.+const TEST_FILE = /(^|\/)(__tests__|test|tests)\/|\.(test|spec)\.[jt]sx?$/++function warnAtFor(file) {+ return TEST_FILE.test(file) ? LIMITS.test : LIMITS.production+}const FUNCTION_KINDS = new Set([ts.SyntaxKind.FunctionDeclaration,@@ -124,7 +134,10 @@ const args = process.argv.slice(2)const asJson = args.includes('--json')const reportIdx = args.indexOf('--report')const reportPath = reportIdx === -1 ? null : args[reportIdx + 1]-const files = args.filter((arg, index) => arg !== '--json' && arg !== '--report' && index !== reportIdx + 1)+// Without --report, reportIdx is -1: guard the value skip or the first file is dropped.+const files = args.filter(+ (arg, index) => arg !== '--json' && arg !== '--report' && (reportIdx === -1 || index !== reportIdx + 1)+)const findings = []for (const file of files) {@@ -134,14 +147,19 @@ for (const file of files) {if (!existsSync(file)) {continue}- findings.push(...lintFile(file).filter((finding) => finding.complexity > WARN_AT))+ const limit = warnAtFor(file)+ findings.push(+ ...lintFile(file)+ .filter((finding) => finding.complexity > limit)+ .map((finding) => ({ ...finding, limit }))+ )}for (const finding of findings) {if (asJson) {continue}- const message = `\`${finding.name}\` has cyclomatic complexity ${finding.complexity} (warn >${WARN_AT})`+ const message = `\`${finding.name}\` has cyclomatic complexity ${finding.complexity} (warn >${finding.limit})`console.info(`${finding.file}:${finding.line}:${finding.column}: warning: ${message}`)if (process.env.GITHUB_ACTIONS === 'true') {console.info(diff --git a/frontend/bin/lint-complexity.test.ts b/frontend/bin/lint-complexity.test.tsnew file mode 100644index 000000000000..af9b5d25f74b--- /dev/null+++ b/frontend/bin/lint-complexity.test.ts@@ -0,0 +1,66 @@+import { execFileSync } from 'child_process'+import { mkdtempSync, rmSync, writeFileSync } from 'fs'+import { tmpdir } from 'os'+import { join, resolve } from 'path'++const REPO_ROOT = resolve(__dirname, '..', '..')+const LINTER = join(REPO_ROOT, 'bin', 'lint-complexity.mjs')++// Cyclomatic complexity = branches + 1.+function branchyFunction(branches: number): string {+ const checks = Array.from({ length: branches }, (_, i) => ` if (n === ${i}) return ${i}\n`).join('')+ return `export function probe(n: number): number {\n${checks} return -1\n}\n`+}++interface Finding {+ file: string+ limit: number+}++describe('lint-complexity.mjs', () => {+ let fixtureDir: string++ beforeEach((): void => {+ fixtureDir = mkdtempSync(join(tmpdir(), 'lint-complexity-'))+ })++ afterEach((): void => {+ rmSync(fixtureDir, { recursive: true, force: true })+ })++ function runLinter(target: string, flags: string[] = []): string {+ return execFileSync('node', [LINTER, ...flags, target], { cwd: REPO_ROOT, encoding: 'utf8' })+ }++ function lintJson(filename: string, branches: number): Finding[] {+ const target = join(fixtureDir, filename)+ writeFileSync(target, branchyFunction(branches))+ return JSON.parse(runLinter(target, ['--json'])) as Finding[]+ }++ it('warns a production file at complexity 12 with limit 10', (): void => {+ const findings = lintJson('probe.ts', 11)+ expect(findings.map((finding) => finding.limit)).toEqual([10])+ })++ it('does not warn a test file at complexity 12', (): void => {+ expect(lintJson('probe.test.ts', 11)).toEqual([])+ })++ it('warns a test file at complexity 17 with limit 15', (): void => {+ const findings = lintJson('probe.test.ts', 16)+ expect(findings.map((finding) => finding.limit)).toEqual([15])+ })++ it('reports the first file argument on a bare invocation', (): void => {+ // ci-frontend.yml passes --report and hogli passes --json, both leading+ // flags. A bare invocation must not drop the first file argument.+ const target = join(fixtureDir, 'probe.tsx')+ writeFileSync(target, branchyFunction(11))++ const output = runLinter(target)++ expect(output).toContain('warning')+ expect(output).toContain('warn >10')+ })+})diff --git a/hogli.yaml b/hogli.yamlindex 877cc62a228a..cdd8ff1bebaf 100644--- a/hogli.yaml+++ b/hogli.yaml@@ -864,7 +864,7 @@ quality:description: Auto-sort FEATURE_FLAGS in constants.tsx alphabeticallylint:complexity:click: hogli_commands.complexity_lint:cmd_lint_complexity- description: Check cyclomatic complexity of changed Python/TypeScript files (warn-only, above 10)+ description: Check cyclomatic complexity of changed Python/TypeScript files (warn-only; test files get a relaxed limit)lint:workflows:click: hogli_commands.workflow_lint.cli:cmd_lint_workflowsdescription: Lint .github/workflows/** for repo conventionsdiff --git a/tools/hogli-commands/hogli_commands/ci_preflight.py b/tools/hogli-commands/hogli_commands/ci_preflight.pyindex bfb8a58c0875..f4b453fb0b16 100644--- a/tools/hogli-commands/hogli_commands/ci_preflight.py+++ b/tools/hogli-commands/hogli_commands/ci_preflight.py@@ -46,7 +46,7 @@ from hogli_commands.build import (_match_commands,)from hogli_commands.change_detection import changed_files, matches_globs-from hogli_commands.complexity_lint import PYTHON_SCOPE, TYPESCRIPT_SCOPE+from hogli_commands.complexity_lint import PYTHON_SCOPE, TEST_WARN_AT, TYPESCRIPT_SCOPE, WARN_ATfrom hogli_commands.devenv.generator import TRACKED_MPROCS_FILESRequirement = Literal["node", "desktop-node", "stack", "clickhouse"]@@ -129,7 +129,7 @@ DIFF_CHECKS: list[DiffCheck] = [),DiffCheck(key="complexity",- label="cyclomatic complexity (warn >10)",+ label=f"cyclomatic complexity (warn >{WARN_AT}, >{TEST_WARN_AT} in tests)",# From complexity_lint.py so preflight and the command can't drift on scope.triggers=[*PYTHON_SCOPE, *TYPESCRIPT_SCOPE],verify=["hogli", "lint:complexity"],diff --git a/tools/hogli-commands/hogli_commands/complexity_lint.py b/tools/hogli-commands/hogli_commands/complexity_lint.pyindex 37b839cb19c6..ddef00808078 100644--- a/tools/hogli-commands/hogli_commands/complexity_lint.py+++ b/tools/hogli-commands/hogli_commands/complexity_lint.py@@ -1,10 +1,12 @@"""Cyclomatic complexity lint, scoped to changed files.-Findings above a threshold of 10 are warnings; the check never fails a build+Findings above a file's limit are warnings; the check never fails a build(advisory while the pre-existing violation backlog settles). Python goesthrough ruff's C901 (repo-wide C901 stays off in pyproject.toml for the samereason; this surfaces it for files a branch actually touches). TypeScript goesthrough ``bin/lint-complexity.mjs`` because oxlint has no complexity rule.+Both sides read their limits from ``bin/lint-complexity.limits.json`` so the+two implementations cannot drift.hogli lint:complexity # changed files vs origin/masterhogli lint:complexity path/to/file.py # explicit files@@ -25,8 +27,12 @@ from hogli.manifest import REPO_ROOTfrom hogli_commands.change_detection import changed_files, matches_globs-# bin/lint-complexity.mjs declares the same threshold; a test binds the two.-WARN_AT = 10+_LIMITS: dict[str, int] = json.loads((REPO_ROOT / "bin" / "lint-complexity.limits.json").read_text())+WARN_AT: int = _LIMITS["production"]+# NIST SP 500-235 permits relaxing the usual limit of 10 up to 15. Tests get the+# relaxed bound because table-driven tests concentrate branching in one function+# without hurting maintainability.+TEST_WARN_AT: int = _LIMITS["test"]# The complexity-linted trees: the posthog, ee, products, and frontend folders.# Python exclusions (products/desktop, generated grammar) come from pyproject's@@ -37,6 +43,17 @@ TYPESCRIPT_SCOPE = ("frontend/*.ts", "frontend/*.tsx", "ee/*.ts", "ee/*.tsx", "p_C901_MESSAGE = re.compile(r"`(?P<name>.+)` is too complex \((?P<complexity>\d+) > \d+\)")+# A test file: named test_*.py or *_test.py (pytest's python_files default),+# conftest.py, or inside a test/tests package. The suffix rule also classifies+# clickhouse-migration and user_scripts *_test.py modules as tests — same as+# pytest, and harmless for an advisory lint. bin/lint-complexity.mjs carries+# the TypeScript equivalent; keep the two in step.+_TEST_FILE = re.compile(r"(?:^|/)(?:test|tests)/|(?:^|/)[^/]*_test\.py$|(?:^|/)test_[^/]*\.py$|(?:^|/)conftest\.py$")+++def is_test_file(path: str) -> bool:+ return bool(_TEST_FILE.search(path))+@dataclass(frozen=True, kw_only=True, slots=True)class Finding:@@ -45,9 +62,11 @@ class Finding:column: intname: strcomplexity: int+ # The limit the finding exceeded: WARN_AT for production files, TEST_WARN_AT for tests.+ limit: int-def _python_findings(files: list[str]) -> list[Finding]:+def _python_findings(files: list[str], *, max_complexity: int = WARN_AT) -> list[Finding]:cmd = ["ruff","check",@@ -58,7 +77,7 @@ def _python_findings(files: list[str]) -> list[Finding]:"--config","lint.ignore=[]","--config",- f"lint.mccabe.max-complexity={WARN_AT}",+ f"lint.mccabe.max-complexity={max_complexity}","--output-format","json",*files,@@ -78,6 +97,7 @@ def _python_findings(files: list[str]) -> list[Finding]:column=violation["location"]["column"],name=match["name"],complexity=int(match["complexity"]),+ limit=max_complexity,))return findings@@ -92,7 +112,7 @@ def _ts_findings(files: list[str]) -> list[Finding]:def _report(finding: Finding) -> None:- message = f"`{finding.name}` has cyclomatic complexity {finding.complexity} (warn >{WARN_AT})"+ message = f"`{finding.name}` has cyclomatic complexity {finding.complexity} (warn >{finding.limit})"click.echo(f"{finding.file}:{finding.line}:{finding.column}: warning: {message}")if os.environ.get("GITHUB_ACTIONS") == "true":click.echo(@@ -128,7 +148,13 @@ def cmd_lint_complexity(files: tuple[str, ...], against: str | None, report_pathclick.echo("complexity: ruff not found — skipping Python files")degraded = Trueelse:- findings += _python_findings(python_files)+ # One ruff run per limit: ruff's mccabe takes a single max-complexity per invocation.+ prod_files = [f for f in python_files if not is_test_file(f)]+ test_files = [f for f in python_files if is_test_file(f)]+ if prod_files:+ findings += _python_findings(prod_files, max_complexity=WARN_AT)+ if test_files:+ findings += _python_findings(test_files, max_complexity=TEST_WARN_AT)checked += len(python_files)if ts_files:diff --git a/tools/hogli-commands/hogli_commands/tests/test_complexity_lint.py b/tools/hogli-commands/hogli_commands/tests/test_complexity_lint.pyindex b73961a46161..9cb108027c5d 100644--- a/tools/hogli-commands/hogli_commands/tests/test_complexity_lint.py+++ b/tools/hogli-commands/hogli_commands/tests/test_complexity_lint.py@@ -1,12 +1,11 @@from __future__ import annotationsimport pytest-from unittest.mock import MagicMock, patch+from unittest.mock import MagicMock, call, patchfrom click.testing import CliRunnerfrom hogli.cli import cli-from hogli.manifest import REPO_ROOT-from hogli_commands.complexity_lint import WARN_AT, Finding, _python_findings+from hogli_commands.complexity_lint import TEST_WARN_AT, WARN_AT, Finding, _python_findings, is_test_filerunner = CliRunner()@@ -35,10 +34,50 @@ class TestComplexityLint:assert [(f.name, f.complexity) for f in findings] == expected+ @pytest.mark.parametrize(+ ("branches", "expected"),+ [+ pytest.param(11, [], id="above_production_limit_below_test_limit"),+ pytest.param(16, [("f", 17, TEST_WARN_AT)], id="above_test_limit_warns"),+ ],+ )+ def test_findings_use_the_given_threshold(self, tmp_path, branches: int, expected: list) -> None:+ # Complexity = branches + 1. The max_complexity argument must reach ruff's config.+ target = tmp_path / "test_sample.py"+ target.write_text(_branchy_function("f", branches))++ findings = _python_findings([str(target)], max_complexity=TEST_WARN_AT)++ assert [(f.name, f.complexity, f.limit) for f in findings] == expected++ @pytest.mark.parametrize(+ ("path", "expected"),+ [+ pytest.param("posthog/api/insight.py", False, id="production_module"),+ pytest.param("posthog/api/insight.test.py", False, id="dot_test_suffix_is_not_a_convention_here"),+ pytest.param("posthog/api/test_insight.py", True, id="colocated_test_prefix"),+ pytest.param("posthog/api/test/test_insight.py", True, id="test_package"),+ pytest.param("products/tasks/backend/tests/test_agent.py", True, id="tests_package"),+ pytest.param("posthog/conftest.py", True, id="conftest"),+ # pytest's python_files default collects *_test.py too, so the lint+ # follows it even where the module is a migration, not a test.+ pytest.param(+ "posthog/clickhouse/migrations/0097_v2_test.py",+ True,+ id="_test_suffix_counts_as_test_even_for_migrations",+ ),+ pytest.param("products/customer_analytics/backend/metrics_test.py", True, id="colocated_test_suffix"),+ ],+ )+ def test_is_test_file(self, path: str, expected: bool) -> None:+ assert is_test_file(path) is expected+def test_cli_reports_warnings_without_failing(self, tmp_path) -> None:# The check is advisory: even a high-complexity finding must exit 0 and be# written to the --report file the CI report poster reads.- finding = Finding(file="posthog/tasks/usage_report.py", line=1, column=1, name="f", complexity=17)+ finding = Finding(+ file="posthog/tasks/usage_report.py", line=1, column=1, name="f", complexity=17, limit=WARN_AT+ )report_path = tmp_path / "findings.json"with patch("hogli_commands.complexity_lint._python_findings", return_value=[finding]):result = runner.invoke(@@ -48,6 +87,7 @@ class TestComplexityLint:assert result.exit_code == 0assert "warning" in result.outputassert "17" in result.output+ assert "warn >10" in result.outputassert finding.name in report_path.read_text()@patch("hogli_commands.complexity_lint._python_findings", return_value=[])@@ -65,15 +105,20 @@ class TestComplexityLint:],)assert result.exit_code == 0- mock_findings.assert_called_once_with(["posthog/tasks/usage_report.py"])-- def test_thresholds_and_ci_contract_match_the_typescript_linter(self) -> None:- # The mjs is invoked directly by ci-frontend.yml, so its threshold and its- # --report flag (whose file the CI report poster reads) are pinned to the- # Python side's contract.- mjs = (REPO_ROOT / "bin" / "lint-complexity.mjs").read_text()- assert f"const WARN_AT = {WARN_AT}\n" in mjs- assert "indexOf('--report')" in mjs+ mock_findings.assert_called_once_with(["posthog/tasks/usage_report.py"], max_complexity=WARN_AT)++ @patch("hogli_commands.complexity_lint._python_findings", return_value=[])+ def test_test_files_are_linted_at_the_relaxed_threshold(self, mock_findings: MagicMock) -> None:+ # Test and production files go to ruff in separate runs, one per limit.+ result = runner.invoke(+ cli,+ ["lint:complexity", "posthog/tasks/usage_report.py", "posthog/api/test/test_activity_log.py"],+ )+ assert result.exit_code == 0+ assert mock_findings.call_args_list == [+ call(["posthog/tasks/usage_report.py"], max_complexity=WARN_AT),+ call(["posthog/api/test/test_activity_log.py"], max_complexity=TEST_WARN_AT),+ ]class TestPreflightSoftCheck: