Repository navigation
feat(codequality): curb cognitive-complexity Goodhart patterns in Go AST and advisory checks - #1321
Conversation
…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.
There was a problem hiding this comment.
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.
| if lit == nil || lit.Type == nil { | ||
| return false | ||
| } | ||
| if _, ok := ast.Unparen(lit.Type).(*ast.ArrayType); !ok { | ||
| return false | ||
| } |
There was a problem hiding this comment.
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
}
}| comp := AnalyzeBlockComplexity(a.fset, fd.Body) | ||
| if isTestEntry { | ||
| comp = AnalyzeSubtestBlockComplexity(a.fset, fd.Body) | ||
| } |
There was a problem hiding this comment.
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.
| 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) | |
| } |
Go Quality Report (
|
| 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 0Similar 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
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 unwrappingt.Runsubtests inline intoTest*bodies to evadetrun_cognitive):Flat-cost idiomatic Go error-return guards (
scripts/codequality/internal/astcheck/cognitive.go)if err != nil { return ... }, including*Errand selector forms liker.err != nil, with noelseand a singlereturnbody) now cost a flat+1(if err != nil guard) without adding+nestor inflatingMaxNesting.else-branched, compound-condition (&&/||), non-return, call-expression, and non-error!= nilchecks retain full nesting penalties, and nested closures insidereturnexpressions still incur nested depth.Detect
closure_slice_indirection(scripts/codequality/internal/advisorycheck)>= 4inline function literals ([]func() error{ ... },[4]func(){ ... }, named func-type slices, and keyed literals), while ignoring< 4closures, declarative[]struct{...}tables, named function references, map dispatch tables, and pre-existing baseline literals.Close the
Test*body vst.Runasymmetry (test_entry_cognitive+test_trun_unwrapped)MUSTFIX(rule,astcheck): Addstest_entry_cognitive(DefaultLimit: 15,CategoryProtocolallowlist, strict no-worsening ratchet on legacy tests) measuringTest*/Benchmark*/Fuzz*/Example*top-level bodies excluding nestedt.Run/b.Runsubtests.advisorycheck): Addstest_trun_unwrappedwhent.Runsubtests decrease (outside table-drivent.Runconsolidation) whileTest*top-level body complexity grows (with increased non-subtest assertions or>= 2complexity gain), including across cross-file test moves.Document updated budgets and preferred idioms (
.agents/rules/go-coding-rule.md)if err != nil { return ... }guards,test_entry_cognitive <= 15, and the new advisory signals (closure_slice_indirection,test_trun_unwrapped).[]struct{...}tables instead of[]func() errorclosure slices, and explicitly warns against unwrappingt.Runinline intoTest*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-exportsclean)