Repository navigation
perf: reduce clone metadata work and isolate checkpoint replay - #29769
Conversation
Reuse the cached fixed-width table IDs to select ranges before copying varlen metadata. Preserve owned range outputs and add read/decode/partial-cleanup tests and a matched component benchmark. Whole-database clone latency proof and remaining review validation are pending; this commit does not establish resolution of issue matrixorigin#29383.
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 80c7924, PR merge-base d7621ea (fresh remote main d2a0055): APPROVE. All 12 changed files reviewed; no blocking findings.
Design gate: the subscription ownership/cancellation/reconnect change requires a design. Reviewed revision 3 at the linked 27032d9, including its distinct local design-review decision. The document is unchanged at this head. PASS: keep state publication with subscribedTable, checkpoint mutation with Partition, and retain capacity one without holding the state lock over I/O. No second subscription state machine, transport generation, background worker or speculative parallel clone execution is introduced. The FK and selected-row optimizations reuse existing inventory/selection and ObjectIO materialization owners.
Closure review:
- FK collection: traced plain CLONE and DATA BRANCH admission/recollection, tenant/snapshot routing, source filtering and getTableInfoMap. Reuse is per collection, preserving the independent post-lock recheck and existing privilege, ordering and rollback owners; there is no cross-statement cache.
- Replay: traced state admission, partition capture, completion publication, logtail pending/apply/clear, unsubscribe/GC and actual reconnect initialization. Lock order remains subscriber -> engine; checkpoint I/O and cancellable Partition.Lock execute outside subscribed.rw. Entry identity/state/database checks reject stale completion. The gate survives reconnect, releases through defer, and queued callers capture no partition. Readiness does not clear pendingTo; the application owner retains that responsibility.
- Reader: checked the checkpoint writer's sorted-table invariant and the unchanged <=v12/all-table readers. The fixed-width ID lease encloses selection; selected materialization has caller-owned cleanup on partial failure. Exported ObjectStats are value copies, not dangling cache aliases. Absent IDs skip remaining columns. Existing readMetaBatch still serves the all-table path and is not dead code.
Independent adjacent challenge: added a temporary reviewer-only test with a blocked nonempty checkpoint, a same-table queued follower, cancellation of the active owner while Partition remains locked, then a pending update and successful follower replay. The follower cannot publish readiness before checkpoint completion and preserves/clears the pending fence through its real owner. Exact-head race count100 PASS, 2.590s, Go1.27.1/macOS arm64 with a matching native build. Probe removed; worktree clean. This complements the author's four individually repeated race100 tests, replacement success/error controls and reader failure/cancellation/cache-release tests.
Evidence reused with boundaries: explicitly revisioned frontend/embed public SQL current/snapshot/FK/rollback/authenticated tests, full disttae/logtailreplay race, and final-head vector/spillio/logtail race plus the final-head whole-SQL cold-reader A/B. Relevant disttae/frontend/embed source bytes are unchanged since the documented earlier closure validation. Latest ALL CI run37934151826 is completed/success at this exact head. Earlier failed-run attribution remains unresolved as documented; the later green run is not presented as proof of their root cause.
Incremental cost: implementation +128/-38 in five files; tests +836/-1 in six; design +114. Tests cover actual collector identity/query work, public SQL effects and rollback, deterministic ownership transitions, and real persisted metadata with fault injection and balanced resources. Large cardinalities are opt-in benchmarks. The shared-cluster cleanup correction is present. No test-line-count exemption was used.
Performance: the main wins are removed repeated FK queries, unrelated subscription-state progress during replay, and copying only a table's metadata rather than every table's varlen vectors. Serial replay capacity is intentionally unchanged. The reported 9.640s -> 2.359s cold SQL median is a synthetic local reader A/B, with higher small-allocation count (31 -> 46) and no consistent warm benefit. It is not a production or general TP throughput claim; already-subscribed TP readers bypass the replay gate. Issue #29383 appropriately stays open for the remaining production latency causes.
Comment audit: no earlier substantive PR review/inline findings were pending. The linked issue's remaining production-performance work is acknowledged, not falsely marked solved; local design revisions' pending-update, stale-completion and capacity concerns are closed in source and tests.
Merge Queue Status
This pull request spent 8 minutes 3 seconds in the queue, with no time running CI. ReasonPull request #29769 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
|
…lay (#32894) ## 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 to #29383. Backports #29769 (merge commit `72d4a49db7`) to `4.2-dev`. ## What this PR does / why we need it: - Reuses source table definitions already collected by `CLONE DATABASE` when selecting foreign-key tables. The backport reuses the existing 4.2 source collector and retains fresh collection after locking. - Moves checkpoint replay outside the global subscription lock while keeping one active replay. Before publishing readiness or returning a replay error, the caller verifies the subscription entry, its incarnation, and the active partition. This preserves 4.2 replay fencing when a subscription or partition is replaced. - Coalesces the v13+ table-specific checkpoint metadata columns into a single read. While the columns are pinned, it selects the requested table and copies only its rows. This cuts cold backing-store column reads from two to one with a memory-only cache and preserves owned output. An absent table still requires loading the metadata columns but produces no owned row copies. The checkpoint format and older reader paths are unchanged. ### Validation The S3FS disk-adapter regression verifies one cold backing-store GET for metadata columns and zero additional GETs on a warm read, with identical data and tombstone ranges. The object header is primed separately. The warm 4,096-row, four-match benchmark allocates about 5.8 KB per operation, compared with 6.5 KB for the prior two-read selection and 734 KB for full-batch materialization. Scoped unit tests, race tests, and an embedded SQL clone test cover live and snapshot source collection, replay isolation and replacement, I/O and decode failures, cancellation and lease release, foreign keys, independent target writes, and clone rollback. The two-CN clone benchmark remains available. Production clone latency for #29383 remains to be validated. Approved-by: XuPeng-SH <[email protected]>
What type of PR is this?
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
collectCloneDatabaseSourcealready enumerates logical source tables and readstheir definitions. After deriving FK order from those definitions and the FK
catalog, it passed a nil source to
getTableInfoMap, causing another per-FK-tableenumeration and
SHOW CREATE. This repeats catalog round trips and replacesthe exact objects used to derive the dependency order.
it for FK selection inside each database-clone source collection.
getTableInfoMap; select thealready collected definitions rather than query them again.
databases without FKs.
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
critical section. Pin the exact partition/entry generation before I/O, reuse
existing checkpoint consumption, and reject stale readiness/error publication.
reconnect. Queued callers pin no partition; no workers, parallel clone/DDL,
configuration or increased active replay capacity are introduced.
publication; clear only through the existing application owner. Cover caller
cancellation, replacement, unsubscribe, clear and identity mismatch paths.
owner. This fixes the PR-introduced UT Coverage interference with subsequent
owning-cluster lifecycle tests.
Design-first subscription contract: reviewed revision 3.
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
readMetaWithTableIDpreviously loaded/copied allfive 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.memmoveamplification identified in the retained QA CPUprofile; schema-only local fixtures omitted this global checkpoint context.
Find the matching contiguous range first; an absent ID returns without
loading the other metadata columns.
LoadColumnsDataIntoselected-row path to materialize thematching rows into an owned batch, then reuse the existing data/tombstone
range export helpers.
success, error and cancellation. Returned ranges own their object-stat values.
new cache, fallback, retry, worker, hook or configuration is introduced.
Product change:
3dbd8220c657d7387d2ac5f49f6c6553211f0369; final reader tests:994b8fadf17cff3d73200f0694799ad8d112d376. The subsequent normal target mergepreserves these source bytes. Independent final reader review: APPROVE.
Regression proof
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.
constructor and verifies missing/out-of-scope objects are not fetched.
current vs snapshot rows, target FK rebinding, invalid-reference rejection,
independent target DML, unchanged source data and explicit clone rollback.
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.
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.
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.
while the ID lease is held. Verify cancellation, no output, equal acquisition/
release counts, zero live MPool bytes and an unaffected subsequent read.
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.
The latter includes planning/creation, not proven pure DDL time.
12.048114s send-to-response and 26.920737s response-to-ready. These sums do
not exclusively attribute elapsed time or isolate resource contention.
occurred sequentially before its first TableMetaReader read.
materialization. This is not a bulk row-copy bottleneck.
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 DDLcreates 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: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:
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
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.
license headers: 6,060 checked / 0 invalid. Native inputs are repository-built/
verified, with no restamped artifacts; local platform is macOS ARM64.
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.
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.
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.
overrides: main 9081663 and then-target d7621ea (perf(vector): skip scalar-null calls for flat UnionOne sources #29756 vector, fix(spillio): batch spill writeback within bounded cache window #29771
spill-cache batching, docs: define general multilevel correlated subquery execution design #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, notUnionOne.Original three-sample timings remain explicitly pre-merge evidence.
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.
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.
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
completed FAILURE. Its four red checks comprise two producer failures and two
downstream failures, not four independent defects:
the only failed subtest was
TestV406UpgradeCreatesViewMetadataCatalogTables/catalog_fence_overlaps_uncommitted_upgrade,at the one-second post-release
upgradeDonedeadline. The same transaction later committed successfullyat 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.
the only failed test was the duplicate-copy subtest of
TestBigDataBulkWriteAndPrimaryKeyCopyPreserveRows, expecting 32,770 rowsbut 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.
a required producer did not publish a complete profile. No changed-code
coverage verdict was calculated; this is not evidence of low coverage.
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 affectedpackages, 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
was already IN_PROGRESS. Preflight/eligibility/shared build succeeded; UT, SCA,
UT Coverage and both BVT groups remained running. Its
Connector/J run37934150298
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.