Skip to content

encoding/json/v2: possibly clarify retention prohibitions in documentation #80885

Open

Description

@thepudds

General suggestion

The current json/v2 documentation lists some prohibitions regarding retaining references to slices or other memory.

Before json/v2 goes out the door, I wonder if it would be worthwhile to do a quick sweep to see if there should be any clarification or additional prohibitions laid out.

Some current examples

For example, the Unmarshaler interface documentation currently says:

Implementations must not retain or mutate the input []byte.

The UnmarshalFunc documentation I think incorporates that by reference ("Implementations must follow the requirements of Unmarshaler"), but goes further and also says:

Implementations must not retain the value of T.

Avoiding retaining destination of unmarshals

I'm particularly interested if it could or should by clearly documented that it is prohibited to retain the unmarshal method receiver or the T value supplied to an unmarshal operation after the method or function returns (or something along those lines -- I'm not trying to suggest exact language at this point).

It's probably already a bad idea for someone to retain a pointer to those? For example, if the destination is an element of a slice, the slice might have grown after the element's unmarshal completed, and the user could be pointing to a stale element in the old backing array and hence not the final element that was shallow copied during growth.

There are some things in the doc that already reference shallow copying, but I'm not sure there is currently a clear prohibition against retaining a pointer to the destination.

I'm not as deep on the latest json/v2 documentation as I probably should be, so sorry in advance if this suggestion is off base (including maybe some or all of this is already implied by a more careful read).

CC @ChrisHines @neild

Activity

  1. thepudds commented on Aug 14, 2026

    @thepudds
    MemberAuthor

    Potential performance optimizations

    I'm hoping this issue is worthwhile even if just as a sanity check on the documentation, but part of the reason I was looking at this was there might be some decent performance wins available in the future that would only be enabled if the user is not allowed to retained something like the method receiver in an unmarshal call.

    One flavor of performance win might be optimizing slice memory when unmarshalling to slices that grow. For example, the slice being built might correspond to a top-level JSON array of objects, or might be many smaller slices, but often they grow, and sometimes that generates quite a bit of intermediate garbage before reaching final size.

    One approach I've implemented as an experiment for json/v2 is similar in spirit to the io.ReadAll slice memory optimization I merged for Go 1.26 in CL 722500 where a slice is built in chunks that are then copied to a final, minimally sized slice.

    That cuts down on total memory allocated as well as total memory retained, which can be the more important on-going effect if some unmarshalled data structure lives multiple GC cycles, for example.

    On top of that, a sync.Pool can (optionally) be used for the intermediate slice chunks, which further cuts down on total memory allocated.

    Sample results using my draft json/v2 CL on the 5 official real-world unmarshalling benchmarks in the json/v2 tests (via go-json-experiment/jsonbench) for Testdata/*/Unmarshal/Concrete-8:

                       memory       memory       sec/op
                       allocated    retained              
                                                        
    CanadaGeometry     -52.3%       −16.4%           ~   
    GolangSource       -50.9%       −19.5%       -4.4%   
    CitmCatalog        -43.2%       −20.4%       -5.3%   
    TwitterStatus      -28.1%        −8.5%       -2.9%   
    SyntheaFhir         -3.2%        −1.0%           ~   
    

    The benefit does depend on the shape of the JSON data. (In those examples -- 3 of those real-world shapes benefit quite a bit, 1 benefits but not as much, and the last hardly benefits based on how its particular JSON arrays are unmarshalled.)

    Some other possibilities for the future include perhaps a reflect.SliceBuilder API or similar to make it easier for others (and also, I've experimented a bit with getting the compiler to do some of this style optimization for non-reflect cases, which is maybe interesting but not strictly related to json/v2).


    All that said, whether we want to do any flavor of those performance optimizations is a separate question for the future (and some chance it might not pan out), so the more immediate question is whether it might be worth tweaking the docs to keep more doors open?

  2. ChrisHines commented on Aug 15, 2026

    @ChrisHines
    Contributor
  3. dsnet commented on Aug 15, 2026

    @dsnet
    Member

    Hi @thepudds, thanks for raising the issue.

    I confess that I had a really hard time understanding what "the user is not allowed to retained something like the method receiver in an unmarshal call" actually meant.

    My thought process was: A method is already declared on a receiver variable. By virtue of it being called, doesn't that imply the value receiver must be retained somewhere else in my program? I'm confused.

    Then I realized that in the unique situation where the "json" package is the one who initially allocated the value in such a way where it might be replaced by something else later on, we can view the "json" package as the owner of that memory, and thus wouldn't want the method implementation to leak the receiver value (and thus confusing ownership).

    I'm okay with documenting this restriction, but several thoughts:

    • The Unmarshaler interface is identical to what v1 declared, so it's possible that some implementations already exist that violate the restriction. We could only realistically enforce this for UnmarshalerFrom and MarshalerTo. If we wanted to have a dynamic check for this, we could check if we're running under the race detector, and for intermediate values that are replaced, we could start a goroutine on a timer that mutates some memory in it to make sure it's not being used elsewhere.
    • I think I'm somewhat of experienced Go programmer? Yet, I struggled initially to understand what the restriction was for. If we add anything, the wording would have to be crystal clear.
  4. prattmic commented on Aug 17, 2026

    @prattmic
    Member

    My understanding was that the "Implementations must not retain the value of T." requirement was there because of "Unmarshal ensures that a value is always addressable (by copying the value if necessary) so that these functions and methods can be consistently called. If a value must be shallow copied to call a pointer-receiver Unmarshaler, UnmarshalerFrom, or encoding.TextUnmarshaler method, then any mutations performed by the method are shallow copied back into the destination value." [1] Are there other reasons?

    If Unmarshal copies the value, then retaining a pointer to the original value is not going to work as expected.

    In this context, the restriction should apply to methods as well. As far as I know, there is nothing special about UnmarshalerToFunc vs UnmarshalerTo in this regard. Both can equally be called on a value that will later be copied.

    That said, I agree with Joe that putting this restriction on methods sounds very weird/confusing.

    Stepping back, is it safe to say that any type that retains a pointer to itself is not (semantically) copyable? Such a type should probably not be stored in []T (should be []*T), etc. It may be prudent for such a type to include a noCopy type (sync.Mutex), so that vet's copylock would flag places that copy. Though I don't think copylock will flag any call to json.Unmarshal that might copy, so it doesn't help for json specifically.

    [1] As far as I can tell, the second sentence here should list UnmarshalerFunc and UnmarshalerToFunc. e.g., here we don't care whether the unmarshaler is a func or not.

  5. thepudds commented on Aug 17, 2026

    @thepudds
    MemberAuthor

    Hi @dsnet and @prattmic, thanks for the feedback, and sorry for not being more precise.

    I'm familiar with json/v2 at a general level (and a fan! 😅) but I'm not yet familiar enough to really understand all the ways users can stack the turtles.

    Before trying to say what the exact wording should be and how widely it should apply, maybe let's look at a narrow example:

    type Message struct {
    	A, B  int
    	Items []Item
    }
    
    type Item struct{ X, Y string }
    
    func (i *Item) UnmarshalJSONFrom(dec *jsontext.Decoder) error {
        // ...
    }

    and then elsewhere:

    	var m Message
    	err := json.Unmarshal(b, &m)

    In this example, the json/v2 package is allocating the memory for the Items slice backing array (and doing a shallow copy as needed as part of growing the backing array), while the user code populates each Item via the *Item receiver of the UnmarshalJSONFrom method.

    For this example at least, would it be reasonable to convey somehow in the UnmarshalerFrom documentation that implementations of UnmarshalJSONFrom must not retain the receiver? And maybe there's also more to say, but would that piece be reasonable to convey?

    That documentation already says:

    Implementations must not retain the pointer to jsontext.Decoder.

  6. added
    NeedsInvestigationSomeone must examine and confirm this is a valid issue and not a duplicate of an existing one.
    on Aug 17, 2026
  7. gopherbot commented on Aug 18, 2026

    @gopherbot
    Contributor

    Change https://go.dev/cl/817040 mentions this issue: encoding/json/v2: document that an UnmarshalJSONFrom implementation should not retain its receiver

  8. added
    FixPendingIssues that have a fix which has not yet been reviewed or submitted.
    on Aug 18, 2026
  9. thepudds commented on Aug 18, 2026

    @thepudds
    MemberAuthor

    Hi @dsnet and @prattmic, I sent https://go.dev/cl/817040, which attempts to document the main restriction I was suggesting here.

    In general, the stdlib doc seems to be pretty spare in terms of supplying rationale for this type of restriction (e.g., io.Reader and io.Writer just say Implementations must not retain p.), so I did not attempt any rationale in the user-facing doc, though I'm happy to adjust based on whatever feedback you might have.

    @dsnet wrote above:

    We could only realistically enforce this for UnmarshalerFrom and MarshalerTo.

    I think I'm not aware of a benefit for documenting a method receiver retention restriction for MarshalerTo, so I only added it to UnmarshalerFrom.


    Separately, @prattmic wrote above:

    If a value must be shallow copied to call a pointer-receiver Unmarshaler, UnmarshalerFrom, or encoding.TextUnmarshaler method, then any mutations performed by the method are shallow copied back into the destination value." [1]
    [...]
    [1] As far as I can tell, the second sentence here should list UnmarshalerFunc and UnmarshalerToFunc. e.g., here we don't care whether the unmarshaler is a func or not.

    I'll also take a stab at a separate CL to address that comment, unless someone waves me off by saying either it is not needed or that someone would prefer to do it themselves.

  10. thepudds commented on Aug 19, 2026

    @thepudds
    MemberAuthor

    I asked @dmitshur about the timing of documenting this restriction vs. the timing of Go 1.27.0, and the main portion of his reply was:

    it is expected that there will be various ways in which encoding/json/v2 will improve after go1.27.0, and we can think of the restriction as already being in place, just underdocumented (until go1.27.1). This is the nature of releases; we would hold a release back in some cases but I think this is okay for .1.

    That said, I believe that was just based on a quick look, so I imagine @dmitshur reserves the right to change his opinion as needed based on more facts or discussion.

  11. prattmic commented on Aug 19, 2026

    @prattmic
    Member

    I agree with Dmitri. I'm not yet sure if we should change these docs, but it's clearly too late for 1.27.0. While we don't strictly need to, we really want to be making these kinds of changes before the freeze, or at least around API review, given that we are effectively slightly modifying the API.

    I already felt bad for sending so many doc changes so late these last few weeks. A day or two before the release is just too late unless a bug is really critical.

  12. dsnet commented on Aug 19, 2026

    @dsnet
    Member

    For what it's worth, documenting this for Go 1.27.1 or even 1.28.0 is probably okay? I'm not sure if I have ever seen a method implementation deliberately leak the receiver.

  13. removed
    NeedsInvestigationSomeone must examine and confirm this is a valid issue and not a duplicate of an existing one.
    on Aug 21, 2026
  14. self-assigned this
    on Aug 21, 2026
  15. thepudds commented on Oct 27, 2026

    @thepudds
    MemberAuthor

    @gopherbot, please open a backport issue for https://go.dev/cl/817040. This is mostly a clarification for json/v2 to add an explicit documented restriction regarding retaining a pointer, where retaining that pointer is already unwise. It also keeps the door open for some future possible optimizations for json/v2 unmarshalling. @dmitshur and others previously said this would likely be reasonable to backport.

  16. gopherbot commented on Oct 27, 2026

    @gopherbot
    Contributor

    Backport issue(s) opened: #82630 (for 1.26), #82631 (for 1.27).

    Remember to create the cherry-pick CL(s) as soon as the patch is submitted to master, according to https://go.dev/wiki/MinorReleases.

  17. added this to the Go1.28 milestone on Oct 27, 2026
  18. thepudds commented on Oct 27, 2026

    @thepudds
    MemberAuthor

    (Sorry, I just meant for Go 1.27. I closed the Go 1.26 backport issue.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

DocumentationIssues describing a change to documentation.FixPendingIssues that have a fix which has not yet been reviewed or submitted.

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions