You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@groovy.apache.org by su...@apache.org on 2026/07/26 07:35:16 UTC

(groovy) branch GROOVY-12191 updated: GROOVY-12191: Address PR review and add index hierarchy for SwitchPoint fan-out

This is an automated email from the ASF dual-hosted git repository.

asf-gitbox-commits pushed a commit to branch GROOVY-12191
in repository https://gitbox.apache.org/repos/asf/groovy.git


The following commit(s) were added to refs/heads/GROOVY-12191 by this push:
     new f48ab19256 GROOVY-12191: Address PR review and add index hierarchy for SwitchPoint fan-out
f48ab19256 is described below

commit f48ab19256f6ae9888dd48bb34cd770dd6a05958
Author: Daniel Sun <su...@apache.org>
AuthorDate: Sun Jul 26 16:30:22 2026 +0900

    GROOVY-12191: Address PR review and add index hierarchy for SwitchPoint fan-out
---
 .../groovy/runtime/indy/ClassHierarchyIndex.java   | 161 +++++++++++++++++++++
 .../groovy/runtime/indy/IndyInvalidation.java      |  46 +++---
 .../runtime/indy/SwitchPointInvalidator.java       |   4 +-
 .../apache/groovy/runtime/indy/package-info.java   |  17 ++-
 .../org/codehaus/groovy/reflection/ClassInfo.java  |  20 ++-
 .../codehaus/groovy/vmplugin/v8/IndyInterface.java |  56 ++++---
 src/test/groovy/bugs/Groovy12191.groovy            |  33 ++++-
 .../runtime/indy/ClassHierarchyIndexTest.groovy    | 160 ++++++++++++++++++++
 .../runtime/indy/IndyInvalidationTest.groovy       | 107 +++++++++++++-
 .../vmplugin/v8/IndyScopedSwitchPointTest.groovy   |  64 ++++++++
 10 files changed, 610 insertions(+), 58 deletions(-)

diff --git a/src/main/java/org/apache/groovy/runtime/indy/ClassHierarchyIndex.java b/src/main/java/org/apache/groovy/runtime/indy/ClassHierarchyIndex.java
new file mode 100644
index 0000000000..5b502c63bd
--- /dev/null
+++ b/src/main/java/org/apache/groovy/runtime/indy/ClassHierarchyIndex.java
@@ -0,0 +1,161 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.groovy.runtime.indy;
+
+import groovy.transform.Internal;
+import org.apache.groovy.util.concurrent.ManagedIdentityConcurrentMap;
+import org.codehaus.groovy.reflection.ClassInfo;
+import org.codehaus.groovy.util.ManagedConcurrentLinkedQueue;
+import org.codehaus.groovy.util.ReferenceBundle;
+
+import java.io.Serializable;
+import java.lang.reflect.Array;
+import java.util.Collection;
+import java.util.LinkedHashSet;
+import java.util.Set;
+
+/**
+ * Ancestor → descendant {@link ClassInfo} index for scoped SwitchPoint fan-out
+ * (GROOVY-12191).
+ * <p>
+ * Built once per {@link ClassInfo} at construction: each type is registered under
+ * every MOP-relevant strict supertype (superclass chain, transitive interfaces,
+ * and the full JLS array-covariance lattice). Hierarchy invalidation for type
+ * {@code T} then walks only the descendants of {@code T} —
+ * {@code O(|subtypes of T|)} — instead of scanning every loaded
+ * {@code ClassInfo} with {@code isAssignableFrom}.
+ * <p>
+ * Keys and values are weakly held so the index does not pin classes or
+ * {@code ClassInfo} instances after they become unreachable.
+ * <p>
+ * <strong>Not a public API.</strong> Wired only from {@link ClassInfo} and
+ * {@link IndyInvalidation}.
+ *
+ * @since 6.0.0
+ */
+@Internal
+public final class ClassHierarchyIndex {
+
+    private static final ReferenceBundle WEAK = ReferenceBundle.getWeakBundle();
+
+    /**
+     * Ancestor class (weak, identity) → weakly-reachable descendant ClassInfos.
+     * A type is never registered under itself.
+     */
+    private static final ManagedIdentityConcurrentMap<Class<?>, ManagedConcurrentLinkedQueue<ClassInfo>> BY_ANCESTOR =
+            new ManagedIdentityConcurrentMap<>(256);
+
+    private ClassHierarchyIndex() {
+    }
+
+    /**
+     * Indexes {@code info} under every strict supertype of its class.
+     * Called exactly once from the {@link ClassInfo} constructor while the
+     * {@link Class} is strongly reachable.
+     *
+     * @param info the newly constructed ClassInfo
+     */
+    @Internal
+    public static void register(final ClassInfo info) {
+        Class<?> type = info.getTheClass();
+        if (type == null) {
+            return;
+        }
+        Set<Class<?>> ancestors = new LinkedHashSet<>();
+        collectStrictSupertypes(type, ancestors);
+        for (Class<?> ancestor : ancestors) {
+            addUnder(ancestor, info);
+        }
+    }
+
+    private static void addUnder(final Class<?> ancestor, final ClassInfo info) {
+        ManagedConcurrentLinkedQueue<ClassInfo> queue =
+                BY_ANCESTOR.applyIfAbsent(ancestor, k -> new ManagedConcurrentLinkedQueue<>(WEAK));
+        queue.add(info);
+    }
+
+    /**
+     * Appends every ClassInfo registered as a descendant of {@code ancestor}
+     * (not including {@code ancestor} itself) to {@code out}. Empty when no
+     * subtypes have been indexed (e.g. finals, primitives, or unused parents).
+     *
+     * @param ancestor the root of the fan-out
+     * @param out      destination collection
+     */
+    @Internal
+    public static void collectDescendants(final Class<?> ancestor, final Collection<ClassInfo> out) {
+        ManagedConcurrentLinkedQueue<ClassInfo> queue = BY_ANCESTOR.get(ancestor);
+        if (queue == null) {
+            return;
+        }
+        for (ClassInfo info : queue) {
+            // Iterator of ManagedConcurrentLinkedQueue skips cleared weak refs.
+            out.add(info);
+        }
+    }
+
+    /**
+     * Collects every strict supertype {@code S} of {@code type} such that
+     * {@code S.isAssignableFrom(type) && S != type}, computed structurally from
+     * the type's hierarchy (no global ClassInfo scan).
+     * <p>
+     * Array types follow the JLS covariance lattice: for component {@code C},
+     * every supertype {@code S} of {@code C} (including {@code C}) yields
+     * {@code S[]} as a supertype of {@code C[]}, plus {@code Object},
+     * {@code Cloneable}, and {@code Serializable}.
+     *
+     * @param type the type whose strict supertypes are collected
+     * @param out  destination set
+     */
+    static void collectStrictSupertypes(final Class<?> type, final Set<Class<?>> out) {
+        if (type == null || type == Object.class || type.isPrimitive()) {
+            return;
+        }
+        if (type.isArray()) {
+            out.add(Object.class);
+            out.add(Cloneable.class);
+            out.add(Serializable.class);
+            Class<?> component = type.getComponentType();
+            // {component} ∪ strict-supers(component) — each lifted to a 1-D array.
+            Set<Class<?>> componentLattice = new LinkedHashSet<>();
+            componentLattice.add(component);
+            collectStrictSupertypes(component, componentLattice);
+            for (Class<?> componentType : componentLattice) {
+                Class<?> arrayOf = Array.newInstance(componentType, 0).getClass();
+                if (arrayOf != type) {
+                    out.add(arrayOf);
+                }
+            }
+            return;
+        }
+        Class<?> superclass = type.getSuperclass();
+        if (superclass != null) {
+            out.add(superclass);
+            collectStrictSupertypes(superclass, out);
+        } else if (type.isInterface()) {
+            // Class.getSuperclass() is null for interfaces; assignability still
+            // treats Object as a supertype (Object.isAssignableFrom(iface) == true).
+            out.add(Object.class);
+        }
+        for (Class<?> iface : type.getInterfaces()) {
+            out.add(iface);
+            collectStrictSupertypes(iface, out);
+        }
+    }
+}
diff --git a/src/main/java/org/apache/groovy/runtime/indy/IndyInvalidation.java b/src/main/java/org/apache/groovy/runtime/indy/IndyInvalidation.java
index 3e11e70dbc..979e5f8e0c 100644
--- a/src/main/java/org/apache/groovy/runtime/indy/IndyInvalidation.java
+++ b/src/main/java/org/apache/groovy/runtime/indy/IndyInvalidation.java
@@ -24,9 +24,7 @@ import org.codehaus.groovy.runtime.NullObject;
 
 import java.lang.invoke.MethodHandle;
 import java.lang.invoke.SwitchPoint;
-import java.lang.reflect.Modifier;
 import java.util.ArrayList;
-import java.util.Collection;
 import java.util.List;
 import java.util.concurrent.atomic.AtomicLong;
 import java.util.logging.Level;
@@ -45,6 +43,11 @@ import java.util.logging.Logger;
  * guard, matching the pre-6.0 monomorphic shape while avoiding global deopt on
  * unrelated MetaClass churn.
  * <p>
+ * <b>Scalability:</b> hierarchy fan-out is {@code O(|loaded subtypes of T|)}
+ * via {@link ClassHierarchyIndex} (built once per {@link ClassInfo}), not
+ * {@code O(|all loaded classes|)}. Category bulk remains a full ClassInfo walk
+ * with cheap no-op detaches for domains that never allocated a SwitchPoint.
+ * <p>
  * Install guards with
  * {@link #guardWithMopSwitchPoints(MethodHandle, MethodHandle, Object)}.
  * Optional stats logging: {@code -Dgroovy.indy.invalidation.stats=true}.
@@ -111,36 +114,33 @@ public final class IndyInvalidation {
 
     /**
      * Invalidates SwitchPoints for {@code type} and all loaded classes assignable
-     * from {@code type}. Final classes short-circuit to a single invalidation.
-     * Non-final types batch via {@link SwitchPoint#invalidateAll(SwitchPoint[])}.
+     * from {@code type}. One path for every kind of type: detach the root domain,
+     * then detach every descendant registered in {@link ClassHierarchyIndex}
+     * (empty for leaves such as finals and primitives; non-empty for classes,
+     * interfaces, and array covariance including {@code Object[]} /
+     * interface-component arrays). Batched through
+     * {@link SwitchPoint#invalidateAll(SwitchPoint[])}.
      *
      * @param type the root of the invalidation fan-out
      */
     public static void invalidateClassHierarchy(final Class<?> type) {
         ClassInfo root = ClassInfo.getClassInfo(type);
-        if (cannotHaveLoadedSubtypes(type)) {
-            root.invalidateIndySwitchPoint();
-            return;
-        }
-
         List<SwitchPoint> batch = new ArrayList<>();
         try {
             SwitchPoint rootSp = root.detachLiveIndySwitchPoint();
             if (rootSp != null) {
                 batch.add(rootSp);
             }
-            Collection<ClassInfo> all = ClassInfo.getAllClassInfo();
-            for (ClassInfo info : all) {
-                Class<?> loaded = info.getTheClass();
-                if (loaded != null && loaded != type && type.isAssignableFrom(loaded)) {
-                    SwitchPoint sp = info.detachLiveIndySwitchPoint();
-                    if (sp != null) {
-                        batch.add(sp);
-                    }
+            List<ClassInfo> descendants = new ArrayList<>();
+            ClassHierarchyIndex.collectDescendants(type, descendants);
+            for (ClassInfo info : descendants) {
+                SwitchPoint sp = info.detachLiveIndySwitchPoint();
+                if (sp != null) {
+                    batch.add(sp);
                 }
             }
         } finally {
-            // Always invalidate detached SPs even if the scan fails mid-way.
+            // Always invalidate detached SPs even if the walk fails mid-way.
             invalidateBatch(batch);
         }
     }
@@ -148,6 +148,8 @@ public final class IndyInvalidation {
     /**
      * Detaches and invalidates every live per-class SwitchPoint.
      * Used for category enter/leave and unattributed MetaClass changes.
+     * Walks all loaded {@link ClassInfo} instances; {@code detachLive} is a
+     * cheap no-op when a domain never allocated a SwitchPoint.
      */
     public static void invalidateAllLoadedClassSwitchPoints() {
         List<SwitchPoint> batch = new ArrayList<>();
@@ -182,14 +184,6 @@ public final class IndyInvalidation {
         SwitchPoint.invalidateAll(batch.toArray(EMPTY_SWITCH_POINTS));
     }
 
-    /**
-     * {@code final} classes and primitives cannot have subclasses. Interfaces
-     * and non-final classes may have loaded implementors/subtypes.
-     */
-    private static boolean cannotHaveLoadedSubtypes(final Class<?> type) {
-        return type.isPrimitive() || (Modifier.isFinal(type.getModifiers()) && !type.isInterface());
-    }
-
     /**
      * Resolves the class used for the per-class SwitchPoint domain of a receiver.
      * {@code null} maps to {@link NullObject}; a {@link Class} receiver uses itself.
diff --git a/src/main/java/org/apache/groovy/runtime/indy/SwitchPointInvalidator.java b/src/main/java/org/apache/groovy/runtime/indy/SwitchPointInvalidator.java
index bc279301ed..18487ef955 100644
--- a/src/main/java/org/apache/groovy/runtime/indy/SwitchPointInvalidator.java
+++ b/src/main/java/org/apache/groovy/runtime/indy/SwitchPointInvalidator.java
@@ -55,9 +55,11 @@ public final class SwitchPointInvalidator {
     private final AtomicInteger retirementCount = new AtomicInteger();
 
     /**
-     * Creates an invalidator.
+     * Creates an invalidator with no live SwitchPoint until the first
+     * {@link #getSwitchPoint()} call. Field initializers own all state.
      */
     public SwitchPointInvalidator() {
+        // Intentionally empty: AtomicReference / AtomicInteger fields are ready.
     }
 
     /**
diff --git a/src/main/java/org/apache/groovy/runtime/indy/package-info.java b/src/main/java/org/apache/groovy/runtime/indy/package-info.java
index 6e55043f4f..b234c339a8 100644
--- a/src/main/java/org/apache/groovy/runtime/indy/package-info.java
+++ b/src/main/java/org/apache/groovy/runtime/indy/package-info.java
@@ -21,9 +21,20 @@
  * Scoped invokedynamic SwitchPoint utilities for the Groovy MOP (GROOVY-12191).
  * <p>
  * One SwitchPoint per class (on {@link org.codehaus.groovy.reflection.ClassInfo}):
- * MetaClass changes retire that class and loaded subtypes; category enter/leave
- * bulk-retires all loaded class SwitchPoints. Linked call sites carry a single
- * guard — no process-wide MOP SwitchPoint on the hot path.
+ * MetaClass changes retire that class and loaded subtypes (including array-type
+ * fan-out for {@code Object[]} and similar); category enter/leave bulk-retires
+ * loaded class SwitchPoints. Linked call sites carry a single guard — no
+ * process-wide MOP SwitchPoint on the hot path.
+ * <p>
+ * Hierarchy fan-out is indexed by {@link ClassHierarchyIndex} so typed MetaClass
+ * invalidation cost is proportional to the number of loaded subtypes of the
+ * changed type, not to the total number of loaded classes.
+ * <p>
+ * External code that previously guarded on
+ * {@link org.codehaus.groovy.vmplugin.v8.IndyInterface#switchPoint} must migrate
+ * to {@link org.apache.groovy.runtime.indy.IndyInvalidation#guardWithMopSwitchPoints}:
+ * the legacy field is rotated only on category / {@code invalidateCallSites()}
+ * bulk events, not on per-class MetaClass changes.
  *
  * @since 6.0.0
  */
diff --git a/src/main/java/org/codehaus/groovy/reflection/ClassInfo.java b/src/main/java/org/codehaus/groovy/reflection/ClassInfo.java
index 005a93e10c..0c7c30956e 100644
--- a/src/main/java/org/codehaus/groovy/reflection/ClassInfo.java
+++ b/src/main/java/org/codehaus/groovy/reflection/ClassInfo.java
@@ -26,6 +26,7 @@ import groovy.lang.MetaClass;
 import groovy.lang.MetaClassRegistry;
 import groovy.lang.MetaMethod;
 import groovy.transform.Internal;
+import org.apache.groovy.runtime.indy.ClassHierarchyIndex;
 import org.apache.groovy.runtime.indy.IndyInvalidation;
 import org.apache.groovy.runtime.indy.SwitchPointInvalidator;
 import org.apache.groovy.util.concurrent.ManagedIdentityConcurrentMap;
@@ -119,6 +120,9 @@ public class ClassInfo implements Finalizable {
         this.classRef = new WeakReference<Class<?>>(klazz);
         cachedClassRef = new LazyCachedClassRef(softBundle, this);
         artifactClassLoader = new LazyClassLoaderRef(softBundle, this);
+        // Index under MOP-relevant ancestors so hierarchy SwitchPoint fan-out is
+        // O(descendants) rather than O(all loaded ClassInfos) (GROOVY-12191).
+        ClassHierarchyIndex.register(this);
     }
 
     /**
@@ -136,12 +140,18 @@ public class ClassInfo implements Finalizable {
      * (and subtype SwitchPoints via hierarchy fan-out).
      * Called when metaclass modifications occur (e.g., adding methods to an {@code ExpandoMetaClass}).
      * <p>
-     * Call sites linked against this class or its subtypes re-link (GROOVY-12191);
-     * unrelated classes keep their optimized targets. Category enter/leave bulk-invalidates
-     * class SwitchPoints via {@link org.codehaus.groovy.vmplugin.VMPlugin#invalidateCallSites()}.
+     * <strong>Behavioral change in 6.0 (GROOVY-12191):</strong> this method no longer
+     * triggers a process-wide call-site flush. It scopes invalidation to this class
+     * and loaded subtypes/implementors only. Callers that previously relied on
+     * {@code incVersion()} as a global “flush everything” hammer should invoke
+     * {@link org.codehaus.groovy.vmplugin.VMPlugin#invalidateCallSites()} (or
+     * {@link IndyInvalidation#invalidateCategory()}) explicitly when a bulk flush
+     * is required. Unrelated classes keep their optimized targets.
      * <p>
-     * SwitchPoint policy is owned by {@link IndyInvalidation}; this method only bumps
-     * generation then delegates hierarchy invalidation.
+     * Category enter/leave still bulk-invalidates class SwitchPoints via
+     * {@link org.codehaus.groovy.vmplugin.VMPlugin#invalidateCallSites()}.
+     * SwitchPoint policy is owned by {@link IndyInvalidation}; this method only
+     * bumps generation then delegates hierarchy invalidation.
      */
     public void incVersion() {
         version.incrementAndGet();
diff --git a/src/main/java/org/codehaus/groovy/vmplugin/v8/IndyInterface.java b/src/main/java/org/codehaus/groovy/vmplugin/v8/IndyInterface.java
index 969f8d20d4..1cc099ee96 100644
--- a/src/main/java/org/codehaus/groovy/vmplugin/v8/IndyInterface.java
+++ b/src/main/java/org/codehaus/groovy/vmplugin/v8/IndyInterface.java
@@ -216,21 +216,24 @@ public class IndyInterface {
     }
 
     /**
-     * Legacy process-wide SwitchPoint retained for binary compatibility.
+     * Legacy process-wide SwitchPoint retained for binary compatibility only.
      * <p>
      * <strong>Behavioral change in 6.0 (GROOVY-12191):</strong> MetaClass changes
      * are scoped per {@link org.codehaus.groovy.reflection.ClassInfo}. This field
-     * is no longer used as the MOP guard on linked call sites. It is rotated when
-     * {@link #invalidateSwitchPoints()} runs (category enter/leave /
-     * {@code VMPlugin.invalidateCallSites()}) so external readers that still
-     * observe the field see an invalidation. Call sites must use
-     * {@link IndyInvalidation#guardWithMopSwitchPoints} instead.
+     * is <em>not</em> the MOP guard on linked call sites and is <em>not</em>
+     * rotated on per-class MetaClass changes. It is rotated only when
+     * {@link #invalidateSwitchPoints()} runs — i.e. category enter/leave and
+     * {@code VMPlugin.invalidateCallSites()} — so external observers of this
+     * field still see those bulk events. Guarding a site on this field alone
+     * will <strong>silently miss</strong> type-scoped MetaClass invalidations;
+     * migrate to {@link IndyInvalidation#guardWithMopSwitchPoints}.
      *
      * @see IndyInvalidation
-     * @deprecated Use {@link IndyInvalidation#guardWithMopSwitchPoints}; this field
-     *             is not the call-site MOP guard.
+     * @deprecated since 6.0.0 — use {@link IndyInvalidation#guardWithMopSwitchPoints};
+     *             this field is not the call-site MOP guard and is not rotated on
+     *             per-class MetaClass changes.
      */
-    @Deprecated
+    @Deprecated(since = "6.0.0", forRemoval = false)
     protected static volatile SwitchPoint switchPoint = new SwitchPoint();
 
     static {
@@ -256,20 +259,28 @@ public class IndyInterface {
     /**
      * Category enter/leave and {@code VMPlugin.invalidateCallSites()}.
      * Bulk-invalidates every loaded class SwitchPoint so sites re-link under the
-     * new category state, and rotates the legacy {@link #switchPoint} field.
+     * new category state, and rotates the legacy {@link #switchPoint} field under
+     * {@code synchronized (IndyInterface.class)} so concurrent bulk invalidations
+     * cannot orphan a live SwitchPoint an external reader just observed.
      * Per-class MetaClass changes use {@link IndyInvalidation#invalidateClass(Class)}
-     * (or {@link org.codehaus.groovy.reflection.ClassInfo#incVersion()}) instead.
+     * (or {@link org.codehaus.groovy.reflection.ClassInfo#incVersion()}) instead
+     * and do <em>not</em> rotate {@link #switchPoint}.
      */
     protected static void invalidateSwitchPoints() {
         if (LOG_ENABLED) {
             LOG.info("invalidating class SwitchPoints for category / invalidateCallSites");
         }
         IndyInvalidation.invalidateCategory();
-        // Binary-compat: rotate the legacy field so external observers still see a change.
-        SwitchPoint old = switchPoint;
-        switchPoint = new SwitchPoint();
-        if (old != null && !old.hasBeenInvalidated()) {
-            SwitchPoint.invalidateAll(new SwitchPoint[]{old});
+        // Binary-compat: rotate the legacy field so external observers of bulk
+        // invalidation still see a change. Synchronized so two concurrent callers
+        // cannot leave a reader holding a live SwitchPoint that will never be
+        // invalidated again (pre-6.0 shape; addresses Sonar S3077 / GROOVY-12191).
+        synchronized (IndyInterface.class) {
+            SwitchPoint old = switchPoint;
+            switchPoint = new SwitchPoint();
+            if (old != null && !old.hasBeenInvalidated()) {
+                SwitchPoint.invalidateAll(new SwitchPoint[]{old});
+            }
         }
     }
 
@@ -491,9 +502,16 @@ public class IndyInterface {
      * via {@code doMethodInvoke}, {@code GroovyRuntimeException} unwrapping via
      * {@code ScriptBytecodeAdapter}). The handle bound to the wrapper has the
      * same {@code (Object[])Object} shape for every call site, arity, and
-     * primitive pattern, so cold dispatch spins no per-shape LambdaForms. On a
-     * failed validity check it takes the standard re-selection route, exactly
-     * like a failed guard in the full chain.
+     * primitive pattern, so cold dispatch spins no per-shape LambdaForms.
+     * <p>
+     * On a failed validity check (or after the reflective-hit promotion
+     * threshold), re-selection uses {@code fallback(..., allowColdReflection=false)}
+     * and writes the full wrapper (or {@link #NULL_METHOD_HANDLE_WRAPPER}) into
+     * the callsite PIC. That prevents an always-invalid class-domain SwitchPoint
+     * from recursing through cold {@code tryBuild → invokeColdReflective}
+     * (GROOVY-12191). This is a deliberate cold-tier promotion change beyond
+     * pure SwitchPoint scoping: validity failure no longer re-enters the cold
+     * reflective path on the same miss.
      */
     private static Object invokeColdReflective(ColdReflectiveMethodHandleWrapper cold, Object[] arguments) throws Throwable {
         if (cold.isValidFor(arguments)) {
diff --git a/src/test/groovy/bugs/Groovy12191.groovy b/src/test/groovy/bugs/Groovy12191.groovy
index a792f09d1d..2ee4500d52 100644
--- a/src/test/groovy/bugs/Groovy12191.groovy
+++ b/src/test/groovy/bugs/Groovy12191.groovy
@@ -18,7 +18,6 @@
  */
 package bugs
 
-import org.apache.groovy.runtime.indy.IndyInvalidation
 import org.codehaus.groovy.reflection.ClassInfo
 import org.junit.jupiter.api.Test
 
@@ -158,6 +157,38 @@ final class Groovy12191 {
         assertFalse(hotSp.hasBeenInvalidated())
     }
 
+    @Test
+    void objectArrayMetaClassChange_invalidatesStringArraySwitchPoint() {
+        // Array types are final, yet Object[] is the MOP supertype of reference
+        // arrays — scoped invalidation must fan out (GROOVY-12191 review).
+        SwitchPoint stringArraySp = ClassInfo.getClassInfo(String[]).indySwitchPoint
+        assertFalse(stringArraySp.hasBeenInvalidated())
+
+        def emc = new ExpandoMetaClass(Object[], true, true)
+        emc.initialize()
+        GroovySystem.metaClassRegistry.setMetaClass(Object[], emc)
+        try {
+            assertTrue(stringArraySp.hasBeenInvalidated(),
+                    'Object[] MetaClass change must retire String[] SwitchPoint')
+        } finally {
+            GroovySystem.metaClassRegistry.removeMetaClass(Object[])
+        }
+    }
+
+    @Test
+    void incVersion_scopesToClassHierarchy_notGlobal() {
+        SwitchPoint hotSp = ClassInfo.getClassInfo(TypeD).indySwitchPoint
+        SwitchPoint targetSp = ClassInfo.getClassInfo(TypeC).indySwitchPoint
+        assertFalse(hotSp.hasBeenInvalidated())
+        assertFalse(targetSp.hasBeenInvalidated())
+
+        ClassInfo.getClassInfo(TypeC).incVersion()
+
+        assertTrue(targetSp.hasBeenInvalidated())
+        assertFalse(hotSp.hasBeenInvalidated(),
+                'incVersion must not act as a process-wide flush (GROOVY-12191)')
+    }
+
     static class TypeA {}
     static class TypeB {
         String id() { 'B' }
diff --git a/src/test/groovy/org/apache/groovy/runtime/indy/ClassHierarchyIndexTest.groovy b/src/test/groovy/org/apache/groovy/runtime/indy/ClassHierarchyIndexTest.groovy
new file mode 100644
index 0000000000..df90a367c8
--- /dev/null
+++ b/src/test/groovy/org/apache/groovy/runtime/indy/ClassHierarchyIndexTest.groovy
@@ -0,0 +1,160 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.groovy.runtime.indy
+
+import org.codehaus.groovy.reflection.ClassInfo
+import org.junit.jupiter.api.Test
+
+import java.lang.invoke.SwitchPoint
+
+import static org.junit.jupiter.api.Assertions.assertFalse
+import static org.junit.jupiter.api.Assertions.assertTrue
+
+/**
+ * Structural and integration tests for {@link ClassHierarchyIndex}.
+ */
+final class ClassHierarchyIndexTest {
+
+    @Test
+    void collectStrictSupertypes_classHierarchy() {
+        def supers = new LinkedHashSet<Class<?>>()
+        ClassHierarchyIndex.collectStrictSupertypes(IndexChild, supers)
+        assertTrue(supers.contains(IndexParent))
+        assertTrue(supers.contains(Object))
+        assertTrue(supers.contains(IndexMarker))
+        assertFalse(supers.contains(IndexChild))
+        assertFalse(supers.contains(IndexSibling))
+    }
+
+    @Test
+    void collectStrictSupertypes_arrayCovariance() {
+        def supers = new LinkedHashSet<Class<?>>()
+        ClassHierarchyIndex.collectStrictSupertypes(String[], supers)
+        assertTrue(supers.contains(Object[]), 'Object[] is a covariant super of String[]')
+        assertTrue(supers.contains(CharSequence[]), 'CharSequence[] via component interfaces')
+        assertTrue(supers.contains(Serializable[]))
+        assertTrue(supers.contains(Object))
+        assertTrue(supers.contains(Cloneable))
+        assertTrue(supers.contains(Serializable))
+        assertFalse(supers.contains(String[]))
+        assertFalse(supers.contains(Integer[]))
+    }
+
+    @Test
+    void collectStrictSupertypes_multiDimArray() {
+        def supers = new LinkedHashSet<Class<?>>()
+        ClassHierarchyIndex.collectStrictSupertypes(String[][], supers)
+        assertTrue(supers.contains(Object[][]))
+        assertTrue(supers.contains(Object[]), 'String[][] <: Object[]')
+        assertTrue(supers.contains(CharSequence[][]))
+        assertFalse(supers.contains(CharSequence[]), 'String[][] is not <: CharSequence[]')
+        assertFalse(supers.contains(String[][]))
+    }
+
+    @Test
+    void collectStrictSupertypes_primitiveArray() {
+        def supers = new LinkedHashSet<Class<?>>()
+        ClassHierarchyIndex.collectStrictSupertypes(int[], supers)
+        assertTrue(supers.contains(Object))
+        assertTrue(supers.contains(Cloneable))
+        assertTrue(supers.contains(Serializable))
+        assertFalse(supers.contains(Object[]), 'int[] is not <: Object[]')
+        assertFalse(supers.contains(long[]))
+    }
+
+    @Test
+    void index_registersDescendantsUnderAncestors() {
+        // Force ClassInfo construction (registers in the index).
+        ClassInfo.getClassInfo(IndexParent)
+        ClassInfo.getClassInfo(IndexChild)
+        ClassInfo.getClassInfo(IndexSibling)
+        ClassInfo.getClassInfo(IndexMarkerImpl)
+
+        def underParent = []
+        ClassHierarchyIndex.collectDescendants(IndexParent, underParent)
+        assertTrue(underParent.any { it.theClass == IndexChild })
+        assertFalse(underParent.any { it.theClass == IndexSibling })
+
+        def underMarker = []
+        ClassHierarchyIndex.collectDescendants(IndexMarker, underMarker)
+        assertTrue(underMarker.any { it.theClass == IndexChild || it.theClass == IndexMarkerImpl },
+                'implementors indexed under IndexMarker')
+    }
+
+    @Test
+    void index_arrayDescendants_underObjectArrayAndInterfaceArray() {
+        ClassInfo.getClassInfo(String[])
+        ClassInfo.getClassInfo(Integer[])
+        ClassInfo.getClassInfo(Object[])
+
+        def underObjectArray = []
+        ClassHierarchyIndex.collectDescendants(Object[], underObjectArray)
+        assertTrue(underObjectArray.any { it.theClass == String[] })
+        assertTrue(underObjectArray.any { it.theClass == Integer[] })
+
+        def underCharSeqArray = []
+        ClassHierarchyIndex.collectDescendants(CharSequence[], underCharSeqArray)
+        assertTrue(underCharSeqArray.any { it.theClass == String[] })
+        assertFalse(underCharSeqArray.any { it.theClass == Integer[] })
+    }
+
+    @Test
+    void invalidateViaIndex_fansOutWithoutMissingDescendants() {
+        SwitchPoint parentSp = ClassInfo.getClassInfo(IndexFanParent).indySwitchPoint
+        SwitchPoint childSp = ClassInfo.getClassInfo(IndexFanChild).indySwitchPoint
+        SwitchPoint otherSp = ClassInfo.getClassInfo(IndexFanOther).indySwitchPoint
+
+        IndyInvalidation.invalidateClassHierarchy(IndexFanParent)
+
+        assertTrue(parentSp.hasBeenInvalidated())
+        assertTrue(childSp.hasBeenInvalidated())
+        assertFalse(otherSp.hasBeenInvalidated())
+    }
+
+    @Test
+    void invalidateViaIndex_finalLeaf_emptyDescendantsStillRetiresRoot() {
+        // Finals have no indexed subtypes; single-path fan-out still retires the root.
+        SwitchPoint stringSp = ClassInfo.getClassInfo(String).indySwitchPoint
+        SwitchPoint siblingSp = ClassInfo.getClassInfo(IndexFanOther).indySwitchPoint
+        IndyInvalidation.invalidateClassHierarchy(String)
+        assertTrue(stringSp.hasBeenInvalidated())
+        assertFalse(siblingSp.hasBeenInvalidated())
+    }
+
+    @Test
+    void invalidateViaIndex_primitive_emptyDescendantsStillRetiresRoot() {
+        SwitchPoint intSp = ClassInfo.getClassInfo(int).indySwitchPoint
+        SwitchPoint siblingSp = ClassInfo.getClassInfo(IndexFanOther).indySwitchPoint
+        IndyInvalidation.invalidateClassHierarchy(int)
+        assertTrue(intSp.hasBeenInvalidated())
+        assertFalse(siblingSp.hasBeenInvalidated())
+    }
+
+    // --- fixtures ---
+
+    private static class IndexParent {}
+    private static final class IndexChild extends IndexParent implements IndexMarker {}
+    private static final class IndexSibling {}
+    private static interface IndexMarker {}
+    private static final class IndexMarkerImpl implements IndexMarker {}
+
+    private static class IndexFanParent {}
+    private static final class IndexFanChild extends IndexFanParent {}
+    private static final class IndexFanOther {}
+}
diff --git a/src/test/groovy/org/apache/groovy/runtime/indy/IndyInvalidationTest.groovy b/src/test/groovy/org/apache/groovy/runtime/indy/IndyInvalidationTest.groovy
index 9159d825f7..e4d105d8d6 100644
--- a/src/test/groovy/org/apache/groovy/runtime/indy/IndyInvalidationTest.groovy
+++ b/src/test/groovy/org/apache/groovy/runtime/indy/IndyInvalidationTest.groovy
@@ -91,7 +91,8 @@ final class IndyInvalidationTest {
     }
 
     @Test
-    void invalidateClassHierarchy_finalClass_skipsSubtypeScan() {
+    void invalidateClassHierarchy_finalClass_emptyDescendantsStillRetiresRoot() {
+        // Finals have no indexed subtypes; single-path fan-out still retires only the root.
         SwitchPoint stringSp = ClassInfo.getClassInfo(String).indySwitchPoint
         SwitchPoint siblingSp = ClassInfo.getClassInfo(ClassB).indySwitchPoint
         IndyInvalidation.invalidateClassHierarchy(String)
@@ -99,6 +100,106 @@ final class IndyInvalidationTest {
         assertFalse(siblingSp.hasBeenInvalidated())
     }
 
+    @Test
+    void invalidateClassHierarchy_objectArray_fansOutToReferenceArrays() {
+        // Arrays are final per Class.getModifiers(), but Object[] is still a
+        // MOP-relevant supertype of every reference array (GROOVY-12191 review).
+        SwitchPoint objectArraySp = ClassInfo.getClassInfo(Object[]).indySwitchPoint
+        SwitchPoint stringArraySp = ClassInfo.getClassInfo(String[]).indySwitchPoint
+        SwitchPoint integerArraySp = ClassInfo.getClassInfo(Integer[]).indySwitchPoint
+        SwitchPoint siblingSp = ClassInfo.getClassInfo(ClassB).indySwitchPoint
+        assertFalse(objectArraySp.hasBeenInvalidated())
+        assertFalse(stringArraySp.hasBeenInvalidated())
+
+        IndyInvalidation.invalidateClassHierarchy(Object[])
+
+        assertTrue(objectArraySp.hasBeenInvalidated())
+        assertTrue(stringArraySp.hasBeenInvalidated(), 'String[] must retire when Object[] domain is invalidated')
+        assertTrue(integerArraySp.hasBeenInvalidated(), 'Integer[] must retire when Object[] domain is invalidated')
+        assertFalse(siblingSp.hasBeenInvalidated())
+    }
+
+    @Test
+    void invalidateClassHierarchy_stringArray_doesNotRetireUnrelatedArrays() {
+        // String[] has no array subtypes; sibling array types must stay live.
+        SwitchPoint stringArraySp = ClassInfo.getClassInfo(String[]).indySwitchPoint
+        SwitchPoint integerArraySp = ClassInfo.getClassInfo(Integer[]).indySwitchPoint
+        SwitchPoint objectArraySp = ClassInfo.getClassInfo(Object[]).indySwitchPoint
+
+        IndyInvalidation.invalidateClassHierarchy(String[])
+
+        assertTrue(stringArraySp.hasBeenInvalidated())
+        assertFalse(integerArraySp.hasBeenInvalidated())
+        assertFalse(objectArraySp.hasBeenInvalidated(), 'supertype Object[] must not be retired by String[] invalidation')
+    }
+
+    @Test
+    void invalidateClassHierarchy_primitiveArray_retiresOnlyThatArrayType() {
+        // Primitive arrays are final and have no subtypes, but must not take the
+        // non-array final short-circuit incorrectly relative to Object[] handling.
+        SwitchPoint intArraySp = ClassInfo.getClassInfo(int[]).indySwitchPoint
+        SwitchPoint longArraySp = ClassInfo.getClassInfo(long[]).indySwitchPoint
+        SwitchPoint objectArraySp = ClassInfo.getClassInfo(Object[]).indySwitchPoint
+
+        IndyInvalidation.invalidateClassHierarchy(int[])
+
+        assertTrue(intArraySp.hasBeenInvalidated())
+        assertFalse(longArraySp.hasBeenInvalidated())
+        assertFalse(objectArraySp.hasBeenInvalidated())
+    }
+
+    @Test
+    void invalidateClass_objectArray_viaApi_fansOut() {
+        SwitchPoint stringArraySp = ClassInfo.getClassInfo(String[]).indySwitchPoint
+        IndyInvalidation.invalidateClass(Object[])
+        assertTrue(stringArraySp.hasBeenInvalidated())
+    }
+
+    @Test
+    void guardWithMopSwitchPoints_stringArrayFallsBackOnObjectArrayInvalidate() {
+        def target = MethodHandles.constant(int, 11)
+        def fallback = MethodHandles.constant(int, 12)
+        def receiver = new String[0]
+        def guarded = IndyInvalidation.guardWithMopSwitchPoints(target, fallback, receiver)
+        assertEquals(11, guarded.invokeWithArguments())
+
+        IndyInvalidation.invalidateClass(Object[])
+        assertEquals(12, guarded.invokeWithArguments(),
+                'String[]-linked site must fall back after Object[] MetaClass-domain invalidation')
+    }
+
+    @Test
+    void invalidateClassHierarchy_interfaceArray_fansOutToImplementorArrays() {
+        // Same final-array trap as Object[]: CharSequence[] is final yet
+        // assignable-from String[] (interface-array covariance).
+        SwitchPoint charSeqArraySp = ClassInfo.getClassInfo(CharSequence[]).indySwitchPoint
+        SwitchPoint stringArraySp = ClassInfo.getClassInfo(String[]).indySwitchPoint
+        SwitchPoint integerArraySp = ClassInfo.getClassInfo(Integer[]).indySwitchPoint
+
+        IndyInvalidation.invalidateClassHierarchy(CharSequence[])
+
+        assertTrue(charSeqArraySp.hasBeenInvalidated())
+        assertTrue(stringArraySp.hasBeenInvalidated(),
+                'String[] must retire when CharSequence[] domain is invalidated')
+        assertFalse(integerArraySp.hasBeenInvalidated())
+    }
+
+    @Test
+    void invalidateClassHierarchy_multiDimObjectArray_fansOut() {
+        // Multi-dim arrays are also final classes; Object[][] still fans out to String[][].
+        SwitchPoint object2dSp = ClassInfo.getClassInfo(Object[][]).indySwitchPoint
+        SwitchPoint string2dSp = ClassInfo.getClassInfo(String[][]).indySwitchPoint
+        SwitchPoint string1dSp = ClassInfo.getClassInfo(String[]).indySwitchPoint
+
+        IndyInvalidation.invalidateClassHierarchy(Object[][])
+
+        assertTrue(object2dSp.hasBeenInvalidated())
+        assertTrue(string2dSp.hasBeenInvalidated(),
+                'String[][] must retire when Object[][] domain is invalidated')
+        assertFalse(string1dSp.hasBeenInvalidated(),
+                '1-D String[] is not assignable-from Object[][]')
+    }
+
     @Test
     void invalidateCategory_bulkInvalidatesClassDomains() {
         SwitchPoint classSp = ClassInfo.getClassInfo(ClassA).indySwitchPoint
@@ -261,8 +362,8 @@ final class IndyInvalidationTest {
     }
 
     @Test
-    void invalidateClassHierarchy_primitive_shortCircuits() {
-        // Primitives cannot have subtypes — hits cannotHaveLoadedSubtypes early path.
+    void invalidateClassHierarchy_primitive_emptyDescendantsStillRetiresRoot() {
+        // Primitives have no indexed subtypes; single-path fan-out still retires the root.
         SwitchPoint intSp = ClassInfo.getClassInfo(int).indySwitchPoint
         SwitchPoint sibling = ClassInfo.getClassInfo(ClassB).indySwitchPoint
         IndyInvalidation.invalidateClassHierarchy(int)
diff --git a/src/test/groovy/org/codehaus/groovy/vmplugin/v8/IndyScopedSwitchPointTest.groovy b/src/test/groovy/org/codehaus/groovy/vmplugin/v8/IndyScopedSwitchPointTest.groovy
index f24f9596d1..7bedfc8fed 100644
--- a/src/test/groovy/org/codehaus/groovy/vmplugin/v8/IndyScopedSwitchPointTest.groovy
+++ b/src/test/groovy/org/codehaus/groovy/vmplugin/v8/IndyScopedSwitchPointTest.groovy
@@ -94,6 +94,69 @@ final class IndyScopedSwitchPointTest {
         assertFalse(IndyInterface.switchPoint.hasBeenInvalidated())
     }
 
+    @Test
+    void perClassMetaClassChange_doesNotRotateLegacySwitchPoint() {
+        // Legacy IndyInterface.switchPoint is only rotated on category /
+        // invalidateCallSites bulk paths — not on type-scoped MetaClass changes
+        // (GROOVY-12191 review: external guards on the field miss per-class events).
+        SwitchPoint legacyBefore = IndyInterface.switchPoint
+        SwitchPoint classSp = ClassInfo.getClassInfo(LegacyMissHost).indySwitchPoint
+        assertFalse(legacyBefore.hasBeenInvalidated())
+        assertFalse(classSp.hasBeenInvalidated())
+
+        def mc = new ExpandoMetaClass(LegacyMissHost, true, true)
+        mc.initialize()
+        GroovySystem.metaClassRegistry.setMetaClass(LegacyMissHost, mc)
+        try {
+            assertTrue(classSp.hasBeenInvalidated())
+            assertTrue(legacyBefore.is(IndyInterface.switchPoint),
+                    'legacy field must not rotate on per-class MetaClass change')
+            assertFalse(legacyBefore.hasBeenInvalidated(),
+                    'legacy field must stay valid across type-scoped invalidation')
+        } finally {
+            GroovySystem.metaClassRegistry.removeMetaClass(LegacyMissHost)
+        }
+    }
+
+    @Test
+    void invalidateSwitchPoints_concurrentRotation_doesNotOrphanLiveSwitchPoint() {
+        // Restore of synchronized (IndyInterface.class) around legacy rotation:
+        // concurrent bulk invalidations must not leave a reader-held SP live forever.
+        int threads = 8
+        def start = new java.util.concurrent.CyclicBarrier(threads)
+        def done = new java.util.concurrent.CountDownLatch(threads)
+        def errors = new java.util.concurrent.ConcurrentLinkedQueue<Throwable>()
+        def observed = java.util.Collections.synchronizedList(new ArrayList<SwitchPoint>())
+
+        threads.times {
+            Thread.start {
+                try {
+                    start.await()
+                    SwitchPoint seen = IndyInterface.switchPoint
+                    observed.add(seen)
+                    IndyInterface.invalidateSwitchPoints()
+                } catch (Throwable t) {
+                    errors.add(t)
+                } finally {
+                    done.countDown()
+                }
+            }
+        }
+        assertTrue(done.await(30, java.util.concurrent.TimeUnit.SECONDS))
+        assertTrue(errors.isEmpty(), "concurrent invalidate failed: $errors")
+
+        // Every SwitchPoint a thread observed before/during rotation must end
+        // invalidated, or equal the final live field (if observed after last write).
+        SwitchPoint live = IndyInterface.switchPoint
+        assertFalse(live.hasBeenInvalidated())
+        for (SwitchPoint sp : observed) {
+            if (sp !== live) {
+                assertTrue(sp.hasBeenInvalidated(),
+                        'orphaned legacy SwitchPoint left live after concurrent rotation')
+            }
+        }
+    }
+
     @Test
     void vmPlugin_invalidateCallSites_routesToScopedCategoryPath() {
         SwitchPoint classSp = ClassInfo.getClassInfo(PluginHost).indySwitchPoint
@@ -154,6 +217,7 @@ final class IndyScopedSwitchPointTest {
 
     static class ApplyHost {}
     static class LegacyHost {}
+    static class LegacyMissHost {}
     static class PluginHost {}
     static class UnscopedHost {}
     static class RegistryHost {}