Skip to content

System.Text.Json 11 rc.3 breaks source generation into net472 projects #136457

Closed

Description

@AArnott

Description

Updating System.Text.Json broke the build in Nerdbank.MessagePack.

It seems that the STJ source generator fails to accommodate for net472 targeted projects, using UnsafeAccessorAttribute even though it only exists on .NET runtimes.

Reproduction Steps

git clone [email protected]:AArnott/Nerdbank.MessagePack.git
cd Nerdbank.MessagePack
git checkout 3974e6fc548c2211f584d3bf2fc95d88cbba5b3f
dotnet build

Expected behavior

The build succeeds.

Actual behavior

The build breaks:

G:\src\Nerdbank.MessagePack\obj\test\Benchmarks\Debug\net472\System.Text.Json.SourceGeneration\System.Text.Json.SourceGeneration.JsonSourceGenerator\STJSourceGenerationContext.PocoAsArrayInit.g.cs(114,50): error CS0122: 'UnsafeAccessorAttribute' is inaccessible due to its protection level

Regression?

Yes. This worked fine with System.Text.Json 10.0.10.

Known Workarounds

None found so far.

Configuration

No response

Other information

No response

Activity

  1. added
    untriaged
    on Oct 26, 2026
  2. AArnott commented on Oct 26, 2026

    @AArnott
    ContributorAuthor

    @eiriktsarpalis heads up.

  3. dotnet-policy-service commented on Oct 26, 2026

    @dotnet-policy-service
    Contributor

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

  4. AArnott commented on Oct 26, 2026

    @AArnott
    ContributorAuthor

    Further investigation narrows this down to a false-positive runtime-capability check caused by an internal polyfill in a referenced assembly, rather than a missing .NET Framework fallback.

    Root cause

    BenchmarkDotNet 0.15.8's netstandard2.0 assembly contains internal types named:

    • System.Runtime.CompilerServices.UnsafeAccessorAttribute
    • System.Runtime.CompilerServices.UnsafeAccessorKind

    Both were confirmed by inspecting the referenced assembly (IsPublic == false).

    In the source revision used by System.Text.Json 11.0.0-rc.3.26522.148, CanUseUnsafeAccessors checks whether the attribute symbol is non-null. The BenchmarkDotNet shim satisfies that check, so the generator emits unsafe-accessor methods for public init setters, resulting in the reported CS0122 errors.

    When the shim is absent, the generator correctly falls back to cached setter delegates created using reflection. That fallback works on .NET Framework.

    Isolated reproduction

    This does not require Nerdbank.MessagePack or PolyType. Use this project:

    <Project Sdk="Microsoft.NET.Sdk">
      <PropertyGroup>
        <TargetFramework>net472</TargetFramework>
        <OutputType>Exe</OutputType>
        <LangVersion>latest</LangVersion>
        <Nullable>enable</Nullable>
      </PropertyGroup>
      <ItemGroup>
        <PackageReference Include="System.Text.Json" Version="11.0.0-rc.3.26522.148" />
        <PackageReference Include="BenchmarkDotNet" Version="0.15.8" />
      </ItemGroup>
    </Project>
    using System;
    using System.Text.Json;
    using System.Text.Json.Serialization;
    
    internal static class Program
    {
        private static void Main()
        {
            Sample value = JsonSerializer.Deserialize(
                "{\"Number\":42,\"Text\":\"hello\"}", Context.Default.Sample)!;
            if (value.Number != 42 || value.Text != "hello")
            {
                throw new InvalidOperationException("Init-only properties were not deserialized correctly.");
            }
    
            Console.WriteLine("net472 source-generated init-only deserialization succeeded.");
        }
    }
    
    public sealed class Sample
    {
        public int Number { get; init; }
        public string? Text { get; init; }
    }
    
    [JsonSerializable(typeof(Sample))]
    internal partial class Context : JsonSerializerContext
    {
    }
    
    namespace System.Runtime.CompilerServices
    {
        internal static class IsExternalInit
        {
        }
    }

    Verified locally:

    • Without the BenchmarkDotNet package reference: builds, runs, and correctly deserializes both init properties.
    • With that reference (no BenchmarkDotNet API usage required): fails with the same inaccessible UnsafeAccessorAttribute / UnsafeAccessorKind errors.

    Repository-specific workaround

    In Nerdbank.MessagePack, all consumers of the generated JSON context are already guarded by #if NET, so the context is unused on net472. Excluding it from that target works around the issue without changing benchmark coverage:

    <ItemGroup Condition="'$(TargetFramework)' == 'net472'">
      <Compile Remove="STJSourceGenerationContext.cs" />
    </ItemGroup>

    Tested the equivalent exclusion through a temporary build target: both net472 and net10.0 built successfully with zero warnings or errors. This is only a workaround for this repository's unused context, not a general fix for applications that need source-generated JSON on .NET Framework.

  5. eiriktsarpalis commented on Oct 26, 2026

    @eiriktsarpalis
    Member

    The issue with platform detection in Roslyn is that it has to rely on heuristics like this. While this particular heuristic could be improved (e.g. by checking the declaring assembly), I would question BDN's decision to polyfill these attributes since they are a runtime feature and not a language feature. Given that a fix here is going to miss the GA release, perhaps asking BDN to walk back these polyfills is the fastest solution.

  6. removed
    untriaged
    on Oct 26, 2026
  7. AArnott commented on Oct 26, 2026

    @AArnott
    ContributorAuthor

    I thought most runtime features were detected via presence of properties on the RuntimeFeature class. That wouldn't be something a polyfill attribute would mess up.

  8. jkotas commented on Oct 26, 2026

    @jkotas
    Member

    I thought most runtime features were detected via presence of properties on the RuntimeFeature class.

    RuntimeFeatures is only used for runtime features that are not exposed via an API.

  9. added a commit that references this issue on Oct 26, 2026
    ffed239
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions