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/28 15:23:50 UTC
(groovy) branch GROOVY-12191 updated: GROOVY-12191: MetaClass-aware SwitchPoint fan-out and PIC sentinel rename
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 0303da79dc GROOVY-12191: MetaClass-aware SwitchPoint fan-out and PIC sentinel rename
0303da79dc is described below
commit 0303da79dcfab874fd3ee503e6b3f96abedc619d
Author: Daniel Sun <su...@apache.org>
AuthorDate: Wed Jul 29 00:19:44 2026 +0900
GROOVY-12191: MetaClass-aware SwitchPoint fan-out and PIC sentinel rename
Narrow hierarchy invalidation to an allow-list of cross-class MOP cases
(EMC, modified custom MetaClass, interface/array, global EMC) while pure
MetaClassImpl replaces and per-instance MetaClass stay exact-class. Rename
NULL_METHOD_HANDLE_WRAPPER to UNCACHEABLE_PIC_SENTINEL and document the
invalidation matrix. Extend unit coverage for blackdrag's scenario and
the refined policy.
---
.../groovy/runtime/indy/ClassHierarchyIndex.java | 13 +-
.../groovy/runtime/indy/IndyInvalidation.java | 307 ++++++++++++++++++---
.../apache/groovy/runtime/indy/package-info.java | 23 +-
.../org/codehaus/groovy/reflection/ClassInfo.java | 15 +-
.../codehaus/groovy/vmplugin/v8/IndyInterface.java | 52 ++--
.../groovy/vmplugin/v8/MethodHandleWrapper.java | 32 ++-
src/test/groovy/bugs/Groovy12191.groovy | 125 ++++++++-
.../runtime/indy/IndyInvalidationTest.groovy | 153 ++++++++++
.../v8/IndyInterfaceCallSiteTargetTest.groovy | 4 +-
.../vmplugin/v8/IndyScopedSwitchPointTest.groovy | 4 +-
10 files changed, 639 insertions(+), 89 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
index bf80ccf496..543cb78f8d 100644
--- a/src/main/java/org/apache/groovy/runtime/indy/ClassHierarchyIndex.java
+++ b/src/main/java/org/apache/groovy/runtime/indy/ClassHierarchyIndex.java
@@ -41,12 +41,13 @@ import java.util.Set;
* {@code O(|subtypes of T|)} — instead of scanning every loaded
* {@code ClassInfo} with {@code isAssignableFrom}.
* <p>
- * The index exists so that <em>supertype</em> MetaClass / registry changes can
- * retire already-linked sites on subtypes (ExpandoMetaClass inheritance,
- * interface MetaClass, array covariance). It is not modelling a shared
- * {@code MetaClassImpl} table up the hierarchy — each class still has its own
- * MetaClass — but dispatch for a subtype can observe MOP state installed on
- * ancestors. See {@link IndyInvalidation} class javadoc for the full rationale.
+ * The index is consulted when MetaClass-aware policy chooses hierarchy fan-out
+ * (EMC install/update, global EMC, interface / array MetaClass changes). It is
+ * not modelling a shared {@code MetaClassImpl} table — each class still has its
+ * own MetaClass — but {@code MetaClassImpl.findMethodInClassHierarchy} can
+ * observe expando methods installed on ancestors, so subtype sites must re-link
+ * when those ancestors change. Pure {@code MetaClassImpl} class replaces do not
+ * walk this index (exact-class invalidation only). See {@link IndyInvalidation}.
* <p>
* Keys and values are weakly held so the index does not pin classes or
* {@code ClassInfo} instances after they become unreachable.
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 46c4fc06c6..15e8744b7d 100644
--- a/src/main/java/org/apache/groovy/runtime/indy/IndyInvalidation.java
+++ b/src/main/java/org/apache/groovy/runtime/indy/IndyInvalidation.java
@@ -18,6 +18,16 @@
*/
package org.apache.groovy.runtime.indy;
+import groovy.lang.AdaptingMetaClass;
+import groovy.lang.DelegatingMetaClass;
+import groovy.lang.ExpandoMetaClass;
+import groovy.lang.ExpandoMetaClassCreationHandle;
+import groovy.lang.GroovySystem;
+import groovy.lang.MetaClass;
+import groovy.lang.MetaClassImpl;
+import groovy.lang.MetaClassRegistry;
+import groovy.lang.MetaClassRegistryChangeEvent;
+import groovy.lang.MutableMetaClass;
import org.apache.groovy.util.SystemUtil;
import org.codehaus.groovy.reflection.ClassInfo;
import org.codehaus.groovy.runtime.NullObject;
@@ -34,44 +44,95 @@ import java.util.logging.Logger;
* Scoped invokedynamic {@link SwitchPoint} invalidation for the Groovy MOP
* (GROOVY-12191).
* <p>
- * <b>Model (intentionally minimal):</b> one SwitchPoint domain per class,
- * attached to {@link ClassInfo}. MetaClass changes for type {@code T} retire
- * {@code T}'s SwitchPoint and those of loaded subtypes/implementors (hierarchy
- * fan-out). Category enter/leave and unscoped MetaClass events bulk-retire
- * every loaded class SwitchPoint — there is no second, process-wide category
- * SwitchPoint on the hot path. Linked handles therefore always carry a single
- * guard, matching the pre-6.0 monomorphic shape while avoiding global deopt on
- * unrelated MetaClass churn.
+ * <b>Model (intentionally minimal for 6.0):</b> one SwitchPoint domain per
+ * class, attached to {@link ClassInfo}. This domain stands for the
+ * <em>class-level MetaClass generation</em> observed by monomorphic indy sites
+ * for receivers of that runtime class. Linked handles carry a single
+ * {@code guardWithTest} — matching the pre-6.0 monomorphic shape — while
+ * avoiding process-wide deopt on unrelated MetaClass churn.
* <p>
- * <b>Why hierarchy fan-out (not only the changed class):</b> a per-class domain
- * is enough for the <em>owner</em> of a {@code MetaClassImpl} table, but Groovy
- * MOP dispatch is not closed under a single class. Supertype MetaClass changes
- * become visible to subtypes:
- * <ul>
- * <li><b>ExpandoMetaClass / registry mutations on a parent</b> —
- * {@code Parent.metaClass.foo = …} must force already-linked sites on
- * {@code Child} to re-select so {@code new Child().foo()} sees the method.
- * That path is not a {@code MetaClassImpl}-internal rewrite of Child's
- * own method table; it is cross-class MOP visibility.</li>
- * <li><b>Interface MetaClass changes</b> — same rule for implementors.</li>
- * <li><b>Array covariance</b> — {@code Object[]} (and interface arrays) are
- * MOP-relevant supertypes of reference arrays even though array classes
- * are {@code final}.</li>
- * </ul>
- * Fan-out is therefore required for correctness of <em>inherited / covariant
- * MOP state</em>, not because {@code MetaClassImpl} shares one table up the
- * hierarchy. Category enter/leave remains bulk (separate path).
+ * <b>What this is not (yet):</b> SwitchPoints do not live on {@link MetaClass}
+ * instances themselves. A MetaClass-owned guard would be the natural place for
+ * MetaClass-specific logic (including custom MetaClass implementations and
+ * true per-instance domains). That is a larger redesign: today per-instance
+ * MetaClass already forces uncacheable PIC entries ({@code canSetTarget=false}),
+ * and class-level generation is retired through {@link ClassInfo}. The policy
+ * below is the conservative, MetaClass-<em>aware</em> approximation on top of
+ * the class-domain model.
+ *
+ * <h2>When do we invalidate, and how wide?</h2>
+ *
+ * <table border="1" summary="Invalidation policy">
+ * <tr><th>Event</th><th>Domain retired</th><th>Why</th></tr>
+ * <tr>
+ * <td>EMC method/property update ({@link ClassInfo#incVersion()})</td>
+ * <td>class + loaded subtypes / implementors / array lattice</td>
+ * <td>{@code MetaClassImpl} method selection walks super MetaClasses
+ * ({@code findMethodInClassHierarchy}); parent EMC methods are visible
+ * on children even without {@link ExpandoMetaClass#enableGlobally()}.</td>
+ * </tr>
+ * <tr>
+ * <td>Registry replace where old or new MC is {@link ExpandoMetaClass}</td>
+ * <td>class + hierarchy</td>
+ * <td>Installing / removing EMC changes cross-class MOP visibility for
+ * already-linked subtype sites.</td>
+ * </tr>
+ * <tr>
+ * <td>Registry replace while global EMC creation handle is active</td>
+ * <td>class + hierarchy</td>
+ * <td>Every class MetaClass is an EMC; inheritance refresh can republish
+ * super methods into subtypes.</td>
+ * </tr>
+ * <tr>
+ * <td>Registry replace of an interface or array type</td>
+ * <td>class + hierarchy (array lattice indexed)</td>
+ * <td>Interface / array MetaClasses participate in the same hierarchy walk
+ * (e.g. {@code Object[].metaClass.foo} is visible on {@code String[]}).</td>
+ * </tr>
+ * <tr>
+ * <td>Class replace where <em>both</em> old and new MetaClass are
+ * hierarchy-local (null, or unmodified {@code MetaClassImpl} /
+ * non-EMC subclass with {@code isModified()==false})</td>
+ * <td><b>exact class only</b></td>
+ * <td>Each class owns its own tables; parent replace does not open
+ * {@code findMethodInClassHierarchy}. Over-fan-out would re-link
+ * subtype sites without a MOP-visibility reason.</td>
+ * </tr>
+ * <tr>
+ * <td>Class replace involving unknown / custom MetaClass kinds</td>
+ * <td>class + hierarchy</td>
+ * <td>Correctness-first: custom MetaClasses may publish cross-class state;
+ * exact-only is an allow-list, not a deny-list of EMC alone.</td>
+ * </tr>
+ * <tr>
+ * <td>Per-instance MetaClass change</td>
+ * <td>exact class only</td>
+ * <td>Only that class's monomorphic sites must re-select; per-instance
+ * dispatch is already uncacheable in the PIC. Subtypes are unaffected.</td>
+ * </tr>
+ * <tr>
+ * <td>Category enter/leave, {@code invalidateCallSites()}, unscoped event</td>
+ * <td>all loaded class domains</td>
+ * <td>Category state is process-wide; no second hot-path guard.</td>
+ * </tr>
+ * </table>
+ *
+ * <p>
+ * <b>Over- vs under-invalidation:</b> exact-class is an <em>allow-list</em>
+ * (hierarchy-local MetaClasses only). Ambiguous or custom MetaClass kinds fan
+ * out. {@link #invalidateClass(Class)} / {@code incVersion} always fan out
+ * (EMC in-place updates). Linked sites for a method that did not change may
+ * still re-link when their receiver class domain is retired — that is the
+ * monomorphic SwitchPoint trade-off (same as pre-6.0, but scoped).
* <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
+ * via {@link ClassHierarchyIndex}. 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)}
* (public / test entry). Production Selector wiring uses
- * {@code IndyInterface.applyMopSwitchPoints}, which performs the same
- * {@code guardWithTest} bind after domain resolution here.
+ * {@code IndyInterface.applyMopSwitchPoints}.
* Optional stats logging: {@code -Dgroovy.indy.invalidation.stats=true}.
*
* @since 6.0.0
@@ -83,6 +144,8 @@ public final class IndyInvalidation {
private static final AtomicLong CLASS_INVALIDATIONS = new AtomicLong();
private static final AtomicLong CATEGORY_INVALIDATIONS = new AtomicLong();
+ private static final AtomicLong EXACT_ONLY_INVALIDATIONS = new AtomicLong();
+ private static final AtomicLong HIERARCHY_INVALIDATIONS = new AtomicLong();
private static final SwitchPoint[] EMPTY_SWITCH_POINTS = new SwitchPoint[0];
@@ -117,8 +180,13 @@ public final class IndyInvalidation {
/**
* Invalidates the per-class SwitchPoint for {@code type} and every loaded
- * subtype/implementor. No-op when {@code type} is {@code null}.
- * Does not bump {@link ClassInfo#getVersion()} on subtypes.
+ * subtype/implementor (hierarchy fan-out). No-op when {@code type} is
+ * {@code null}. Does not bump {@link ClassInfo#getVersion()} on subtypes.
+ * <p>
+ * Used by {@link ClassInfo#incVersion()} (EMC method updates) and any
+ * caller that needs the conservative full-hierarchy policy. Registry
+ * listeners prefer {@link #invalidateForMetaClassChange(MetaClassRegistryChangeEvent)}
+ * so pure {@code MetaClassImpl} replacements stay exact-class.
*
* @param type the class whose MetaClass changed
*/
@@ -128,12 +196,164 @@ public final class IndyInvalidation {
}
invalidateClassHierarchy(type);
CLASS_INVALIDATIONS.incrementAndGet();
+ HIERARCHY_INVALIDATIONS.incrementAndGet();
if (STATS_LOG && LOG.isLoggable(Level.FINE)) {
LOG.fine("class SwitchPoint hierarchy invalidated for " + type.getName()
+ "; total=" + CLASS_INVALIDATIONS.get());
}
}
+ /**
+ * Retires only {@code type}'s SwitchPoint domain (no subtype fan-out).
+ * Used when MetaClass change cannot affect cross-class MOP visibility
+ * (pure {@code MetaClassImpl} class replace, per-instance MetaClass).
+ *
+ * @param type the class whose domain is retired; no-op when {@code null}
+ */
+ public static void invalidateClassExact(final Class<?> type) {
+ if (type == null) {
+ return;
+ }
+ ClassInfo root = ClassInfo.getClassInfo(type);
+ SwitchPoint sp = root.detachLiveIndySwitchPoint();
+ if (sp != null) {
+ SwitchPointInvalidator.invalidateIfLive(sp);
+ }
+ CLASS_INVALIDATIONS.incrementAndGet();
+ EXACT_ONLY_INVALIDATIONS.incrementAndGet();
+ if (STATS_LOG && LOG.isLoggable(Level.FINE)) {
+ LOG.fine("exact-class SwitchPoint invalidated for " + type.getName()
+ + "; totalExact=" + EXACT_ONLY_INVALIDATIONS.get());
+ }
+ }
+
+ /**
+ * Registry-driven invalidation with MetaClass-aware fan-out policy.
+ * See class javadoc table for the decision matrix.
+ *
+ * @param event the registry change event (must not be {@code null})
+ */
+ public static void invalidateForMetaClassChange(final MetaClassRegistryChangeEvent event) {
+ Class<?> type = event.getClassToUpdate();
+ if (type == null) {
+ invalidateUnscoped();
+ return;
+ }
+ if (event.isPerInstanceMetaClassChange()) {
+ // Per-instance MC: only this class's monomorphic sites re-select.
+ invalidateClassExact(type);
+ return;
+ }
+ if (needsHierarchyFanOut(type, event.getOldMetaClass(), event.getNewMetaClass())) {
+ invalidateClass(type);
+ } else {
+ invalidateClassExact(type);
+ }
+ }
+
+ /**
+ * Whether a class-level MetaClass change for {@code type} can affect
+ * already-linked sites on subtypes / array-covariance descendants.
+ * <p>
+ * Hierarchy fan-out is the default. Exact-class is an <em>allow-list</em>:
+ * both old and new MetaClass must be {@linkplain #isHierarchyLocalMetaClass
+ * hierarchy-local}, and {@code type} must not be an interface/array, and
+ * global EMC must be off. Unknown / custom MetaClass kinds therefore fan
+ * out (correctness-first).
+ *
+ * @param type the class being updated (not {@code null})
+ * @param oldMc previous MetaClass (may be {@code null})
+ * @param newMc new MetaClass (may be {@code null} on remove)
+ * @return {@code true} if subtype fan-out is required
+ */
+ public static boolean needsHierarchyFanOut(
+ final Class<?> type, final MetaClass oldMc, final MetaClass newMc) {
+ if (type.isInterface() || type.isArray()) {
+ return true;
+ }
+ if (isGlobalEmcEnabled()) {
+ return true;
+ }
+ // Exact-only only when BOTH sides are hierarchy-local.
+ return !isHierarchyLocalMetaClass(oldMc) || !isHierarchyLocalMetaClass(newMc);
+ }
+
+ /**
+ * Whether {@code mc} cannot publish cross-class MOP state into subtype
+ * selection. Hierarchy-local means:
+ * <ul>
+ * <li>{@code null} (absent / removed), or</li>
+ * <li>unwrapped {@code MetaClassImpl} that is not an
+ * {@link ExpandoMetaClass} and reports {@code isModified()==false}.</li>
+ * </ul>
+ * EMC, modified mutable MetaClasses, and unknown MetaClass kinds return
+ * {@code false} so fan-out remains correctness-first.
+ *
+ * @param mc MetaClass to classify (may be {@code null})
+ * @return {@code true} if a replace involving only this kind needs no fan-out
+ */
+ public static boolean isHierarchyLocalMetaClass(final MetaClass mc) {
+ MetaClass current = unwrapMetaClass(mc);
+ if (current == null) {
+ return true;
+ }
+ // EMC always participates in cross-class visibility (even before the
+ // first method marks isModified), so it is never hierarchy-local.
+ if (current instanceof ExpandoMetaClass) {
+ return false;
+ }
+ if (current instanceof MutableMetaClass mutable && mutable.isModified()) {
+ return false;
+ }
+ // Unmodified MetaClassImpl (and non-EMC subclasses with isModified==false).
+ return current instanceof MetaClassImpl;
+ }
+
+ /**
+ * {@code true} when the registry creates {@link ExpandoMetaClass} instances
+ * by default ({@link ExpandoMetaClass#enableGlobally()}).
+ */
+ static boolean isGlobalEmcEnabled() {
+ MetaClassRegistry registry = GroovySystem.getMetaClassRegistry();
+ return registry.getMetaClassCreationHandler() instanceof ExpandoMetaClassCreationHandle;
+ }
+
+ /**
+ * Whether {@code mc} is (or wraps) an {@link ExpandoMetaClass}.
+ * Wrappers are unwrapped via {@link AdaptingMetaClass#getAdaptee()} or
+ * {@link DelegatingMetaClass#getAdaptee()} ({@code HandleMetaClass}).
+ */
+ static boolean isExpandoMetaClass(final MetaClass mc) {
+ return unwrapMetaClass(mc) instanceof ExpandoMetaClass;
+ }
+
+ /**
+ * Unwraps {@link AdaptingMetaClass} / {@link DelegatingMetaClass} wrappers
+ * (bounded depth) to the underlying MetaClass.
+ */
+ static MetaClass unwrapMetaClass(final MetaClass mc) {
+ MetaClass current = mc;
+ // Bound unwrap depth: HandleMetaClass is typically one level; be defensive.
+ for (int i = 0; i < 4 && current != null; i++) {
+ MetaClass adaptee = adapteeOf(current);
+ if (adaptee == null || adaptee == current) {
+ return current;
+ }
+ current = adaptee;
+ }
+ return current;
+ }
+
+ private static MetaClass adapteeOf(final MetaClass mc) {
+ if (mc instanceof AdaptingMetaClass adapting) {
+ return adapting.getAdaptee();
+ }
+ if (mc instanceof DelegatingMetaClass delegating) {
+ return delegating.getAdaptee();
+ }
+ return null;
+ }
+
/**
* Invalidates SwitchPoints for {@code type} and all loaded classes assignable
* from {@code type}. One path for every kind of type: detach the root domain,
@@ -279,7 +499,8 @@ public final class IndyInvalidation {
/**
* Returns the total number of scoped class invalidations
- * ({@link #invalidateClass(Class)} / {@link #invalidateUnscoped()} events).
+ * ({@link #invalidateClass(Class)} / {@link #invalidateClassExact(Class)} /
+ * {@link #invalidateForMetaClassChange} / {@link #invalidateUnscoped()} events).
*
* @return class invalidation count
*/
@@ -287,6 +508,24 @@ public final class IndyInvalidation {
return CLASS_INVALIDATIONS.get();
}
+ /**
+ * Returns how many class invalidations used hierarchy fan-out.
+ *
+ * @return hierarchy fan-out event count
+ */
+ public static long hierarchyInvalidationCount() {
+ return HIERARCHY_INVALIDATIONS.get();
+ }
+
+ /**
+ * Returns how many class invalidations were exact-class only.
+ *
+ * @return exact-only event count
+ */
+ public static long exactOnlyInvalidationCount() {
+ return EXACT_ONLY_INVALIDATIONS.get();
+ }
+
/**
* Returns the total number of category-style bulk invalidations.
*
@@ -302,5 +541,7 @@ public final class IndyInvalidation {
public static void resetCountersForTesting() {
CLASS_INVALIDATIONS.set(0);
CATEGORY_INVALIDATIONS.set(0);
+ EXACT_ONLY_INVALIDATIONS.set(0);
+ HIERARCHY_INVALIDATIONS.set(0);
}
}
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 a5c48f3668..d82fd9947b 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
@@ -20,17 +20,24 @@
/**
* 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 (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.
+ * One SwitchPoint per class (on {@link org.codehaus.groovy.reflection.ClassInfo})
+ * models the class-level MetaClass generation used by monomorphic indy sites.
+ * MetaClass-aware policy decides exact-class vs hierarchy fan-out
+ * (exact-class is an allow-list):
+ * <ul>
+ * <li>EMC, modified custom MetaClass, global EMC, interface and array types
+ * → class + loaded subtypes (incl. array lattice)</li>
+ * <li>hierarchy-local {@code MetaClassImpl} pair, per-instance MetaClass
+ * → exact class only</li>
+ * <li>category enter/leave and unscoped events → bulk retire all class domains</li>
+ * </ul>
+ * Linked call sites carry a single guard — no process-wide MOP SwitchPoint on
+ * the hot path. See {@link IndyInvalidation} for the full decision matrix and
+ * the relationship to a future MetaClass-owned SwitchPoint design.
* <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. Fan-out covers
- * cross-class MOP visibility (parent ExpandoMetaClass, interface MetaClass,
- * array covariance), not a shared {@code MetaClassImpl} table.
+ * changed type, not to the total number of loaded classes.
* <p>
* Install guards via {@link IndyInvalidation#guardWithMopSwitchPoints} (public)
* or {@code IndyInterface.applyMopSwitchPoints} (production link path). The
diff --git a/src/main/java/org/codehaus/groovy/reflection/ClassInfo.java b/src/main/java/org/codehaus/groovy/reflection/ClassInfo.java
index 0c7c30956e..1ed081ca8e 100644
--- a/src/main/java/org/codehaus/groovy/reflection/ClassInfo.java
+++ b/src/main/java/org/codehaus/groovy/reflection/ClassInfo.java
@@ -140,6 +140,14 @@ 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>
+ * Hierarchy fan-out is intentional here: {@code incVersion} is the path used
+ * when an existing MetaClass is <em>updated in place</em> (EMC method/property
+ * add). Parent EMC methods are visible to subtype receivers through
+ * {@code MetaClassImpl.findMethodInClassHierarchy}, so already-linked subtype
+ * sites must re-select. Registry-driven full MetaClass <em>replacements</em>
+ * use MetaClass-aware policy instead (pure {@code MetaClassImpl} replace stays
+ * exact-class; see {@link IndyInvalidation#invalidateForMetaClassChange}).
+ * <p>
* <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
@@ -166,8 +174,11 @@ public class ClassInfo implements Finalizable {
/**
* Bumps {@link #getVersion()} and, when {@code retireSwitchPoint} is true,
* retires this class's SwitchPoint only (no subtype fan-out). Used by
- * strong/weak MetaClass install paths; hierarchy fan-out is applied by the
- * MetaClass registry listener via {@link IndyInvalidation#invalidateClass(Class)}.
+ * strong/weak MetaClass install paths; MetaClass-aware hierarchy fan-out is
+ * applied by the MetaClass registry listener via
+ * {@link IndyInvalidation#invalidateForMetaClassChange}
+ * (exact-class for hierarchy-local {@code MetaClassImpl} replaces; hierarchy
+ * for EMC / interface / array / custom MetaClass).
* <p>
* First MetaClass install ({@code null →} default MC) only bumps version.
* Replacement and clear retire the SwitchPoint so any already-linked sites re-link.
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 d947917e72..eb86c95676 100644
--- a/src/main/java/org/codehaus/groovy/vmplugin/v8/IndyInterface.java
+++ b/src/main/java/org/codehaus/groovy/vmplugin/v8/IndyInterface.java
@@ -66,7 +66,13 @@ public class IndyInterface {
*/
public static final int SAFE_NAVIGATION=1, THIS_CALL=2, GROOVY_OBJECT=4, IMPLICIT_THIS=8, SPREAD_CALL=16, UNCACHED_CALL=32;
- private static final MethodHandleWrapper NULL_METHOD_HANDLE_WRAPPER = MethodHandleWrapper.getNullMethodHandleWrapper();
+ /**
+ * PIC sentinel meaning "this receiver shape is not class-keyed-cacheable".
+ * Written when {@code canSetTarget} is false (per-instance MetaClass, spread
+ * call, …). Not a real method handle — {@code fromCacheHandle} re-runs
+ * selection when it observes this value.
+ */
+ private static final MethodHandleWrapper UNCACHEABLE_PIC_SENTINEL = MethodHandleWrapper.getUncacheablePicSentinel();
private static final String NULL_OBJECT_CLASS_NAME = "org.codehaus.groovy.runtime.NullObject";
/**
@@ -223,15 +229,16 @@ public class IndyInterface {
// That field is removed (vmplugin is internal-by-intent): call sites now guard on
// per-ClassInfo domains via applyMopSwitchPoints.
GroovySystem.getMetaClassRegistry().addMetaClassRegistryChangeEventListener(cmcu -> {
- Class<?> type = cmcu.getClassToUpdate();
- if (type != null) {
- IndyInvalidation.invalidateClass(type);
- if (LOG_ENABLED) {
- LOG.info("invalidating class SwitchPoint hierarchy for " + type.getName());
- }
- } else {
- IndyInvalidation.invalidateUnscoped();
- if (LOG_ENABLED) {
+ // MetaClass-aware fan-out: EMC / interface / array / global-EMC → hierarchy;
+ // pure MetaClassImpl class replace and per-instance MC → exact class only.
+ // See IndyInvalidation class javadoc for the decision matrix (GROOVY-12191).
+ IndyInvalidation.invalidateForMetaClassChange(cmcu);
+ if (LOG_ENABLED) {
+ Class<?> type = cmcu.getClassToUpdate();
+ if (type != null) {
+ LOG.info("MetaClass registry change invalidation for " + type.getName()
+ + (cmcu.isPerInstanceMetaClassChange() ? " (per-instance)" : ""));
+ } else {
LOG.info("unscoped SwitchPoint invalidation (unattributed MetaClass change)");
}
}
@@ -241,9 +248,10 @@ 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. Per-class MetaClass changes use
- * {@link IndyInvalidation#invalidateClass(Class)} (or
- * {@link org.codehaus.groovy.reflection.ClassInfo#incVersion()}) instead.
+ * new category state. Per-class MetaClass changes use the MetaClass-aware
+ * registry path ({@link IndyInvalidation#invalidateForMetaClassChange}) or
+ * {@link org.codehaus.groovy.reflection.ClassInfo#incVersion()} (hierarchy
+ * fan-out for in-place EMC updates).
* <p>
* Pre-6.0 this method also rotated a process-wide {@code switchPoint} field.
* That field is gone; bulk policy lives entirely in {@link IndyInvalidation}.
@@ -425,10 +433,10 @@ public class IndyInterface {
MethodHandleWrapper mhw = callSite.getAndPut(receiverClassName, (theName) -> {
MethodHandleWrapper fallback = fallbackSupplier.get();
if (fallback.isCanSetTarget()) return fallback;
- return NULL_METHOD_HANDLE_WRAPPER;
+ return UNCACHEABLE_PIC_SENTINEL;
});
- if (mhw == NULL_METHOD_HANDLE_WRAPPER) {
+ if (mhw == UNCACHEABLE_PIC_SENTINEL) {
// The PIC stores a sentinel to remember "do not relink this receiver shape";
// execution still needs a real handle for the current invocation.
mhw = fallbackSupplier.get();
@@ -485,7 +493,7 @@ public class IndyInterface {
* <p>
* On a failed validity check (or after the reflective-hit promotion
* threshold), re-selection uses {@code fallback(..., allowColdReflection=false)}
- * and may write the full wrapper — or {@link #NULL_METHOD_HANDLE_WRAPPER} —
+ * and may write the full wrapper — or {@link #UNCACHEABLE_PIC_SENTINEL} —
* 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
@@ -526,19 +534,19 @@ public class IndyInterface {
// • canSetTarget == true → store the full wrapper so the next hit for
// this receiver class reuses the linked chain (and can promote the
// call-site target).
- // • canSetTarget == false → store NULL_METHOD_HANDLE_WRAPPER, the PIC
- // sentinel meaning "this receiver shape is not cacheable". Typical
- // causes: per-instance MetaClass, spread-call (selector.cache=false).
+ // • canSetTarget == false → store UNCACHEABLE_PIC_SENTINEL, meaning
+ // "this receiver shape is not class-keyed-cacheable". Typical causes:
+ // per-instance MetaClass, spread-call (selector.cache=false).
// Storing the real uncacheable wrapper would pin a selection that is
// only valid for one instance / one spread shape and would skip
// re-selection on the next PIC hit. The sentinel forces
// fromCacheHandle to re-run fallback while this invocation still
// uses full.getCachedMethodHandle() for the current call.
//
- // NULL_METHOD_HANDLE_WRAPPER is therefore the only safe PIC value when
+ // UNCACHEABLE_PIC_SENTINEL is therefore the only safe PIC value when
// the re-selected wrapper must not become a class-keyed cache entry.
cold.callSite.put(receiverCacheKey(arguments[0]),
- full.isCanSetTarget() ? full : NULL_METHOD_HANDLE_WRAPPER);
+ full.isCanSetTarget() ? full : UNCACHEABLE_PIC_SENTINEL);
return full.getCachedMethodHandle().invokeExact(arguments);
}
@@ -572,7 +580,7 @@ public class IndyInterface {
Object receiver = arguments[0];
// Avoid PIC pollution: don't write back uncached wrappers, e.g. for instance-level metaClass dispatches.
- callSite.put(receiverCacheKey(receiver), mhw.isCanSetTarget() ? mhw : NULL_METHOD_HANDLE_WRAPPER);
+ callSite.put(receiverCacheKey(receiver), mhw.isCanSetTarget() ? mhw : UNCACHEABLE_PIC_SENTINEL);
}
return mhw.getCachedMethodHandle();
diff --git a/src/main/java/org/codehaus/groovy/vmplugin/v8/MethodHandleWrapper.java b/src/main/java/org/codehaus/groovy/vmplugin/v8/MethodHandleWrapper.java
index 71c3cb5dbb..33ff56fb1f 100644
--- a/src/main/java/org/codehaus/groovy/vmplugin/v8/MethodHandleWrapper.java
+++ b/src/main/java/org/codehaus/groovy/vmplugin/v8/MethodHandleWrapper.java
@@ -112,21 +112,35 @@ class MethodHandleWrapper {
}
/**
- * Returns the sentinel wrapper used when no cacheable handle is available.
+ * Returns the PIC sentinel used when a selection must not be stored under a
+ * receiver-class cache key ({@code canSetTarget == false}).
+ * <p>
+ * Renamed from the historical {@code getNullMethodHandleWrapper} name: the
+ * value is not “null work”, it is the deliberate “do not class-key-cache
+ * this shape” marker consumed by {@code fromCacheHandle} (GROOVY-12191).
*
- * @return the null sentinel wrapper
+ * @return the uncacheable PIC sentinel (identity-comparable singleton)
*/
+ public static MethodHandleWrapper getUncacheablePicSentinel() {
+ return UncacheablePicSentinel.INSTANCE;
+ }
+
+ /**
+ * @deprecated use {@link #getUncacheablePicSentinel()}
+ */
+ @Deprecated
public static MethodHandleWrapper getNullMethodHandleWrapper() {
- return NullMethodHandleWrapper.INSTANCE;
+ return getUncacheablePicSentinel();
}
- private static class NullMethodHandleWrapper extends MethodHandleWrapper {
- /**
- * Shared sentinel wrapper representing the absence of a reusable method handle.
- */
- public static final NullMethodHandleWrapper INSTANCE = new NullMethodHandleWrapper();
+ /**
+ * Shared sentinel wrapper: not a real handle, only a PIC marker for
+ * uncacheable receiver shapes (per-instance MetaClass, spread-call, …).
+ */
+ private static final class UncacheablePicSentinel extends MethodHandleWrapper {
+ static final UncacheablePicSentinel INSTANCE = new UncacheablePicSentinel();
- private NullMethodHandleWrapper() {
+ private UncacheablePicSentinel() {
super(null, null, null, false);
}
}
diff --git a/src/test/groovy/bugs/Groovy12191.groovy b/src/test/groovy/bugs/Groovy12191.groovy
index 273ff0b115..6f307475fd 100644
--- a/src/test/groovy/bugs/Groovy12191.groovy
+++ b/src/test/groovy/bugs/Groovy12191.groovy
@@ -133,23 +133,46 @@ final class Groovy12191 {
}
@Test
- void parentMetaClassImplReplace_stillFansOutToSubclassSwitchPoint() {
- // Even without EMC method tables, replacing Parent's MetaClass can
- // change what Child dispatch observes; hierarchy fan-out still applies.
+ void parentMetaClassImplReplace_doesNotFanOutToSubclassSwitchPoint() {
+ // Pure MetaClassImpl ↔ MetaClassImpl replace has no cross-class EMC
+ // visibility: each class owns its own tables. Hierarchy fan-out would
+ // only re-link subtype sites without a MOP reason (blackdrag review).
+ SwitchPoint parentSp = ClassInfo.getClassInfo(HierParentMcImpl).indySwitchPoint
SwitchPoint childSp = ClassInfo.getClassInfo(HierChildMcImpl).indySwitchPoint
+ assertFalse(parentSp.hasBeenInvalidated())
assertFalse(childSp.hasBeenInvalidated())
def mc = new MetaClassImpl(HierParentMcImpl)
mc.initialize()
GroovySystem.metaClassRegistry.setMetaClass(HierParentMcImpl, mc)
try {
- assertTrue(childSp.hasBeenInvalidated(),
- 'MetaClassImpl replacement on parent must retire subclass SwitchPoint')
+ assertTrue(parentSp.hasBeenInvalidated(),
+ 'MetaClassImpl replacement must retire the exact class domain')
+ assertFalse(childSp.hasBeenInvalidated(),
+ 'pure MetaClassImpl parent replace must not retire subclass SwitchPoint')
} finally {
GroovySystem.metaClassRegistry.removeMetaClass(HierParentMcImpl)
}
}
+ @Test
+ void parentEmcReplace_fansOutToSubclassSwitchPoint() {
+ // Installing EMC on Parent publishes methods into Child via hierarchy
+ // walk — subtype sites must re-link.
+ SwitchPoint childSp = ClassInfo.getClassInfo(HierChildEmc).indySwitchPoint
+ assertFalse(childSp.hasBeenInvalidated())
+
+ def emc = new ExpandoMetaClass(HierParentEmc, true, true)
+ emc.initialize()
+ GroovySystem.metaClassRegistry.setMetaClass(HierParentEmc, emc)
+ try {
+ assertTrue(childSp.hasBeenInvalidated(),
+ 'EMC install on parent must retire subclass SwitchPoint')
+ } finally {
+ GroovySystem.metaClassRegistry.removeMetaClass(HierParentEmc)
+ }
+ }
+
@Test
void unrelatedTypeMetaClassChange_doesNotInvalidateSiblingHierarchy() {
// Hierarchy fan-out is only to subtypes of the changed type — not global.
@@ -223,6 +246,90 @@ final class Groovy12191 {
'incVersion must not act as a process-wide flush (GROOVY-12191)')
}
+ /**
+ * Blackdrag scenario matrix (PR #2736): {@code call(c)} uses receiver class C.
+ * Mutations on B/A must not retire C's domain; methods added on B/A must not
+ * become visible on a pure C instance. Documents old-vs-new blast radius and
+ * actual MOP visibility.
+ */
+ @Test
+ void blackdragScenario_callOnC_notInvalidatedBySubclassMetaClassChurn() {
+ SwitchPoint spC = ClassInfo.getClassInfo(BdC).indySwitchPoint
+ SwitchPoint spB = ClassInfo.getClassInfo(BdB).indySwitchPoint
+ SwitchPoint spA = ClassInfo.getClassInfo(BdA).indySwitchPoint
+ assertFalse(spC.hasBeenInvalidated())
+ assertFalse(spB.hasBeenInvalidated())
+ assertFalse(spA.hasBeenInvalidated())
+
+ def c = new BdC()
+ assert c.fooC() == 'fooC'
+
+ // B.metaClass = EMC + method — fans out to A (subtype of B), not to C (supertype).
+ def emcB = new ExpandoMetaClass(BdB, true, true)
+ emcB.initialize()
+ GroovySystem.metaClassRegistry.setMetaClass(BdB, emcB)
+ try {
+ assertTrue(spB.hasBeenInvalidated())
+ assertTrue(spA.hasBeenInvalidated(), 'EMC on B must fan out to A')
+ assertFalse(spC.hasBeenInvalidated(), 'EMC on B must not retire C (supertype)')
+ assert c.fooC() == 'fooC'
+ assert !c.metaClass.respondsTo(c, 'fooB0')
+
+ spC = ClassInfo.getClassInfo(BdC).indySwitchPoint
+ spA = ClassInfo.getClassInfo(BdA).indySwitchPoint
+ BdB.metaClass.fooB0 = { -> 'fooB0' }
+ assertTrue(spA.hasBeenInvalidated(), 'B EMC update (incVersion) fans out to A')
+ assertFalse(spC.hasBeenInvalidated())
+ assert new BdB().fooB0() == 'fooB0'
+ assert new BdA().fooB0() == 'fooB0'
+ assert !c.metaClass.respondsTo(c, 'fooB0')
+ assert c.fooC() == 'fooC'
+ } finally {
+ GroovySystem.metaClassRegistry.removeMetaClass(BdB)
+ }
+
+ // A.fooA = {} — exact class A (+ subtypes of A if any), not C.
+ spC = ClassInfo.getClassInfo(BdC).indySwitchPoint
+ BdA.metaClass.fooA = { -> 'fooA' }
+ try {
+ assertFalse(spC.hasBeenInvalidated())
+ assert new BdA().fooA() == 'fooA'
+ assert !c.metaClass.respondsTo(c, 'fooA')
+ assert c.fooC() == 'fooC'
+ } finally {
+ GroovySystem.metaClassRegistry.removeMetaClass(BdA)
+ }
+
+ // Per-instance EMC on a B instance — does not affect C domain or visibility on c.
+ spC = ClassInfo.getClassInfo(BdC).indySwitchPoint
+ def b = new BdB()
+ def emcInst = new ExpandoMetaClass(BdB, false, true)
+ emcInst.initialize()
+ emcInst.fooB2 = { -> 'fooB2' }
+ b.metaClass = emcInst
+ assertFalse(spC.hasBeenInvalidated(),
+ 'per-instance MetaClass on B must not retire C SwitchPoint')
+ assert b.fooB2() == 'fooB2'
+ assert b.fooC() == 'fooC'
+ assert !c.metaClass.respondsTo(c, 'fooB2')
+ assert c.fooC() == 'fooC'
+ b.metaClass = null
+ }
+
+ @Test
+ void objectArrayEmcMethod_visibleOnStringArray() {
+ // Empirical MOP fact that justifies array lattice fan-out for EMC.
+ assertScript '''
+ Object[].metaClass.arrHello = { -> 'arr' }
+ try {
+ assert (new Object[0]).arrHello() == 'arr'
+ assert (new String[0]).arrHello() == 'arr'
+ } finally {
+ GroovySystem.metaClassRegistry.removeMetaClass(Object[])
+ }
+ '''
+ }
+
static class TypeA {}
static class TypeB {
String id() { 'B' }
@@ -238,6 +345,14 @@ final class Groovy12191 {
static class HierChild extends HierParent {}
static class HierParentMcImpl {}
static class HierChildMcImpl extends HierParentMcImpl {}
+ static class HierParentEmc {}
+ static class HierChildEmc extends HierParentEmc {}
static class HierParentScope {}
static class HierChildScope extends HierParentScope {}
+ /** blackdrag scenario types: A extends B extends C */
+ static class BdC {
+ String fooC() { 'fooC' }
+ }
+ static class BdB extends BdC {}
+ static class BdA extends BdB {}
}
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 e4d105d8d6..baf0f66740 100644
--- a/src/test/groovy/org/apache/groovy/runtime/indy/IndyInvalidationTest.groovy
+++ b/src/test/groovy/org/apache/groovy/runtime/indy/IndyInvalidationTest.groovy
@@ -18,6 +18,8 @@
*/
package org.apache.groovy.runtime.indy
+import groovy.lang.ExpandoMetaClass
+import groovy.lang.GroovySystem
import org.codehaus.groovy.reflection.ClassInfo
import org.codehaus.groovy.runtime.NullObject
import org.junit.jupiter.api.BeforeEach
@@ -289,11 +291,149 @@ final class IndyInvalidationTest {
void resetCountersForTesting_zerosCounters() {
IndyInvalidation.invalidateClass(ClassA)
IndyInvalidation.invalidateCategory()
+ IndyInvalidation.invalidateClassExact(ClassB)
assertTrue(IndyInvalidation.classInvalidationCount() > 0)
assertTrue(IndyInvalidation.categoryInvalidationCount() > 0)
+ assertTrue(IndyInvalidation.hierarchyInvalidationCount() > 0)
+ assertTrue(IndyInvalidation.exactOnlyInvalidationCount() > 0)
IndyInvalidation.resetCountersForTesting()
assertEquals(0, IndyInvalidation.classInvalidationCount())
assertEquals(0, IndyInvalidation.categoryInvalidationCount())
+ assertEquals(0, IndyInvalidation.hierarchyInvalidationCount())
+ assertEquals(0, IndyInvalidation.exactOnlyInvalidationCount())
+ }
+
+ @Test
+ void invalidateClassExact_doesNotFanOutToSubtypes() {
+ SwitchPoint parentSp = ClassInfo.getClassInfo(Parent).indySwitchPoint
+ SwitchPoint childSp = ClassInfo.getClassInfo(Child).indySwitchPoint
+ IndyInvalidation.invalidateClassExact(Parent)
+ assertTrue(parentSp.hasBeenInvalidated())
+ assertFalse(childSp.hasBeenInvalidated())
+ }
+
+ @Test
+ void needsHierarchyFanOut_emcVsMetaClassImpl() {
+ def mcImpl = new groovy.lang.MetaClassImpl(ClassA)
+ mcImpl.initialize()
+ def emc = new ExpandoMetaClass(ClassA, true, true)
+ emc.initialize()
+
+ assertTrue(IndyInvalidation.isHierarchyLocalMetaClass(mcImpl))
+ assertTrue(IndyInvalidation.isHierarchyLocalMetaClass(null))
+ assertFalse(IndyInvalidation.isHierarchyLocalMetaClass(emc))
+
+ assertFalse(IndyInvalidation.needsHierarchyFanOut(ClassA, mcImpl, mcImpl),
+ 'pure MetaClassImpl replace must not require fan-out')
+ assertFalse(IndyInvalidation.needsHierarchyFanOut(ClassA, null, mcImpl),
+ 'first MetaClassImpl install must not require fan-out')
+ assertTrue(IndyInvalidation.needsHierarchyFanOut(ClassA, null, emc),
+ 'EMC install must require fan-out')
+ assertTrue(IndyInvalidation.needsHierarchyFanOut(ClassA, emc, mcImpl),
+ 'EMC remove must require fan-out')
+ assertTrue(IndyInvalidation.needsHierarchyFanOut(Marker, mcImpl, mcImpl),
+ 'interface MetaClass change must require fan-out')
+ assertTrue(IndyInvalidation.needsHierarchyFanOut(String[], mcImpl, mcImpl),
+ 'array MetaClass change must require fan-out')
+ }
+
+ @Test
+ void needsHierarchyFanOut_modifiedCustomMetaClass_fansOut() {
+ // MetaClassImpl subclass with isModified()==true is not hierarchy-local
+ // (same gate as findMethodInClassHierarchy).
+ def custom = new ModifiedCustomMetaClass(ClassA)
+ custom.initialize()
+ assertFalse(IndyInvalidation.isHierarchyLocalMetaClass(custom))
+ def mcImpl = new groovy.lang.MetaClassImpl(ClassA)
+ mcImpl.initialize()
+ assertTrue(IndyInvalidation.needsHierarchyFanOut(ClassA, mcImpl, custom),
+ 'modified custom MetaClass must fan out (correctness-first)')
+ }
+
+ @Test
+ void needsHierarchyFanOut_globalEmcEnabled() {
+ def mcImpl = new groovy.lang.MetaClassImpl(ClassA)
+ mcImpl.initialize()
+ try {
+ ExpandoMetaClass.enableGlobally()
+ assertTrue(IndyInvalidation.isGlobalEmcEnabled())
+ assertTrue(IndyInvalidation.needsHierarchyFanOut(ClassA, mcImpl, mcImpl),
+ 'global EMC must force hierarchy fan-out even for MetaClassImpl pair')
+ } finally {
+ ExpandoMetaClass.disableGlobally()
+ assertFalse(IndyInvalidation.isGlobalEmcEnabled())
+ }
+ }
+
+ @Test
+ void isExpandoMetaClass_detectsDirectAndWrapped() {
+ def emc = new ExpandoMetaClass(ClassA, true, true)
+ emc.initialize()
+ assertTrue(IndyInvalidation.isExpandoMetaClass(emc))
+ assertFalse(IndyInvalidation.isExpandoMetaClass(new groovy.lang.MetaClassImpl(ClassA)))
+ assertFalse(IndyInvalidation.isExpandoMetaClass(null))
+ def handle = new org.codehaus.groovy.runtime.HandleMetaClass(emc)
+ assertTrue(IndyInvalidation.isExpandoMetaClass(handle),
+ 'HandleMetaClass wrapping EMC must be recognised')
+ }
+
+ @Test
+ void invalidateForMetaClassChange_exactForPureMetaClassImpl() {
+ SwitchPoint parentSp = ClassInfo.getClassInfo(PolicyParent).indySwitchPoint
+ SwitchPoint childSp = ClassInfo.getClassInfo(PolicyChild).indySwitchPoint
+ def oldMc = new groovy.lang.MetaClassImpl(PolicyParent)
+ oldMc.initialize()
+ def newMc = new groovy.lang.MetaClassImpl(PolicyParent)
+ newMc.initialize()
+ def event = new groovy.lang.MetaClassRegistryChangeEvent(
+ GroovySystem.metaClassRegistry, null, PolicyParent, oldMc, newMc)
+
+ IndyInvalidation.invalidateForMetaClassChange(event)
+
+ assertTrue(parentSp.hasBeenInvalidated())
+ assertFalse(childSp.hasBeenInvalidated(),
+ 'pure MetaClassImpl replace must stay exact-class')
+ }
+
+ @Test
+ void invalidateForMetaClassChange_hierarchyForEmc() {
+ SwitchPoint childSp = ClassInfo.getClassInfo(PolicyChildEmc).indySwitchPoint
+ def emc = new ExpandoMetaClass(PolicyParentEmc, true, true)
+ emc.initialize()
+ def event = new groovy.lang.MetaClassRegistryChangeEvent(
+ GroovySystem.metaClassRegistry, null, PolicyParentEmc, null, emc)
+
+ IndyInvalidation.invalidateForMetaClassChange(event)
+
+ assertTrue(childSp.hasBeenInvalidated(),
+ 'EMC install on parent must fan out to child')
+ }
+
+ @Test
+ void invalidateForMetaClassChange_perInstance_exactOnly() {
+ SwitchPoint parentSp = ClassInfo.getClassInfo(PolicyParentPerInst).indySwitchPoint
+ SwitchPoint childSp = ClassInfo.getClassInfo(PolicyChildPerInst).indySwitchPoint
+ def instance = new PolicyParentPerInst()
+ def emc = new ExpandoMetaClass(PolicyParentPerInst, false, true)
+ emc.initialize()
+ def event = new groovy.lang.MetaClassRegistryChangeEvent(
+ GroovySystem.metaClassRegistry, instance, PolicyParentPerInst, null, emc)
+
+ assertTrue(event.isPerInstanceMetaClassChange())
+ IndyInvalidation.invalidateForMetaClassChange(event)
+
+ assertTrue(parentSp.hasBeenInvalidated())
+ assertFalse(childSp.hasBeenInvalidated(),
+ 'per-instance MetaClass must not fan out to subtypes')
+ }
+
+ @Test
+ void invalidateForMetaClassChange_nullType_unscoped() {
+ SwitchPoint sp = ClassInfo.getClassInfo(ClassA).indySwitchPoint
+ def event = new groovy.lang.MetaClassRegistryChangeEvent(
+ GroovySystem.metaClassRegistry, null, null, null, null)
+ IndyInvalidation.invalidateForMetaClassChange(event)
+ assertTrue(sp.hasBeenInvalidated())
}
@Test
@@ -503,8 +643,21 @@ final class IndyInvalidationTest {
private static final class ClearedIncVersionHost {}
private static interface Marker {}
private static final class MarkerImpl implements Marker {}
+ private static class PolicyParent {}
+ private static final class PolicyChild extends PolicyParent {}
+ private static class PolicyParentEmc {}
+ private static final class PolicyChildEmc extends PolicyParentEmc {}
+ private static class PolicyParentPerInst {}
+ private static final class PolicyChildPerInst extends PolicyParentPerInst {}
}
/** Top-level host for per-instance MetaClass SwitchPoint coverage. */
class Groovy12191PerInstHost {}
+/** MetaClassImpl subclass that reports modified, forcing hierarchy fan-out. */
+class ModifiedCustomMetaClass extends groovy.lang.MetaClassImpl {
+ ModifiedCustomMetaClass(Class theClass) { super(theClass) }
+ @Override
+ boolean isModified() { true }
+}
+
diff --git a/src/test/groovy/org/codehaus/groovy/vmplugin/v8/IndyInterfaceCallSiteTargetTest.groovy b/src/test/groovy/org/codehaus/groovy/vmplugin/v8/IndyInterfaceCallSiteTargetTest.groovy
index 2a499a222a..e54e44a5d8 100644
--- a/src/test/groovy/org/codehaus/groovy/vmplugin/v8/IndyInterfaceCallSiteTargetTest.groovy
+++ b/src/test/groovy/org/codehaus/groovy/vmplugin/v8/IndyInterfaceCallSiteTargetTest.groovy
@@ -385,7 +385,7 @@ final class IndyInterfaceCallSiteTargetTest {
)
assertEquals(staticEcho('bar'), methodHandle.invokeWithArguments([args] as Object[]))
- assertSame(MethodHandleWrapper.getNullMethodHandleWrapper(), requireCachedWrapper(callSite, IndyInterfaceCallSiteTargetTest))
+ assertSame(MethodHandleWrapper.getUncacheablePicSentinel(), requireCachedWrapper(callSite, IndyInterfaceCallSiteTargetTest))
assertSame(callSite.defaultTarget, callSite.target)
}
@@ -451,7 +451,7 @@ final class IndyInterfaceCallSiteTargetTest {
AtomicInteger providerCalls = new AtomicInteger()
MethodHandleWrapper wrapper = callSite.getAndPut(receiverClassName(receiver), { key ->
providerCalls.incrementAndGet()
- MethodHandleWrapper.getNullMethodHandleWrapper()
+ MethodHandleWrapper.getUncacheablePicSentinel()
})
assertEquals(0, providerCalls.get())
wrapper
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 bdc8d6b431..23477b02f3 100644
--- a/src/test/groovy/org/codehaus/groovy/vmplugin/v8/IndyScopedSwitchPointTest.groovy
+++ b/src/test/groovy/org/codehaus/groovy/vmplugin/v8/IndyScopedSwitchPointTest.groovy
@@ -175,7 +175,7 @@ final class IndyScopedSwitchPointTest {
}
@Test
- void coldReflective_picWrite_usesNullSentinelWhenUncacheable() {
+ void coldReflective_picWrite_usesUncacheableSentinelWhenUncacheable() {
// Mirrors invokeColdReflective / selectMethodHandle PIC policy:
// uncacheable wrappers must not be stored under the receiver class key.
def type = MethodType.methodType(Object, Object)
@@ -187,7 +187,7 @@ final class IndyScopedSwitchPointTest {
false)
assertFalse(uncacheable.isCanSetTarget())
def key = ColdHost.name
- def sentinel = MethodHandleWrapper.nullMethodHandleWrapper
+ def sentinel = MethodHandleWrapper.uncacheablePicSentinel
site.put(key, uncacheable.isCanSetTarget() ? uncacheable : sentinel)
// Next PIC hit must observe the sentinel, not the uncacheable wrapper.
def fromPic = site.getAndPut(key, { k -> uncacheable })