Skip to content

CA1508 runs for an hour or more on a method with recursive local functions called from nested loops #57327

In review

Description

@MaceWindu

CA1508 (AvoidDeadConditionalCode) can run for an hour or more on one method. This happens when the method has a recursive local function that it calls from several sites inside nested foreach loops. The compiler process is busy on a single thread, and almost all of that time is spent in GC.

This looks like the same root cause as dotnet/roslyn#86003 (closed as a duplicate of dotnet/roslyn-analyzers#4914). It is not fixed by #56414 / #56580 ("Reduce CA1508 analysis cost for local-function calls"). I applied that change to release/11.0.1xx and the repro below was still running after 15 CPU-minutes.

Repro

A class library (net10.0, Nullable enabled), referencing Microsoft.CodeAnalysis.NetAnalyzers 11.0.100, with dotnet_diagnostic.CA1508.severity = warning. Built with:

dotnet build -t:Rebuild -p:RunAnalyzersDuringBuild=true -p:ReportAnalyzer=true -p:UseSharedCompilation=false -v:detailed
Repro.cs (one method, two recursive static local functions)
using System;
using System.Collections.Generic;

namespace Repro;

public abstract class Shape { }

public sealed class StructShape : Shape
{
    public Guid Id { get; set; }
}

public sealed class ListShape : Shape
{
    public Shape? Element { get; set; }
}

public sealed class EnumShape : Shape
{
    public Guid Id { get; set; }
}

public sealed class Header
{
    public Shape? Shape { get; set; }
}

public sealed class Field
{
    public Shape? Shape { get; set; }
    public List<Header>? Headers { get; set; }
}

public sealed class StructDef
{
    public Guid Id { get; set; }
    public List<Field>? Fields { get; set; }
}

public sealed class Operation
{
    public List<Field>? Inputs { get; set; }
    public Shape? Output { get; set; }
    public bool Broken { get; set; }
}

public sealed class Schema
{
    public List<Operation>? Operations { get; set; }
    public List<StructDef>? Structs { get; set; }
    public Dictionary<Guid, StructDef>? StructMap { get; set; }
    public HashSet<Guid>? EnumIds { get; set; }
}

public static class SchemaChecker
{
    public static int Check(Schema schema, bool markBroken)
    {
        var count = 0;
        var structIds = new HashSet<Guid>();
        var enumIds = new HashSet<Guid>();

        if (schema.Operations != null)
        {
            foreach (var op in schema.Operations)
            {
                if (op.Inputs != null)
                {
                    foreach (var input in op.Inputs)
                    {
                        Collect(input.Shape, structIds, enumIds, schema.StructMap, schema.EnumIds);
                    }
                }

                Collect(op.Output, structIds, enumIds, schema.StructMap, schema.EnumIds);
                count++;
            }
        }

        var marker = new object();
        if (marker == null)
        {
            count--;
        }

        var bad = new HashSet<Guid>();
        if (schema.Structs != null)
        {
            foreach (var s in schema.Structs)
            {
                if (!structIds.Remove(s.Id))
                {
                    _ = bad.Add(s.Id);
                }
            }
        }

#if !SMALL
        if (schema.Operations != null && markBroken && bad.Count > 0)
        {
            foreach (var op in schema.Operations)
            {
                if (op.Broken)
                {
                    continue;
                }

                if (Uses([], schema.StructMap, op.Output, bad))
                {
                    op.Broken = true;
                    continue;
                }

                if (op.Inputs != null)
                {
                    foreach (var input in op.Inputs)
                    {
                        if (Uses([], schema.StructMap, input.Shape, bad))
                        {
                            op.Broken = true;
                        }
                    }
                }
            }
        }

#endif

        return count;

#if !SMALL
        static bool Uses(HashSet<Guid> visited, Dictionary<Guid, StructDef>? map, Shape? shape, HashSet<Guid> ids)
        {
            if (shape is StructShape st)
            {
                if (!visited.Add(st.Id))
                {
                    return false;
                }

                if (ids.Contains(st.Id))
                {
                    return true;
                }

                if (map?.TryGetValue(st.Id, out var def) == true && def.Fields != null)
                {
                    foreach (var field in def.Fields)
                    {
                        if (Uses(visited, map, field.Shape, ids))
                        {
                            return true;
                        }

                        if (field.Headers != null)
                        {
                            foreach (var header in field.Headers)
                            {
                                if (Uses(visited, map, header.Shape, ids))
                                {
                                    return true;
                                }
                            }
                        }
                    }
                }
            }

            return shape is ListShape list && Uses(visited, map, list.Element, ids);
        }
#endif

        static void Collect(Shape? shape, HashSet<Guid> structIds, HashSet<Guid> enumIds, Dictionary<Guid, StructDef>? map, HashSet<Guid>? knownEnums)
        {
            if (shape is StructShape st)
            {
                if (structIds.Add(st.Id))
                {
                    if (map?.TryGetValue(st.Id, out var def) == true && def.Fields != null)
                    {
                        foreach (var field in def.Fields)
                        {
                            Collect(field.Shape, structIds, enumIds, map, knownEnums);

                            if (field.Headers != null)
                            {
                                foreach (var header in field.Headers)
                                {
                                    Collect(header.Shape, structIds, enumIds, map, knownEnums);
                                }
                            }
                        }
                    }
                }
            }
            else if (shape is EnumShape en && knownEnums?.Contains(en.Id) == true)
            {
                _ = enumIds.Add(en.Id);
            }
            else if (shape is ListShape list)
            {
                Collect(list.Element, structIds, enumIds, map, knownEnums);
            }
        }
    }
}

Define SMALL to compile out the second recursive function (Uses) and its call sites.

Variant Analyzer Wall CA1508 time CA1508 warnings
SMALL 11.0.100 (NuGet) 3,902 s 3,883 s 1 (marker == null is always false)
SMALL 11.0.1xx + proposed fix 7 s 0.66 s same 1
SMALL 11.0.1xx + #56414 + proposed fix 44 s 4.9 s same 1
full 11.0.100 (NuGet) not finished after 15 CPU-min – –
full 11.0.1xx + #56414 not finished after 15 CPU-min – –
full 11.0.1xx + #56414 + proposed fix 56 s 7.7 s 1 (same marker line)
full* 11.0.1xx + proposed fix 35 s 4.2 s 0
full* 11.0.100 + max_interprocedural_lambda_or_local_function_call_chain = 0 40 s 2.4 s 0
full* CA1508 disabled 45 s 0 0

* Measured before the marker check (the one intentional CA1508 hit) was added to the file, so 0 warnings is the expected result there.

Measured at below-normal priority on a machine busy with other builds, so absolute times are noisy. The gap between rows is not. "11.0.1xx" is release/11.0.1xx built from source; I could not build main locally because its SDK 12 alpha would not download.

Analysis

On the original (private) code base, where one method hung the compiler for more than 100 CPU-minutes, a 60 s CPU sample of the stuck compiler showed this hot path:
AvoidDeadConditionalCode → ValueContentAnalysis.TryGetOrComputeResult → PointsToAnalysis.TryGetOrComputeResult → DataFlowOperationVisitor.VisitInvocation_LambdaOrDelegateOrLocalFunction → PerformInterproceduralAnalysis → (nested several levels) → AnalysisEntityMapAbstractDomain<T>.Merge → AnalysisEntity.WithMergedInstanceLocation → SetAbstractDomain<T>.Merge → ImmutableHashSet.Union. About 94% of the busy thread's time is spent waiting for GC (Thread.PollGCWorker). The analysis logic itself accounts for under 1% exclusive time.

In DataFlowOperationVisitor.PerformInterproceduralAnalysis:

  • Lambdas and local functions are always analyzed context-sensitively, whatever InterproceduralAnalysisKind is. Only max_interprocedural_lambda_or_local_function_call_chain (default 3) bounds the depth.
  • The recursion guard checks MethodsBeingAnalyzed.Add(DataFlowAnalysisContext). A recursive call carries a different analysis state, so it creates a new context and the guard never fires.
  • So every recursive call site is analyzed again down to the depth limit. With k recursive call sites and the default depth of 3, one analysis of a call can fan out into roughly k^3 nested analyses (an estimate from reading the code, not measured). The enclosing loops then repeat this on every fixed-point iteration, until the state stops changing. Each join also allocates new entities and merged location sets (WithMergedInstanceLocation), which is where the GC load comes from.

Workaround

dotnet_code_quality.CA1508.max_interprocedural_lambda_or_local_function_call_chain = 0

Activity

  1. added
    untriaged
    on Nov 23, 2026
  2. locked and limited conversation to collaborators on Nov 23, 2026
  3. unlocked this conversation on Nov 23, 2026
  4. github-actions commented on Nov 23, 2026

    @github-actions
    Contributor

    🎯 Agentic Issue Triage

    Triage Assessment:

    ➡️ Summary: CA1508 analysis takes an hour or more on a method with recursive local functions called from nested foreach loops. Follow up by profiling the dataflow analysis on the provided repro.

    Generated by 🏷️ Issue Triage for #57327 · copilot · auto (Claude Sonnet 5.5) · ~15 AIC · ⌖ ~2 AIC · ⊞ 15.5K · ◷

  5. removed their assignment
    on Nov 27, 2026
  6. Genbox commented on Nov 28, 2026

    @Genbox

    I've had this issue too. Took 20 minutes for the analyzer to complete. The fix in the PR works, but also removes a valid warning. @MaceWindu this code should give a warning, but doesn't with your PR.

    static bool Check()
    {
        static void Assign(object? next, out int value)
        {
            value = 3;
            if (next != null)
                Assign(null, out value);
        }
    
        Assign(new object(), out int x);
        return x == 3; //Should warn here
    }
  7. Genbox commented on Nov 28, 2026

    @Genbox

    For everyone else, a temp workaround is to put this in an .editorconfig:

    dotnet_code_quality.CA1508.max_interprocedural_lambda_or_local_function_call_chain = 1
    
  8. MaceWindu commented on Nov 28, 2026

    @MaceWindu
    Author

    @Genbox thanks, confirmed. The first version of #57328 bailed out on every recursive call, so the inner Assign(null, out value) was never analyzed and value became unknown.

    Fixed in 87ba0c9: one recursive call is now analyzed before bailing out. Your snippet and a mutual-recursion variant (A -> B -> A) are added as tests that expect the x == 3 diagnostic.

    Cost: the repro in this issue now takes about 1–2 minutes in CA1508 instead of 12–14 s with the first version (and over an hour before). Most of that is repeated analysis of identical calls; I'm looking at caching it in a follow-up PR.

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