Skip to content

[4.2-dev] perf: reduce clone metadata work and isolate checkpoint replay - #32894

Merged
mergify[bot] merged 2 commits into
matrixorigin:4.2-devfrom
gouhongshen:codex/backport-29769-4.2-dev
Nov 18, 2026
Merged

mergify[bot] merged 2 commits into
matrixorigin:4.2-devfrom
gouhongshen:codex/backport-29769-4.2-dev

Conversation

@gouhongshen

@gouhongshen gouhongshen commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • API-change
  • BUG
  • 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.

…xorigin#29769)

- [ ] API-change
- [ ] BUG
- [x] Improvement
- [ ] Documentation
- [ ] Feature
- [ ] Test and CI
- [ ] Code Refactoring

Related matrixorigin#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.

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

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

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.

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

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.

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.

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.

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.

- 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 / matrixorigin#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 (matrixorigin#29756
vector, matrixorigin#29771
  spill-cache batching, matrixorigin#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.

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>
(cherry picked from commit 72d4a49)
Signed-off-by: gouhongshen <[email protected]>
@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

@mergify

mergify Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Queue requested — the merge queue status continues in this comment ↓.

@XuPeng-SH

XuPeng-SH commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

mo-bot review · mo-bot-local · done

Commit: 7906a18ef68e2aaffb00df5c0254abdbf86b3718

Review completed. Read the assessment.

@XuPeng-SH XuPeng-SH 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.

mo-bot review · mo-bot-local · review

Commit: 7906a18ef68e2aaffb00df5c0254abdbf86b3718

Assessment: request_changes

The backport reuses the clone’s foreign-key inventory and isolates checkpoint replay while preserving its one-replay limit. The selective metadata reader cuts allocations for sparse matches on a warm cache, but doubles backing-store reads for matching tables on a cold cache when disk caching is disabled.

Model: gpt-6.2-sol / xhigh

Session: 01a1a004-9884-72c0-ad39-f096c4209c4a · slot 1 · generation 0

  • P2 pkg/vm/engine/tae/logtail/ckp_reader.go:510: A table-specific v13 checkpoint read finds the requested table and its metadata columns are cold on S3FS with only a memory cache.
    Impact: The reader fetches the entire metadata object twice. The extra request and transfer extend the serialized checkpoint replay path and also affect historical table reads through the same reader.
    Evidence: The table-ID read at line 483 and the full-column read at line 510 both use policy 0, which selects a full-object read in pkg/fileservice/io_vector.go:67. In three runs, the baseline fetched the 146,406-byte object once and the candidate fetched it twice. The disk-cache control used one backing-store read in both cases. See checkpoint-cache-control.jsonl and receipt 1794998936699600842-3.json. Use one coalesced read for a matching table and select rows while the columns are pinned, preserving the allocation savings and returning owned ranges.

Validation:

  • Verified the frozen diff and formatting, then compared the v13 metadata schema and v12 reader dispatch against 4.2 release and hotfix tags. See source-audit.log and format-audit.log.

  • Six focused frontend and subscription tests passed, including cross-account restore authorization. All four new replay tests and two existing controls passed five times under the race detector. See frontend-subscription-focused.jsonl and checkpoint-race.jsonl with receipts 1794998941978260579-3.json and 1794998956072376390-3.json.

  • The embedded SQL test passed for live and snapshot clones, foreign-key enforcement, independent target writes, and rollback. See embed-focused.jsonl and receipt 1794999058520057878-3.json.

  • Four checkpoint-reader tests passed. For a warm checkpoint with 4,096 metadata rows and four matches, allocations fell from 734,256 to 6,456 bytes per operation. See reader-focused.jsonl and receipt 1794998920986735958-3.json.

Limitations:

  • The backing-store probe used the production S3FS read path with a local disk object-storage adapter. It measured request counts without measuring cloud latency.

  • End-to-end production clone latency for #29383 remains open.

Read v13 metadata columns together and copy only rows for the requested table while the cache leases are held. Verify that cold memory-only S3FS fetches the column data once and that failure and cancellation release all leases.
@XuPeng-SH

XuPeng-SH commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

mo-bot review · mo-bot-local · failed

Commit: 5b567ed32d8750ae018f83df097034060776149a

{"message": "This content was flagged for possible cybersecurity risk. If this seems wrong, try rephrasing your request. If you\u2019re doing authorized security work that requires more cyber permissive safeguards, apply for Daybreak access via https://platform.openai.com/settings/organization/status-and-access before retrying.", "codexErrorInfo": "cyberPolicy", "additionalDetails": null, "misalignment": null}

@XuPeng-SH XuPeng-SH 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.

Deep review of 5b567ed32d87 against 4.2-dev at 971bbf280fc9.

Request changes for the high-match v13+ checkpoint metadata path. Please keep the coalesced read and owned ranges, and remove or otherwise address the measured materialization regression described inline.

The original review's cold S3FS issue is resolved. I ran the current regression on the original reader and observed two metadata GETs. The current head uses one cold GET and zero additional warm GETs. The object header was primed on both runs.

The FK change reuses the inventory that determines dependency order, and PITR and snapshot restore retain their existing lookup path. Replay continues to use the partition's existing checkpoint consumer. The capacity-one gate limits replay while the subscription lock is released. Publication checks the entry, incarnation, and partition. Current-head validation passed for the owning disttae and logtail packages under race, all four new replay tests repeated individually 100 times under race, FK collection and restore-authorization controls, and live/snapshot embedded SQL clone with rollback. The two-CN empty/FK benchmark passed a smoke run. Its iterations reuse the source, so that run measures a mixture of initial and warm clone work. Production latency for #29383 remains open.

Please also correct the PR description's post-lock collection claim. The 4.2-dev clone path collects once and then performs the existing snapshot/lock revalidation where applicable. The unit test's second collection is an independent call. A documentation correction is sufficient here. Please link the backport design from the PR description so the 4.2 incarnation check is easy to trace.

Comment thread pkg/vm/engine/tae/logtail/ckp_reader.go Resolved

@XuPeng-SH XuPeng-SH 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.

Reassessed my previous request for changes on the same head. The high-match metadata cost remains measured, and I am withdrawing it as a merge blocker.

A second warm-cache A/B at 2, 4, 16, 64, and 256 fully matching ranges measured about 0.4–5.1 µs of additional reader time per metadata block. The synthetic 4,096-range case still shows about 83 µs and 266 KB of additional allocations. The production writer coalesces consecutive rows for a table and object type in each checkpoint data file. Thousands of ranges for one table therefore also entail substantial downstream checkpoint data processing. End-to-end dense replay and clone impact remain unmeasured.

For this backport, one coalesced metadata read and the sparse-selection allocation savings justify the measured cost of using the existing owned-vector materialization. Keep the dense benchmark case as a follow-up if useful. The PR description about post-lock collection should still be corrected, as noted in the prior review. No remaining merge blocker from this review.

@mergify mergify Bot added the queued label Nov 18, 2026
@mergify
mergify Bot merged commit 44183ff into matrixorigin:4.2-dev Nov 18, 2026
@mergify

mergify Bot commented Nov 18, 2026

Copy link
Copy Markdown
Contributor

✅ Merged into 4.2-dev as 44183ff at 13:14 UTC

Less than a minute in the queue, with no time running CI.

So far

  • ✅ Entered the queue Wed 18 Nov, 13:13 · rule release-4.2 · triggered by rule Automatic queue on approval for release-4.2
  • ✅ Checks skipped · PR is already up-to-date
  • ✅ Merged 13:14 · 44183ff · squash
3 merge conditions met
  • #review-threads-unresolved = 0 · required by GitHub branch protection
  • github-review-approved · required by GitHub branch protection
  • any of · required by GitHub branch protection:
    • check-success = CI Required
    • check-neutral = CI Required
    • check-skipped = CI Required

Times in UTC · dashboard · how the merge queue works

@mergify mergify Bot removed the queued label Nov 18, 2026
XuPeng-SH added a commit that referenced this pull request Nov 23, 2026
## 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 #33097. This PR improves the current `main` reader; release
rollout and production workload validation are tracked separately in the
issue.

## What this PR does / why we need it:

For v13 checkpoint metadata, use a valid table-ID block zone map to
avoid reading the ID column when its bounds prove the requested table is
absent. An ID inside the bounds still uses the existing exact lookup, so
a gap does not trigger speculative reads of the large metadata columns.
Reuse the header already loaded by the reader when reading the ID
column; this avoids an additional backing-store request when the
metadata cache does not admit the header.

Allocate filtered `TableRange` results to their exact size in the
existing conversion function. This removes repeated growth and copies
while preserving row order, nil results, and owned object-stat values.

On an 8,192-row synthetic checkpoint using the actual ObjectIO writer
and reader, Go 1.27.1, and a warm memory cache:

- One matching row (three 300 ms runs): both versions allocated 3,960
B/op in 31 allocations; the timings overlap at 4.68–4.84 µs before and
4.59–4.75 µs after.
- 64 matching rows (three 300 ms runs): 31,696 to 18,064 B/op, 42 to 32
allocs/op, and 11.1–12.3 to 8.1–8.9 µs/op. With 4,096 matches: 3,295,720
to 921,256 B/op, 59 to 33 allocs/op, and 486–529 to 262–272 µs/op. These
can be reproduced with `BenchmarkCheckpointMetadataSelection`.
- All 8,192 rows matching (three 500 ms runs): 6,670,992 to 1,838,928
B/op, 66 to 36 allocs/op, and 805–845 to 424–442 µs/op.
- A 10-lookup public-reader window (three 500 ms runs) with an
**assumed** 60% outside misses, 20% in-range misses and 20% one-row
hits: 13,872 to 9,744 B/window and 16.7–17.3 to 11.7–11.9 µs/window.
This mix is not an observed production distribution.

The 64-, 4,096-, and 8,192-match cases are dense synthetic stress cases,
not measured production frequencies. Each metadata range represents a
table/object-type run in a checkpoint data file; with sorted data, each
file contributes at most one range per type. The actual request-weighted
match count and outside-range miss rates, especially for alphaTask
subscriptions, have not been measured.

On an isolated local MinIO server over HTTP, with the same synthetic
checkpoint, an outside miss changed from 2 to 1 GET with an unprimed
header and from 1 to 0 GET with a primed header. The in-range miss and
matching cases kept the same GET and byte counts. These are loopback
measurements, not remote-S3 or production replay measurements. The 4.2.9
release source already contains #32894's earlier selective-read fix; the
deployed image and its allocation, GC and RSS effects are not
established by this PR.

Validation:

- Focused reader, cleanup, malformed zone-map, cancellation, concurrent
subscription and range-export tests.
- Real ObjectIO/S3FS backing-read tests, including disabled file cache
and metadata-cache admission, first cold read, and blocks over 8,192
rows.
- Full owning-package tests with `-race`: `./pkg/objectio/ioutil`,
`./pkg/vm/engine/ckputil`, `./pkg/vm/engine/tae/logtail`; focused
`logtailreplay` tests cover the existing appendable-object caller.
- Repository incremental SCA against the `main` merge base, plus
changed-file gofmt and `git diff --check`.

This branch was previously deployed

1 inactive deployment
ci — 5b567ed3 Deployed Nov 18, 2026 by XuPeng-SH
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind/enhancement size/XL Denotes a PR that changes [1000, 1999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants