Repository navigation
fix(spillio): batch spill writeback within bounded cache window - #29771
Conversation
Qodo reviews are paused for this user.Troubleshooting steps vary by plan Learn more → On a Teams plan? Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center? |
XuPeng-SH
left a comment
There was a problem hiding this comment.
Deep review of 86d997eabdd1b7abbbba23611e0fe8c325af1986: approve. No blocking finding in the complete two-file change and the HashBuild, BucketWriter and Group caller chains.
The extra submitted cursor belongs in the existing per-file cache-policy owner: it separates asynchronous submission from reclamation without adding a second writer, buffering allocation, FD owner, or spill format. For the supported page sizes, batch-aligned reclamation remains behind submitted full pages and keeps the post-call retained window at most 256 KiB. The subtraction before rounding also leaves room for the rounding increment near MaxInt64. Finish still handles the unsubmitted final tail, is idempotent, and precedes reader handoff; descriptor reopening retains progress in the file owner. Short/error writes and cancellation retain the existing failure/cleanup paths.
Reviewed the full production delta (+26/-9) separately from the test delta (+84/-15); no documentation files change. The tests combine real writes, repeated FD reopening and an independent CRC roundtrip with bounds/invalid-progress checks. Exact-head Linux CI 37898032813 succeeds; local go test -race -count=1 -timeout=120s ./pkg/sql/colexec/spillio passes (2.113s). Local macOS exercises the policy and file-data behavior, not Linux cache-reclamation syscalls. I also checked the Linux wrappers against the documented writeback semantics and partial-page advisory behavior.
Performance acceptance is scoped to batching: the PR's matched Linux component measurements support fewer small-range operations and a local improvement. They do not establish recovery of the full BigData I3 regression or whole-process memory bounds. Keep #29755 open for the stated SQL/BigData acceptance; this PR correctly says it only partially addresses that issue. Ordinary non-spilling TP execution does not enter this changed helper.
Merge Queue Status
This pull request spent 19 minutes 20 seconds in the queue, with no time running CI. ReasonPull request #29771 has been dequeued Pull request from fork cannot be queued. This pull request comes from a fork, and Mergify needs the author's permission to update its branch.
HintYou should look at the reason for the failure and decide if the pull request needs to be fixed or if you want to requeue it. Waiting for any of
All conditions
Tick the box to put this pull request back in the merge queue (same as
|
## What type of PR is this? - [ ] API-change - [ ] BUG - [x] Improvement - [ ] Documentation - [ ] Feature - [ ] Test and CI - [ ] Code Refactoring ## Which issue(s) this PR fixes: Related #29383. An actual clone of the reported source on the deployed v4.2.5 environment took 72.327s. This PR removes redundant FK metadata work, a deterministically reproduced checkpoint/subscription lock convoy, and repeated full-global-checkpoint metadata copies before selecting a single table. A real two-CN whole-SQL cold-clone reproduction now demonstrates the reader amplification and its reduction: three-sample median 9.640s -> 2.359s, 75.53% lower. This is a bounded local result with synthetic global checkpoint cardinality, not a production speedup. The issue remains open; this PR was subsequently marked Ready externally. QA warm clones also took 16.66-45.76s without new source subscriptions under high CPU/throttling, and the new code has not been deployed or measured there. No claim that every cause of the original latency is fixed. ## What this PR does / why we need it: ### Cause and implementation #### Reuse collected FK definitions `collectCloneDatabaseSource` already enumerates logical source tables and reads their definitions. After deriving FK order from those definitions and the FK catalog, it passed a nil source to `getTableInfoMap`, causing another per-FK-table enumeration and `SHOW CREATE`. This repeats catalog round trips and replaces the exact objects used to derive the dependency order. - Extract the existing partial-restore logical inventory constructor and reuse it for FK selection inside each database-clone source collection. - Keep DB/table/system filtering in the existing `getTableInfoMap`; select the already collected definitions rather than query them again. - Build the index only when FK dependencies exist, avoiding extra indexing for databases without FKs. - Keep the separate post-lock source collection fresh. No cross-collection cache, target-FK shortcut, permission fallback or transaction split is added. Sequence/FK/view/routine ordering and rollback owners are unchanged. #### Separate checkpoint I/O from subscription-state ownership - Move latest-checkpoint materialization out of the global subscription RW critical section. Pin the exact partition/entry generation before I/O, reuse existing checkpoint consumption, and reject stale readiness/error publication. - Preserve one active replay with a cancellable PushClient-owned gate across reconnect. Queued callers pin no partition; no workers, parallel clone/DDL, configuration or increased active replay capacity are introduced. - Preserve pending logtail markers from SubRspReceived through readiness publication; clear only through the existing application owner. Cover caller cancellation, replacement, unsubscribe, clear and identity mismatch paths. - Close the new public test's shared cluster through the existing outer cleanup owner. This fixes the PR-introduced UT Coverage interference with subsequent owning-cluster lifecycle tests. Design-first subscription contract: [reviewed revision 3](https://github.com/gouhongshen/matrixone/blob/27032d97db8f57978cbc690109c124953b5525c9/docs/design/20261009-clone-checkpoint-subscription.md). Independent local design PASS preceded implementation; final independent ten-file implementation review was APPROVE. Neither is a GitHub human approval. #### Materialize only the selected table's checkpoint metadata The common v13+ single-table `readMetaWithTableID` previously loaded/copied all five global metadata vectors, including variable-length object statistics, before filtering the table ID. Hundreds of cold source/index subscriptions therefore repeatedly copied unrelated tables' metadata. This is the concrete `Vector.Dup`/`runtime.memmove` amplification identified in the retained QA CPU profile; schema-only local fixtures omitted this global checkpoint context. - Load and pin only the fixed-width table-ID column with the existing loader. Find the matching contiguous range first; an absent ID returns without loading the other metadata columns. - Use the existing `LoadColumnsDataInto` selected-row path to materialize the matching rows into an owned batch, then reuse the existing data/tombstone range export helpers. - Release the ID cache lease and clean partial or completed owned batches on success, error and cancellation. Returned ranges own their object-stat values. - Leave checkpoint format, version <=12 and all-table readers unchanged. No new cache, fallback, retry, worker, hook or configuration is introduced. Product change: `3dbd8220c657d7387d2ac5f49f6c6553211f0369`; final reader tests: `994b8fadf17cff3d73200f0694799ad8d112d376`. The subsequent normal target merge preserves these source bytes. Independent final reader review: APPROVE. ### Regression proof - Actual collector UT covers live/historical scope, query work, pointer identity, fresh recollection, no-FK databases, tenant IDs and schema lookup failures. Restoring the old nil-source wiring fails the identity oracle for both scopes with complete fixtures for the original SQL path. - Existing scoped snapshot/PITR source-map regression uses the shared constructor and verifies missing/out-of-scope objects are not fetched. - Public MySQL SQL regression uses the existing shared cluster to verify current vs snapshot rows, target FK rebinding, invalid-reference rejection, independent target DML, unchanged source data and explicit clone rollback. - Opt-in two-CN benchmark: source setup on CN0, clone on CN1; empty, unflushed, explicitly flushed and FK-chain variants across table counts. Setup, validation and cleanup are outside the clone timer. Flush is diagnostic fixture preparation, not product behavior or a workaround. - Four deterministic checkpoint tests use real nonempty partition checkpoints and phase barriers. Verify unrelated progress, same-table fencing, pending updates, stale success/error, cancelled/replaced callers, terminal state transitions, and replay capacity/queued cancellation without partition pins. Each was separately repeated 100 times under race; no sleeps or retries. - Reader tests use real persisted metadata and cover absent/first/middle/last table IDs, repeated IDs, data-only/tombstone-only/both-kind ranges, and output independence after cache/MPool release. Injected ID/selected-column read and decode failures verify partial-copy cleanup and cache-lease release. - Cancellation is deterministic both before reading and at the selected read while the ID lease is held. Verify cancellation, no output, equal acquisition/ release counts, zero live MPool bytes and an unaffected subsequent read. - Extend the existing real-object consumer fixture: persist checkpoint metadata, execute `CKPReader.ReadMeta`, then consume its actual data and tombstone objects. The large diagnostic fixture below is private/opt-in, not a normal-CI cost. ### Actual source investigation On 2026-10-09 the reported source contained 135 ordinary logical tables, 393 ordinary hidden index tables and one fulltext table: 529 physical relations. There was one FK edge and no views/sequences or incoming cross-database FKs. Only unique task-owned destinations were cloned, checked, dropped and verified absent. No source data/schema/flush, grants, deployment or configuration changed; production transport and log followers were closed. No business rows exported. - Actual deployed v4.2.5 clone: 72.326717s; both relation counts 529. - 135 RestoreTable spans sum 42.804366s; between-table spans 27.965375s. The latter includes planning/creation, not proven pure DDL time. - 478 complete source cold-subscription spans sum 38.968851s, including 12.048114s send-to-response and 26.920737s response-to-ready. These sums do not exclusively attribute elapsed time or isolate resource contention. - The slowest logical table was empty and took 6.356s; table/index subscriptions occurred sequentially before its first TableMetaReader read. - Shared immutable objects dominate; only three data rows required new materialization. This is not a bulk row-copy bottleneck. - Both deployed and pre-fix source hold the global subscription state lock through checkpoint loading. A blocked real checkpoint reproduces unrelated state-lock starvation locally; the new owner split removes that convoy. Actual SHOW CREATE definitions, without business data, were replayed on two local CNs: the empty schema cold clone took 1.447s and warm clones 0.714/0.827s. Earlier post-merge functional control also passed (1.709/0.696/0.687s); it ran alongside validation and is not a matched performance comparison. Different platform/revision and checkpoint/workload state mean these schema-only results do not reproduce production 72s or establish production speedup. Private source schemas/logs are not committed to this public PR. #### Warm/load controls and retained CPU profiles Three consecutive clones on the same deployed CN took 21.130334 / 45.762739 / 16.660020 seconds, with no new source-table subscription events. All three destinations were checked (529 relations), dropped and verified absent. DROP latency is separate, not included in clone timing. Measured cgroup CPU averaged 13.66-15.71 cores against a 16-core limit; 41.6-80.2% of sampled periods were throttled. These are shared CN counters, not the statement's CPU/wait shares. Cold subscriptions alone do not explain the remaining latency. A lower-load ingress-CN control failed with a cross-CN TCP reset and was cleaned up; it is not a successful comparison or proof of the load's contribution. Existing Pyroscope retained the original 72-second window; no profiler was stopped/reconfigured. Synchronous clone-family stacks contain 17.48 sampled CPU seconds, including checkpoint load 12.74s, Vector.Dup 12.37s and runtime.memmove 10.46s. These are retained process samples without statement labels; concurrent clone work cannot be excluded and full-window coverage is not asserted. They cannot be converted into the statement's wall-time savings. ### Whole-SQL cold-path reproduction and A/B Local macOS ARM64 / Apple M5 / 32GiB / Go1.27.1, two real embedded CNs and the native MySQL public `CREATE DATABASE ... CLONE ...` path. Captured source DDL creates 135 logical/529 physical relations. One additional payload table has three inserted rows and a deletion, leaving two live rows: 136 logical/530 physical relations total. 262,144 unrelated, committed TN catalog relations share a real immutable primary-key object, as clones legitimately can. Normal TN checkpoint APIs write the persisted v13 global checkpoint; actual metadata cardinality and first/last object PK reads are verified. No fake metadata rows, sleeps, deliberately slow filesystem or clone execution override. Only the local test-owned merge scheduler is paused, identically in both arms. This cardinality is synthetic, not a measured QA checkpoint size. Both arms retain the earlier FK and subscription changes. Identical private instrumentation is used; only the reader implementation differs. Each sample uses a fresh cluster without restarting a peer. The timer covers SQL execution through its return, excluding setup/checkpoint creation, result checks, DROP and cluster teardown. Process allocations include both CNs and TN, not clone alone. The three-sample comparison was completed before the final target merge, at the reader source delivered by `3dbd8220`/`994b8fad`: | | Old full-metadata reader | Selected-row reader | | --- | ---: | ---: | | Whole SQL sample 1 | 6.504761s | 1.225894s | | Whole SQL sample 2 | 9.639648s | 2.358957s | | Whole SQL sample 3 | 23.258254s | 3.104479s | | Whole SQL median | 9.639648s | 2.358957s | | Process allocation median | 26,013,628,880 B | 650,493,680 B | | Metadata read count | 540-542 | 539-540 | | Metadata read elapsed sum | 4.297-19.522s | 30.389-43.470ms | Observed median SQL latency is 75.53% lower (4.09x); process allocation median is 97.50% lower. All six whole tests pass, including relation counts, querying every source-DDL table, exact surviving payload rows, target-only DML, unchanged source and successful destination DROP/absence. Host load was not fully controlled; raw slow samples are retained. This is an incremental reader A/B, not the whole PR versus untouched upstream or a production throughput claim. Same-CN consecutive-clone controls on that revision: | Reader | Cold SQL | Warm SQL 1 | Warm SQL 2 | Metadata reads | | --- | ---: | ---: | ---: | --- | | Old | 7.504944s | 0.835917s | 0.724325s | 541 / 0 / 0 | | Selected | 1.454788s | 0.603479s | 1.011951s | 542 / 0 / 0 | Both full tests pass; warm allocations are approximately 0.56-0.58GB in both arms. No consistent warm benefit is proved. The amplification is on the cold checkpoint path, not every slow clone. A smaller 131,072-relation preliminary pair passed but reduced whole SQL only 3.308s -> 3.173s (4.1%), not a material latency claim. Initial harness failures (incorrect object PK-writer flag and peer-restart stale lock bindings) are retained and were corrected in the private fixture, without product retries or lock-policy changes. The final owning-package component benchmark separately confirms the mechanism: at 131,072 persisted metadata rows, both arms export data and tombstone ranges; old 1,489,681ns / 23,339,514 B per read versus selected 3,790ns / 9,768 B. Small allocations rise from 31 to 46 per read. This is a component result, not the whole-SQL timing above. Checkpoint format and the serial replay bound remain. ### Earlier FK measurement and limits Controlled two-CN, 100 empty tables forming an FK chain, five standalone samples per revision with identical temporary diagnostics: median 688.389ms -> 468.620ms (31.9% lower), ranges 636.593-760.746ms versus 441.542-611.776ms. A two-table collector performs five SQL statements instead of nine, without repeated FK enumeration/DDL lookup. Both admission collections remain independent and diagnostics were removed before delivery. This synthetic FK-heavy result cannot explain the actual source's single FK or establish production throughput. Initial no-FK controls reached about 2.92s for 1,000 empty tables and 1.16s for 100 single-row unflushed tables; they did not reproduce 82s or 0.4-0.6s/table. The PR does not remove serial table/index subscriptions, increase replay capacity, redesign transaction ownership or prove lower remote-I/O latency. There is no patched QA deployment, same-platform after measurement, complete mo-tester BVT, production coverage or full-workload performance proof. ### Validation and revision boundaries - Earlier FK full frontend race: PASS, 37.251s. Public SQL and empty100/FK100 smoke: PASS, 25.482s, not the standalone performance comparison. All six authenticated Issue29399 restore/ownership/privilege/principal tests: PASS, 32.659s, including optimistic-SI removal arms and rollback/PITR. - Original configured frontend/embed lint: 0 issues; err-check PASS; configured license headers: 6,060 checked / 0 invalid. Native inputs are repository-built/ verified, with no restamped artifacts; local platform is macOS ARM64. - Previous bc6b8fa UT Coverage failed because the added public test left the shared cluster active. Complete logs/local ordered selection reproduce this PR-introduced fixture defect. Cleanup-fixed atomic ordered selection: PASS, 10.655s; full embed race: PASS, 366.784s. This precedes the checkpoint changes. - Normal merge of main c2c1031 / #29472: full disttae/logtailreplay race PASS, 20.925/27.259s; four new concurrency tests individually race count100 PASS. Public current/snapshot FK clone PASS, 10.441s; authenticated Issue29399 family PASS, 82.536s. Changed-package lint 0 issues, err-check PASS, configured license headers 6,068 / 0 invalid. Initial missing-native-flags lint preprocessing failure is retained; corrected flags match the repository wrapper. - Reader revision 994b8fa: final focused normal PASS, full owning logtail normal plus benchmark PASS (2.381s), focused race count10 PASS (2.948s), owning-package vet exit0, configured incremental lint 0 issues, err-check PASS, gofmt/diff clean. Real consumer, cancellation/error and whole-SQL evidence above passed. Independent read-only reader review APPROVE; not a GitHub approval. - Normal target merges retain upstream changes, without conflicts/manual overrides: main 9081663 and then-target d7621ea (#29756 vector, #29771 spill-cache batching, #29751 design-only docs). Final candidate is 80c7924. Reader product/test bytes are unchanged from 994b8fa. The target merge includes a shared vector optimization; selected metadata materialization uses `Vector.Union`, not `UnionOne`. Original three-sample timings remain explicitly pre-merge evidence. - Fresh final-candidate full vector/spillio/logtail race suites PASS, 7.323s / 1.457s / 6.402s respectively. On this merged candidate, an additional one-pair whole-SQL cold A/B smoke passes all correctness and cleanup oracles: old reader 12.584351s / 25,991,143,288 B process allocations; selected reader 2.155264s / 644,057,120 B. Metadata read sum 9.797180s -> 58.943695ms, 540 -> 539 reads. Package results 39.413s / 41.106s, both exit0. This is one supplementary pair, not a new repeated-sample median or QA after measurement. - Fresh merged vector/spillio/logtail vet exit0; configured incremental lint vs 994b8fa: 0 issues; err-check PASS, gofmt and diff whitespace clean. Prior PR closures' evidence is retained with its revision boundaries, not reported as new full-repository SCA or full BVT on this candidate. - Same previously authorized independent read-only reviewer approved the narrow target merge, reusing earlier closure reviews and fresh proof. Its two description-only fact corrections were verified and applied; final description review also APPROVE. No GitHub review was submitted by this task. ### Remote CI Historical head 27032d9, ALL CI run37903208186: actual Ubuntu UT, shared build, SCA, UT Coverage, PESSIMISTIC BVT and Connector/J succeeded. PROXY job113734853257 failed one pub_sub4.sql prepared JDBC metadata query with `context canceled`; full producer logs and CN artifacts are retained. Cause is not yet attributed to this PR or a clean baseline, and it is not classified as infrastructure. Coverage job113749307931 failed for a missing producer profile, with no coverage verdict; CI Required also failed. Draft Iceberg was SKIPPED, not a functional pass. No blind rerun was requested. These historical results do not establish current-head CI or merge protection success. Current pushed head remains 80c7924. It is now OPEN/Ready/MERGEABLE/BEHIND, with no submitted reviews or inline threads. The Ready transition was external; this task did not change that state. The first current-head [ALL CI run37920067820](https://github.com/matrixorigin/matrixone/actions/runs/37920067820) completed FAILURE. Its four red checks comprise two producer failures and two downstream failures, not four independent defects: - [Ubuntu UT job113785658801](https://github.com/matrixorigin/matrixone/actions/runs/37920067820/job/113785658801): the only failed subtest was `TestV406UpgradeCreatesViewMetadataCatalogTables/catalog_fence_overlaps_uncommitted_upgrade`, at the one-second post-release `upgradeDone` deadline. The same transaction later committed successfully at TN with 1.942332923s commit latency; WAL latency was observed. The callback also waits for committed-log application. Cleanup awaited completion but discarded its error, and the post-timeout correctness assertions did not execute. This is not proof of every assertion passing, the underlying resource cause, or PR attribution. - [UT Coverage job113785711398](https://github.com/matrixorigin/matrixone/actions/runs/37920067820/job/113785711398): the only failed test was the duplicate-copy subtest of `TestBigDataBulkWriteAndPrimaryKeyCopyPreserveRows`, expecting 32,770 rows but observing 32,769 after the second CN1 insert and an immediate CN0 read. The shared fixture uses existing sacrificing-freshness defaults, without a writer-commit-to-reader-logtail barrier. That is a verified visibility precondition gap, but the retained incident does not contain the second insert's CommitTS and the final count query's snapshot. It does not establish that this gap caused the incident or exclude a product defect. - [Coverage job113801901899](https://github.com/matrixorigin/matrixone/actions/runs/37920067820/job/113801901899): a required producer did not publish a complete profile. No changed-code coverage verdict was calculated; this is not evidence of low coverage. - [CI Required job113825991329](https://github.com/matrixorigin/matrixone/actions/runs/37920067820/job/113825991329): failed because the UT/coverage dependencies failed. In that same run, SCA, shared build, both PROXY/PESSIMISTIC BVT groups and Connector/J succeeded. Draft Iceberg was SKIPPED, not a functional pass. Complete failing logs and the full coverage diagnostics artifact were retained. Focused local comparison, macOS ARM64 / Go1.27.1, with matching verified native inputs and no product/test edits: candidate80c and clean detached base d7621ea each passed 20 upgrade race repetitions (28.647s / 21.791s) and 20 bulk-write coverage repetitions (18.274s / 18.292s). Both used `-short -tags matrixone_test`; bulk coverage instrumented four affected packages, not the complete CI package set. The clean worktree was removed after completion; evidence remains. Neither reproduced the incident signature, so these failures are not labelled pre-existing or fixed. Independent read-only triage review approved preserving scope and avoiding speculative fixes; not a GitHub approval or a CI success claim. At 2026-10-09 13:16 UTC, the second same-head [ALL CI run37934151826](https://github.com/matrixorigin/matrixone/actions/runs/37934151826) was already IN_PROGRESS. Preflight/eligibility/shared build succeeded; UT, SCA, UT Coverage and both BVT groups remained running. Its [Connector/J run37934150298](https://github.com/matrixorigin/matrixone/actions/runs/37934150298) succeeded; Iceberg run37934150248 was SKIPPED. This task requested zero job or workflow reruns and no cancellation, and did not modify unrelated test assertions, workflows or product consistency. Running/queued/skipped checks are not successful tests. Review, latest-base and protection gates remain separate from test results; the PR is not claimed CI-green or merge-ready. No CI workflow, mo-tester, generated transfer files or dependency policy changed. --------- Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
What type of PR is this?
Which issue(s) this PR fixes:
Partially addresses #29755, introduced by #29646.
What this PR does / why we need it:
The spill cache policy submits writeback for every physical append and, beyond its retained tail, waits and drops cache on every append. HashBuild already coalesces records into approximately 64 KiB writes, so this still adds repeated small-range writeback operations.
This change:
No optimizer, stats, DOP, spill threshold, memory admission, disk accounting, FD ownership, or spill-format changes. This retains the memory-protection policy rather than restoring unbounded cache retention. Existing best-effort/advisory OS semantics remain unchanged.
Completed local validation:
spillio,hashbuild,spillutil,hashjoin, andgroup.spilliorace tests; incrementalgo vetand repository-pinned golangci-lint v2.14.0 (zero issues).Matched Linux component comparison: 32 MiB files, 64 KiB appends, 32 samples per revision in four alternating before/after rounds, GOMAXPROCS=1, CPU2 pinned, same filesystem and CRC.
CRC matches in every sample. These are component results, not a claim that all of the observed BigData I3 73% regression is fixed. Full TPC-DS 1T and I3 have not been rerun with this patch; repeated HashBuild FD open/close remains unchanged.
Benchmark records and diagnostic fixtures remain outside this PR. The rebase onto current main adds only unrelated DECIMAL BVT coverage; the code and dependencies relevant to the retained validation evidence are unchanged.