Skip to content

feat(codequality): curb cognitive-complexity Goodhart patterns in Go AST and advisory checks - #1321

Merged
kyasbal merged 1 commit into
mainfrom
push-tolnvvonuwrm
Dec 1, 2026
Merged

kyasbal merged 1 commit into
mainfrom
push-tolnvvonuwrm

Conversation

@kyasbal

@kyasbal kyasbal commented Dec 1, 2026

Copy link
Copy Markdown
Member

Summary

Closes cognitive-complexity Goodhart loopholes observed in Go production and test code (e.g. wrapping sequential error-checked calls into []func() error{ ... } closure slices or unwrapping t.Run subtests inline into Test* bodies to evade trun_cognitive):

  1. Flat-cost idiomatic Go error-return guards (scripts/codequality/internal/astcheck/cognitive.go)

    • Simple early-return guards (if err != nil { return ... }, including *Err and selector forms like r.err != nil, with no else and a single return body) now cost a flat +1 (if err != nil guard) without adding +nest or inflating MaxNesting.
    • Multi-statement, else-branched, compound-condition (&&/||), non-return, call-expression, and non-error != nil checks retain full nesting penalties, and nested closures inside return expressions still incur nested depth.
  2. Detect closure_slice_indirection (scripts/codequality/internal/advisorycheck)

    • Adds a differential fast-advisory check across both production and test Go files that flags newly added slice/array literals containing >= 4 inline function literals ([]func() error{ ... }, [4]func(){ ... }, named func-type slices, and keyed literals), while ignoring < 4 closures, declarative []struct{...} tables, named function references, map dispatch tables, and pre-existing baseline literals.
  3. Close the Test* body vs t.Run asymmetry (test_entry_cognitive + test_trun_unwrapped)

    • AST MUSTFIX (rule, astcheck): Adds test_entry_cognitive (DefaultLimit: 15, CategoryProtocol allowlist, strict no-worsening ratchet on legacy tests) measuring Test*/Benchmark*/Fuzz*/Example* top-level bodies excluding nested t.Run/b.Run subtests.
    • Advisory diff signal (advisorycheck): Adds test_trun_unwrapped when t.Run subtests decrease (outside table-driven t.Run consolidation) while Test* top-level body complexity grows (with increased non-subtest assertions or >= 2 complexity gain), including across cross-file test moves.
  4. Document updated budgets and preferred idioms (.agents/rules/go-coding-rule.md)

    • Documents flat-cost if err != nil { return ... } guards, test_entry_cognitive <= 15, and the new advisory signals (closure_slice_indirection, test_trun_unwrapped).
    • Prescribes error-latching recorder/builder structs or declarative []struct{...} tables instead of []func() error closure slices, and explicitly warns against unwrapping t.Run inline into Test* bodies.

Verification

  • go test -race ./scripts/codequality/... — PASS (all 17 packages)
  • make qa-fast-must QA_LANG=go BASE=64596ccac12a8b — PASS (0 mustfix)
  • make qa-fast-advisory QA_LANG=go BASE=64596ccac12a8b — PASS (0 advisory)
  • make qa-slow-must QA_LANG=go BASE=64596ccac12a8b — PASS (0 mustfix)
  • make qa-slow-advisory QA_LANG=go BASE=64596ccac12a8b — PASS (31/31 reached mutants killed, 0 uncovered lines, 0 advisory)
  • make lint-go LINT_PKGS=./scripts/codequality/... — PASS (0 issues, conventions & unused-exports clean)
…AST and advisory checks

Reduce incentives for cognitive-complexity Goodhart workarounds (such as wrapping
sequential error-checked statements into []func() error closure slices or
unwrapping t.Run subtests into Test* bodies):

- Score simple early-return Go error guards (if err != nil { return ... },
  matching err or *Err without else) at a flat +1 cognitive cost with no
  nesting-depth increment, while preserving full nesting penalties on
  multi-statement, else-branched, compound-condition, or non-error checks.
- Add advisory signal closure_slice_indirection across production and test Go
  files for newly added slice/array literals with >= 4 inline function literals.
- Enforce test_entry_cognitive (MUSTFIX, default limit 15, ratcheted) on
  Test*/Benchmark*/Fuzz*/Example* entry bodies excluding nested t.Run/b.Run
  subtests, paired with advisory diff signal test_trun_unwrapped when t.Run
  subtests are unwrapped inline into Test* bodies.
- Document the updated cognitive budgets, new advisory signals, and preferred
  idioms (error-latching recorder/builder structs or declarative []struct tables)
  in .agents/rules/go-coding-rule.md.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces new code quality advisory checks (closure_slice_indirection and test_trun_unwrapped) and a new test_entry_cognitive rule to prevent cognitive complexity evasion in Go tests. It also updates the cognitive complexity calculation to treat simple if err != nil guards as a flat +1 penalty without increasing nesting depth. The review feedback highlights two key improvement opportunities: first, handling cases where lit.Type is nil in nested composite literals to prevent bypassing the closure slice check; second, conditionally executing complexity analysis in analyzeFuncDecl to avoid redundant AST traversals for test entry functions.

Comment on lines +65 to +70
if lit == nil || lit.Type == nil {
return false
}
if _, ok := ast.Unparen(lit.Type).(*ast.ArrayType); !ok {
return false
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

In Go, nested composite literals (such as slices of slices or slices of structs) can omit the type definition (e.g., [][]func() error{ {func() error { ... }, ...} }). In these cases, lit.Type is nil. By strictly requiring lit.Type != nil, the closure_slice_indirection check can be easily bypassed using nested literals. We should allow lit.Type to be nil and only enforce the *ast.ArrayType check when lit.Type is explicitly provided.

	if lit == nil {
		return false
	}
	if lit.Type != nil {
		if _, ok := ast.Unparen(lit.Type).(*ast.ArrayType); !ok {
			return false
		}
	}
Comment on lines 233 to +236
comp := AnalyzeBlockComplexity(a.fset, fd.Body)
if isTestEntry {
comp = AnalyzeSubtestBlockComplexity(a.fset, fd.Body)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

For test entry functions, AnalyzeBlockComplexity is called first, and then immediately overwritten by AnalyzeSubtestBlockComplexity. This results in redundant AST traversals and complexity calculations for every test entry function. We should conditionally call the appropriate analysis function instead to improve efficiency.

Suggested change
comp := AnalyzeBlockComplexity(a.fset, fd.Body)
if isTestEntry {
comp = AnalyzeSubtestBlockComplexity(a.fset, fd.Body)
}
var comp ComplexitySummary
if isTestEntry {
comp = AnalyzeSubtestBlockComplexity(a.fset, fd.Body)
} else {
comp = AnalyzeBlockComplexity(a.fset, fd.Body)
}
@github-actions

github-actions Bot commented Dec 1, 2026

Copy link
Copy Markdown

Go Quality Report (origin/main) — ✅ PASS (0 blocking, 9 advisory finding(s))

Metric Result
Changed Scope 7 prod file(s), 5 test file(s), 29 unit(s)
Patch Coverage 97.2% (105/108 lines)
Mutation Score 81.4% (79/97 killed, 18 survived)
Function Similarity Advisory (1/9 new unit(s) matched across 3192 corpus units)

Quality Rule Violations

# Rule Status Value (Limit) Location Subject
[Q1] func_surviving_mutants ADVISORY 1 (<= 0) scripts/codequality/internal/advisorycheck/go_complexity_signals.go:46 collectFuncClosureSliceLiterals
[Q2] func_uncovered_lines ADVISORY 1 (<= 0) scripts/codequality/internal/advisorycheck/go_complexity_signals.go:47 collectFuncClosureSliceLiterals
[Q3] func_surviving_mutants ADVISORY 1 (<= 0) scripts/codequality/internal/advisorycheck/go_complexity_signals.go:65 isClosureSliceLiteral
[Q4] func_surviving_mutants ADVISORY 4 (<= 0) scripts/codequality/internal/advisorycheck/go_complexity_signals.go:95 compareGoTestTRunUnwrapped
[Q5] func_surviving_mutants ADVISORY 5 (<= 0) scripts/codequality/internal/advisorycheck/go_complexity_signals.go:118 isTableSubtestConsolidation
[Q6] func_surviving_mutants ADVISORY 1 (<= 0) scripts/codequality/internal/advisorycheck/go_complexity_signals.go:122 countAllTestingRuns
[Q7] func_uncovered_lines ADVISORY 1 (<= 0) scripts/codequality/internal/advisorycheck/go_complexity_signals.go:123 countAllTestingRuns
[Q8] func_surviving_mutants ADVISORY 6 (<= 0) scripts/codequality/internal/advisorycheck/go_complexity_signals.go:137 countEntryTestingAsserts
[Q9] func_uncovered_lines ADVISORY 1 (<= 0) scripts/codequality/internal/advisorycheck/go_complexity_signals.go:138 countEntryTestingAsserts
[Q1] func_surviving_mutants — scripts/codequality/internal/advisorycheck/go_complexity_signals.go:46 (collectFuncClosureSliceLiterals)
  • Why: Mutating operators or branches in this touched function did not cause any unit test to fail.
  • Fix: Delete redundant guards first, or strengthen assertions (cmp.Diff on full outputs and boundary inputs).
  • Detail: 1 mutant(s) survived unit tests
- if fd == nil || fd.Body == nil {
+ if fd == nil && fd.Body == nil {
[Q2] func_uncovered_lines — scripts/codequality/internal/advisorycheck/go_complexity_signals.go:47 (collectFuncClosureSliceLiterals)
  • Why: Substantive branches in touched functions were never executed by unit tests (boilerplate error guards are already excluded).
  • Fix: Add focused table-driven test cases covering the unexecuted branch, or delete unreachable production code.
  • Detail: 1 substantive uncovered line(s) across 1 span(s)
  46 | 	if fd == nil || fd.Body == nil {
  47 | 		return out
[Q3] func_surviving_mutants — scripts/codequality/internal/advisorycheck/go_complexity_signals.go:65 (isClosureSliceLiteral)
  • Why: Mutating operators or branches in this touched function did not cause any unit test to fail.
  • Fix: Delete redundant guards first, or strengthen assertions (cmp.Diff on full outputs and boundary inputs).
  • Detail: 1 mutant(s) survived unit tests
- if lit == nil || lit.Type == nil {
+ if lit == nil && lit.Type == nil {
[Q4] func_surviving_mutants — scripts/codequality/internal/advisorycheck/go_complexity_signals.go:95 (compareGoTestTRunUnwrapped)
  • Why: Mutating operators or branches in this touched function did not cause any unit test to fail.
  • Fix: Delete redundant guards first, or strengthen assertions (cmp.Diff on full outputs and boundary inputs).
  • Detail: 4 mutant(s) survived unit tests
- cognitiveGain := targetFn.entryCognitive - baseFn.entryCognitive
+ cognitiveGain := targetFn.entryCognitive + baseFn.entryCognitive
- if cognitiveGain <= 0 {
+ if cognitiveGain < 0 {
- if cognitiveGain < minTRunUnwrapCognitiveGain && targetFn.entryAsserts <= baseFn.entryAsserts {
+ if cognitiveGain <= minTRunUnwrapCognitiveGain && targetFn.entryAsserts <= baseFn.entryAsserts {
- item.ReviewPrompt = "Verify whether t.Run subtests were unwrapped inline into the Test* body to bypass trun_cognitive; keep focused t.Run subtests or split into separate Test* functions."
+ /* skipped: item.ReviewPrompt = "Verify whether t.Run subtests were unwrapped inline into the Test* body to bypass trun_cognitive; keep focused t.Run subtests or split into separate Test* functions." */
[Q5] func_surviving_mutants — scripts/codequality/internal/advisorycheck/go_complexity_signals.go:118 (isTableSubtestConsolidation)
  • Why: Mutating operators or branches in this touched function did not cause any unit test to fail.
  • Fix: Delete redundant guards first, or strengthen assertions (cmp.Diff on full outputs and boundary inputs).
  • Detail: 5 mutant(s) survived unit tests
- return targetFn.tableElems > baseFn.tableElems && targetFn.totalRuns > 0
+ return targetFn.tableElems > baseFn.tableElems || targetFn.totalRuns > 0
- return targetFn.tableElems > baseFn.tableElems && targetFn.totalRuns > 0
+ return targetFn.tableElems >= baseFn.tableElems && targetFn.totalRuns > 0
- return targetFn.tableElems > baseFn.tableElems && targetFn.totalRuns > 0
+ return targetFn.tableElems <= baseFn.tableElems && targetFn.totalRuns > 0
- return targetFn.tableElems > baseFn.tableElems && targetFn.totalRuns > 0
+ return targetFn.tableElems > baseFn.tableElems && targetFn.totalRuns >= 0
- return targetFn.tableElems > baseFn.tableElems && targetFn.totalRuns > 0
+ return targetFn.tableElems > baseFn.tableElems && targetFn.totalRuns <= 0
[Q6] func_surviving_mutants — scripts/codequality/internal/advisorycheck/go_complexity_signals.go:122 (countAllTestingRuns)
  • Why: Mutating operators or branches in this touched function did not cause any unit test to fail.
  • Fix: Delete redundant guards first, or strengthen assertions (cmp.Diff on full outputs and boundary inputs).
  • Detail: 1 mutant(s) survived unit tests
- if fd == nil || fd.Body == nil {
+ if fd == nil && fd.Body == nil {
[Q7] func_uncovered_lines — scripts/codequality/internal/advisorycheck/go_complexity_signals.go:123 (countAllTestingRuns)
  • Why: Substantive branches in touched functions were never executed by unit tests (boilerplate error guards are already excluded).
  • Fix: Add focused table-driven test cases covering the unexecuted branch, or delete unreachable production code.
  • Detail: 1 substantive uncovered line(s) across 1 span(s)
 122 | 	if fd == nil || fd.Body == nil {
 123 | 		return 0
[Q8] func_surviving_mutants — scripts/codequality/internal/advisorycheck/go_complexity_signals.go:137 (countEntryTestingAsserts)
  • Why: Mutating operators or branches in this touched function did not cause any unit test to fail.
  • Fix: Delete redundant guards first, or strengthen assertions (cmp.Diff on full outputs and boundary inputs).
  • Detail: 6 mutant(s) survived unit tests
- if fd == nil || fd.Body == nil {
+ if fd == nil && fd.Body == nil {
- if isRunSubtestCall(call) && isTestingRunCall(call, testingParams) {
+ if isRunSubtestCall(call) || isTestingRunCall(call, testingParams) {
- return false
+ return true
- if isCmpCallExpr(call) {
+ if false {
- count++
+ /* skipped: count++ */
- return true
+ return false
[Q9] func_uncovered_lines — scripts/codequality/internal/advisorycheck/go_complexity_signals.go:138 (countEntryTestingAsserts)
  • Why: Substantive branches in touched functions were never executed by unit tests (boilerplate error guards are already excluded).
  • Fix: Add focused table-driven test cases covering the unexecuted branch, or delete unreachable production code.
  • Detail: 1 substantive uncovered line(s) across 1 span(s)
 137 | 	if fd == nil || fd.Body == nil {
 138 | 		return 0

Similar Existing Go Functions (Advisory)

New Unit Top Existing Candidate AST-Norm Score Action
isErrorIdentExpr (scripts/codequality/internal/astcheck/cognitive.go:343) isErrorLikeExpr (scripts/codequality/internal/rule/exclusion.go:314) 0.967 Similar logic exists in another module; extract a shared helper or verify intentional symmetry.

Commit: 8ec97e48e8ec · Cloud Build Logs

@kyasbal
kyasbal added this pull request to the merge queue Dec 1, 2026
Merged via the queue into main with commit bc7beb5 Dec 1, 2026
23 checks passed
@kyasbal
kyasbal deleted the push-tolnvvonuwrm branch December 1, 2026 04:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

1 participant