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/25 16:54:46 UTC
(groovy) branch GROOVY-12191 updated (66e01476ff -> 25142bc7b9)
This is an automated email from the ASF dual-hosted git repository.
asf-gitbox-commits pushed a change to branch GROOVY-12191
in repository https://gitbox.apache.org/repos/asf/groovy.git
discard 66e01476ff GROOVY-12191: Scope indy SwitchPoint invalidation and harden PIC/math paths
new 25142bc7b9 GROOVY-12191: Scope indy SwitchPoint invalidation and harden PIC/math paths
This update added new revisions after undoing existing revisions.
That is to say, some revisions that were in the old version of the
branch are not in the new version. This situation occurs
when a user --force pushes a change and generates a repository
containing something like this:
* -- * -- B -- O -- O -- O (66e01476ff)
\
N -- N -- N refs/heads/GROOVY-12191 (25142bc7b9)
You should already have received notification emails for all of the O
revisions, and so the following emails describe only the N revisions
from the common base, B.
Any revisions marked "omit" are not gone; other references still
refer to them. Any revisions marked "discard" are gone forever.
The 1 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
Summary of changes:
.../groovy/runtime/indy/CallSiteTracker.java | 147 --------
.../apache/groovy/runtime/indy/package-info.java | 14 +-
.../groovy/vmplugin/v8/CacheableCallSite.java | 387 +--------------------
.../codehaus/groovy/vmplugin/v8/IndyInterface.java | 117 ++-----
.../org/codehaus/groovy/vmplugin/v8/IndyMath.java | 183 +---------
.../groovy/vmplugin/v8/MethodHandleWrapper.java | 48 ---
.../org/codehaus/groovy/vmplugin/v8/Selector.java | 2 +-
.../indy/BimorphicDispatchScriptTest.groovy | 84 -----
.../groovy/runtime/indy/CallSiteTrackerTest.groovy | 97 ------
.../runtime/indy/MegamorphicCallSiteTest.groovy | 181 ----------
.../groovy/vmplugin/v8/IndyMathTest.groovy | 173 ---------
.../groovy/runtime/indy/BimorphicCallSiteTest.java | 220 ------------
subprojects/performance/README.adoc | 14 +-
.../apache/groovy/bench/DynamicDispatchCold.groovy | 15 -
.../groovy/bench/DynamicDispatchColdBench.java | 12 -
.../org/apache/groovy/bench/IndyMathBench.java | 258 --------------
.../apache/groovy/bench/IndyMathWorkload.groovy | 139 --------
.../groovy/bench/dispatch/CallsiteBench.java | 83 +----
18 files changed, 47 insertions(+), 2127 deletions(-)
delete mode 100644 src/main/java/org/apache/groovy/runtime/indy/CallSiteTracker.java
delete mode 100644 src/test/groovy/org/apache/groovy/runtime/indy/BimorphicDispatchScriptTest.groovy
delete mode 100644 src/test/groovy/org/apache/groovy/runtime/indy/CallSiteTrackerTest.groovy
delete mode 100644 src/test/groovy/org/apache/groovy/runtime/indy/MegamorphicCallSiteTest.groovy
delete mode 100644 src/test/groovy/org/codehaus/groovy/vmplugin/v8/IndyMathTest.groovy
delete mode 100644 src/test/java/org/apache/groovy/runtime/indy/BimorphicCallSiteTest.java
delete mode 100644 subprojects/performance/src/jmh/groovy/org/apache/groovy/bench/IndyMathBench.java
delete mode 100644 subprojects/performance/src/jmh/groovy/org/apache/groovy/bench/IndyMathWorkload.groovy
(groovy) 01/01: GROOVY-12191: Scope indy SwitchPoint invalidation and harden PIC/math paths
Posted by su...@apache.org.
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
commit 25142bc7b90c45c5645d818ee19888fbf020d9e8
Author: Daniel Sun <su...@apache.org>
AuthorDate: Sat Jul 25 20:06:58 2026 +0900
GROOVY-12191: Scope indy SwitchPoint invalidation and harden PIC/math paths
---
.../groovy/runtime/indy/IndyInvalidation.java | 485 +++++++++++++++++++++
.../runtime/indy/SwitchPointInvalidator.java | 286 ++++++++++++
.../apache/groovy/runtime/indy/package-info.java | 32 ++
.../org/codehaus/groovy/reflection/ClassInfo.java | 143 +++++-
.../v8/ColdReflectiveMethodHandleWrapper.java | 50 ++-
.../groovy/vmplugin/v8/IndyCompoundAssign.java | 4 +-
.../codehaus/groovy/vmplugin/v8/IndyInterface.java | 77 +++-
.../org/codehaus/groovy/vmplugin/v8/Selector.java | 13 +-
src/test/groovy/bugs/Groovy12191.groovy | 183 ++++++++
.../runtime/indy/IndyInvalidationTest.groovy | 368 ++++++++++++++++
.../runtime/indy/SwitchPointInvalidatorTest.groovy | 251 +++++++++++
subprojects/performance/README.adoc | 10 +
.../groovy/bench/ScopedInvalidationBench.groovy | 272 ++++++++++++
13 files changed, 2139 insertions(+), 35 deletions(-)
diff --git a/src/main/java/org/apache/groovy/runtime/indy/IndyInvalidation.java b/src/main/java/org/apache/groovy/runtime/indy/IndyInvalidation.java
new file mode 100644
index 0000000000..29a5472bc9
--- /dev/null
+++ b/src/main/java/org/apache/groovy/runtime/indy/IndyInvalidation.java
@@ -0,0 +1,485 @@
+/*
+ * 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.apache.groovy.util.SystemUtil;
+import org.codehaus.groovy.reflection.ClassInfo;
+import org.codehaus.groovy.runtime.NullObject;
+
+import java.lang.invoke.MethodHandle;
+import java.lang.invoke.MethodHandles;
+import java.lang.invoke.MethodType;
+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.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+/**
+ * Facade for scoped invokedynamic {@link SwitchPoint} invalidation (GROOVY-12191).
+ * <p>
+ * Two independent domains are maintained:
+ * <ul>
+ * <li><b>Per-class</b> — attached to each {@link ClassInfo}; invalidated when that
+ * class's MetaClass / version changes, and also for subclasses/implementors
+ * (hierarchy fan-out) so sites linked on a receiver subtype re-link.</li>
+ * <li><b>Category-global</b> — process-wide; invalidated on category enter/leave so
+ * monomorphic sites re-link and can pick up category methods. The category
+ * domain never fails over (correctness over deopt-storm protection).
+ * Category guards are installed lazily: until the first category enter/leave
+ * (or other category-domain use), linked handles carry only the per-class
+ * SwitchPoint so the steady-state monomorphic path matches a single-guard
+ * shape. The first arm of the category domain bulk-invalidates class domains
+ * so sites re-link with the category guard installed.</li>
+ * </ul>
+ * Linked method-handle chains should install guards via
+ * {@link #guardWithMopSwitchPoints(MethodHandle, MethodHandle, Object)}.
+ * <p>
+ * Per-class failover after repeated invalidations is controlled by
+ * {@code -Dgroovy.indy.switchpoint.max.failures=} (default {@value #DEFAULT_MAX_FAILURES};
+ * {@code <= 0} disables failover). After class-domain failover, a
+ * {@link ClassInfo#getVersion()} equality guard is used instead of a SwitchPoint.
+ * Counters are always updated; optional logging is enabled with
+ * {@code -Dgroovy.indy.invalidation.stats=true}.
+ *
+ * @since 6.0.0
+ */
+public final class IndyInvalidation {
+
+ /**
+ * Default maximum live SwitchPoint retirements before per-class failover.
+ */
+ public static final int DEFAULT_MAX_FAILURES = 100;
+
+ private static final Logger LOG = Logger.getLogger(IndyInvalidation.class.getName());
+ private static final boolean STATS_LOG = SystemUtil.getBooleanSafe("groovy.indy.invalidation.stats");
+ private static final int MAX_FAILURES = SystemUtil.getIntegerSafe(
+ "groovy.indy.switchpoint.max.failures", DEFAULT_MAX_FAILURES);
+
+ private static final AtomicLong CLASS_INVALIDATIONS = new AtomicLong();
+ private static final AtomicLong CATEGORY_INVALIDATIONS = new AtomicLong();
+ private static final AtomicLong FAILOVERS = new AtomicLong();
+
+ /**
+ * Category domain never fails over: enter/leave must always force re-link.
+ */
+ private static final SwitchPointInvalidator CATEGORY = new SwitchPointInvalidator(
+ 0, // unlimited
+ null);
+
+ /**
+ * Whether linked handles should install the category-domain SwitchPoint.
+ * Stays false until the first category-domain invalidation so monomorphic
+ * steady-state sites pay only one SwitchPoint check.
+ */
+ private static final AtomicBoolean CATEGORY_DOMAIN_ARMED = new AtomicBoolean();
+
+ private static final SwitchPoint[] EMPTY_SWITCH_POINTS = new SwitchPoint[0];
+
+ private static final MethodHandle CLASS_VERSION_OK;
+
+ static {
+ try {
+ CLASS_VERSION_OK = MethodHandles.lookup().findStatic(
+ IndyInvalidation.class,
+ "classVersionMatches",
+ MethodType.methodType(boolean.class, ClassInfo.class, int.class));
+ } catch (ReflectiveOperationException e) {
+ throw new ExceptionInInitializerError(e);
+ }
+ }
+
+ private IndyInvalidation() {
+ }
+
+ /**
+ * Returns whether {@code info}'s version still equals {@code expected}.
+ * Bound into generation guards after per-class SwitchPoint failover.
+ *
+ * @param info the class info
+ * @param expected the version captured at link time
+ * @return {@code true} when the version is unchanged
+ */
+ @SuppressWarnings("unused") // MethodHandle target
+ private static boolean classVersionMatches(final ClassInfo info, final int expected) {
+ return info.getVersion() == expected;
+ }
+
+ /**
+ * Returns the maximum SwitchPoint retirements configured for new class invalidators.
+ *
+ * @return the max-failures setting ({@code <= 0} means unlimited)
+ */
+ public static int maxFailures() {
+ return MAX_FAILURES;
+ }
+
+ /**
+ * Creates a SwitchPoint invalidator with the process-wide max-failure budget
+ * and failover accounting. Used by {@link ClassInfo} for the per-class domain.
+ *
+ * @return a new invalidator
+ */
+ public static SwitchPointInvalidator newClassInvalidator() {
+ return new SwitchPointInvalidator(MAX_FAILURES, failures -> {
+ FAILOVERS.incrementAndGet();
+ if (STATS_LOG && LOG.isLoggable(Level.INFO)) {
+ LOG.info("class SwitchPoint failover after " + failures + " invalidations");
+ }
+ });
+ }
+
+ /**
+ * Returns the category-domain switch point (process-wide). Never fails over.
+ *
+ * @return the category switch point
+ */
+ public static SwitchPoint categorySwitchPoint() {
+ return CATEGORY.getSwitchPoint();
+ }
+
+ /**
+ * Returns a live category switch point, or {@code null} if failed over
+ * (category domain is unlimited, so this is always non-null in practice).
+ *
+ * @return the live category switch point
+ */
+ public static SwitchPoint liveCategorySwitchPoint() {
+ return CATEGORY.getLiveSwitchPoint();
+ }
+
+ /**
+ * Returns the category-domain invalidator (for tests and advanced callers).
+ *
+ * @return the category invalidator
+ */
+ public static SwitchPointInvalidator categoryInvalidator() {
+ return CATEGORY;
+ }
+
+ /**
+ * Returns whether linked handles install a category-domain SwitchPoint.
+ * Remains {@code false} until the first {@link #invalidateCategory()} (or
+ * equivalent category-domain arming).
+ *
+ * @return {@code true} when the category domain is armed
+ * @since 6.0.0
+ */
+ public static boolean isCategoryDomainArmed() {
+ return CATEGORY_DOMAIN_ARMED.get();
+ }
+
+ /**
+ * Invalidates the category-global switch point. Called on category enter/leave
+ * and by {@code VMPlugin.invalidateCallSites()}.
+ * <p>
+ * The first invocation arms the category domain and bulk-invalidates every
+ * live per-class SwitchPoint so sites that linked without a category guard
+ * re-link and install one. Subsequent invocations only rotate the category
+ * SwitchPoint (class domains stay optimized unless they themselves change).
+ */
+ public static void invalidateCategory() {
+ armCategoryDomainIfNeeded();
+ CATEGORY.invalidate();
+ CATEGORY_INVALIDATIONS.incrementAndGet();
+ if (STATS_LOG && LOG.isLoggable(Level.FINE)) {
+ LOG.fine("category SwitchPoint invalidated; total=" + CATEGORY_INVALIDATIONS.get());
+ }
+ }
+
+ /**
+ * Arms the category domain on first use. Bulk-invalidates class domains so
+ * sites re-link with a category SwitchPoint installed.
+ */
+ private static void armCategoryDomainIfNeeded() {
+ if (CATEGORY_DOMAIN_ARMED.compareAndSet(false, true)) {
+ invalidateAllLoadedClassSwitchPoints();
+ if (STATS_LOG && LOG.isLoggable(Level.INFO)) {
+ LOG.info("category SwitchPoint domain armed; bulk class-domain invalidation");
+ }
+ }
+ }
+
+ /**
+ * Invalidates the per-class switch point for {@code type} and for every loaded
+ * subtype/implementor (hierarchy fan-out). No-op when {@code type} is {@code null}.
+ * Does not bump {@link ClassInfo#getVersion()} on subtypes (classic call sites
+ * keep their existing version checks); only indy SwitchPoints are cleared.
+ *
+ * @param type the class whose MetaClass changed
+ */
+ public static void invalidateClass(final Class<?> type) {
+ if (type == null) {
+ return;
+ }
+ invalidateClassHierarchy(type);
+ noteClassInvalidation();
+ if (STATS_LOG && LOG.isLoggable(Level.FINE)) {
+ LOG.fine("class SwitchPoint hierarchy invalidated for " + type.getName()
+ + "; total=" + CLASS_INVALIDATIONS.get());
+ }
+ }
+
+ /**
+ * Invalidates SwitchPoints for {@code type} and all loaded classes assignable
+ * from {@code type} (i.e. {@code type} itself and its subtypes).
+ * <p>
+ * Final classes short-circuit to a single invalidation (no subtype scan).
+ * Non-final types detach live switch points and invalidate them in one
+ * {@link SwitchPoint#invalidateAll(SwitchPoint[])} batch.
+ *
+ * @param type the root of the invalidation fan-out
+ */
+ public static void invalidateClassHierarchy(final Class<?> type) {
+ // Always invalidate the exact class first (cheap, correct even if weak refs cleared).
+ 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);
+ }
+ }
+ }
+ } finally {
+ // Always invalidate detached SPs even if the scan fails mid-way (e.g. OOM),
+ // otherwise sites could keep valid guards after a MetaClass change.
+ invalidateBatch(batch);
+ }
+ }
+
+ /**
+ * Detaches and invalidates every live per-class SwitchPoint currently held
+ * by loaded {@link ClassInfo} entries. Used when arming the category domain
+ * and for unattributed MetaClass changes that cannot be scoped.
+ *
+ * @since 6.0.0
+ */
+ public static void invalidateAllLoadedClassSwitchPoints() {
+ List<SwitchPoint> batch = new ArrayList<>();
+ try {
+ for (ClassInfo info : ClassInfo.getAllClassInfo()) {
+ SwitchPoint sp = info.detachLiveIndySwitchPoint();
+ if (sp != null) {
+ batch.add(sp);
+ }
+ }
+ } finally {
+ invalidateBatch(batch);
+ }
+ }
+
+ /**
+ * Invalidates every live class-domain SwitchPoint (and the category domain
+ * when already armed). Used for MetaClass registry events that carry no
+ * {@code Class} attribution so sites cannot be scoped safely.
+ *
+ * @since 6.0.0
+ */
+ public static void invalidateUnscoped() {
+ invalidateAllLoadedClassSwitchPoints();
+ if (CATEGORY_DOMAIN_ARMED.get()) {
+ CATEGORY.invalidate();
+ CATEGORY_INVALIDATIONS.incrementAndGet();
+ }
+ noteClassInvalidation();
+ if (STATS_LOG && LOG.isLoggable(Level.FINE)) {
+ LOG.fine("unscoped SwitchPoint invalidation; classTotal=" + CLASS_INVALIDATIONS.get());
+ }
+ }
+
+ private static void invalidateBatch(final List<SwitchPoint> batch) {
+ if (batch.isEmpty()) {
+ return;
+ }
+ 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 that need fan-out.
+ * Arrays are final but are not used as MetaClass roots in practice; treating
+ * them as no-subtype is still correct (array component hierarchy is separate).
+ */
+ private static boolean cannotHaveLoadedSubtypes(final Class<?> type) {
+ return type.isPrimitive() || (Modifier.isFinal(type.getModifiers()) && !type.isInterface());
+ }
+
+ /**
+ * Records a per-class invalidation for metrics. Called from
+ * {@link ClassInfo#incVersion()} after hierarchy SwitchPoints are invalidated.
+ */
+ public static void noteClassInvalidation() {
+ CLASS_INVALIDATIONS.incrementAndGet();
+ }
+
+ /**
+ * 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
+ * (static call sites).
+ *
+ * @param receiver the call receiver (may be {@code null})
+ * @return the class whose {@link ClassInfo} SwitchPoint guards this site
+ */
+ public static Class<?> switchPointClassFor(final Object receiver) {
+ if (receiver == null) {
+ return NullObject.class;
+ }
+ if (receiver instanceof Class<?> c) {
+ return c;
+ }
+ return receiver.getClass();
+ }
+
+ /**
+ * Returns the per-class switch point for the given receiver object.
+ *
+ * @param receiver the call receiver (may be {@code null})
+ * @return the class-domain switch point (possibly permanent invalid after failover)
+ */
+ public static SwitchPoint classSwitchPointFor(final Object receiver) {
+ return ClassInfo.getClassInfo(switchPointClassFor(receiver)).getIndySwitchPoint();
+ }
+
+ /**
+ * Returns the per-class switch point for the given class.
+ *
+ * @param type the class (must not be {@code null})
+ * @return the class-domain switch point
+ */
+ public static SwitchPoint classSwitchPointFor(final Class<?> type) {
+ return ClassInfo.getClassInfo(type).getIndySwitchPoint();
+ }
+
+ /**
+ * Installs class-domain then (when armed) category-domain guards on {@code handle}.
+ * Either domain change causes the site to take {@code fallback}.
+ *
+ * @param handle the fast-path handle
+ * @param fallback the re-link / fallback handle
+ * @param receiver the receiver used to select the class-domain switch point
+ * @return the guarded handle
+ */
+ public static MethodHandle guardWithMopSwitchPoints(
+ final MethodHandle handle, final MethodHandle fallback, final Object receiver) {
+ return guardWithMopSwitchPoints(handle, fallback, switchPointClassFor(receiver));
+ }
+
+ /**
+ * Installs class-domain then (when armed) category-domain guards on {@code handle}.
+ * <p>
+ * Live SwitchPoints are installed when available. After per-class failover,
+ * a {@link ClassInfo#getVersion()} equality guard preserves correctness without
+ * allocating further switch points. The category domain does not fail over and
+ * is installed only after {@link #isCategoryDomainArmed()} becomes {@code true}.
+ *
+ * @param handle the fast-path handle
+ * @param fallback the re-link / fallback handle
+ * @param receiverClass the class whose MetaClass domain guards this site
+ * @return the guarded handle
+ */
+ public static MethodHandle guardWithMopSwitchPoints(
+ final MethodHandle handle, final MethodHandle fallback, final Class<?> receiverClass) {
+ MethodHandle guarded = handle;
+ ClassInfo info = ClassInfo.getClassInfo(receiverClass);
+ SwitchPoint classSp = info.getLiveIndySwitchPoint();
+ if (classSp != null) {
+ guarded = classSp.guardWithTest(guarded, fallback);
+ } else {
+ // failed over: generation guard on ClassInfo.version
+ int version = info.getVersion();
+ MethodHandle test = MethodHandles.insertArguments(CLASS_VERSION_OK, 0, info, version);
+ test = MethodHandles.dropArguments(test, 0, guarded.type().parameterArray());
+ guarded = MethodHandles.guardWithTest(test, guarded, fallback);
+ }
+ // Category guards only after the domain is armed — keeps monomorphic
+ // steady-state at a single SwitchPoint until categories are used.
+ if (CATEGORY_DOMAIN_ARMED.get()) {
+ SwitchPoint catSp = CATEGORY.getLiveSwitchPoint();
+ if (catSp != null) {
+ guarded = catSp.guardWithTest(guarded, fallback);
+ }
+ }
+ return guarded;
+ }
+
+ /**
+ * Returns whether the category domain has entered permanent SwitchPoint failover.
+ * Category domain is unlimited, so this is always {@code false} under default config.
+ *
+ * @return {@code true} when category SwitchPoints are no longer refreshed
+ */
+ public static boolean isCategoryFailedOver() {
+ return CATEGORY.isFailedOver();
+ }
+
+ /**
+ * Returns the total number of per-class invalidations observed.
+ *
+ * @return class-domain invalidation count
+ */
+ public static long classInvalidationCount() {
+ return CLASS_INVALIDATIONS.get();
+ }
+
+ /**
+ * Returns the total number of category-domain invalidations observed.
+ *
+ * @return category-domain invalidation count
+ */
+ public static long categoryInvalidationCount() {
+ return CATEGORY_INVALIDATIONS.get();
+ }
+
+ /**
+ * Returns how many class invalidators have entered permanent failover.
+ *
+ * @return failover count
+ */
+ public static long failoverCount() {
+ return FAILOVERS.get();
+ }
+
+ /**
+ * Resets process-wide counters (tests only). Does not reset live switch points
+ * or the category-domain armed flag (arming is process-lifetime once set).
+ */
+ public static void resetCountersForTesting() {
+ CLASS_INVALIDATIONS.set(0);
+ CATEGORY_INVALIDATIONS.set(0);
+ FAILOVERS.set(0);
+ }
+}
diff --git a/src/main/java/org/apache/groovy/runtime/indy/SwitchPointInvalidator.java b/src/main/java/org/apache/groovy/runtime/indy/SwitchPointInvalidator.java
new file mode 100644
index 0000000000..18f04ea9d1
--- /dev/null
+++ b/src/main/java/org/apache/groovy/runtime/indy/SwitchPointInvalidator.java
@@ -0,0 +1,286 @@
+/*
+ * 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 java.lang.invoke.SwitchPoint;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.LongConsumer;
+
+/**
+ * Manages a lazily allocated {@link SwitchPoint} with optional failover after
+ * repeated invalidations.
+ * <p>
+ * Call sites capture the {@link SwitchPoint} returned by {@link #getLiveSwitchPoint()}
+ * in {@code guardWithTest} chains. On {@link #invalidate()}, that switch point is
+ * invalidated so linked sites fall back and re-link. A fresh switch point is
+ * allocated on the next live get unless the failure budget is exhausted.
+ * <p>
+ * After failover, {@link #getLiveSwitchPoint()} returns {@code null} so callers can
+ * install an alternate correct guard (e.g. a generation/version check) instead of
+ * a permanently invalid switch point (which would recurse through re-link forever).
+ * <p>
+ * Failover is concurrent-safe: any switch point that races into {@code current}
+ * between a live retirement and the permanent {@code INVALID} sentinel is itself
+ * invalidated, so no orphaned valid switch point can outlive the domain.
+ * <p>
+ * Hierarchy fan-out and other bulk paths should prefer {@link #detachLive()} and a
+ * single {@link SwitchPoint#invalidateAll(SwitchPoint[])} over many individual
+ * {@link #invalidate()} calls (GROOVY-12191).
+ * <p>
+ * {@code maxFailures <= 0} means unlimited replacements (no failover).
+ * Only invalidations that actually retire a live switch point count toward the budget.
+ *
+ * @since 6.0.0
+ */
+public final class SwitchPointInvalidator {
+
+ /**
+ * Pre-invalidated switch point used only as an internal sentinel after failover.
+ * Never installed as a live call-site guard.
+ */
+ private static final SwitchPoint INVALID = new SwitchPoint();
+
+ /**
+ * Reusable one-element array for single-SP {@link SwitchPoint#invalidateAll},
+ * guarded by {@link #SINGLE_INVALIDATE_LOCK}. Invalidation is rare relative to
+ * steady-state dispatch, so the lock is not on a hot path.
+ */
+ private static final Object SINGLE_INVALIDATE_LOCK = new Object();
+ private static final SwitchPoint[] SINGLE_INVALIDATE_BUF = new SwitchPoint[1];
+
+ static {
+ SwitchPoint.invalidateAll(new SwitchPoint[]{INVALID});
+ }
+
+ private final int maxFailures;
+ private final LongConsumer onFailover;
+ /**
+ * {@code null} means no live switch point yet (lazy). {@link #INVALID} means
+ * permanently failed over.
+ */
+ private final AtomicReference<SwitchPoint> current = new AtomicReference<>();
+ private final AtomicInteger failureCount = new AtomicInteger();
+ private final AtomicInteger failoverOnce = new AtomicInteger();
+
+ /**
+ * Creates an invalidator.
+ *
+ * @param maxFailures maximum live-switch-point retirements before failover;
+ * {@code <= 0} disables failover
+ * @param onFailover optional callback invoked once when failover engages
+ * (may be {@code null})
+ */
+ public SwitchPointInvalidator(final int maxFailures, final LongConsumer onFailover) {
+ this.maxFailures = maxFailures;
+ this.onFailover = onFailover;
+ }
+
+ /**
+ * Creates an invalidator with no failover callback.
+ *
+ * @param maxFailures maximum live-switch-point retirements before failover;
+ * {@code <= 0} disables failover
+ */
+ public SwitchPointInvalidator(final int maxFailures) {
+ this(maxFailures, null);
+ }
+
+ /**
+ * Returns a live switch point to install in a call-site guard chain, or
+ * {@code null} when this invalidator has failed over (callers must use an
+ * alternate correct guard).
+ * <p>
+ * Lazily allocates a valid switch point on first use unless failover is active.
+ * This method is atomic w.r.t. failover: it never returns the permanent
+ * invalid sentinel for use as a live guard.
+ *
+ * @return a live switch point, or {@code null} if failed over
+ */
+ public SwitchPoint getLiveSwitchPoint() {
+ for (;;) {
+ if (isFailedOver()) {
+ return null;
+ }
+ SwitchPoint sp = current.get();
+ if (sp == INVALID) {
+ return null;
+ }
+ if (sp != null) {
+ return sp;
+ }
+ SwitchPoint created = new SwitchPoint();
+ if (current.compareAndSet(null, created)) {
+ // A concurrent invalidate may have failed over after our CAS.
+ // Never hand out a switch point once the domain is permanent.
+ if (isFailedOver()) {
+ SwitchPoint raced = current.getAndSet(INVALID);
+ invalidateIfLive(raced);
+ invalidateIfLive(created);
+ return null;
+ }
+ return created;
+ }
+ // lost the race — retry
+ }
+ }
+
+ /**
+ * Returns a switch point for observability / tests. Prefer
+ * {@link #getLiveSwitchPoint()} when building call-site guards.
+ * After failover this returns the permanent invalid sentinel.
+ *
+ * @return a switch point (possibly permanently invalid after failover)
+ */
+ public SwitchPoint getSwitchPoint() {
+ SwitchPoint live = getLiveSwitchPoint();
+ return live != null ? live : INVALID;
+ }
+
+ /**
+ * Invalidates the current live switch point (if any) so linked sites re-link.
+ * After the failure budget is exhausted, further calls are no-ops and
+ * {@link #getLiveSwitchPoint()} returns {@code null}.
+ * <p>
+ * Only retirements of a non-null live switch point count toward
+ * {@link #getFailureCount()} / the failover budget. Concurrent installs that
+ * race into {@code current} during failover are captured and invalidated so
+ * they cannot remain valid after the domain has failed over.
+ */
+ public void invalidate() {
+ SwitchPoint retired = detachLive();
+ invalidateIfLive(retired);
+ }
+
+ /**
+ * Atomically detaches the live switch point for bulk {@link SwitchPoint#invalidateAll}
+ * without invalidating it yet. Counts toward the failover budget exactly as
+ * {@link #invalidate()} would. Returns {@code null} when nothing was live or
+ * the domain has failed over.
+ * <p>
+ * The caller <em>must</em> invalidate any non-null return value (typically
+ * batched with other detached switch points). Racing installs that force
+ * failover are invalidated inside this method so they cannot outlive the domain.
+ *
+ * @return the detached live switch point, or {@code null}
+ * @since 6.0.0
+ */
+ public SwitchPoint detachLive() {
+ if (isFailedOver()) {
+ // Ensure the permanent sentinel is installed (may race with getLive).
+ pinInvalidAndDrain();
+ return null;
+ }
+ for (;;) {
+ SwitchPoint sp = current.get();
+ if (sp == INVALID) {
+ return null;
+ }
+ if (sp == null) {
+ // Nothing live. If a concurrent invalidator already exhausted the
+ // budget, pin the sentinel so getLive cannot install a fresh SP.
+ if (maxFailures > 0 && failureCount.get() >= maxFailures) {
+ pinInvalidAndDrain();
+ }
+ return null;
+ }
+ if (!current.compareAndSet(sp, null)) {
+ continue;
+ }
+ // We own retirement of sp.
+ int failures = failureCount.incrementAndGet();
+ if (maxFailures > 0 && failures >= maxFailures) {
+ // Failover: install INVALID and drain any SP that raced in after
+ // our CAS to null (getLive could have CAS'd null → created).
+ SwitchPoint raced = current.getAndSet(INVALID);
+ invalidateIfLive(raced);
+ if (failoverOnce.compareAndSet(0, 1) && onFailover != null) {
+ onFailover.accept(failures);
+ }
+ }
+ return sp;
+ }
+ }
+
+ /**
+ * Installs the permanent invalid sentinel and invalidates any live switch
+ * point that was present (including one that raced in after budget exhaust).
+ */
+ private void pinInvalidAndDrain() {
+ SwitchPoint prev = current.getAndSet(INVALID);
+ invalidateIfLive(prev);
+ }
+
+ /**
+ * Invalidates a single live switch point, reusing a process-wide one-element
+ * buffer under a short lock to avoid allocating {@code SwitchPoint[]} on the
+ * rare invalidation path.
+ *
+ * @param sp candidate switch point (may be {@code null} or the permanent invalid sentinel)
+ */
+ static void invalidateIfLive(final SwitchPoint sp) {
+ if (sp != null && sp != INVALID && !sp.hasBeenInvalidated()) {
+ synchronized (SINGLE_INVALIDATE_LOCK) {
+ SINGLE_INVALIDATE_BUF[0] = sp;
+ try {
+ SwitchPoint.invalidateAll(SINGLE_INVALIDATE_BUF);
+ } finally {
+ SINGLE_INVALIDATE_BUF[0] = null;
+ }
+ }
+ }
+ }
+
+ /**
+ * Returns whether this invalidator has exhausted its failure budget.
+ *
+ * @return {@code true} when live switch points are no longer allocated
+ */
+ public boolean isFailedOver() {
+ return maxFailures > 0 && failureCount.get() >= maxFailures;
+ }
+
+ /**
+ * Returns how many live switch points have been retired by {@link #invalidate()}
+ * or {@link #detachLive()}.
+ *
+ * @return the retirement count
+ */
+ public int getFailureCount() {
+ return failureCount.get();
+ }
+
+ /**
+ * Returns the configured failure budget ({@code <= 0} means unlimited).
+ *
+ * @return the max failure setting
+ */
+ public int getMaxFailures() {
+ return maxFailures;
+ }
+
+ /**
+ * Returns the shared permanently-invalidated switch point (for tests).
+ *
+ * @return the invalid dummy switch point
+ */
+ static SwitchPoint invalidSwitchPoint() {
+ return INVALID;
+ }
+}
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
new file mode 100644
index 0000000000..7756ffa6cf
--- /dev/null
+++ b/src/main/java/org/apache/groovy/runtime/indy/package-info.java
@@ -0,0 +1,32 @@
+/*
+ * 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.
+ */
+
+/**
+ * Invokedynamic SwitchPoint utilities for the Groovy MOP (GROOVY-12191).
+ * <p>
+ * Provides scoped {@link java.lang.invoke.SwitchPoint} management so MetaClass
+ * changes affect only the classes that changed (per-class domain + hierarchy
+ * fan-out), with a separate process-wide category domain for
+ * {@code use(Category)} enter/leave. Category guards are armed lazily so
+ * monomorphic steady-state sites pay a single SwitchPoint until the first
+ * category use.
+ *
+ * @since 6.0.0
+ */
+package org.apache.groovy.runtime.indy;
diff --git a/src/main/java/org/codehaus/groovy/reflection/ClassInfo.java b/src/main/java/org/codehaus/groovy/reflection/ClassInfo.java
index aa08713430..cb4073a820 100644
--- a/src/main/java/org/codehaus/groovy/reflection/ClassInfo.java
+++ b/src/main/java/org/codehaus/groovy/reflection/ClassInfo.java
@@ -25,6 +25,9 @@ import groovy.lang.GroovySystem;
import groovy.lang.MetaClass;
import groovy.lang.MetaClassRegistry;
import groovy.lang.MetaMethod;
+import groovy.transform.Internal;
+import org.apache.groovy.runtime.indy.IndyInvalidation;
+import org.apache.groovy.runtime.indy.SwitchPointInvalidator;
import org.apache.groovy.util.concurrent.ManagedIdentityConcurrentMap;
import org.codehaus.groovy.reflection.GroovyClassValue.ComputeValue;
import org.codehaus.groovy.reflection.stdclasses.ArrayCachedClass;
@@ -49,9 +52,9 @@ import org.codehaus.groovy.util.LockableObject;
import org.codehaus.groovy.util.ManagedConcurrentLinkedQueue;
import org.codehaus.groovy.util.ManagedReference;
import org.codehaus.groovy.util.ReferenceBundle;
-import org.codehaus.groovy.vmplugin.VMPluginFactory;
import java.io.Serial;
+import java.lang.invoke.SwitchPoint;
import java.lang.ref.WeakReference;
import java.math.BigDecimal;
import java.math.BigInteger;
@@ -77,6 +80,11 @@ public class ClassInfo implements Finalizable {
public final int hash = -1;
private final WeakReference<Class<?>> classRef;
private final AtomicInteger version = new AtomicInteger();
+ /**
+ * Per-class SwitchPoint domain for indy call sites (GROOVY-12191).
+ * Invalidated on MetaClass / version changes for this class only.
+ */
+ private final SwitchPointInvalidator indySwitchPoint = IndyInvalidation.newClassInvalidator();
private MetaClass strongMetaClass;
private ManagedReference<MetaClass> weakMetaClass;
MetaMethod[] dgmMetaMethods = MetaMethod.EMPTY_ARRAY;
@@ -124,12 +132,118 @@ public class ClassInfo implements Finalizable {
}
/**
- * Increments the version number and invalidates call sites.
+ * Increments the version number and invalidates this class's indy SwitchPoint
+ * (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 uses a
+ * separate process-wide domain via {@link org.codehaus.groovy.vmplugin.VMPlugin#invalidateCallSites()}.
+ * <p>
+ * Prefer this over bare {@link #invalidateIndySwitchPoint()} when the MetaClass
+ * actually changed: it is the public generation-bump entry that also fans out
+ * to loaded subtypes. {@link #setStrongMetaClass} / {@link #setWeakMetaClass}
+ * bump generation for this class only (registry listeners apply hierarchy fan-out).
*/
public void incVersion() {
version.incrementAndGet();
- VMPluginFactory.getPlugin().invalidateCallSites();
+ Class<?> type = getTheClass();
+ if (type != null) {
+ IndyInvalidation.invalidateClassHierarchy(type);
+ } else {
+ invalidateIndySwitchPoint();
+ }
+ IndyInvalidation.noteClassInvalidation();
+ }
+
+ /**
+ * Bumps {@link #getVersion()} and, when {@code invalidateSwitchPoint} is true,
+ * invalidates this class's indy SwitchPoint only (no subtype fan-out, no
+ * process-wide counter). Used by strong/weak/per-instance MetaClass paths;
+ * callers that need hierarchy fan-out follow up via
+ * {@link IndyInvalidation#invalidateClassHierarchy(Class)} or {@link #incVersion()}.
+ * <p>
+ * First MetaClass install ({@code null →} default MC) typically has no linked
+ * call sites holding this class's SwitchPoint yet, so it only bumps version.
+ * Replacement and clear always retire the SwitchPoint.
+ */
+ private void bumpGenerationLocal(final boolean invalidateSwitchPoint) {
+ version.incrementAndGet();
+ if (invalidateSwitchPoint) {
+ invalidateIndySwitchPoint();
+ }
+ }
+
+ /**
+ * Whether this class currently has a class-level MetaClass (strong or weak).
+ */
+ private boolean hasClassLevelMetaClass() {
+ if (strongMetaClass != null) {
+ return true;
+ }
+ ManagedReference<MetaClass> weakRef = weakMetaClass;
+ return weakRef != null && weakRef.get() != null;
+ }
+
+ /**
+ * Returns the SwitchPoint that guards indy targets for this class's MetaClass state.
+ * Prefer {@link #getLiveIndySwitchPoint()} when installing call-site guards.
+ *
+ * @return the class-domain SwitchPoint for indy
+ * @since 6.0.0
+ */
+ @Internal
+ public SwitchPoint getIndySwitchPoint() {
+ return indySwitchPoint.getSwitchPoint();
+ }
+
+ /**
+ * Returns a live class-domain SwitchPoint, or {@code null} after failover
+ * (callers should install a version/generation guard instead).
+ *
+ * @return a live SwitchPoint, or {@code null} if failed over
+ * @since 6.0.0
+ */
+ @Internal
+ public SwitchPoint getLiveIndySwitchPoint() {
+ return indySwitchPoint.getLiveSwitchPoint();
+ }
+
+ /**
+ * Invalidates this class's indy SwitchPoint without bumping {@link #getVersion()}.
+ * Prefer {@link #incVersion()} when the MetaClass actually changed.
+ *
+ * @since 6.0.0
+ */
+ @Internal
+ public void invalidateIndySwitchPoint() {
+ indySwitchPoint.invalidate();
+ }
+
+ /**
+ * Detaches the live indy SwitchPoint for bulk {@link SwitchPoint#invalidateAll}
+ * without invalidating it yet. Counts toward the per-class failover budget.
+ * The caller must invalidate any non-null return value.
+ *
+ * @return the detached live SwitchPoint, or {@code null} if none / failed over
+ * @since 6.0.0
+ * @see org.apache.groovy.runtime.indy.IndyInvalidation#invalidateClassHierarchy(Class)
+ */
+ @Internal
+ public SwitchPoint detachLiveIndySwitchPoint() {
+ return indySwitchPoint.detachLive();
+ }
+
+ /**
+ * Returns whether this class's indy SwitchPoint domain has entered permanent
+ * failover after repeated invalidations.
+ *
+ * @return {@code true} when class SwitchPoints are no longer refreshed
+ * @since 6.0.0
+ */
+ @Internal
+ public boolean isIndySwitchPointFailedOver() {
+ return indySwitchPoint.isFailedOver();
}
/**
@@ -254,11 +368,20 @@ public class ClassInfo implements Finalizable {
/**
* Sets the strong (immutable) metaclass for this class.
* Increments the version number and manages ExpandoMetaClass registry.
+ * <p>
+ * On replacement or clear, also invalidates this class's indy SwitchPoint
+ * (GROOVY-12191). First install ({@code null →} MC) only bumps version;
+ * hierarchy fan-out for subtypes is applied by MetaClass registry listeners
+ * or {@link #incVersion()}.
*
* @param answer the metaclass to set, or {@code null} to clear
*/
public void setStrongMetaClass(MetaClass answer) {
- version.incrementAndGet();
+ // Version always; SwitchPoint when replacing/clearing an established MC.
+ // Hierarchy fan-out for subtypes is applied by registry listeners / incVersion
+ // (GROOVY-12191). First install (null → MC) only bumps version.
+ boolean replaceOrClear = hasClassLevelMetaClass() || answer == null;
+ bumpGenerationLocal(replaceOrClear);
// safe value here to avoid multiple reads with possibly
// differing values due to concurrency
@@ -300,11 +423,16 @@ public class ClassInfo implements Finalizable {
/**
* Sets the weak (mutable) metaclass for this class.
* Clears the strong metaclass and increments the version number.
+ * <p>
+ * On replacement or clear, also invalidates this class's indy SwitchPoint
+ * (GROOVY-12191). First install only bumps version.
*
* @param answer the metaclass to set, or {@code null} to clear
*/
public void setWeakMetaClass(MetaClass answer) {
- version.incrementAndGet();
+ // Version always; SwitchPoint when replacing/clearing (GROOVY-12191).
+ boolean replaceOrClear = hasClassLevelMetaClass() || answer == null;
+ bumpGenerationLocal(replaceOrClear);
strongMetaClass = null;
ManagedReference<MetaClass> newRef = null;
@@ -527,7 +655,10 @@ public class ClassInfo implements Finalizable {
* @param metaClass the metaclass to set, or {@code null} to remove the association
*/
public void setPerInstanceMetaClass(Object obj, MetaClass metaClass) {
- version.incrementAndGet();
+ // Per-instance MetaClass changes always retire the class SwitchPoint so
+ // sites that may observe instance-level dispatch re-link (GROOVY-12191).
+ // Registry listeners still apply hierarchy fan-out.
+ bumpGenerationLocal(true);
if (metaClass != null) {
if (perInstanceMetaClassMap == null)
diff --git a/src/main/java/org/codehaus/groovy/vmplugin/v8/ColdReflectiveMethodHandleWrapper.java b/src/main/java/org/codehaus/groovy/vmplugin/v8/ColdReflectiveMethodHandleWrapper.java
index 6cbd8f3687..c414e205b2 100644
--- a/src/main/java/org/codehaus/groovy/vmplugin/v8/ColdReflectiveMethodHandleWrapper.java
+++ b/src/main/java/org/codehaus/groovy/vmplugin/v8/ColdReflectiveMethodHandleWrapper.java
@@ -21,7 +21,9 @@ package org.codehaus.groovy.vmplugin.v8;
import groovy.lang.GroovyObject;
import groovy.lang.MetaClass;
import groovy.lang.MetaMethod;
+import org.apache.groovy.runtime.indy.IndyInvalidation;
import org.codehaus.groovy.reflection.CachedMethod;
+import org.codehaus.groovy.reflection.ClassInfo;
import org.codehaus.groovy.runtime.GroovyCategorySupport;
import org.codehaus.groovy.runtime.wrappers.Wrapper;
import org.codehaus.groovy.vmplugin.VMPluginFactory;
@@ -48,10 +50,9 @@ import java.lang.reflect.Modifier;
* hot path unchanged.
* <p>
* The plain-Java validity checks in {@link #isValidFor} mirror the guards the
- * full chain would install: switch-point freshness (which also covers
- * category enter/leave, as those invalidate the switch point), exact argument
- * classes (at least as strict as the chain's same-class guards), and
- * metaclass identity for {@code GroovyObject} receivers.
+ * full chain would install: per-class and category switch-point freshness
+ * (GROOVY-12191), exact argument classes (at least as strict as the chain's
+ * same-class guards), and metaclass identity for {@code GroovyObject} receivers.
*/
class ColdReflectiveMethodHandleWrapper extends MethodHandleWrapper {
@@ -63,7 +64,11 @@ class ColdReflectiveMethodHandleWrapper extends MethodHandleWrapper {
final Boolean thisCall;
final Boolean spreadCall;
private final MetaClass selectionMetaClass;
- private final SwitchPoint validity;
+ private final SwitchPoint classValidity;
+ private final SwitchPoint categoryValidity;
+ private final boolean classFailedOver;
+ private final int classVersionAtLink;
+ private final ClassInfo classInfo;
private final Class<?>[] argClasses;
private final MethodHandle reflectiveHandle;
/**
@@ -76,7 +81,8 @@ class ColdReflectiveMethodHandleWrapper extends MethodHandleWrapper {
private ColdReflectiveMethodHandleWrapper(MetaMethod method, CacheableCallSite callSite, Class<?> sender,
String methodName, int callID, Boolean safeNavigation, Boolean thisCall, Boolean spreadCall,
- MetaClass selectionMetaClass, SwitchPoint validity, Class<?>[] argClasses) {
+ MetaClass selectionMetaClass, SwitchPoint classValidity, SwitchPoint categoryValidity,
+ boolean classFailedOver, int classVersionAtLink, ClassInfo classInfo, Class<?>[] argClasses) {
super(null, null, method, true);
this.callSite = callSite;
this.sender = sender;
@@ -86,7 +92,11 @@ class ColdReflectiveMethodHandleWrapper extends MethodHandleWrapper {
this.thisCall = thisCall;
this.spreadCall = spreadCall;
this.selectionMetaClass = selectionMetaClass;
- this.validity = validity;
+ this.classValidity = classValidity;
+ this.categoryValidity = categoryValidity;
+ this.classFailedOver = classFailedOver;
+ this.classVersionAtLink = classVersionAtLink;
+ this.classInfo = classInfo;
this.argClasses = argClasses;
this.reflectiveHandle = IndyInterface.COLD_REFLECTIVE_INVOKER.bindTo(this);
}
@@ -112,7 +122,13 @@ class ColdReflectiveMethodHandleWrapper extends MethodHandleWrapper {
* @return {@code true} if the cached selection is still valid for them
*/
boolean isValidFor(Object[] arguments) {
- if (validity.hasBeenInvalidated()) return false;
+ if (classFailedOver) {
+ if (classInfo.getVersion() != classVersionAtLink) return false;
+ } else if (classValidity != null && classValidity.hasBeenInvalidated()) {
+ return false;
+ }
+ // Category domain never fails over under default config.
+ if (categoryValidity != null && categoryValidity.hasBeenInvalidated()) return false;
Class<?>[] classes = argClasses;
if (arguments.length != classes.length) return false;
for (int i = 0; i < classes.length; i++) {
@@ -152,8 +168,24 @@ class ColdReflectiveMethodHandleWrapper extends MethodHandleWrapper {
if (a instanceof Wrapper) return null; // cast markers need the full coercion path
argClasses[i] = (a == null) ? null : a.getClass();
}
+ Object receiver = arguments[0];
+ Class<?> spClass = IndyInvalidation.switchPointClassFor(receiver);
+ ClassInfo classInfo = ClassInfo.getClassInfo(spClass);
+ SwitchPoint liveClassSp = classInfo.getLiveIndySwitchPoint();
+ boolean classFailedOver = liveClassSp == null;
+ // Match full-path guards: omit category SwitchPoint until the domain is armed
+ // (first category use bulk-invalidates class SPs, forcing cold revalidation).
+ SwitchPoint categorySp = IndyInvalidation.isCategoryDomainArmed()
+ ? IndyInvalidation.liveCategorySwitchPoint()
+ : null;
return new ColdReflectiveMethodHandleWrapper(cm, callSite, sender, methodName, callID,
- safeNavigation, thisCall, spreadCall, mc, IndyInterface.switchPoint, argClasses);
+ safeNavigation, thisCall, spreadCall, mc,
+ liveClassSp,
+ categorySp,
+ classFailedOver,
+ classInfo.getVersion(),
+ classInfo,
+ argClasses);
}
/**
diff --git a/src/main/java/org/codehaus/groovy/vmplugin/v8/IndyCompoundAssign.java b/src/main/java/org/codehaus/groovy/vmplugin/v8/IndyCompoundAssign.java
index 81325caa32..46d9a3f89f 100644
--- a/src/main/java/org/codehaus/groovy/vmplugin/v8/IndyCompoundAssign.java
+++ b/src/main/java/org/codehaus/groovy/vmplugin/v8/IndyCompoundAssign.java
@@ -146,8 +146,8 @@ public final class IndyCompoundAssign {
Class<?> ac = (arg == null) ? null : arg.getClass();
MethodHandle test = MethodHandles.insertArguments(GUARD, 0, rc, ac);
MethodHandle guarded = MethodHandles.guardWithTest(test, invoke, elseTarget);
- // a metaclass change invalidates the site, exactly as for a normal indy call.
- guarded = IndyInterface.switchPoint.guardWithTest(guarded, elseTarget);
+ // Per-class + category SwitchPoints, same domains as a normal indy call (GROOVY-12191).
+ guarded = IndyInterface.applyMopSwitchPoints(guarded, elseTarget, receiver);
// Per-instance metaclasses make a class-keyed cache unsound, so mark such
// shapes uncacheable (the wrapper is still used for the current call) —
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 9379244204..1ef0f4bdd2 100644
--- a/src/main/java/org/codehaus/groovy/vmplugin/v8/IndyInterface.java
+++ b/src/main/java/org/codehaus/groovy/vmplugin/v8/IndyInterface.java
@@ -20,6 +20,7 @@ package org.codehaus.groovy.vmplugin.v8;
import groovy.lang.GroovyRuntimeException;
import groovy.lang.GroovySystem;
+import org.apache.groovy.runtime.indy.IndyInvalidation;
import org.apache.groovy.util.SystemUtil;
import org.codehaus.groovy.GroovyBugError;
import org.codehaus.groovy.runtime.GeneratedClosure;
@@ -215,27 +216,72 @@ public class IndyInterface {
}
/**
- * Shared switch point invalidated when metaclass state changes.
+ * Category-domain SwitchPoint snapshot for binary compatibility and legacy
+ * readers. Metaclass changes are scoped per class (and subtypes) via
+ * {@link org.codehaus.groovy.reflection.ClassInfo} SwitchPoints (GROOVY-12191);
+ * this field tracks the <em>category</em> invalidation domain only and is
+ * refreshed when {@link #invalidateSwitchPoints()} runs.
+ * <p>
+ * <strong>Behavioral change in 6.0:</strong> this is no longer a process-wide
+ * MOP SwitchPoint for MetaClass changes — only the category domain.
+ *
+ * @see IndyInvalidation
*/
- protected static SwitchPoint switchPoint = new SwitchPoint();
+ protected static volatile SwitchPoint switchPoint = IndyInvalidation.categorySwitchPoint();
static {
- GroovySystem.getMetaClassRegistry().addMetaClassRegistryChangeEventListener(cmcu -> invalidateSwitchPoints());
+ // MetaClass registry changes invalidate the affected class + subtypes (GROOVY-12191).
+ 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 {
+ // Unattributed change: cannot scope — re-link every class domain
+ // (and the category domain when armed). Do not use category-only
+ // invalidation: sites may not yet install a category SwitchPoint
+ // until the category domain is armed (lazy category guards).
+ IndyInvalidation.invalidateUnscoped();
+ switchPoint = IndyInvalidation.categorySwitchPoint();
+ if (LOG_ENABLED) {
+ LOG.info("unscoped SwitchPoint invalidation (unattributed MetaClass change)");
+ }
+ }
+ });
}
/**
- * Callback for constant metaclass update change
+ * Invalidates the category-global SwitchPoint domain.
+ * <p>
+ * Used by category enter/leave and {@code VMPlugin.invalidateCallSites()}.
+ * Per-class MetaClass changes must use {@link IndyInvalidation#invalidateClass(Class)}
+ * (or {@link org.codehaus.groovy.reflection.ClassInfo#incVersion()}) instead
+ * so unrelated call sites stay optimized (GROOVY-12191).
+ * <p>
+ * Note: this no longer flushes all MetaClass-linked indy sites — only the
+ * category domain. That is intentional for GROOVY-12191.
*/
protected static void invalidateSwitchPoints() {
if (LOG_ENABLED) {
- LOG.info("invalidating switch point");
+ LOG.info("invalidating category switch point");
}
+ IndyInvalidation.invalidateCategory();
+ // Keep the protected field pointing at the live category SwitchPoint.
+ switchPoint = IndyInvalidation.categorySwitchPoint();
+ }
- synchronized (IndyInterface.class) {
- SwitchPoint old = switchPoint;
- switchPoint = new SwitchPoint();
- SwitchPoint.invalidateAll(new SwitchPoint[]{old});
- }
+ /**
+ * Installs per-class and (when armed) category SwitchPoint guards on a linked handle.
+ *
+ * @param handle fast-path handle
+ * @param fallback re-link handle
+ * @param receiver call receiver (may be {@code null})
+ * @return guarded handle
+ */
+ static MethodHandle applyMopSwitchPoints(final MethodHandle handle, final MethodHandle fallback, final Object receiver) {
+ return IndyInvalidation.guardWithMopSwitchPoints(handle, fallback, receiver);
}
/**
@@ -472,9 +518,14 @@ public class IndyInterface {
throw ScriptBytecodeAdapter.unwrap(gre);
}
}
- MethodHandle mh = selectMethodHandle(cold.callSite, cold.sender, cold.methodName, cold.callID,
- cold.safeNavigation, cold.thisCall, cold.spreadCall, 1, arguments);
- return mh.invokeExact(arguments);
+ // Re-select without the cold tier so an always-invalid SwitchPoint (or any
+ // permanent cold miss after class-domain failover) cannot recurse through
+ // tryBuild → invokeColdReflective (GROOVY-12191).
+ MethodHandleWrapper full = fallback(cold.callSite, cold.sender, cold.methodName, cold.callID,
+ cold.safeNavigation, cold.thisCall, cold.spreadCall, 1, arguments, false);
+ cold.callSite.put(receiverCacheKey(arguments[0]),
+ full.isCanSetTarget() ? full : NULL_METHOD_HANDLE_WRAPPER);
+ return full.getCachedMethodHandle().invokeExact(arguments);
}
/**
diff --git a/src/main/java/org/codehaus/groovy/vmplugin/v8/Selector.java b/src/main/java/org/codehaus/groovy/vmplugin/v8/Selector.java
index 989e1eb0f5..cdc7284a37 100644
--- a/src/main/java/org/codehaus/groovy/vmplugin/v8/Selector.java
+++ b/src/main/java/org/codehaus/groovy/vmplugin/v8/Selector.java
@@ -100,7 +100,7 @@ import static org.codehaus.groovy.vmplugin.v8.IndyGuardsFiltersAndSignatures.unw
import static org.codehaus.groovy.vmplugin.v8.IndyInterface.CallType;
import static org.codehaus.groovy.vmplugin.v8.IndyInterface.LOG;
import static org.codehaus.groovy.vmplugin.v8.IndyInterface.LOG_ENABLED;
-import static org.codehaus.groovy.vmplugin.v8.IndyInterface.switchPoint;
+import static org.codehaus.groovy.vmplugin.v8.IndyInterface.applyMopSwitchPoints;
/**
* Base state holder for invokedynamic method, property, constructor, and cast selection.
@@ -1283,9 +1283,11 @@ public abstract class Selector {
}
}
- // handle constant metaclass and category changes
- handle = switchPoint.guardWithTest(handle, fallback);
- if (LOG_ENABLED) LOG.info("added switch point guard");
+ // Per-class MetaClass domain + category-global domain (GROOVY-12191).
+ // Metaclass changes invalidate only the receiver class's SwitchPoint;
+ // category enter/leave invalidates the category domain for all sites.
+ handle = applyMopSwitchPoints(handle, fallback, receiver);
+ if (LOG_ENABLED) LOG.info("added class and category switch point guards");
java.util.function.Predicate<Class<?>> nonFinalOrNullUnsafe = (t) -> {
return !Modifier.isFinal(t.getModifiers())
@@ -1444,7 +1446,8 @@ public abstract class Selector {
* ({@code arguments[0]} is the receiver). The result has type
* {@code callSite.type()}. Guard and switch-point wrapping are intentionally
* omitted — the caller (compound-assignment) applies its own per-shape guard
- * and shares the global MOP {@link IndyInterface#switchPoint}. The caller must
+ * and the scoped MOP SwitchPoints (per-class + category; see
+ * {@link org.apache.groovy.runtime.indy.IndyInvalidation}). The caller must
* have already established that {@code methodName} resolves for this receiver
* (e.g. via {@code respondsTo}); this routes the actual invocation through the
* same selection, coercion and wrapping path as a normal call.
diff --git a/src/test/groovy/bugs/Groovy12191.groovy b/src/test/groovy/bugs/Groovy12191.groovy
new file mode 100644
index 0000000000..343096c2bc
--- /dev/null
+++ b/src/test/groovy/bugs/Groovy12191.groovy
@@ -0,0 +1,183 @@
+/*
+ * 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 bugs
+
+import org.apache.groovy.runtime.indy.IndyInvalidation
+import org.codehaus.groovy.reflection.ClassInfo
+import org.junit.jupiter.api.Test
+
+import java.lang.invoke.SwitchPoint
+
+import static groovy.test.GroovyAssert.assertScript
+import static org.junit.jupiter.api.Assertions.assertFalse
+import static org.junit.jupiter.api.Assertions.assertTrue
+
+/**
+ * GROOVY-12191: scoped indy SwitchPoint invalidation.
+ * Metaclass changes for class A must not invalidate class B's SwitchPoint;
+ * category enter/leave still uses a process-wide domain so category methods
+ * become visible to previously linked sites.
+ */
+final class Groovy12191 {
+
+ @Test
+ void metaclassChange_invalidatesOnlyAffectedClassSwitchPoint() {
+ SwitchPoint spA = ClassInfo.getClassInfo(TypeA).indySwitchPoint
+ SwitchPoint spB = ClassInfo.getClassInfo(TypeB).indySwitchPoint
+ assertFalse(spA.hasBeenInvalidated())
+ assertFalse(spB.hasBeenInvalidated())
+
+ TypeA.metaClass.extra = { -> 'from-emc' }
+ // ExpandoMetaClass.incVersion → ClassInfo.incVersion → class-domain only
+ assertTrue(spA.hasBeenInvalidated())
+ assertFalse(spB.hasBeenInvalidated())
+
+ // functional: A sees the new method; B is unaffected
+ assertScript '''
+ class TypeA { }
+ class TypeB {
+ String id() { 'B' }
+ }
+ TypeA.metaClass.extra = { -> 'from-emc' }
+ assert new TypeA().extra() == 'from-emc'
+ assert new TypeB().id() == 'B'
+ '''
+ }
+
+ @Test
+ void registrySetMetaClass_invalidatesClassDomain() {
+ SwitchPoint sp = ClassInfo.getClassInfo(TypeC).indySwitchPoint
+ def mc = new ExpandoMetaClass(TypeC, true, true)
+ mc.initialize()
+ GroovySystem.metaClassRegistry.setMetaClass(TypeC, mc)
+ assertTrue(sp.hasBeenInvalidated())
+ }
+
+ @Test
+ void categoryEnterLeave_invalidatesCategoryDomain_notUnrelatedClassOnly() {
+ // First category-domain arm bulk-invalidates class SwitchPoints so sites
+ // that linked without a category guard re-link (lazy category guards).
+ // Observe steady-state behaviour after the domain is armed: further
+ // enter/leave rotate only the category SwitchPoint.
+ if (!IndyInvalidation.categoryDomainArmed) {
+ IndyInvalidation.invalidateCategory()
+ }
+ SwitchPoint classSp = ClassInfo.getClassInfo(TypeD).liveIndySwitchPoint
+ SwitchPoint catBefore = IndyInvalidation.categorySwitchPoint()
+
+ use(TypeDCategory) {
+ assert 'decorated' == new TypeD().label()
+ }
+
+ // enter + leave each invalidate the category domain
+ assertTrue(catBefore.hasBeenInvalidated())
+ // After arming, class domain for TypeD is independent of category enter/leave
+ assertFalse(classSp.hasBeenInvalidated())
+ }
+
+ @Test
+ void categoryMethods_areVisibleToDynamicCalls() {
+ assertScript '''
+ class Host {
+ String name() { 'host' }
+ }
+ class HostCategory {
+ static String name(Host self) { 'category' }
+ }
+ def h = new Host()
+ assert h.name() == 'host'
+ use (HostCategory) {
+ assert h.name() == 'category'
+ }
+ assert h.name() == 'host'
+ '''
+ }
+
+ @Test
+ void indyCalls_pickUpNewMetaClassMethodsAfterChange() {
+ // Adding a *new* method via EMC must become visible on instances that
+ // pick up the class-level MetaClass (clear any instance-cached MetaClass).
+ // Class SwitchPoint invalidation (GROOVY-12191) forces re-link of sites.
+ assertScript '''
+ class Svc {
+ int add(int a, int b) { a + b }
+ }
+ def s = new Svc()
+ assert s.add(1, 2) == 3
+ Svc.metaClass.mul = { int a, int b -> a * b }
+ s.metaClass = null
+ assert s.mul(3, 4) == 12
+ assert s.add(3, 4) == 7
+ // new instances also see the expanded MetaClass
+ assert new Svc().mul(2, 5) == 10
+ '''
+ }
+
+ @Test
+ void parentMetaClassChange_invalidatesSubclassSwitchPoint() {
+ // Hierarchy fan-out: MetaClass change on Parent must invalidate Child's
+ // SwitchPoint so subclass receiver sites re-link (GROOVY-12191).
+ SwitchPoint childSp = ClassInfo.getClassInfo(HierChild).liveIndySwitchPoint
+ assertFalse(childSp.hasBeenInvalidated())
+
+ HierParent.metaClass.hello = { -> 'from-parent' }
+
+ assertTrue(childSp.hasBeenInvalidated())
+ // functional smoke: subclass observes parent EMC method
+ assertScript '''
+ class HierParent {}
+ class HierChild extends HierParent {}
+ HierParent.metaClass.hello = { -> 'from-parent' }
+ assert new HierChild().hello() == 'from-parent'
+ '''
+ }
+
+ @Test
+ void indyCalls_overrideViaFreshMetaClassInstance() {
+ // Replacing the MetaClass identity (not only mutating EMC in place) must
+ // be observed by sites that guard on MetaClass equality and/or SwitchPoint.
+ assertScript '''
+ class Svc {
+ String greet() { 'hello' }
+ }
+ def s = new Svc()
+ assert s.greet() == 'hello'
+ def emc = new ExpandoMetaClass(Svc, true, true)
+ emc.greet = { -> 'world' }
+ emc.initialize()
+ GroovySystem.metaClassRegistry.setMetaClass(Svc, emc)
+ s.metaClass = null // drop any instance-cached MetaClass
+ assert s.greet() == 'world'
+ '''
+ }
+
+ static class TypeA {}
+ static class TypeB {
+ String id() { 'B' }
+ }
+ static class TypeC {}
+ static class TypeD {
+ String label() { 'plain' }
+ }
+ static class TypeDCategory {
+ static String label(TypeD self) { 'decorated' }
+ }
+ static class HierParent {}
+ static class HierChild extends HierParent {}
+}
diff --git a/src/test/groovy/org/apache/groovy/runtime/indy/IndyInvalidationTest.groovy b/src/test/groovy/org/apache/groovy/runtime/indy/IndyInvalidationTest.groovy
new file mode 100644
index 0000000000..08227bbf9c
--- /dev/null
+++ b/src/test/groovy/org/apache/groovy/runtime/indy/IndyInvalidationTest.groovy
@@ -0,0 +1,368 @@
+/*
+ * 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.codehaus.groovy.runtime.NullObject
+import org.junit.jupiter.api.Assumptions
+import org.junit.jupiter.api.BeforeEach
+import org.junit.jupiter.api.Test
+
+import java.lang.invoke.MethodHandles
+import java.lang.invoke.SwitchPoint
+
+import static org.junit.jupiter.api.Assertions.assertEquals
+import static org.junit.jupiter.api.Assertions.assertFalse
+import static org.junit.jupiter.api.Assertions.assertNotSame
+import static org.junit.jupiter.api.Assertions.assertSame
+import static org.junit.jupiter.api.Assertions.assertTrue
+
+/**
+ * Unit tests for {@link IndyInvalidation} façade and dual SwitchPoint domains.
+ */
+final class IndyInvalidationTest {
+
+ @BeforeEach
+ void resetCounters() {
+ IndyInvalidation.resetCountersForTesting()
+ }
+
+ @Test
+ void switchPointClassFor_null_classReceiver_andInstance() {
+ assertSame(NullObject, IndyInvalidation.switchPointClassFor(null))
+ assertSame(String, IndyInvalidation.switchPointClassFor(String))
+ assertSame(String, IndyInvalidation.switchPointClassFor('hi'))
+ assertSame(Integer, IndyInvalidation.switchPointClassFor(42))
+ }
+
+ @Test
+ void invalidateClass_onlyAffectsThatClass_notSiblings() {
+ SwitchPoint spA = ClassInfo.getClassInfo(ClassA).liveIndySwitchPoint
+ SwitchPoint spB = ClassInfo.getClassInfo(ClassB).liveIndySwitchPoint
+ assertFalse(spA.hasBeenInvalidated())
+ assertFalse(spB.hasBeenInvalidated())
+
+ long before = IndyInvalidation.classInvalidationCount()
+ IndyInvalidation.invalidateClass(ClassA)
+ assertTrue(spA.hasBeenInvalidated())
+ assertFalse(spB.hasBeenInvalidated())
+ assertEquals(before + 1, IndyInvalidation.classInvalidationCount())
+
+ // ClassB still has a live switch point; ClassA gets a fresh one on next get
+ SwitchPoint spA2 = ClassInfo.getClassInfo(ClassA).liveIndySwitchPoint
+ assertNotSame(spA, spA2)
+ assertFalse(spA2.hasBeenInvalidated())
+ assertSame(spB, ClassInfo.getClassInfo(ClassB).liveIndySwitchPoint)
+ }
+
+ @Test
+ void invalidateClass_fansOutToSubtypes() {
+ // Ensure ClassInfo entries exist for hierarchy members.
+ SwitchPoint parentSp = ClassInfo.getClassInfo(Parent).liveIndySwitchPoint
+ SwitchPoint childSp = ClassInfo.getClassInfo(Child).liveIndySwitchPoint
+ SwitchPoint siblingSp = ClassInfo.getClassInfo(ClassB).liveIndySwitchPoint
+
+ IndyInvalidation.invalidateClass(Parent)
+
+ assertTrue(parentSp.hasBeenInvalidated())
+ assertTrue(childSp.hasBeenInvalidated())
+ assertFalse(siblingSp.hasBeenInvalidated())
+ }
+
+ @Test
+ void invalidateClass_null_isNoOp() {
+ long before = IndyInvalidation.classInvalidationCount()
+ IndyInvalidation.invalidateClass(null)
+ assertEquals(before, IndyInvalidation.classInvalidationCount())
+ }
+
+ @Test
+ void invalidateCategory_armsDomain_andSubsequentCallsDoNotTouchClassDomain() {
+ // First category invalidation arms the domain and bulk-invalidates class
+ // SwitchPoints so sites that linked without a category guard re-link.
+ // After the domain is armed, further category invalidations rotate only
+ // the category SwitchPoint (class domains stay optimized).
+ boolean alreadyArmed = IndyInvalidation.categoryDomainArmed
+ SwitchPoint classSp = ClassInfo.getClassInfo(ClassA).liveIndySwitchPoint
+ SwitchPoint catBefore = IndyInvalidation.categorySwitchPoint()
+ long catCount = IndyInvalidation.categoryInvalidationCount()
+
+ IndyInvalidation.invalidateCategory()
+
+ assertTrue(IndyInvalidation.categoryDomainArmed)
+ assertTrue(catBefore.hasBeenInvalidated())
+ assertEquals(catCount + 1, IndyInvalidation.categoryInvalidationCount())
+ if (!alreadyArmed) {
+ // First arm: class domains were bulk-invalidated for re-link.
+ assertTrue(classSp == null || classSp.hasBeenInvalidated())
+ }
+
+ // Capture a fresh class SP after arming; next category invalidate must not touch it.
+ SwitchPoint classAfterArm = ClassInfo.getClassInfo(ClassA).liveIndySwitchPoint
+ assertTrue(classAfterArm != null)
+ assertFalse(classAfterArm.hasBeenInvalidated())
+ SwitchPoint catMid = IndyInvalidation.categorySwitchPoint()
+ IndyInvalidation.invalidateCategory()
+ assertTrue(catMid.hasBeenInvalidated())
+ assertFalse(classAfterArm.hasBeenInvalidated(),
+ 'armed category invalidate must not retire class-domain SwitchPoints')
+ if (!IndyInvalidation.categoryInvalidator().failedOver) {
+ SwitchPoint catAfter = IndyInvalidation.categorySwitchPoint()
+ assertNotSame(catMid, catAfter)
+ assertFalse(catAfter.hasBeenInvalidated())
+ }
+ }
+
+ @Test
+ void invalidateClassHierarchy_finalClass_skipsSubtypeScan() {
+ // Final class short-circuit: only the root SwitchPoint is retired.
+ SwitchPoint stringSp = ClassInfo.getClassInfo(String).liveIndySwitchPoint
+ SwitchPoint siblingSp = ClassInfo.getClassInfo(ClassB).liveIndySwitchPoint
+ IndyInvalidation.invalidateClassHierarchy(String)
+ assertTrue(stringSp.hasBeenInvalidated())
+ assertFalse(siblingSp.hasBeenInvalidated())
+ }
+
+ @Test
+ void invalidateUnscoped_retiresLoadedClassSwitchPoints() {
+ SwitchPoint spA = ClassInfo.getClassInfo(ClassA).liveIndySwitchPoint
+ SwitchPoint spB = ClassInfo.getClassInfo(ClassB).liveIndySwitchPoint
+ long before = IndyInvalidation.classInvalidationCount()
+ IndyInvalidation.invalidateUnscoped()
+ assertTrue(spA.hasBeenInvalidated())
+ assertTrue(spB.hasBeenInvalidated())
+ assertEquals(before + 1, IndyInvalidation.classInvalidationCount())
+ }
+
+ @Test
+ void guardWithMopSwitchPoints_omitsCategoryGuardUntilArmed() {
+ // When the category domain is already armed (earlier tests / process state),
+ // this assertion cannot observe the unarmed shape — skip in that case.
+ Assumptions.assumeFalse(IndyInvalidation.categoryDomainArmed,
+ 'category domain already armed in this JVM')
+ def target = MethodHandles.constant(int, 1)
+ def fallback = MethodHandles.constant(int, 2)
+ def receiver = new ClassA()
+ def guarded = IndyInvalidation.guardWithMopSwitchPoints(target, fallback, receiver)
+ assertEquals(1, guarded.invokeWithArguments())
+ // Category invalidate would arm + bulk-invalidate; unarmed sites use only class SP,
+ // so a pure category rotate is not observable until armed. Arm and re-link instead.
+ IndyInvalidation.invalidateCategory()
+ assertTrue(IndyInvalidation.categoryDomainArmed)
+ guarded = IndyInvalidation.guardWithMopSwitchPoints(target, fallback, receiver)
+ assertEquals(1, guarded.invokeWithArguments())
+ IndyInvalidation.invalidateCategory()
+ assertEquals(2, guarded.invokeWithArguments())
+ }
+
+ @Test
+ void classInfoIncVersion_invalidatesClassDomainOnly() {
+ SwitchPoint spA = ClassInfo.getClassInfo(ClassA).indySwitchPoint
+ SwitchPoint spB = ClassInfo.getClassInfo(ClassB).indySwitchPoint
+ SwitchPoint cat = IndyInvalidation.categorySwitchPoint()
+ int versionBefore = ClassInfo.getClassInfo(ClassA).version
+
+ ClassInfo.getClassInfo(ClassA).incVersion()
+
+ assertEquals(versionBefore + 1, ClassInfo.getClassInfo(ClassA).version)
+ assertTrue(spA.hasBeenInvalidated())
+ assertFalse(spB.hasBeenInvalidated())
+ assertFalse(cat.hasBeenInvalidated())
+ }
+
+ @Test
+ void guardWithMopSwitchPoints_fallsBackOnClassOrCategoryInvalidate() {
+ def target = MethodHandles.constant(int, 1)
+ def fallback = MethodHandles.constant(int, 2)
+ def receiver = new ClassA()
+
+ def guarded = IndyInvalidation.guardWithMopSwitchPoints(target, fallback, receiver)
+ assertEquals(1, guarded.invokeWithArguments())
+
+ IndyInvalidation.invalidateClass(ClassA)
+ assertEquals(2, guarded.invokeWithArguments())
+
+ // re-link with fresh guards
+ guarded = IndyInvalidation.guardWithMopSwitchPoints(target, fallback, receiver)
+ assertEquals(1, guarded.invokeWithArguments())
+ IndyInvalidation.invalidateCategory()
+ assertEquals(2, guarded.invokeWithArguments())
+ }
+
+ @Test
+ void noteClassInvalidation_incrementsCounter() {
+ long before = IndyInvalidation.classInvalidationCount()
+ IndyInvalidation.noteClassInvalidation()
+ assertEquals(before + 1, IndyInvalidation.classInvalidationCount())
+ }
+
+ @Test
+ void maxFailures_isReadable() {
+ // Default process config (no -Dgroovy.indy.switchpoint.max.failures override
+ // in the ordinary unit-test JVM).
+ assertEquals(IndyInvalidation.DEFAULT_MAX_FAILURES, IndyInvalidation.maxFailures())
+ }
+
+ @Test
+ void categoryDomain_neverFailedOver_andLiveSpAvailable() {
+ assertFalse(IndyInvalidation.isCategoryFailedOver())
+ SwitchPoint live = IndyInvalidation.liveCategorySwitchPoint()
+ assertTrue(live != null)
+ assertFalse(live.hasBeenInvalidated())
+ assertSame(live, IndyInvalidation.categorySwitchPoint())
+ }
+
+ @Test
+ void classSwitchPointFor_classAndReceiverOverloads() {
+ SwitchPoint byClass = IndyInvalidation.classSwitchPointFor(String)
+ SwitchPoint byReceiver = IndyInvalidation.classSwitchPointFor('x')
+ assertSame(byClass, byReceiver)
+ assertFalse(byClass.hasBeenInvalidated())
+ SwitchPoint byNull = IndyInvalidation.classSwitchPointFor((Object) null)
+ assertSame(ClassInfo.getClassInfo(NullObject).indySwitchPoint, byNull)
+ }
+
+ @Test
+ void resetCountersForTesting_zerosAllCounters() {
+ IndyInvalidation.invalidateClass(ClassA)
+ IndyInvalidation.invalidateCategory()
+ IndyInvalidation.noteClassInvalidation()
+ assertTrue(IndyInvalidation.classInvalidationCount() > 0)
+ assertTrue(IndyInvalidation.categoryInvalidationCount() > 0)
+ IndyInvalidation.resetCountersForTesting()
+ assertEquals(0, IndyInvalidation.classInvalidationCount())
+ assertEquals(0, IndyInvalidation.categoryInvalidationCount())
+ assertEquals(0, IndyInvalidation.failoverCount())
+ }
+
+ @Test
+ void guardWithMopSwitchPoints_skipsFailedOverClassDomain() {
+ // Exhaust the class-domain SwitchPoint budget, then re-link: the façade
+ // must omit a permanently-invalid SP and still produce an invokable
+ // handle (generation guard). Subsequent version bumps force fallback.
+ def info = ClassInfo.getClassInfo(FailoverSkipHost)
+ int budget = IndyInvalidation.maxFailures()
+ Assumptions.assumeTrue(budget > 0, 'unlimited SwitchPoints (max.failures <= 0)')
+ budget.times {
+ SwitchPoint live = info.liveIndySwitchPoint
+ if (live != null) {
+ info.invalidateIndySwitchPoint()
+ }
+ }
+ assertTrue(info.indySwitchPointFailedOver)
+ assertEquals(null, info.liveIndySwitchPoint)
+
+ def target = MethodHandles.constant(int, 11)
+ def fallback = MethodHandles.constant(int, 22)
+ def guarded = IndyInvalidation.guardWithMopSwitchPoints(target, fallback, new FailoverSkipHost())
+ assertEquals(11, guarded.invokeWithArguments())
+ info.incVersion()
+ assertEquals(22, guarded.invokeWithArguments())
+ }
+
+ @Test
+ void setStrongMetaClass_firstInstall_bumpsVersionWithoutSwitchPoint() {
+ // First MetaClass install should not retire a pre-captured SwitchPoint —
+ // no call site has linked against an established MC yet.
+ def info = ClassInfo.getClassInfo(LocalGen)
+ // ensure clean class-level MC
+ info.setStrongMetaClass(null)
+ info.setWeakMetaClass(null)
+ SwitchPoint sp = info.liveIndySwitchPoint
+ assertFalse(sp.hasBeenInvalidated())
+ int versionBefore = info.version
+
+ def mc = new groovy.lang.MetaClassImpl(LocalGen)
+ mc.initialize()
+ info.setStrongMetaClass(mc)
+
+ assertEquals(versionBefore + 1, info.version)
+ assertFalse(sp.hasBeenInvalidated(), 'first install must not invalidate SwitchPoint')
+ // cleanup
+ info.setStrongMetaClass(null)
+ }
+
+ @Test
+ void setStrongMetaClass_replace_invalidatesLocalSwitchPoint() {
+ def info = ClassInfo.getClassInfo(LocalGenReplace)
+ def mc1 = new groovy.lang.MetaClassImpl(LocalGenReplace)
+ mc1.initialize()
+ info.setStrongMetaClass(mc1)
+ SwitchPoint sp = info.liveIndySwitchPoint
+ assertFalse(sp.hasBeenInvalidated())
+
+ def mc2 = new groovy.lang.MetaClassImpl(LocalGenReplace)
+ mc2.initialize()
+ info.setStrongMetaClass(mc2)
+
+ assertTrue(sp.hasBeenInvalidated(), 'replacement must invalidate SwitchPoint')
+ info.setStrongMetaClass(null)
+ }
+
+ @Test
+ void setWeakMetaClass_replace_invalidatesLocalSwitchPoint() {
+ def info = ClassInfo.getClassInfo(LocalGenWeak)
+ def mc1 = new groovy.lang.MetaClassImpl(LocalGenWeak)
+ mc1.initialize()
+ info.setWeakMetaClass(mc1)
+ SwitchPoint sp = info.liveIndySwitchPoint
+ assertFalse(sp.hasBeenInvalidated())
+
+ def mc2 = new groovy.lang.MetaClassImpl(LocalGenWeak)
+ mc2.initialize()
+ info.setWeakMetaClass(mc2)
+
+ assertTrue(sp.hasBeenInvalidated())
+ info.setWeakMetaClass(null)
+ }
+
+ @Test
+ void guardWithMopSwitchPoints_versionGuardAfterClassFailover() {
+ // After class-domain failover, re-link must use ClassInfo.version guards
+ // so MetaClass changes still force fallback without a live SwitchPoint.
+ def info = ClassInfo.getClassInfo(FailoverHost)
+ int budget = IndyInvalidation.maxFailures()
+ Assumptions.assumeTrue(budget > 0, 'unlimited SwitchPoints (max.failures <= 0)')
+ budget.times {
+ SwitchPoint live = info.liveIndySwitchPoint
+ if (live != null) {
+ info.invalidateIndySwitchPoint()
+ }
+ }
+ assertTrue(info.indySwitchPointFailedOver)
+ assertEquals(null, info.liveIndySwitchPoint)
+
+ def target = MethodHandles.constant(int, 7)
+ def fallback = MethodHandles.constant(int, 9)
+ def guarded = IndyInvalidation.guardWithMopSwitchPoints(target, fallback, new FailoverHost())
+ assertEquals(7, guarded.invokeWithArguments())
+ info.incVersion() // version bump must trip generation guard
+ assertEquals(9, guarded.invokeWithArguments())
+ }
+
+ private static final class ClassA {}
+ private static final class ClassB {}
+ private static class Parent {}
+ private static final class Child extends Parent {}
+ private static final class LocalGen {}
+ private static final class LocalGenReplace {}
+ private static final class LocalGenWeak {}
+ private static final class FailoverHost {}
+ private static final class FailoverSkipHost {}
+}
diff --git a/src/test/groovy/org/apache/groovy/runtime/indy/SwitchPointInvalidatorTest.groovy b/src/test/groovy/org/apache/groovy/runtime/indy/SwitchPointInvalidatorTest.groovy
new file mode 100644
index 0000000000..42d55ba4a3
--- /dev/null
+++ b/src/test/groovy/org/apache/groovy/runtime/indy/SwitchPointInvalidatorTest.groovy
@@ -0,0 +1,251 @@
+/*
+ * 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.junit.jupiter.api.Test
+
+import java.lang.invoke.MethodHandles
+import java.lang.invoke.SwitchPoint
+import java.util.concurrent.CountDownLatch
+import java.util.concurrent.atomic.AtomicInteger
+
+import static org.junit.jupiter.api.Assertions.assertEquals
+import static org.junit.jupiter.api.Assertions.assertFalse
+import static org.junit.jupiter.api.Assertions.assertNotSame
+import static org.junit.jupiter.api.Assertions.assertSame
+import static org.junit.jupiter.api.Assertions.assertTrue
+
+/**
+ * Unit tests for {@link SwitchPointInvalidator}.
+ */
+final class SwitchPointInvalidatorTest {
+
+ @Test
+ void lazyAllocation_returnsValidSwitchPointOnFirstUse() {
+ def inv = new SwitchPointInvalidator(10)
+ SwitchPoint sp = inv.switchPoint
+ assertFalse(sp.hasBeenInvalidated())
+ assertSame(sp, inv.switchPoint)
+ assertEquals(0, inv.failureCount)
+ assertFalse(inv.failedOver)
+ }
+
+ @Test
+ void invalidate_withoutPriorGet_isSafe_andDoesNotCount() {
+ def inv = new SwitchPointInvalidator(10)
+ inv.invalidate()
+ // no live SP was retired — budget unchanged
+ assertEquals(0, inv.failureCount)
+ SwitchPoint sp = inv.liveSwitchPoint
+ assertFalse(sp.hasBeenInvalidated())
+ }
+
+ @Test
+ void detachLive_returnsLiveSpWithoutInvalidating_andCountsBudget() {
+ def inv = new SwitchPointInvalidator(10)
+ SwitchPoint live = inv.liveSwitchPoint
+ assertFalse(live.hasBeenInvalidated())
+ SwitchPoint detached = inv.detachLive()
+ assertSame(live, detached)
+ assertFalse(detached.hasBeenInvalidated(), 'detach must not invalidate; caller batches')
+ assertEquals(1, inv.failureCount)
+ assertEquals(null, inv.detachLive()) // nothing live
+ // caller invalidates
+ SwitchPoint.invalidateAll(detached)
+ assertTrue(detached.hasBeenInvalidated())
+ SwitchPoint fresh = inv.liveSwitchPoint
+ assertNotSame(live, fresh)
+ assertFalse(fresh.hasBeenInvalidated())
+ }
+
+ @Test
+ void detachLive_afterFailover_returnsNull() {
+ def inv = new SwitchPointInvalidator(1)
+ inv.liveSwitchPoint
+ inv.invalidate()
+ assertTrue(inv.failedOver)
+ assertEquals(null, inv.detachLive())
+ }
+
+ @Test
+ void getLiveSwitchPoint_returnsNullAfterFailover() {
+ def inv = new SwitchPointInvalidator(1)
+ SwitchPoint first = inv.liveSwitchPoint
+ inv.invalidate()
+ assertTrue(inv.failedOver)
+ assertTrue(first.hasBeenInvalidated())
+ assertEquals(null, inv.liveSwitchPoint)
+ assertSame(SwitchPointInvalidator.invalidSwitchPoint(), inv.switchPoint)
+ }
+
+ @Test
+ void invalidate_invalidatesCapturedSwitchPoint_andAllocatesFresh() {
+ def inv = new SwitchPointInvalidator(10)
+ SwitchPoint first = inv.switchPoint
+ inv.invalidate()
+ assertTrue(first.hasBeenInvalidated())
+ SwitchPoint second = inv.switchPoint
+ assertNotSame(first, second)
+ assertFalse(second.hasBeenInvalidated())
+ assertEquals(1, inv.failureCount)
+ }
+
+ @Test
+ void failover_afterMaxFailures_returnsPermanentInvalid() {
+ def failovers = new AtomicInteger()
+ def inv = new SwitchPointInvalidator(2, { failovers.incrementAndGet() })
+ SwitchPoint a = inv.liveSwitchPoint
+ inv.invalidate()
+ SwitchPoint b = inv.liveSwitchPoint
+ inv.invalidate() // reaches maxFailures=2 → failover
+ assertTrue(inv.failedOver)
+ assertEquals(1, failovers.get())
+ assertEquals(null, inv.liveSwitchPoint)
+ SwitchPoint after = inv.switchPoint
+ assertTrue(after.hasBeenInvalidated())
+ assertSame(SwitchPointInvalidator.invalidSwitchPoint(), after)
+ // further invalidates are no-ops
+ inv.invalidate()
+ assertEquals(2, inv.failureCount)
+ assertSame(after, inv.switchPoint)
+ assertTrue(a.hasBeenInvalidated())
+ assertTrue(b.hasBeenInvalidated())
+ }
+
+ @Test
+ void unlimitedFailures_neverFailOver() {
+ def inv = new SwitchPointInvalidator(0)
+ for (int i = 0; i < 50; i++) {
+ SwitchPoint sp = inv.switchPoint
+ inv.invalidate()
+ assertTrue(sp.hasBeenInvalidated())
+ assertFalse(inv.failedOver)
+ }
+ assertFalse(inv.switchPoint.hasBeenInvalidated())
+ assertEquals(50, inv.failureCount)
+ assertEquals(0, inv.maxFailures)
+ }
+
+ @Test
+ void guardWithTest_fallsBackAfterInvalidate() {
+ def inv = new SwitchPointInvalidator(10)
+ def target = MethodHandles.constant(int, 1)
+ def fallback = MethodHandles.constant(int, 2)
+ def guarded = inv.switchPoint.guardWithTest(target, fallback)
+ assertEquals(1, guarded.invokeWithArguments())
+ inv.invalidate()
+ assertEquals(2, guarded.invokeWithArguments())
+ }
+
+ @Test
+ void failover_guardWithTest_doesNotUsePermanentInvalidAsLiveGuard() {
+ // After failover, callers should omit SwitchPoint guards (see IndyInvalidation).
+ // This unit test only checks the invalidator itself reports failover and
+ // returns the permanent invalid switch point.
+ def inv = new SwitchPointInvalidator(1)
+ SwitchPoint first = inv.switchPoint
+ inv.invalidate()
+ assertTrue(inv.failedOver)
+ assertTrue(first.hasBeenInvalidated())
+ assertTrue(inv.switchPoint.hasBeenInvalidated())
+ assertSame(SwitchPointInvalidator.invalidSwitchPoint(), inv.switchPoint)
+ }
+
+ @Test
+ void concurrentInvalidate_isThreadSafe() {
+ def inv = new SwitchPointInvalidator(1000)
+ int threads = 8
+ int perThread = 50
+ def start = new CountDownLatch(1)
+ def done = new CountDownLatch(threads)
+ threads.times {
+ Thread.start {
+ start.await()
+ perThread.times {
+ inv.switchPoint
+ inv.invalidate()
+ }
+ done.countDown()
+ }
+ }
+ start.countDown()
+ assertTrue(done.await(30, java.util.concurrent.TimeUnit.SECONDS))
+ // Concurrent invalidates may race on a null current (sibling already
+ // cleared); only live retirements count, so expect a positive count
+ // not exceeding the attempted total.
+ assertTrue(inv.failureCount > 0)
+ assertTrue(inv.failureCount <= threads * perThread)
+ // under budget: still allocates a valid SwitchPoint after the storm
+ assertFalse(inv.failedOver)
+ assertFalse(inv.liveSwitchPoint.hasBeenInvalidated())
+ }
+
+ @Test
+ void concurrentFailover_doesNotLeaveOrphanValidSwitchPoint() {
+ // Stress the invalidate ↔ getLive handoff at the failover boundary.
+ // Any switch point observed by a reader after the domain has failed over
+ // must already be invalidated (no permanently-valid orphan).
+ def inv = new SwitchPointInvalidator(3)
+ int threads = 8
+ int perThread = 200
+ def start = new CountDownLatch(1)
+ def done = new CountDownLatch(threads)
+ def orphans = new AtomicInteger()
+ threads.times {
+ Thread.start {
+ start.await()
+ perThread.times {
+ SwitchPoint sp = inv.liveSwitchPoint
+ inv.invalidate()
+ if (sp != null && inv.failedOver && !sp.hasBeenInvalidated()) {
+ // Give a brief moment for the invalidator to drain the race;
+ // a true orphan stays valid forever.
+ Thread.yield()
+ if (!sp.hasBeenInvalidated()) {
+ orphans.incrementAndGet()
+ }
+ }
+ }
+ done.countDown()
+ }
+ }
+ start.countDown()
+ assertTrue(done.await(30, java.util.concurrent.TimeUnit.SECONDS))
+ assertTrue(inv.failedOver)
+ assertEquals(null, inv.liveSwitchPoint)
+ assertEquals(0, orphans.get(), 'orphaned valid SwitchPoint after failover')
+ assertTrue(inv.switchPoint.hasBeenInvalidated())
+ // further gets stay failed-over
+ assertEquals(null, inv.liveSwitchPoint)
+ inv.invalidate()
+ assertEquals(null, inv.liveSwitchPoint)
+ }
+
+ @Test
+ void getLiveSwitchPoint_afterFailover_neverReturnsValidSp() {
+ def inv = new SwitchPointInvalidator(1)
+ SwitchPoint first = inv.liveSwitchPoint
+ inv.invalidate()
+ assertTrue(inv.failedOver)
+ assertTrue(first.hasBeenInvalidated())
+ 20.times {
+ assertEquals(null, inv.liveSwitchPoint)
+ }
+ }
+}
diff --git a/subprojects/performance/README.adoc b/subprojects/performance/README.adoc
index ad8ebc47ec..15ccbb78b0 100644
--- a/subprojects/performance/README.adoc
+++ b/subprojects/performance/README.adoc
@@ -134,6 +134,16 @@ threshold (`groovy.indy.optimize.threshold`, default 1000). Static and
instance dispatch take different cold paths (static sites promote on first
hit, GROOVY-11935), hence the two benches.
+== Scoped invalidation (GROOVY-12191)
+
+`ScopedInvalidationBench` measures the dual SwitchPoint domains: per-class
+scoping (unrelated MetaClass churn must not deoptimize a hot monomorphic
+site) versus same-type re-link, category enter/leave, and hierarchy fan-out.
+Category guards are armed lazily (single per-class SwitchPoint on the
+steady-state monomorphic path until the first category enter/leave).
+It complements the Grails-oriented `CallSiteInvalidationBench` under
+`org.apache.groovy.perf.grails`.
+
== Dashboard pages
The `dashboard/` directory is the source of truth for the hand-crafted pages
diff --git a/subprojects/performance/src/jmh/groovy/org/apache/groovy/bench/ScopedInvalidationBench.groovy b/subprojects/performance/src/jmh/groovy/org/apache/groovy/bench/ScopedInvalidationBench.groovy
new file mode 100644
index 0000000000..43bd21e93e
--- /dev/null
+++ b/subprojects/performance/src/jmh/groovy/org/apache/groovy/bench/ScopedInvalidationBench.groovy
@@ -0,0 +1,272 @@
+/*
+ * 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.bench
+
+import groovy.lang.GroovySystem
+
+import org.openjdk.jmh.annotations.Benchmark
+import org.openjdk.jmh.annotations.BenchmarkMode
+import org.openjdk.jmh.annotations.Fork
+import org.openjdk.jmh.annotations.Level
+import org.openjdk.jmh.annotations.Measurement
+import org.openjdk.jmh.annotations.Mode
+import org.openjdk.jmh.annotations.OutputTimeUnit
+import org.openjdk.jmh.annotations.Scope
+import org.openjdk.jmh.annotations.Setup
+import org.openjdk.jmh.annotations.State
+import org.openjdk.jmh.annotations.Warmup
+import org.openjdk.jmh.infra.Blackhole
+
+import java.util.concurrent.TimeUnit
+
+/**
+ * Steady-state cost of scoped invokedynamic SwitchPoint invalidation (GROOVY-12191).
+ * <p>
+ * Complements the Grails-oriented {@code CallSiteInvalidationBench} (AverageTime,
+ * grails suite) with a bench-suite Throughput regression set for the dual
+ * SwitchPoint domains. Baseline / cross-type / same-type rows intentionally
+ * overlap that bench so ratios are available under the same {@code .bench.}
+ * include pattern; unique coverage here is category enter/leave, hierarchy
+ * fan-out, and setup-isolated post-burst steady state. Domains:
+ * <ul>
+ * <li><b>Per-class</b> — MetaClass changes on an unrelated type must not
+ * deoptimize a hot monomorphic site;</li>
+ * <li><b>Same-type</b> — MetaClass changes on the hot type must re-link;</li>
+ * <li><b>Category-global</b> — {@code use(Category)} enter/leave still forces
+ * re-link so category methods become visible;</li>
+ * <li><b>Hierarchy fan-out</b> — parent MetaClass changes invalidate
+ * subclass-linked sites.</li>
+ * </ul>
+ * Compare {@link #hotLoop_afterUnrelatedBurst} / {@link #hotLoop_unrelatedMetaClassChurn}
+ * against {@link #hotLoop_baseline} (should stay close after scoping) and against
+ * {@link #hotLoop_sameTypeMetaClassChurn} (must pay re-link cost).
+ *
+ * @see <a href="https://issues.apache.org/jira/browse/GROOVY-12191">GROOVY-12191</a>
+ */
+@Warmup(iterations = 3, time = 2, timeUnit = TimeUnit.SECONDS)
+@Measurement(iterations = 5, time = 2, timeUnit = TimeUnit.SECONDS)
+@Fork(2)
+@BenchmarkMode(Mode.Throughput)
+@OutputTimeUnit(TimeUnit.MILLISECONDS)
+@State(Scope.Thread)
+class ScopedInvalidationBench {
+
+ /** Iterations of the hot call loop per benchmark invocation. */
+ static final int ITERATIONS = 100_000
+
+ /** How often to perform a MetaClass mutation inside the churn loops. */
+ static final int CHURN_EVERY = 1_000
+
+ /**
+ * Hot monomorphic call-site receiver.
+ */
+ static class Hot {
+ int value = 42
+ int compute() { value * 2 }
+ }
+
+ /**
+ * Unrelated type used only for cross-type MetaClass churn.
+ */
+ static class Unrelated {
+ String label = 'cold'
+ }
+
+ /**
+ * Parent of {@link HierChild} for hierarchy fan-out churn.
+ */
+ static class HierParent {
+ int base() { 1 }
+ }
+
+ /**
+ * Subclass receiver whose SwitchPoint must clear when the parent MetaClass changes.
+ */
+ static class HierChild extends HierParent {
+ int leaf() { 2 }
+ }
+
+ /**
+ * Category that decorates {@link Hot#compute()}.
+ */
+ static class HotCategory {
+ static int compute(Hot self) { self.value * 3 }
+ }
+
+ Hot hot
+ HierChild child
+
+ /**
+ * Resets MetaClasses and allocates fresh receivers each iteration so
+ * SwitchPoint state from a previous sample does not bleed into the next.
+ */
+ @Setup(Level.Iteration)
+ void setup() {
+ GroovySystem.metaClassRegistry.removeMetaClass(Hot)
+ GroovySystem.metaClassRegistry.removeMetaClass(Unrelated)
+ GroovySystem.metaClassRegistry.removeMetaClass(HierParent)
+ GroovySystem.metaClassRegistry.removeMetaClass(HierChild)
+ hot = new Hot()
+ child = new HierChild()
+ }
+
+ /**
+ * Steady-state monomorphic calls with no MetaClass mutation.
+ * @param bh blackhole for the accumulated result
+ */
+ @Benchmark
+ void hotLoop_baseline(Blackhole bh) {
+ int sum = 0
+ for (int i = 0; i < ITERATIONS; i++) {
+ sum += hot.compute()
+ }
+ bh.consume(sum)
+ }
+
+ /**
+ * Hot monomorphic loop with MetaClass changes on an <em>unrelated</em> type.
+ * With scoped invalidation the hot site should keep its linked target;
+ * residual cost vs baseline is mostly MetaClass mutation work, not deopt.
+ * Prefer {@link #hotLoop_afterUnrelatedBurst} for a pure no-deopt check.
+ * @param bh blackhole for the accumulated result
+ */
+ @Benchmark
+ void hotLoop_unrelatedMetaClassChurn(Blackhole bh) {
+ int sum = 0
+ for (int i = 0; i < ITERATIONS; i++) {
+ sum += hot.compute()
+ if (i % CHURN_EVERY == 0) {
+ Unrelated.metaClass."dyn${i % 5}" = { -> i }
+ }
+ }
+ bh.consume(sum)
+ }
+
+ /**
+ * Pure hot loop after a burst of unrelated MetaClass changes performed in
+ * {@link AfterUnrelatedBurstState#setup()}. After scoping (GROOVY-12191),
+ * this should approach {@link #hotLoop_baseline}.
+ * @param state state that applied the unrelated MetaClass burst
+ * @param bh blackhole for the accumulated result
+ */
+ @Benchmark
+ void hotLoop_afterUnrelatedBurst(AfterUnrelatedBurstState state, Blackhole bh) {
+ int sum = 0
+ Hot h = state.hot
+ for (int i = 0; i < ITERATIONS; i++) {
+ sum += h.compute()
+ }
+ bh.consume(sum)
+ }
+
+ /**
+ * Hot monomorphic loop with MetaClass changes on the <em>same</em> type —
+ * each change must retire the class-domain SwitchPoint and re-link.
+ * @param bh blackhole for the accumulated result
+ */
+ @Benchmark
+ void hotLoop_sameTypeMetaClassChurn(Blackhole bh) {
+ int sum = 0
+ for (int i = 0; i < ITERATIONS; i++) {
+ sum += hot.compute()
+ if (i % CHURN_EVERY == 0) {
+ Hot.metaClass."dyn${i % 5}" = { -> i }
+ }
+ }
+ bh.consume(sum)
+ }
+
+ /**
+ * Category enter/leave interleaved with hot calls — exercises the
+ * process-wide category SwitchPoint domain (never fails over).
+ * Uses a modest number of {@code use} blocks so category re-link cost
+ * is visible without dominating wall-clock.
+ * @param bh blackhole for the accumulated result
+ */
+ @Benchmark
+ void hotLoop_categoryEnterLeave(Blackhole bh) {
+ int sum = 0
+ int callsPerUse = ITERATIONS / 10
+ for (int b = 0; b < 10; b++) {
+ use(HotCategory) {
+ for (int i = 0; i < callsPerUse; i++) {
+ sum += hot.compute()
+ }
+ }
+ }
+ bh.consume(sum)
+ }
+
+ /**
+ * Subclass receiver calls with periodic parent MetaClass changes (hierarchy
+ * fan-out must invalidate the child SwitchPoint).
+ * @param bh blackhole for the accumulated result
+ */
+ @Benchmark
+ void hierarchy_parentMetaClassChurn(Blackhole bh) {
+ int sum = 0
+ for (int i = 0; i < ITERATIONS; i++) {
+ sum += child.leaf()
+ sum += child.base()
+ if (i % CHURN_EVERY == 0) {
+ HierParent.metaClass."dyn${i % 5}" = { -> i }
+ }
+ }
+ bh.consume(sum)
+ }
+
+ /**
+ * Subclass receiver calls with no MetaClass mutation (hierarchy baseline).
+ * @param bh blackhole for the accumulated result
+ */
+ @Benchmark
+ void hierarchy_baseline(Blackhole bh) {
+ int sum = 0
+ for (int i = 0; i < ITERATIONS; i++) {
+ sum += child.leaf()
+ sum += child.base()
+ }
+ bh.consume(sum)
+ }
+
+ /**
+ * Iteration state for {@link ScopedInvalidationBench#hotLoop_afterUnrelatedBurst}:
+ * resets MetaClasses, then applies a burst of unrelated MetaClass mutations
+ * <em>outside</em> the measured loop so residual deopt (if any) is isolated.
+ */
+ @State(Scope.Thread)
+ static class AfterUnrelatedBurstState {
+ /** Hot receiver used by the measured loop. */
+ Hot hot
+
+ /**
+ * Resets MetaClasses, allocates a fresh hot receiver, and applies
+ * unrelated MetaClass churn before the benchmark body runs.
+ */
+ @Setup(Level.Iteration)
+ void setup() {
+ GroovySystem.metaClassRegistry.removeMetaClass(Hot)
+ GroovySystem.metaClassRegistry.removeMetaClass(Unrelated)
+ hot = new Hot()
+ for (int i = 0; i < 50; i++) {
+ Unrelated.metaClass."startup${i % 10}" = { -> i }
+ }
+ }
+ }
+}