Skip to content

Thread safety issue in STJ.JsonObject #120617

Closed

Description

@eangelin

Description

Calling GetPath on a JsonObject child node in parallel triggers InvalidOperationException.

Reproduction Steps

var tree = (JsonNode.Parse(
    """
    {
      "oh": "noes"
    }
    """
) as JsonObject)!;

// Workaround, do this once before parallel
// tree.First().Value!.GetPath();

Parallel.ForEach(Enumerable.Range(0, 10), _ =>
{
    tree.First().Value!.GetPath();
});

Expected behavior

I expect parallel reads from the JsonNode/Object/Values to be thread safe.

Actual behavior

On JsonObject.GetPath, line string propertyName = FindValue(child)!.Value.Key; I get the following exception + stack trace:

System.InvalidOperationException: Nullable object must have a value.
   at System.Nullable`1.get_Value()
   at System.Text.Json.Nodes.JsonObject.GetPath(ValueStringBuilder& path, JsonNode child)
   at System.Text.Json.Nodes.JsonNode.GetPath()
   ...

Regression?

Possibly regression from #77421

Known Workarounds

Traverse the object hierarchy serially once before parallel access to force lazy-initialization.

Configuration

Using .net sdk 9.0.305.

I don't think the rest matters, but macOS 15.7.1, arm64.

Other information

I guess calling tree.First() in the repro triggers initialization of the underlying Dictionary and I can't see anything in place to avoid a race condition there.

Activity

  1. added
    untriaged
    on Oct 11, 2025
  2. dotnet-policy-service commented on Oct 11, 2025

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @dotnet/area-system-text-json, @gregsdennis
    See info in area-owners.md if you want to be subscribed.

  3. MihuBot commented on Oct 11, 2025

    @MihuBot

    I'm a bot. Here is a possible related and/or duplicate issue (I may be wrong):

  4. eangelin commented on Oct 11, 2025

    @eangelin
    Author

    It does indeed look related, so perhaps this counts as a regression.

  5. stephentoub commented on Oct 11, 2025

    @stephentoub
    Member

    Just based on code inspection, I suspect the issue is that InitializeDictionary when called concurrently could end up returning two different dictionary instances with different node objects. While idempotent in terms of contents, reference equality will be different, and FindValue is relying on reference equality to locate the child object.

  6. added and removed
    untriaged
    on Oct 12, 2025
  7. locked and limited conversation to collaborators on Nov 13, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions