Repository navigation
[linter-miner] Add JSON decoder trailing-data linter - #78157
Conversation
Co-authored-by: copilot-swe-agent[bot] <[email protected]>
Co-authored-by: copilot-swe-agent[bot] <[email protected]>
This comment has been minimized.
This comment has been minimized.
|
✅ Test Quality Sentinel completed test quality analysis. Test Quality SentinelOutcome: The agent completed and reported no action. A no-op output alone does not verify that all required work was completed or that publication was possible. Agent messages are omitted from this comment. The category uses structured run status, not interpretation of agent prose.
|
|
✅ Ponytail Reviewer completed successfully! Ponytail ReviewerOutcome: The agent completed and reported no action. A no-op output alone does not verify that all required work was completed or that publication was possible. Agent messages are omitted from this comment. The category uses structured run status, not interpretation of agent prose.
|
|
✅ PR Code Quality Reviewer completed the code quality review. PR Code Quality ReviewerOutcome: The agent completed and reported one or more actions. The no-op output is a completion signal, not a claim that no action was taken. Agent messages are omitted from this comment. The category uses structured run status, not interpretation of agent prose.
|
|
✅ PR Specification Reviewer completed successfully! PR Specification ReviewerOutcome: The agent completed and reported one or more actions. The no-op output is a completion signal, not a claim that no action was taken. Agent messages are omitted from this comment. The category uses structured run status, not interpretation of agent prose.
|
|
🧠 Matt Pocock Skills Reviewer has completed the skills-based review. ✅
|
Comment MemoryPeek at saved memory (spec-review-history)History |
🏗️ Design Decision Gate — ADR RequiredThis PR makes significant changes to core business logic (>100 new lines) but does not have a linked Architecture Decision Record (ADR). 📄 Draft ADR committed:
📋 What to do next
Once an ADR is linked in the PR body, this gate will re-run and verify the implementation matches the decision. 🔍 Evidence checked
❓ Why ADRs MatterADRs create a searchable, permanent record of why the codebase looks the way it does. Future contributors (and your future self) will thank you. 📋 Michael Nygard ADR Format ReferenceAn ADR must contain these four sections to be considered complete:
All ADRs are stored in
|
Comment MemoryPeek at saved memory (pr-code-quality-reviewer)Note This comment is managed by comment memory.Expand the saved memory block to view or edit the persistent context for this thread.
|
There was a problem hiding this comment.
Found a high-severity correctness issue: the analyzer blesses EOF comparisons that still accept trailing JSON when the second Decode succeeds. The test suite currently encodes these broken patterns as valid, so the linter can miss its primary target.
🔎 Code quality review by PR Code Quality Reviewer · copilot · gpt50 · ~3 AIC · ⌖ ~2 AIC · ⊞ 1.5K
Comment /review to run again
| switch node := node.(type) { | ||
| case *ast.BinaryExpr: | ||
| if node.Op == token.EQL || node.Op == token.NEQ { | ||
| found = (sameObject(pass, node.X, errorObject) && isIOEOF(pass, node.Y)) || |
There was a problem hiding this comment.
The analyzer treats any comparison with io.EOF as a valid trailing-data check, but this accepts the exact bug the linter is meant to prevent: when the second Decode succeeds because trailing JSON exists, err != io.EOF is true and return err returns nil. The same issue applies to !errors.Is(err, io.EOF) in the adjacent test.
💡 Validate the rejecting branch, not just the comparison
Require that the non-EOF path rejects a successful second decode (or otherwise prove the branch returns a non-nil error), and update both “good” test cases to expect diagnostics. A syntactic EOF comparison alone does not establish whole-document validation.
There was a problem hiding this comment.
EOF checks now suppress diagnostics only when the non-EOF branch rejects with a guaranteed non-nil error; fixtures cover comparisons that return the potentially nil Decode error. Commit 16d8d97.
Comment MemoryPeek at saved memory (review-history)History |
There was a problem hiding this comment.
Skills-Based Review 🧠
Applied /tdd and /codebase-design. Requesting changes: the analyzer's own testdata encodes the bug it is meant to catch, and the analyzer produces false positives on the canonical streaming pattern.
📋 Key Themes & Highlights
Key Themes
- Testdata blesses trailing data:
goodEOFComparisonandgoodEOFCheckAfterAssignmentuseerr != io.EOFand returnnilon{"a":1} {"b":2}. I confirmed this by running them.goodErrorsIshas the same flaw. - Guard check ignores branch direction:
conditionChecksEOFaccepts any==or!=againstio.EOF, so it cannot distinguish a correct guard from a broken one. - False positive on loops: any
Decodeinside aforloop is reported, including loops that checkio.EOF.
Positive Highlights
- ✅ Analyzer is registered in
registry.goandspec_test.go, and the docs (doc.go,README.md) and the 96 to 97 count are updated consistently. - ✅ Generated-file and
nolinthandling follow the existing linter pattern. - ✅
go test ./pkg/linters/...passes on this branch. The gap is in test coverage, not in the build.
See the inline comments for file-level fixes. @copilot please address the review comments above.
🧠 Reviewed using Matt Pocock's skills by Matt Pocock Skills Reviewer · copilot · routed: haiku55 xhigh · ~7 AIC · ⌖ ~2 AIC · ⊞ 6.6K
Comment /matt to run again
| if err := decoder.Decode(&value); err != nil { | ||
| return err | ||
| } | ||
| if err := decoder.Decode(&trailing); err != io.EOF { |
There was a problem hiding this comment.
[/tdd] goodEOFComparison is labelled as a good case, but it accepts trailing data. For input {"a":1} {"b":2} the second Decode succeeds with err == nil, so err != io.EOF is true and the function returns nil. I confirmed this by running it. The same bug affects goodEOFCheckAfterAssignment (line 60).
💡 Suggested fix
if err := decoder.Decode(&trailing); err == nil {
return errors.New("trailing JSON data")
} else if !errors.Is(err, io.EOF) {
return err
}Add a case that asserts trailing data is rejected. A test that only checks clean input cannot catch this.
@copilot please address this.
There was a problem hiding this comment.
Corrected the EOF fixture to reject successful trailing decodes with a non-nil error, and added a negative fixture for the unsafe return err form. Commit 16d8d97.
| if err := decoder.Decode(&value); err != nil { | ||
| return err | ||
| } | ||
| if err := decoder.Decode(&trailing); !errors.Is(err, io.EOF) { |
There was a problem hiding this comment.
[/tdd] Same false negative in goodErrorsIs. When the second Decode succeeds, err is nil, so !errors.Is(nil, io.EOF) is true and the function returns nil. Use the guard shown on line 47 instead.
There was a problem hiding this comment.
Updated the errors.Is fixture to reject non-EOF results with a non-nil error and added a negative fixture for the unsafe return err form. Commit 16d8d97.
| return pass.TypesInfo.ObjectOf(ident) | ||
| } | ||
|
|
||
| func conditionChecksEOF(pass *analysis.Pass, condition ast.Expr, errorObject types.Object) bool { |
There was a problem hiding this comment.
[/codebase-design] conditionChecksEOF accepts any == or != comparison against io.EOF and never checks which branch returns. That is why the two broken patterns in the testdata pass, so the analyzer gives false assurance on the exact bug it targets.
💡 Suggested change
Accept a guard only when its nil path returns a non-nil error and its io.EOF path is the success path. Then add testdata for both broken forms so they stay reported.
@copilot please address this.
There was a problem hiding this comment.
The analyzer now validates that the failed EOF condition rejects with a guaranteed non-nil error, rather than accepting a comparison alone. Regression fixtures cover both unsafe forms. Commit 16d8d97.
| slices.SortFunc(calls, func(a, b *ast.CallExpr) int { | ||
| return int(a.Pos() - b.Pos()) | ||
| }) | ||
| if len(calls) > 1 && decodeChecksEOF(pass, body, calls[1]) { //nolint:uncheckedsliceindex // len(calls) > 1 guards the second Decode. |
There was a problem hiding this comment.
[/tdd] False positive on the canonical streaming loop. Any Decode inside a loop is reported, because len(calls) > 1 is false. I confirmed this with a temporary testdata file, since removed: both an EOF-checked for {} loop and a for decoder.More() loop are reported.
💡 Suggested test and fix
for {
var v any
if err := decoder.Decode(&v); err == io.EOF {
return nil
} else if err != nil {
return err
}
}This loop already consumes every value, so it should not be reported. Skip decoders whose Decode is inside a loop and whose error is compared to io.EOF, and add this case to testdata.
@copilot please address this.
There was a problem hiding this comment.
Added a regression for the EOF-terminated Decode loop and exempted loops that check the same Decode result for EOF. Commit 16d8d97.
There was a problem hiding this comment.
🟡 Changes recommended
The analyzer has unresolved false positives for valid EOF-checked decoding patterns and misses unchecked trailing data in inline, reassigned, and conditionally checked decoder flows.
6 open issues
What changed in this PR
Adds jsondecodertrailingdataunchecked to gh-aw’s custom Go analyzers to detect missing trailing-data validation after decoding JSON from in-memory readers.
Changes:
- Implements decoder tracking and follow-up EOF-check detection, with reader exclusions and
nolintsupport. - Adds analyzer fixtures and registers the rule in the canonical registry.
- Synchronizes linter documentation and records that CI enforcement awaits an audit.
| File | Description |
|---|---|
pkg/linters/spec_test.go |
Adds the analyzer to documentation contract checks. |
pkg/linters/registry.go |
Registers the analyzer with the shared runner. |
pkg/linters/README.md |
Documents the new rule and analyzer package. |
pkg/linters/jsondecodertrailingdataunchecked/testdata/src/jsondecodertrailingdataunchecked/jsondecodertrailingdataunchecked.go |
Adds reporting, EOF-check, exclusion, and suppression fixtures. |
pkg/linters/jsondecodertrailingdataunchecked/jsondecodertrailingdataunchecked.go |
Implements decoder tracking and diagnostics. |
pkg/linters/jsondecodertrailingdataunchecked/jsondecodertrailingdataunchecked_test.go |
Runs analyzer tests against the fixtures. |
pkg/linters/doc.go |
Updates the analyzer list and count. |
pkg/linters/doc_sync_test.go |
Records deferred CI enforcement pending an audit. |
Review effort: Balanced (dynamic)
| if len(calls) > 1 && decodeChecksEOF(pass, body, calls[1]) { //nolint:uncheckedsliceindex // len(calls) > 1 guards the second Decode. | ||
| continue |
There was a problem hiding this comment.
Follow-up suppression is now limited to a directly subsequent check in the same block, so conditional and mutually exclusive checks no longer suppress the diagnostic. Added both fixtures. Commit 16d8d97.
| if len(calls) > 1 && decodeChecksEOF(pass, body, calls[1]) { //nolint:uncheckedsliceindex // len(calls) > 1 guards the second Decode. | ||
| continue | ||
| } | ||
| firstDecodes = append(firstDecodes, calls[0]) //nolint:uncheckedsliceindex // entries are created only when a Decode call is appended. |
There was a problem hiding this comment.
Recognized EOF-terminated Decode loops are excluded, with a regression fixture demonstrating the stream-consumer pattern. Commit 16d8d97.
| if len(calls) > 1 && decodeChecksEOF(pass, body, calls[1]) { //nolint:uncheckedsliceindex // len(calls) > 1 guards the second Decode. | ||
| continue | ||
| } | ||
| firstDecodes = append(firstDecodes, calls[0]) //nolint:uncheckedsliceindex // entries are created only when a Decode call is appended. |
There was a problem hiding this comment.
Token-driven decoding is excluded when the same decoder’s Token flow checks for EOF; added a mixed Token/Decode regression fixture. Commit 16d8d97.
| if obj := inMemoryDecoderObject(pass, lhs, rhs); obj != nil { | ||
| decoders[obj] = struct{}{} | ||
| } |
There was a problem hiding this comment.
Decoder provenance is now keyed to each in-memory construction; reassignment to a generic reader invalidates it, and a new in-memory decoder gets its own check. Added fixtures for both cases. Commit 16d8d97.
| receiver, ok := astutil.UnwrapParenExpr(selector.X).(*ast.Ident) | ||
| if !ok || !isJSONDecoder(pass, selector.X) { | ||
| break |
There was a problem hiding this comment.
Inline json.NewDecoder(strings.NewReader(...)).Decode and bytes.NewReader calls are now recognized and covered by reporting fixtures. Commit 16d8d97.
| if ifStmt, ok := node.(*ast.IfStmt); ok { | ||
| if obj := decodeErrorObject(pass, ifStmt.Init, call); obj != nil && conditionChecksEOF(pass, ifStmt.Cond, obj) { | ||
| checked = true | ||
| return false | ||
| } | ||
| } |
There was a problem hiding this comment.
The EOF guard now recognizes direct Decode calls as well as Decode results checked via errors.Is; both valid forms have regression fixtures. Commit 16d8d97.
|
🍳 A little prep to help this PR along! Copilot assignment requested for the following outstanding work:
Keeping the changes focused; human review and CI get the final taste test. No merging or CI triggering. Structured data{
"completed_task": 0,
"head": "6ff4a5d186f779dbb6bdede9f8ea669127d90b76",
"kind": "requested",
"schema_version": "1",
"state": "2b0568898307f78e65733ea5585d90009eacb407726944540964f327e142f419",
"work": [
"2cc2367e7a1654726f5d3943a75ade52f82b29170e9fc7aecf89edb3f12681c6",
"4730b14e4c9ae4ecadd88fcaa39a030311df860622278254403c3910550b40fa",
"529ccdb3ab913c1753c67bc5cd692222223fc041c60181d7eaa00359dde01f05",
"5c6145fa927d0bb6863d68af3d85cd061b23d3bfd79d77faf81fa6d2dd9a9970",
"69c4860091d840b64786b39e379061439df778022a5ee81fefcee106bda33ca4",
"8643f2f1df7f56c2c5f9125ef3bc827146b3d9dac8ef0877ac92ef47dfdffa87",
"937e20750a7aec993e027a2393eecc5e9215304196e108011b260cd15d792429",
"9a45ac9ef3710d8124c801fc8ffdbdbbdad6992a7ad8bcfee424b408b95f24de",
"9c2edb419124dc4c5728eafc9406919544044777e33d115b71c9f6408b5cb188",
"db608cc77ee881fa96891e8d5ce9bb7e91c6e8c3d6ce2e3e3b6d1e4785db360e",
"ebae21607a267679cb8ce017543117ec7ba3dfdc2e882d1014bbaa7ce7dff853"
],
"workflow": "pr-sous-chef"
}
|
…son-decoder-trailing-data-unchecked-3 Co-authored-by: copilot-swe-agent[bot] <[email protected]>
Co-authored-by: copilot-swe-agent[bot] <[email protected]>
Co-authored-by: copilot-swe-agent[bot] <[email protected]>
|
🎉 This pull request is included in a new release. Release: |

json.Decoder.Decodereads one JSON value, so trailing data can go unnoticed unless another decode verifiesio.EOF. Add an analyzer for decoders backed bystrings.NewReaderorbytes.NewReader.nolint.