Skip to content

🐛 bug: add nil-safety to response decode helpers#4081

Merged
ReneWerner87 merged 2 commits intomainfrom
add-nil-safety-for-decode-helpers
Feb 11, 2026
Merged

🐛 bug: add nil-safety to response decode helpers#4081
ReneWerner87 merged 2 commits intomainfrom
add-nil-safety-for-decode-helpers

Conversation

@gaby
Copy link
Member

@gaby gaby commented Feb 11, 2026

Motivation

  • Response decode helpers (JSON, CBOR, XML) could panic when used on a pooled Response without an attached Client, producing unpredictable behavior.
  • Introduce a stable exported error to make the API predictable and easier to handle by callers.
  • Harden response helper behavior so decode helpers are safe to call even when Client was not set.

Description

  • Add a new exported error ErrResponseClientNil in client/core.go.
  • Guard Response.JSON, Response.CBOR, and Response.XML in client/response.go to check r.client == nil and return ErrResponseClientNil instead of dereferencing a nil client.
  • Add Test_Response_DecodeHelpers_ClientNilSafety in client/response_test.go to assert there is no panic and that the exported error is returned when client is nil, and to verify normal decode still works when a Client is attached.

Copilot AI review requested due to automatic review settings February 11, 2026 05:23
@gaby gaby requested a review from a team as a code owner February 11, 2026 05:23
@gaby gaby added the codex label Feb 11, 2026
@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @gaby, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request enhances the robustness of the Response decode helpers (JSON, CBOR, XML) by introducing nil-safety checks. Previously, using these helpers on a Response without an attached Client could lead to panics. The changes prevent this by returning a new, exported error, ErrResponseClientNil, making the API more predictable and easier to handle for consumers.

Highlights

  • Nil-safety for Response Decode Helpers: Implemented checks in Response.JSON, Response.CBOR, and Response.XML methods to prevent panics when used with a nil Client instance, ensuring predictable behavior.
  • New Exported Error: Introduced ErrResponseClientNil in client/core.go to provide a stable and explicit error for callers when a Response decode helper is invoked without an associated Client.
  • Comprehensive Testing: Added Test_Response_DecodeHelpers_ClientNilSafety to verify that decode helpers correctly return ErrResponseClientNil when Client is nil and continue to function as expected when a Client is present.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Changelog
  • client/core.go
    • Added a new exported error, ErrResponseClientNil, for cases where a response client is nil.
  • client/response.go
    • Added nil checks to JSON, CBOR, and XML methods to return ErrResponseClientNil if the client is not set.
  • client/response_test.go
    • Added Test_Response_DecodeHelpers_ClientNilSafety to validate nil-safety and correct error handling for decode helpers.
Activity
  • Ran go test ./client -run Test_Response_DecodeHelpers_ClientNilSafety -count=1 which passed.
  • Executed the full test suite via make test, which passed.
  • Performed make generate, make betteralign, make modernize, make format, and make lint, all succeeding.
  • Ran make audit, which failed due to environment-specific govulncheck issues unrelated to the PR changes.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 11, 2026

Walkthrough

This pull request adds defensive nil-checking to the Response decode methods (JSON, CBOR, XML) that return ErrClientNil before delegating to unmarshal operations. Comprehensive test coverage verifies these nil-safety checks prevent panics and validate normal operation with initialized clients.

Changes

Cohort / File(s) Summary
Nil-safety guards
client/response.go
Added nil-check guards in Response.JSON, Response.CBOR, and Response.XML methods to return ErrClientNil when r.client is nil, preventing downstream panics.
Test coverage
client/response_test.go
Added Test_Response_DecodeHelpers_ClientNilSafety with parallel subtests verifying nil-safety behavior across JSON, XML, and CBOR decoders, including both scenarios with and without initialized clients.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Suggested reviewers

  • sixcolors
  • efectn
  • ReneWerner87

Poem

🐰 Nil checks now guard the decode path,
No panics from a client's wrath!
JSON, XML, CBOR too—
Each tested safe, through and through. ✨

🚥 Pre-merge checks | ✅ 1 | ❌ 2
❌ Failed checks (1 warning, 1 inconclusive)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ❓ Inconclusive The description covers motivation, implementation details, and test coverage but lacks explicit checkboxes for the template requirements. Provide explicit checkbox selections from the template (e.g., 'Code consistency' checklist items) to fully comply with repository standards.
✅ Passed checks (1 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the main change: adding nil-safety guards to response decode helpers to prevent panics.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch add-nil-safety-for-decode-helpers

No actionable comments were generated in the recent review. 🎉

🧹 Recent nitpick comments
client/response_test.go (1)

475-478: Nit: require inside NotPanics can mask the real failure message.

require.ErrorIs calls t.FailNow()runtime.Goexit() on failure. While recover() won't intercept it (so NotPanics won't false-positive report a panic), the test output can be confusing because NotPanics still runs its own assertion after Goexit unwinds deferred functions. A clearer pattern is to capture the error and assert outside:

♻️ Suggested refactor (example for the JSON subtest)
-			require.NotPanics(t, func() {
-				err := resp.JSON(&decoded)
-				require.ErrorIs(t, err, ErrClientNil)
-			})
+			var err error
+			require.NotPanics(t, func() {
+				err = resp.JSON(&decoded)
+			})
+			require.ErrorIs(t, err, ErrClientNil)

Same pattern applies to the XML and CBOR nil-client subtests.

Also applies to: 491-494, 507-510


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@codecov
Copy link

codecov bot commented Feb 11, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 91.04%. Comparing base (8ca5213) to head (9e831cb).
⚠️ Report is 19 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #4081      +/-   ##
==========================================
+ Coverage   90.99%   91.04%   +0.05%     
==========================================
  Files         119      119              
  Lines       11256    11277      +21     
==========================================
+ Hits        10242    10267      +25     
+ Misses        642      638       -4     
  Partials      372      372              
Flag Coverage Δ
unittests 91.04% <100.00%> (+0.05%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Copy link
Contributor

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

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 effectively addresses a potential panic in the response decode helpers (JSON, CBOR, XML) by adding nil-safety checks for the client. The introduction of the ErrResponseClientNil error and the corresponding guards in the decode methods are well-implemented. The accompanying tests are thorough, covering both the new error condition and ensuring existing functionality remains intact. My feedback includes a suggestion to refactor the new tests into a table-driven format to improve maintainability and reduce code duplication.

Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This PR hardens the client.Response decode helper methods so they no longer panic when called on pooled responses that have no associated Client, and instead return a stable exported error.

Changes:

  • Added a new exported error ErrResponseClientNil for missing response client state.
  • Added nil checks to Response.JSON, Response.CBOR, and Response.XML to return the exported error instead of panicking.
  • Added a regression test covering nil-safety and normal decode behavior when a client is present.

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 2 comments.

File Description
client/response.go Adds r.client == nil guards to decode helpers to prevent nil dereference panics.
client/core.go Introduces exported sentinel error ErrResponseClientNil used by decode helpers.
client/response_test.go Adds coverage ensuring decode helpers don’t panic without a client and still succeed with one.

### Motivation

- Response decode helpers (`JSON`, `CBOR`, `XML`) could panic when used on a pooled `Response` without an attached `Client`, producing unpredictable behavior.
- Introduce a stable exported error to make the API predictable and easier to handle by callers.
- Harden response helper behavior so decode helpers are safe to call even when `Client` was not set.

### Description

- Add a new exported error `ErrResponseClientNil` in `client/core.go`.
- Guard `Response.JSON`, `Response.CBOR`, and `Response.XML` in `client/response.go` to check `r.client == nil` and return `ErrResponseClientNil` instead of dereferencing a nil `client`.
- Add `Test_Response_DecodeHelpers_ClientNilSafety` in `client/response_test.go` to assert there is no panic and that the exported error is returned when client is nil, and to verify normal decode still works when a `Client` is attached.

### Testing

- Ran `go test ./client -run Test_Response_DecodeHelpers_ClientNilSafety -count=1` which passed.
- Ran the full test suite via `make test` and it passed (`PASS` for the client package and the repository tests ran to completion with tests passing; new test included).</n- Ran `make generate`, `make betteralign`, `make modernize`, `make format`, and `make lint` and all succeeded.
- Ran `make audit` which failed in this environment because `govulncheck` reported Go standard library vulnerabilities for the environment toolchain (`go1.25.1`); this is a tooling/environment issue and not caused by the change in this PR.
@ReneWerner87 ReneWerner87 merged commit c64bda1 into main Feb 11, 2026
16 of 17 checks passed
@ReneWerner87 ReneWerner87 deleted the add-nil-safety-for-decode-helpers branch February 11, 2026 14:14
@github-project-automation github-project-automation bot moved this to Done in v3 Feb 11, 2026
@ReneWerner87 ReneWerner87 modified the milestones: v3, v3.1.0 Feb 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

3 participants