Repository navigation
Description
Is there an existing issue for the same bug?
- I have checked the existing issues.
Branch Name
main
Commit ID
- Reproduced with test-only additions at
66da3877e9e77f01083c4aac0cb9f94ab6e11fe6. - Rechecked the relevant cleanup/ownership code on main
d7d940e93bd037e9aacdc0f1256b91e32df84642on 2026-09-24. The same reference chain remains. This is source verification of current main, not a claim that the SQL reproducer was rerun on this newer SHA.
Other Environment Information
- Local macOS, Go 1.26.4, native dependencies built from the exact reproduction commit.
- SQL validation uses the existing embedded single-CN cluster fixture and the real MySQL binary prepared-statement protocol.
- An ordinary, nonpartitioned table, a primary-key point SELECT, and two rows are sufficient to observe the retained reference. No open result cursor, ongoing user transaction, special failure injection, or large TPCC workload is required.
- Only test files were changed. No production behavior was patched for the reproduction.
Actual Behavior
After a prepared table scan has completed and its results have been fully consumed, the session's cached compiled plan still retains the closed execution-local reader. That reader retains its LocalDisttaeDataSource, which retains the old table-level PartitionState.
Session -> PrepareStmt -> cached Compile (isPrepare=true)
-> Scope.DataSource.R [closed reader]
-> readutil.reader.source
-> LocalDisttaeDataSource.pState [old table snapshot]
-> PartitionState.rows
-> RowEntry.Batch -> vectors/backing data
This is not useful prepared-plan reuse: the next execution explicitly drops Scope.DataSource.R and constructs a new reader. While the handle is idle, however, its completed execution can keep obsolete row/batch data reachable after the current partition state has removed it.
The defect is unnecessary post-execution memory retention, not a demonstrated wrong query result. Re-executing the statement in the SQL test returns the newly inserted row correctly and replaces the old snapshot reference.
Expected Behavior
Once an execution is finished and its scan is closed, the reusable prepared plan should not keep that execution's obsolete reader/snapshot alive. The plan and reusable relation metadata may remain cached, but execution-owned snapshot references should end with execution cleanup rather than waiting for an arbitrary future EXECUTE or statement deallocation.
This expectation does not require disabling prepared-plan caching or releasing a snapshot while a reader is still active.
Steps to Reproduce
1. Real prepared SQL path
The local test TestPreparedTableScanRetainsOldPartitionStateUntilNextExecute adds the following sequence to the existing pkg/embed fixture:
- Create
t(id int primary key, payload varchar(32)), then insert(1, 'first'). - On a dedicated
database/sql.Conn, callPrepareContextforselect id, payload from t where id = ?. - Execute with
1, drain and close the result, and runSELECT 1on the same connection as a request-completion barrier. - Locate the frontend session using
connection_id()and inspect the matching session-owned prepared handle. Read-only reflection through its cached compile/scopes/reader/source finds a nonnilpState. - Insert
(2, 'second'); an ordinarySELECT count(*)confirms two committed rows. Without another execution of the prepared handle, its cached reader still references the same old state. - Execute the same prepared handle with
2. It returns the correct row, and the retained state address changes. - Close the prepared handle and pass another same-connection barrier. The handle is absent from the session's prepared-statement map.
The observer records snapshot addresses as uintptr, not strong PartitionState pointers. It does not install a reader in the plan or modify its lifetime. The prepared handle is still owned by the real frontend session while retention is checked.
Important: SQL output alone is expected to be correct. This is a lifetime reproducer, so the server-side ownership inspection is essential; a successful two-row SELECT does not by itself test the defect. Handle removal in step 7 is not a measurement of when RSS is returned to the OS.
2. Closed reader plus COW row cleanup
TestClosedLocalReaderRetainsRowsAfterCurrentStateGC, added locally to pkg/vm/engine/disttae/local_disttae_datasource_test.go, provides a separate bounded discriminator:
- Use the existing materialized-snapshot fixture to build a
PartitionStatecontaining one row with a nonempty batch. - Construct a real
readutil.readerusing aLocalDisttaeDataSourceover that state; callreader.Close(). - Copy the state and apply a dropped appendable object through the production
HandleObjectEntrypath, removing the row from the current copy. current.ScanRows(...)returns 0 rows.source.pState.ScanRows(...)still returns 1 row with nonnil, nonempty batch backing.
This component test deliberately holds the source for inspection. It proves the COW/backing-data consequence, not session ownership by itself; the SQL and scope tests independently establish that ownership.
3. Scope cleanup discriminator
TestPreparedScopeRunRetainsBuiltClosedReaderInDataSource starts with DataSource.R == nil. Actual Scope.Run builds a reader through an existing mock relation and runs pipeline cleanup. Assertions show:
reader.Close called = 1
TableScan.Reader after cleanup = nil
Scope.DataSource.R after cleanup = the closed reader
after doCompileRelease = still the closed reader (isPrepare=true)
after Scope.Reset = nil
The relation is mocked only in this component test. The separate SQL test uses a real disttae relation and a real protocol connection.
Additional information
Root cause and code locations
The following links are pinned to the reproduced commit:
Scope.Runinstalls the reader ins.DataSource.R. Its deferred pipeline cleanup does not clear that field.Pipeline.Cleanup/cleanupInOrderresets prepared operators, while skipping their final Free.TableScan.Reset/closeReadercloses and clearsTableScan.Reader, but that is a different reference fromScope.DataSource.R.readutil.reader.Closecallssource.Close()without clearing its source reference.LocalDisttaeDataSource.Closecloses the row iterator and clears tombstone-index state, but retainspState.doCompileReleaseskips freeing a prepared compile, leaving its scopes session-reachable.Scope.resetForReuseclears the reader on the next execution. This is evidence that the old reader is execution state, not something needed for reuse.Partition.MutateStateandPartitionState.Copypublish COW snapshots. Removing rows from the current tree does not remove them from an independently retained older snapshot.
The normal local nonpartitioned reader path is reachable without a mergeReader wrapper. mergeReader.Close clearing its child list therefore does not protect every prepared scan. Scope.buildReaders already clears NodeInfo.Data; this report does not count that field as the retained owner.
Validation record
Four local test-only probes passed on 66da3877e9:
| Probe | Evidence and limitation |
|---|---|
TestPreparedTableScanRetainsOldPartitionStateUntilNextExecute |
Real single-CN MySQL prepared SQL and session ownership; parent independently reran it, PASS in 9.52s. No heap/RSS measurement. |
TestPreparedScopeRunRetainsBuiltClosedReaderInDataSource |
Actual scope/pipeline cleanup and next-reset boundary; mock relation. |
TestLocalDisttaeDataSourceCloseRetainsPartitionState |
Real reader Close leaves source references; synthetic cached batch is not a production memory measurement. |
TestClosedLocalReaderRetainsRowsAfterCurrentStateGC |
Old snapshot has 1 row with batch backing after current copy has 0; package PASS in 0.358s. Not a unique-retained-byte measurement. |
The probes are local diagnostic additions, not existing committed regression tests. Raw JSON output was preserved for the SQL rerun and COW probe. Native prerequisites were built from the tested commit, and git diff --check passed.
Impact and evidence boundaries
- Even a point-select reader references a table-level state, not just its one result row. An idle prepared handle can extend the lifetime of old row/batch data after current-state cleanup.
- Many long-lived connections/handles at different execution generations can increase live memory and GC pressure. BTree nodes and batches are shared; multiplying handle count by table size would be incorrect.
- This is not demonstrated unbounded growth on every execution: next execution/reset, invalidation, or deallocation can remove the old chain. Retention duration can nevertheless be as long as the idle handle remains cached.
- No wrong result, retained lock, or data corruption was observed in these tests. No claim is made that the small reproduction OOMs.
- Found during investigation of [Bug]: TPCC 100W/1000 terminals OOM-kills 84GiB single-node MO on main #29270, but not yet proven to be the dominant or sufficient cause of that incident's 84GiB cgroup OOM. The original pre-OOM profiles were not retained. A related later passing run's allocation profiles cannot identify the exact retaining roots in the original failure.
- The listed scope/reader/source cleanup code is unchanged between the earlier control
c154cf5a0449b5b7c2b497ffc57924a04e74dd52and66da3877e9. This report does not assign introduction to feat(sql): support EXCEPT ALL multiset subtraction #29228 or claim a newly introduced regression. Current-main source still contains the defect. - A memory-pressure accounting/admission change such as fix(rscthrottler): account for cgroup memory usage #29294 does not remove this reference chain; its effectiveness against [Bug]: TPCC 100W/1000 terminals OOM-kills 84GiB single-node MO on main #29270 is a separate question.
Duplicate check
Searched open/closed issues for PartitionState, LocalDisttaeDataSource, prepared retention, prepared snapshot, and recent prepared/logtail memory issues. No exact duplicate was found. #23983 concerns parameter-vector reuse across executions; #29187 concerns streamed parameter accumulation; #24534 concerns cache pressure and PK-conflict IO. Those are different ownership paths. #29270 remains the related incident, not a proven causal equivalence.
Follow-up acceptance boundary
A correction should preserve prepared-plan reuse and active-reader snapshot semantics while releasing completed execution references. Validate repeated execution, ordinary completion, error/cancellation, statement close, and reader-close idempotency. Quantitative post-GC heap/RSS comparisons under a controlled prepared workload are still needed before claiming any particular OOM reduction or that #29270 is fixed.
Activity
fix(compile): release completed prepared scan readers (#29352)
Ariznawlll commentedon Sep 27, 2026
测试版本
main5be6cd90b501da225be591ffffe6000bf01f515e原问题验证
该问题依赖内部 reader 生命周期或 I/O 故障注入,公开 SQL 无法稳定制造目标失败点。已在最新 main 上运行对应定向测试
TestPreparedScopeRunReleasesCompletedReader、TestPreparedScopeRunReleasesBuiltReader、TestPreparedParallelWorkersReleaseBuiltReaders,连续 3 次通过。Happy Path 覆盖
Unhappy Path 覆盖
白盒验证
确认修复提交
c701ffa4ef762818cae277e0af9be98ca3e32df7是当前 main 的祖先,并直接执行该提交新增的定向测试,结果 3/3 PASS。回归测试
回归已落在 MatrixOne UT:
TestPreparedScopeRunReleasesCompletedReader、TestPreparedScopeRunReleasesBuiltReader、TestPreparedParallelWorkersReleaseBuiltReaders。未加入 MOTR,因为该场景必须注入内部 reader/I/O 失败,SQL 黑盒无法可靠触发;按覆盖矩阵应保留在 UT 层。测试证据
5be6cd90b501da225be591ffffe6000bf01f515ec701ffa4ef762818cae277e0af9be98ca3e32df7测试结论
测试通过。