Skip to content

[fix](nereids) Release statement planning graphs without finalization - #71156

Open
yujun777 wants to merge 1 commit into
apache:masterfrom
yujun777:codex/fix-statement-context-retention
Open

yujun777 wants to merge 1 commit into
apache:masterfrom
yujun777:codex/fix-statement-context-retention

Conversation

@yujun777

Copy link
Copy Markdown
Contributor

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 unit tests check explicit release. SQL regressions exercise planning and query results, with no assertion about the lifetime of the planning graph after the statement completes.

  • 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.

  • Behavior change: Completed statement contexts can be reclaimed independently of Java finalization. A leaked lock scope logs the first locked table, owner thread, and query ID.

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: Yes (see Details)
  • Does this need documentation: No
  • Pre-submission status: Partially verified: production-scale heap and release-branch validation are pending.

### 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
@yujun777

Copy link
Copy Markdown
Contributor Author

run buildall

@yujun777

Copy link
Copy Markdown
Contributor Author

/review

@hello-stephen hello-stephen left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No actionable source-level findings were found on head 36eb73e65e884d972932e00d4bc861334e048016. The detached phantom reference removes the finalization-based retention path while preserving explicit table-lock cleanup. No inline comments are proposed. The supplied existing-comments list is empty, so there are no previously reported blocking findings to carry forward.

Critical checkpoint conclusions

  • Task goal and regression evidence: StatementContext no longer declares finalize(). PlannerLockLeakTracker.java:29-54 retains only three strings alongside its phantom referent; it does not capture the statement, table, unlock callback, or plan graph. StatementContextPlannerLockTest.java:35-40 guards removal of the finalizer. Actual graph reclamation is not proved by these unit tests.
  • Minimal, clear scope: The three-file diff changes the diagnostic mechanism, simplifies CloseableResource, and adds five focused tests. Planning algorithms and table-lock policy are unchanged (StatementContext.java:1594-1648).
  • Concurrency, lightweight critical sections, and lock order: Statement-thread registration and release share the context monitor. Queue processing touches only immutable identifiers and concurrent PENDING; atomic removal permits at most one report (PlannerLockLeakTracker.java:45-62). ID-sorted acquisition, the one-minute timeout, and reverse-order release remain intact. The callback acquires no table locks and performs no unlock. New work under the monitor is bounded diagnostic setup, with queue initialization on first use; no new RPC or external metadata lookup was added.
  • Lifecycle and static initialization: LOG and PENDING precede the static queue; normal release removes and clears the reference, while queue delivery removes abandoned references. The reference has no strong back-reference into the planning graph. This matches the existing dependency's Guava 33.2.1 reference-queue implementation.
  • Parallel functional paths: Ordinary planning releases in NereidsPlanner.planWithLock()'s finally (NereidsPlanner.java:301-303). SQL-cache acquisition also calls StatementContext.lock() (NereidsSqlCacheManager.java:688) and releases in ConnectProcessor.parseFromSqlCache()'s finally (ConnectProcessor.java:454-456). Direct and forwarded statement teardown reuse close(). These paths share the replacement diagnostic.
  • Conditional checks and error handling: The null-tracker guard creates one diagnostic per acquired scope and resets on release. Concurrent removal suppresses duplicate or already-unregistered reports. Null connections/query IDs are handled by the call site and DebugUtil.printId(TUniqueId). Timeout unwind and propagation after attempted resource cleanup remain unchanged (StatementContext.java:1612-1648).
  • Test coverage: The five added tests cover finalizer removal, repeated acquisition, idempotent close, LIFO unlock order, partial-acquisition failure, one-time reporting, and suppression after release. TestLogAppender stores immutable events in a CopyOnWriteArrayList; the asynchronous test waits for the observed log. Existing ConnectorStatementScopeTest.java:202-238 covers planning cleanup, including an unlock exception. Real GC, real table locks, and queue/close races are not exercised by the new mocked tests.
  • Test-result changes: No regression .out files or other expected-result artifacts changed. The new assertions agree with the inspected control flow; execution results were not independently verified.
  • Observability: Abandoned scopes still emit an ERROR with a qualified table name, owning thread name, and query ID (PlannerLockLeakTracker.java:61-62). Reporting once per scope, without retaining SQL or all table objects, is consistent with the retention fix. Unlock failures still propagate to the caller.
  • Performance: Tracking is allocated only after acquiring a planning read lock, once per scope. Explicit release removes its pending entry. The change removes finalization from every statement context and avoids per-table diagnostic strings; production heap and throughput effects remain unmeasured here.
  • Compatibility and remaining invariants: Inspection of all changed paths found no configuration, public protocol, storage format, generated definition, transaction/persistence, FE-to-BE state, or optimizer-result change. No additional source-level correctness issue was identified.

Requester focus

No additional focus was supplied.

Validation and coverage limits

Source coverage is complete for all three changed files and all eight diff hunks, with relevant planner, SQL-cache, statement-teardown, table-lock, logging-helper, dependency, and supporting-test paths inspected. The supplied diff matches the requested base and head. Main-agent verification and two review agents converged in one round with no actionable findings.

This was a source-only review: no build, Checkstyle, unit/regression tests, service execution, benchmark, or GC/heap experiment was run. Consequently, actual reclamation timing and heap/throughput impact, real-lock behavior, and runtime queue scheduling/fallback behavior remain unverified. Those require runtime validation excluded from this review. There are no remaining uncovered source areas or unresolved source-level questions within the changed behavior.

Review converged after 1 round(s).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants