Skip to content

Fix JsonPatch to not drop empty reference tokens and adhere to RFC - #68613

Merged
Youssef1313 merged 10 commits into
mainfrom
dev/ygerges/jsonpatch-rfc
Aug 26, 2026
Merged

Youssef1313 merged 10 commits into
mainfrom
dev/ygerges/jsonpatch-rfc

Conversation

@Youssef1313

Copy link
Copy Markdown
Member

Fixes #67819

Copilot AI lite review requested due to automatic review settings August 18, 2026 08:32

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Updates ParsedPath parsing in both JsonPatch implementations to reject empty JSON Pointer reference tokens (e.g., //, trailing /), aligning behavior with the intended “no empty tokens” policy and preventing silent path collapsing.

Changes:

  • Add explicit rejection of empty reference tokens during path parsing in ParsedPath.
  • Treat empty string ("") as a valid “root pointer” path (returns no segments).
  • Expand unit tests to cover leading / paths, empty path, and empty-token rejection cases.

Reviewed changes

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

File Description
src/Features/JsonPatch/src/Internal/ParsedPath.cs Rejects empty reference tokens and handles empty path early.
src/Features/JsonPatch/test/Internal/ParsedPathTests.cs Adds coverage for leading /, empty string, and empty-token failures.
src/Features/JsonPatch.SystemTextJson/src/Internal/ParsedPath.cs Mirrors the same empty-token rejection + empty-path handling for STJ.
src/Features/JsonPatch.SystemTextJson/test/Internal/ParsedPathTests.cs Mirrors the same test coverage changes for STJ.

💡 Add a code-review agent skill for context-aware, tailored reviews. Learn more in the docs.

@Youssef1313 Youssef1313 changed the title Reject empty reference tokens in JsonPatch Fix JsonPatch to not drop empty reference tokens and adhere to RFC Aug 25, 2026
@Youssef1313

This comment was marked as outdated.

@Youssef1313

Copy link
Copy Markdown
Member Author

Copilot-generated:

using BenchmarkDotNet.Running;
using JsonPatchParsedPathBenchmarks;

BenchmarkSwitcher.FromAssembly(typeof(ParsedPathBenchmarks).Assembly).Run(args);
// Self-contained copies of the JsonPatch ParsedPath parsing logic, extracted to
// benchmark the change made in https://github.com/dotnet/aspnetcore/pull/68613
//
//   * Old:  StringBuilder char-by-char scan (dropped empty reference tokens).
//   * New (Newtonsoft flavor):  path.Substring(1).Split('/') + per-token validate/unescape.
//   * New (System.Text.Json flavor):  pre-sized array + ReadOnlySpan<char>.Split('/').
//
// The New variants mirror the current implementation in the dotnet/aspnetcore repo
// (src/Features/JsonPatch{,.SystemTextJson}/src/Internal/ParsedPath.cs). The exception
// type is simplified to a plain exception so the code is standalone.

using System.Text;

namespace JsonPatchParsedPathBenchmarks;

internal sealed class JsonPatchException(string message) : Exception(message);

/// <summary>
/// Pre-PR implementation (both JsonPatch and JsonPatch.SystemTextJson were identical).
/// Uses a <see cref="StringBuilder"/> and a manual character scan. Note that this
/// version silently dropped empty reference tokens and did not normalize the path.
/// </summary>
internal static class OldParsedPath
{
    public static string[] Parse(string path)
    {
        var strings = new List<string>();
        var sb = new StringBuilder(path.Length);

        for (var i = 0; i < path.Length; i++)
        {
            if (path[i] == '/')
            {
                if (sb.Length > 0)
                {
                    strings.Add(sb.ToString());
                    sb.Length = 0;
                }
            }
            else if (path[i] == '~')
            {
                ++i;
                if (i >= path.Length)
                {
                    throw new JsonPatchException($"The provided string '{path}' is an invalid path.");
                }

                if (path[i] == '0')
                {
                    sb.Append('~');
                }
                else if (path[i] == '1')
                {
                    sb.Append('/');
                }
                else
                {
                    throw new JsonPatchException($"The provided string '{path}' is an invalid path.");
                }
            }
            else
            {
                sb.Append(path[i]);
            }
        }

        if (sb.Length > 0)
        {
            strings.Add(sb.ToString());
        }

        return strings.ToArray();
    }
}

/// <summary>
/// Current implementation of the Newtonsoft-based <c>Microsoft.AspNetCore.JsonPatch</c>.
/// Normalizes the path, then <c>Substring(1).Split('/')</c> and validates/unescapes
/// each token in a single scan (only allocating a replacement when a '~' is present).
/// </summary>
internal static class NewParsedPathNewtonsoft
{
    public static string[] Parse(string path)
    {
        return ParsePath(NormalizePath(path));
    }

    private static string NormalizePath(string path)
    {
        // An empty string on its own is valid, and is different from "/".
        // So, we never want to normalize an empty string.
        if (path.Length > 0 && !path.StartsWith('/'))
        {
            return $"/{path}";
        }

        return path;
    }

    private static string[] ParsePath(string path)
    {
        if (path.Length == 0)
        {
            return [];
        }

        if (path[0] != '/')
        {
            throw new JsonPatchException($"The provided string '{path}' is an invalid path.");
        }

        var referenceTokens = path.Substring(1).Split('/');

        for (var i = 0; i < referenceTokens.Length; i++)
        {
            referenceTokens[i] = ValidateAndUnescapeReferenceToken(referenceTokens[i]);
        }

        return referenceTokens;
    }

    private static string ValidateAndUnescapeReferenceToken(string referenceToken)
    {
        var hasTilde = false;
        for (var i = 0; i < referenceToken.Length; i++)
        {
            if (referenceToken[i] == '~')
            {
                hasTilde = true;
                if (i + 1 >= referenceToken.Length || (referenceToken[i + 1] != '0' && referenceToken[i + 1] != '1'))
                {
                    throw new JsonPatchException($"The provided string '{referenceToken}' is an invalid path.");
                }
            }
        }

        return hasTilde ? referenceToken.Replace("~1", "/").Replace("~0", "~") : referenceToken;
    }
}

/// <summary>
/// Current implementation of <c>Microsoft.AspNetCore.JsonPatch.SystemTextJson</c>.
/// Normalizes the path, sizes the result array up front via
/// <see cref="MemoryExtensions.Count{T}(ReadOnlySpan{T}, T)"/>, then uses the span
/// split (<c>ReadOnlySpan&lt;char&gt;.Split('/')</c>) and validates/unescapes each token.
/// </summary>
internal static class NewParsedPathSystemTextJson
{
    public static string[] Parse(string path)
    {
        return ParsePath(NormalizePath(path));
    }

    private static string NormalizePath(string path)
    {
        if (path.Length > 0 && !path.StartsWith('/'))
        {
            return $"/{path}";
        }

        return path;
    }

    private static string[] ParsePath(string path)
    {
        if (path.Length == 0)
        {
            return [];
        }

        var span = path.AsSpan();

        if (span[0] != '/')
        {
            throw new JsonPatchException($"The provided string '{path}' is an invalid path.");
        }

        var strings = new string[span.Count('/')];

        // When we have a path like "/a/b/c//d/e", the expectation is
        // to have the segments be ["a", "b", "c", "", "d", "e"].
        // So, before splitting on "/", we want to slice off the leading "/".
        span = span.Slice(1);

        var index = 0;
        foreach (var referenceTokenRange in span.Split('/'))
        {
            var referenceToken = span[referenceTokenRange].ToString();
            strings[index++] = ValidateAndUnescapeReferenceToken(referenceToken);
        }

        return strings;
    }

    private static string ValidateAndUnescapeReferenceToken(string referenceToken)
    {
        var hasTilde = false;
        for (var i = 0; i < referenceToken.Length; i++)
        {
            if (referenceToken[i] == '~')
            {
                hasTilde = true;
                if (i + 1 >= referenceToken.Length || (referenceToken[i + 1] != '0' && referenceToken[i + 1] != '1'))
                {
                    throw new JsonPatchException($"The provided string '{referenceToken}' is an invalid path.");
                }
            }
        }

        return hasTilde ? referenceToken.Replace("~1", "/").Replace("~0", "~") : referenceToken;
    }
}
using BenchmarkDotNet.Attributes;

namespace JsonPatchParsedPathBenchmarks;

[MemoryDiagnoser]
public class ParsedPathBenchmarks
{
    // Representative JSON Patch paths (RFC 6901 pointers) covering common and edge shapes.
    [Params(
        "/foo/bar",                         // simple, already normalized
        "foo/bar",                          // needs leading-slash normalization
        "/a/b/c/d/e/f/g/h",                 // deep path, no escapes
        "/foo/bar~1baz/~0/qux",             // escape sequences (~0 / ~1)
        "/store/book/0/author/name/value")] // typical realistic pointer
    public string Path { get; set; } = "";

    [Benchmark(Baseline = true, Description = "Old (StringBuilder scan)")]
    public string[] Old() => OldParsedPath.Parse(Path);

    [Benchmark(Description = "New Newtonsoft (Substring.Split)")]
    public string[] NewNewtonsoft() => NewParsedPathNewtonsoft.Parse(Path);

    [Benchmark(Description = "New STJ (Span.Split)")]
    public string[] NewSystemTextJson() => NewParsedPathSystemTextJson.Parse(Path);
}
Method Path Mean Ratio Allocated Alloc Ratio
Old (StringBuilder scan) /foo/bar 43.7 ns 1.00 280 B 1.00
New Newtonsoft (Substring.Split) /foo/bar 33.8 ns 0.77 144 B 0.51
New STJ (Span.Split) /foo/bar 26.4 ns 0.60 104 B 0.37
Old (StringBuilder scan) /a/b/c/d/e/f/g/h 104.2 ns 1.00 560 B 1.00
New Newtonsoft (Substring.Split) /a/b/c/d/e/f/g/h 68.3 ns 0.66 336 B 0.60
New STJ (Span.Split) /a/b/c/d/e/f/g/h 70.8 ns 0.68 280 B 0.50
Old (StringBuilder scan) /foo/bar~1baz/~0/qux 69.6 ns 1.00 384 B 1.00
New Newtonsoft (Substring.Split) /foo/bar~1baz/~0/qux 161.2 ns 2.32 320 B 0.83
New STJ (Span.Split) /foo/bar~1baz/~0/qux 173.9 ns 2.50 256 B 0.67

Takeaway from this run: for the common case (paths without ~ escapes) the new
implementations are both faster (≈0.5–0.8× the old time) and allocate less
(≈40–65% fewer bytes). For escape-heavy tokens they are slower, because a ~ forces
two string.Replace passes on top of the validation scan — a correctness cost of RFC
6901 unescaping, not a regression in the common path. Numbers vary by machine; run
locally for your own baseline.

@Youssef1313
Youssef1313 merged commit 5af8f89 into main Aug 26, 2026
25 checks passed
@Youssef1313
Youssef1313 deleted the dev/ygerges/jsonpatch-rfc branch August 26, 2026 16:44
@dotnet-milestone-bot dotnet-milestone-bot Bot added this to the 12.0-preview1 milestone Aug 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

JsonPatch: ParsedPath drops empty JSON Pointer tokens (RFC 6901)

3 participants