From 36eb73e65e884d972932e00d4bc861334e048016 Mon Sep 17 00:00:00 2001 From: yujun Date: Mon, 30 Nov 2026 17:31:38 +0800 Subject: [PATCH] [fix](nereids) Release statement planning graphs without finalization ### Background Nereids uses a statement context to store table locks and planning data such as CTE consumer groups and derived statistics. The planner releases the locks explicitly when planning exits. A fallback diagnostic reports an abandoned scope with outstanding locks. ### What problem does this PR solve? Issue Number: None Related PR: None PR Type: Bugfix Problem Summary: The fallback lock diagnostic makes every StatementContext finalizable. This extends the lifetime of its planning graph even when the lock stack is empty and the query no longer holds the context. Register a detached phantom reference only for a scope that acquired a table read lock. ### Details - **Frequency:** The JVM registers all instances for finalization on the affected code. Heap impact rises with the volume and size of planner graphs awaiting collection. - **Root cause:** StatementContext overrides Object.finalize, so pending final references preserve its CTE groups, candidate plans and statistics until finalization. - **Why existing tests missed it:** Planner and connector tests check explicit resource cleanup. They allow the context to remain finalizable afterward. - **Fix:** Use a detachable reference containing a table name, thread name and query ID. Explicit release unregisters the diagnostic. If the scope is abandoned, queue delivery logs it once. The owning thread releases table locks. - **Other paths and branches:** SQL cache planning, ordinary planning and statement teardown share the existing release method. The implementation uses the repository's Guava version and Java 8 language and reference APIs to ease a separate backport. ### Testing - On upstream/master, StatementContextPlannerLockTest ran three tests. The finalization regression failed as expected. The two resource release tests passed. - On the fix, 107 FE tests passed across StatementContextPlannerLockTest, StatementContextTest, StatementContextPartitionPredicateSafetyTest, NereidsPlannerConnectorPlanningTest and ConnectorStatementScopeTest. - A dedicated G1 JVM paused its Finalizer thread. The old code retained data reachable solely from the statement context until the thread resumed. The fixed code reclaimed that data while the thread was paused, including a path with a registered lock diagnostic. - The fe-core Checkstyle audit completed with zero violations. ### Release note The frontend can reclaim completed Nereids statement planning graphs without waiting for Java finalization. ### Check List (For Author) - Behavior changed: No - Does this need documentation: No - Pre-submission status: Partially verified: production-scale heap and release-branch validation are pending. ### AI Disclosure - Tool: Codex (GPT-6.2-sol) - Generated: Implementation, tests, description draft and verification notes - Human review: Pending --- .../doris/nereids/PlannerLockLeakTracker.java | 65 +++++++++ .../doris/nereids/StatementContext.java | 44 ++---- .../StatementContextPlannerLockTest.java | 135 ++++++++++++++++++ 3 files changed, 214 insertions(+), 30 deletions(-) create mode 100644 fe/fe-core/src/main/java/org/apache/doris/nereids/PlannerLockLeakTracker.java create mode 100644 fe/fe-core/src/test/java/org/apache/doris/nereids/StatementContextPlannerLockTest.java diff --git a/fe/fe-core/src/main/java/org/apache/doris/nereids/PlannerLockLeakTracker.java b/fe/fe-core/src/main/java/org/apache/doris/nereids/PlannerLockLeakTracker.java new file mode 100644 index 00000000000000..9eae75c1beee2b --- /dev/null +++ b/fe/fe-core/src/main/java/org/apache/doris/nereids/PlannerLockLeakTracker.java @@ -0,0 +1,65 @@ +// 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.doris.nereids; + +import com.google.common.base.FinalizablePhantomReference; +import com.google.common.base.FinalizableReferenceQueue; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +/** Reports abandoned planner locks without retaining the statement's plan graph. */ +final class PlannerLockLeakTracker extends FinalizablePhantomReference { + private static final Logger LOG = LogManager.getLogger(PlannerLockLeakTracker.class); + private static final Set PENDING = ConcurrentHashMap.newKeySet(); + private static final FinalizableReferenceQueue QUEUE = new FinalizableReferenceQueue(); + + private final String table; + private final String ownerThread; + private final String queryId; + + private PlannerLockLeakTracker(StatementContext owner, String table, String queryId) { + super(owner, QUEUE); + this.table = table; + this.ownerThread = Thread.currentThread().getName(); + this.queryId = queryId; + } + + static PlannerLockLeakTracker register(StatementContext owner, String table, String queryId) { + PlannerLockLeakTracker reference = new PlannerLockLeakTracker(owner, table, queryId); + // Keep the phantom reference itself alive until the lock scope is released or reported. + PENDING.add(reference); + return reference; + } + + void unregister() { + PENDING.remove(this); + clear(); + } + + @Override + public void finalizeReferent() { + if (PENDING.remove(this)) { + // Table read locks must be released on the owning thread. + LOG.error("Resources leak: planner lock scope abandoned for table {}, thread {}, query {}", + table, ownerThread, queryId); + } + } +} diff --git a/fe/fe-core/src/main/java/org/apache/doris/nereids/StatementContext.java b/fe/fe-core/src/main/java/org/apache/doris/nereids/StatementContext.java index 2136c1cb1dc9f2..52814eaa8804bc 100644 --- a/fe/fe-core/src/main/java/org/apache/doris/nereids/StatementContext.java +++ b/fe/fe-core/src/main/java/org/apache/doris/nereids/StatementContext.java @@ -35,6 +35,7 @@ import org.apache.doris.common.Id; import org.apache.doris.common.IdGenerator; import org.apache.doris.common.Pair; +import org.apache.doris.common.util.DebugUtil; import org.apache.doris.connector.ConnectorStatementScopeImpl; import org.apache.doris.connector.spi.ConnectorStatementScope; import org.apache.doris.connector.spi.handle.ConnectorTransaction; @@ -279,6 +280,8 @@ public enum TableFrom { // table locks private final Stack plannerResources = new Stack<>(); + @GuardedBy("this") + private PlannerLockLeakTracker plannerLockLeakTracker; // Scan nodes that hold something on this frontend for the backend (a remote Doris scan's Flight // SQL session on the other frontend) and release it in ScanNode.stop(), which the coordinator @@ -1610,16 +1613,21 @@ public synchronized void lock() { close(); throw new RuntimeException("Failed to get read lock on table:" + tableIf.getName()); } - String fullTableName = tableIf.getNameWithFullQualifiers(); - String resourceName = "tableReadLock(" + fullTableName + ")"; - plannerResources.push(new CloseableResource( - resourceName, Thread.currentThread().getName(), - originStatement == null ? null : originStatement.originStmt, tableIf::readUnlock)); + plannerResources.push(new CloseableResource(tableIf::readUnlock)); + if (plannerLockLeakTracker == null) { + String queryId = connectContext == null ? "" : DebugUtil.printId(connectContext.queryId()); + plannerLockLeakTracker = PlannerLockLeakTracker.register( + this, tableIf.getNameWithFullQualifiers(), queryId); + } } } /** releasePlannerResources */ public synchronized void releasePlannerResources() { + if (plannerLockLeakTracker != null) { + plannerLockLeakTracker.unregister(); + plannerLockLeakTracker = null; + } Throwable throwable = null; while (!plannerResources.isEmpty()) { try { @@ -1682,17 +1690,6 @@ private void stopScanNodesLeftBehind() { } } - // CHECKSTYLE OFF - @Override - protected void finalize() throws Throwable { - if (!plannerResources.isEmpty()) { - String msg = "Resources leak: " + plannerResources; - LOG.error(msg); - throw new IllegalStateException(msg); - } - } - // CHECKSTYLE ON - @Override public void close() { releasePlannerResources(); @@ -2232,18 +2229,11 @@ private boolean containsPlanReadLockTable(Collection tableIfs) { } private static class CloseableResource implements Closeable { - public final String resourceName; - public final String threadName; - public final String sql; - private final Closeable resource; private boolean closed; - public CloseableResource(String resourceName, String threadName, String sql, Closeable resource) { - this.resourceName = resourceName; - this.threadName = threadName; - this.sql = sql; + public CloseableResource(Closeable resource) { this.resource = resource; } @@ -2259,12 +2249,6 @@ public void close() { closed = true; } } - - @Override - public String toString() { - return "\nResource {\n name: " + resourceName + ",\n thread: " + threadName - + ",\n sql:\n" + sql + "\n}"; - } } public void addKeySlot(SlotReference slot) { diff --git a/fe/fe-core/src/test/java/org/apache/doris/nereids/StatementContextPlannerLockTest.java b/fe/fe-core/src/test/java/org/apache/doris/nereids/StatementContextPlannerLockTest.java new file mode 100644 index 00000000000000..7fbccf2a43d679 --- /dev/null +++ b/fe/fe-core/src/test/java/org/apache/doris/nereids/StatementContextPlannerLockTest.java @@ -0,0 +1,135 @@ +// 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.doris.nereids; + +import org.apache.doris.catalog.TableIf; +import org.apache.doris.mysql.authenticate.TestLogAppender; + +import org.apache.logging.log4j.Level; +import org.awaitility.Awaitility; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.mockito.InOrder; +import org.mockito.Mockito; + +import java.lang.reflect.Field; +import java.util.Arrays; +import java.util.concurrent.TimeUnit; + +class StatementContextPlannerLockTest { + @Test + void statementContextDoesNotParticipateInFinalization() { + // Finalization holds the full graph alive even after all table locks have been released. + Assertions.assertThrows(NoSuchMethodException.class, + () -> StatementContext.class.getDeclaredMethod("finalize")); + } + + @Test + void releasesLocksInReverseOrderAndCanAcquireThemAgain() { + StatementContext context = new StatementContext(0); + TableIf first = addTable(context, 1, "t1", true); + TableIf second = addTable(context, 2, "t2", true); + + for (int cycle = 0; cycle < 2; cycle++) { + context.lock(); + context.close(); + context.close(); + } + + InOrder order = Mockito.inOrder(first, second); + for (int cycle = 0; cycle < 2; cycle++) { + order.verify(first).tryReadLock(1, TimeUnit.MINUTES); + order.verify(second).tryReadLock(1, TimeUnit.MINUTES); + order.verify(second).readUnlock(); + order.verify(first).readUnlock(); + } + Mockito.verify(first, Mockito.times(2)).readUnlock(); + Mockito.verify(second, Mockito.times(2)).readUnlock(); + } + + @Test + void releasesPreviouslyAcquiredLockWhenNextAcquireFails() { + StatementContext context = new StatementContext(0); + TableIf first = addTable(context, 1, "t1", true); + TableIf second = addTable(context, 2, "t2", false); + + try { + RuntimeException failure = Assertions.assertThrows(RuntimeException.class, context::lock); + Assertions.assertTrue(failure.getMessage().contains("t2")); + Mockito.verify(first).readUnlock(); + Mockito.verify(second, Mockito.never()).readUnlock(); + } finally { + context.close(); + } + } + + @Test + void reportsAbandonedScopeOnlyOnce() throws ReflectiveOperationException { + StatementContext context = new StatementContext(0); + TableIf table = addTable(context, 1, "abandoned", true); + context.lock(); + try { + PlannerLockLeakTracker tracker = getTracker(context); + String message = "planner lock scope abandoned for table internal.db.abandoned"; + try (TestLogAppender log = TestLogAppender.attach(PlannerLockLeakTracker.class)) { + Assertions.assertTrue(tracker.enqueue()); + Awaitility.await().atMost(5, TimeUnit.SECONDS).until(() -> log.contains(Level.ERROR, message)); + } + try (TestLogAppender log = TestLogAppender.attach(PlannerLockLeakTracker.class)) { + tracker.finalizeReferent(); + Assertions.assertFalse(log.contains(Level.ERROR, message)); + } + Mockito.verify(table, Mockito.never()).readUnlock(); + } finally { + context.close(); + } + } + + @Test + void releasedScopeCannotReportALeak() throws ReflectiveOperationException { + StatementContext context = new StatementContext(0); + addTable(context, 1, "released", true); + context.lock(); + PlannerLockLeakTracker tracker = getTracker(context); + context.close(); + + try (TestLogAppender log = TestLogAppender.attach(PlannerLockLeakTracker.class)) { + tracker.finalizeReferent(); + Assertions.assertFalse(log.contains(Level.ERROR, + "planner lock scope abandoned for table internal.db.released")); + } + } + + private PlannerLockLeakTracker getTracker(StatementContext context) throws ReflectiveOperationException { + // Control reference-queue delivery without relying on when GC runs. + Field field = StatementContext.class.getDeclaredField("plannerLockLeakTracker"); + field.setAccessible(true); + return (PlannerLockLeakTracker) field.get(context); + } + + private TableIf addTable(StatementContext context, long tableId, String name, boolean acquired) { + TableIf table = Mockito.mock(TableIf.class); + Mockito.when(table.getId()).thenReturn(tableId); + Mockito.when(table.getName()).thenReturn(name); + Mockito.when(table.getNameWithFullQualifiers()).thenReturn("internal.db." + name); + Mockito.when(table.needReadLockWhenPlan()).thenReturn(true); + Mockito.when(table.tryReadLock(1, TimeUnit.MINUTES)).thenReturn(acquired); + context.getTables().put(Arrays.asList("internal", "db", name), table); + return table; + } +}