Skip to content

fix(branch): prune historical catalog replay and prefer snapshot reads - #32707

Merged
mergify[bot] merged 14 commits into
matrixorigin:mainfrom
gouhongshen:codex/fix-merge-checkpoint-pk-main
Nov 20, 2026
Merged

mergify[bot] merged 14 commits into
matrixorigin:mainfrom
gouhongshen:codex/fix-merge-checkpoint-pk-main

Conversation

@gouhongshen

@gouhongshen gouhongshen commented Nov 13, 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:

Fixes #32708.

Related: #32704 (production FDB DATA BRANCH MERGE timeout, v4.2.8-hotfix) and #32705 (4.2-dev sibling). This brings the full fix, including the replacement-chain review correction, to main.

What this PR does / why we need it:

The production incident merged a one-row update into a six-row table but spent 29.859 of 29.942 seconds resolving table-creation metadata. Checkpoint recovery dropped the exact-table PK predicate and delivered 1,861,139 historical catalog data/tombstone versions before cancellation.

Preserve the existing predicate through checkpoint recovery and use it to prune object/block payloads. Require explicit confirmation that an object sort-key zonemap describes the requested user PK; unknown zonemaps, cluster-by keys and rowid-sorted tombstones stay eligible. Persisted appendable objects can use PK block pruning, while tombstone blocks use the tombstone PK sequence number. Commit-timestamp pruning retains its TN non-appendable restriction.

Retain all temporally eligible TN replacement metadata while resolving deleted predecessors, then apply pruning to terminal payloads. This includes the review fix from #32704: a disjoint replacement cannot be removed from the lineage index and mistaken for a missing successor. Genuinely missing metadata/matching files still fail.

Adaptation to main

Source commits: 80708c0d8ebf4ec210596b2afa2b91e04effe51c and d72ab2a1b5a1624adda860d9047e45a6a26b9e71, ported onto main@1064837ae2648aa20e5e1abb7edd0564493e6b4d.

  • The main range constructor already receives pkFilter; retain that implementation, its logical/physical column mapping, bounded-memory/spill handling, trailing-delete policy and all-version policy.
  • Add the PK-sort metadata guard and populate it for the catalog and all existing PICK key-materialization paths. The release branch already had these supporting fields; main did not.
  • Preserve main's error handling and checkpoint reader allocation while resolving cherry-pick conflicts.
  • Adapt the integration tests to inspect Partition.Snapshot().GetStart() because main no longer exposes the release branch's GetPartitionStateStart helper. The assertion that historical recovery is required remains in place.

CI follow-up

The full Linux race run detected concurrent callback reads/reset in the existing issue31401CopyObserver, between background ISCP SQL and the ALTER COPY integration test. Protect hook installation/reset and snapshot reads with a mutex; release the mutex before invoking callbacks so nested SQL remains possible. This follow-up changes only the test observer, with all existing assertions and CI checks retained. The test is not present on 4.2-dev.

The CI trace provides the before-fix race evidence; three local pre-fix plugin runs did not reproduce it. After the fix, both complete TestIssue31401AlterCopyRebuildTransaction and TestIssue31401AlterCopyWaitsForLoad scenarios pass three repetitions with -race -tags matrixone_test; go vet -tags matrixone_test ./pkg/tests/issues passes. Targeted race rechecks also pass for the other failed workspace-GC, numeric SQL, publication lifecycle, statement diagnostic capacity and disk-download tests, plus the checkpoint-catalog MERGE regression.

Validation

Passed on the original PK-pruning port using Go 1.27.1 / macOS arm64, with native libraries built in the isolated worktree via make cgo:

go test -p 3 -count=1 -timeout 10m ./pkg/vm/engine/disttae/logtailreplay ./pkg/frontend/databranchutils ./pkg/vm/engine
go test -p 3 -count=1 -timeout 10m ./pkg/frontend ./pkg/vm/engine/test -run '^(Test.*DataBranch.*|Test.*PKFilter.*|Test.*ChangesHandle.*|TestFileNotFoundFallbackToSnapshotRead|TestRealStaleReadStillReturnsError|TestPackMoDatabaseCPKey|TestDatabaseCreatedTimeToCollectLowerBound|TestGetObjectsFromCheckpoint.*)$'
go test -p 3 -count=1 -timeout 7m ./pkg/tests/dml -run '^(TestDataBranchPick|TestDataBranchMerge|TestDataBranchMergeWithCheckpointCatalog)$' -v

The full logtailreplay package includes main's bounded range/spill/layout regressions as well as the added real-file PK and replacement-chain tests. The engine integration test verifies checkpoint and visible-state policies after partition GC and original creation timestamps. The SQL test checks all business rows for rename, repeated merge, conflict SKIP, inserts/deletes; existing MERGE/PICK suites pass too.

The source PR records the before-fix failures and controlled performance comparison. Those performance samples were not rerun on main and are not a production-latency guarantee. Repository-wide tests were not run locally. No schema, storage format, CLI timeout, FDB application-state recovery or production configuration is changed.

Follow-up: prefer snapshot reads for table creation timestamps

The QA follow-up showed that the expensive work could be avoided for an original catalog row. Prefer a compound-primary-key snapshot probe and accept its creation timestamp only when the table ID, original catalog version, and timestamp range all match. Keep historical CollectChanges replay and the ID-based recovery for cases where the probe cannot prove the creation timestamp. Reuse the proven boundary for the same physical generation so an ALTER that rewrites a catalog row cannot hide an earlier conflicting write.

The historical path also reuses bounded checkpoint metadata within each statement, avoids repeat file prefetches, overlaps catalog metadata reads, coalesces overlapping persisted-block reads, and uses less allocation when collapsing per-key versions. On main, the probe uses each operand's physical owner account. Coalescing applies to unbounded reads, retains each block's special-column layout, and leaves the bounded window, spill, and trailing-delete handling in place.

On QA, the six-row single-update MERGE took 62.946 s on the existing CN and 0.834 s on one isolated CN with these optimizations, using the same older database. Each CN ran once. The baseline spent 56.10 s on four catalog replays. The optimized run resolved both timestamps via snapshot reads in 4.08 ms and 0.12 ms and verified all six output rows. This benchmark used the QA hotfix-based image. The 4.2-dev counterpart is #32925.

Local validation for this follow-up on Go 1.27.1 / macOS arm64:

  • Full tests for objectio, objectio/ioutil, tae/logtail, disttae/logtailreplay, and vm/engine, including main's bounded replay and spill tests.
  • Targeted frontend, vm/engine/test, and tests/dml regressions for DATA BRANCH, checkpoint range and metadata reuse, PK filtering, stale-read recovery, and branch operand identity.
  • The checkpoint-catalog SQL regression checks rename, repeated merge, conflict preservation after a catalog rewrite, inserts, and deletes.

Repository-wide CI runs on this PR.

@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 added kind/bug Something isn't working kind/enhancement kind/test-ci labels Nov 13, 2026
@mergify

mergify Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

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

@matrix-meow matrix-meow added the size/L Denotes a PR that changes [500,999] lines label Nov 13, 2026
gouhongshen added a commit that referenced this pull request Nov 13, 2026
…g reads (#32704)

## What type of PR is this?

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

## Which issue(s) this PR fixes:

Fixes #32708.

Sibling ports: #32705 (`4.2-dev`) and #32707 (`main`).

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

A production merge of a six-row table, with one customer-name update,
spent 29.859 seconds of its 29.942-second execution resolving a table's
creation commit timestamp. That lookup emitted 1,861,139 historical
`mo_catalog.mo_tables` data/tombstone versions. The business table's
size was not the source of that scan.

The frontend already builds a composite-PK predicate for the exact
account/database/table. After catalog history leaves the CN
partition-state window, checkpoint replay and range-based visible-state
reconstruction lost that predicate. Consequently, resolving the branch
ancestor read unrelated catalog history before doing the merge.

This change:

- Preserves the existing PK predicate in both historical-read
constructors and applies it while selecting checkpoint objects.
- Marks the `mo_tables` composite key as its object sort key. The shared
object-pruning helper only compares a sort-key zonemap with a PK
predicate when that relationship is explicitly known. Unknown zonemaps,
cluster-by keys and rowid-sorted tombstones remain eligible for reading.
- Applies PK-column block pruning to persisted appendable objects as
well. Tombstone block pruning uses the tombstone PK sequence number
rather than the data table's PK sequence number. Existing
commit-timestamp pruning restrictions remain in place.

No storage format, schema, merge conflict policy, transaction/rollback
policy, or CLI timeout is changed. Callers without a PK predicate retain
the unfiltered behavior. Recovery of an application-level change record
already stuck in `committing` is outside this engine fix.

### Reproduction and correctness evidence

- Added a real TAE/disttae checkpoint integration test with unrelated
catalog insertions and deletions, then GC of the CN partition-state
history. With the production/base implementation
(`10d204b8763f19b2b37ba2147d1d4c1a7828d6d4`, substituted using Go's
overlay), the test fails under **both** checkpoint replay and
visible-state policies because it emits an unrelated table ID. The same
test passes with this change and verifies the exact target table ID and
original creation commit timestamp for every emitted version. Its
unfiltered control still sees the unrelated history.
- Added a SQL integration test using the repository's isolated embedded
cluster (1 LOG, 1 TN, 3 CN). After catalog checkpoint/history
truncation, it verifies every resulting row for a six-row rename,
repeated merge, conflict `SKIP`, insertion and deletion.
- Ran the existing SQL MERGE/PICK suites, including explicit transaction
commit/rollback, conflict policies and mixed DML.
- Added object-file/block tests for data, tombstones, persisted
appendable objects, and a distinct cluster-by key of the same physical
type as the PK. Matching data stays readable; only disjoint PK blocks
are skipped. Unfiltered controls and unknown-object-zonemap cases remain
readable.

### Validation

All commands were run from the worktree root with its locally built CGO
dependencies (`make cgo`), `GOWORK=off`, on macOS arm64 / Go 1.26.4:

```sh
go test -p 4 -count=1 -timeout 10m ./pkg/vm/engine/disttae/logtailreplay ./pkg/frontend/databranchutils ./pkg/vm/engine
go test -p 3 -count=1 -timeout 10m ./pkg/frontend ./pkg/vm/engine/test -run '^(Test.*DataBranch.*|Test.*PKFilter.*|Test.*ChangesHandle.*|TestFileNotFoundFallbackToSnapshotRead|TestRealStaleReadStillReturnsError|TestPackMoDatabaseCPKey|TestDatabaseCreatedTimeToCollectLowerBound|TestGetObjectsFromCheckpoint.*)$'
go test -p 4 -count=1 -timeout 7m ./pkg/tests/dml -run '^(TestDataBranchPick|TestDataBranchMerge|TestDataBranchMergeWithCheckpointCatalog)$' -v
```

The baseline reproduction intentionally fails; the corrected
implementation and the listed regression suites pass. This establishes
the lost-filter fix and the tested data-correctness boundaries.
Repository-wide tests and a production-sized historical-catalog
benchmark were not run locally; CI and deployment verification are still
required. Production data/configuration were not modified.

### Controlled local performance comparison

Compared the base production source
(`10d204b8763f19b2b37ba2147d1d4c1a7828d6d4`) and this PR
(`80708c0d8ebf4ec210596b2afa2b91e04effe51c`) on the same macOS arm64
host (10 logical CPUs, 32 GiB RAM), Go 1.26.4, `GOMAXPROCS=6`, and the
same isolated 1 LOG / 1 TN / 3 CN test-cluster configuration. Both
binaries use the same temporary Go-overlay harness; the base overlay
substitutes the two changed production Go files with their exact base
versions. Production was not used for these measurements.

For each run, the harness creates the given number of unrelated tables
in `sales`, flushes catalog data in groups of 256, drops half the
unrelated tables, and creates seven independent six-row
source/destination branch pairs. Each source has exactly one changed
row. After checkpointing and truncating only the CN `mo_tables`
partition history, the harness asserts that checkpoint recovery is
required, then measures each actual MERGE and checks all six destination
rows. Preparation, validation queries and cleanup are excluded from the
MERGE timer. Runs are serial; the larger fixture reverses the base/fixed
order. The table reports medians of rounds 1–6, with the first request
retained separately. Caches were not forcibly cleared.

| Unrelated tables | MERGE median, base → fixed | Catalog lookup
cumulative median, base → fixed | Returned catalog versions/merge, base
→ fixed |
| ---: | ---: | ---: | ---: |
| 2,048 | 45.22 → 32.70 ms (27.7% lower) | 19.94 → 4.96 ms (4.02×) |
8,236 → 2,120 |
| 8,192 | 136.75 → 33.84 ms (75.3% lower) | 110.05 → 5.09 ms (21.63×) |
98,348 → 2,120 |

Catalog lookup duration is the sum of the four
`DataBranch-TableCTS-CollectChanges-Done` calls within each MERGE.
Returned catalog versions count data plus tombstone rows delivered by
those calls; this is **not** physical I/O bytes. All measured MERGEs
passed the same complete-row correctness check.

The long-database-name control (`branch_catalog_performance`, 2,048
unrelated tables) did **not** show a speedup: MERGE medians were 44.16 →
47.15 ms; catalog lookup medians were 21.18 → 23.29 ms. The fixture's
full composite key is 46 bytes; existing varlen zonemaps keep only 30
bytes per boundary. An executable key-range probe confirms that
unrelated and target keys overlap in this control, while the 25-byte
`sales` key remains distinguishable. Preserving the PK filter cannot
guarantee a selective zonemap in every naming/data layout. All control
runs still returned the correct business rows.

The base 8,192-table run completed all seven measured MERGEs and all
complete-row validations, but its later single-transaction `DROP
DATABASE sales` cleanup failed with `row level lock is too large that
need upgrade to table level lock` (20707). That whole test process
exited 1; it is not reported as a passing test. The timing/result
markers precede this cleanup failure. The other five test processes
passed. This baseline-only post-measurement failure is preserved in the
report and raw logs; it was not retried or hidden.

These are local workload comparisons, not a production-latency SLA. They
do not justify comparing the incident's approximately 30 seconds
directly with the local approximately 30 milliseconds. Production has a
larger history, object-storage/network costs and concurrent load. The
harness, all samples and exact commands are retained in the local
investigation artifacts; no timing thresholds or CI gates were added.

### Review follow-up: preserve replacement-chain metadata

Addressed the P2 finding in [the
review](#32704 (comment)).
A historical predecessor may have an unknown or broad PK zonemap even
when its terminal TN replacement is disjoint from the requested PK.
Removing that replacement from the create-time index makes a complete
chain look like missing metadata.

The range-recovery path now retains all temporally eligible TN
replacement metadata, follows deleted intermediate objects, and applies
PK pruning only to terminal payload candidates (including orphan live
objects). A genuinely missing successor or a missing matching object
file still fails with `ErrFileNotFound`.

The new `TestHistoricalChangesPKFilterReplacementChain` exercises the
public range-recovery constructor and real object-file reads together.
Four valid unknown/coarse appendable/CN predecessor cases reproduce the
error on `80708c0d8ebf4ec210596b2afa2b91e04effe51c` only with the filter
enabled; they pass after the follow-up fix and preserve the target row's
original commit timestamp. Controls verify that missing successor
metadata, a missing matching successor file, and a disjoint intermediate
without its next successor remain errors. Every scenario also runs
without the filter.

Revalidated the full directly affected `logtailreplay`,
`databranchutils` and engine packages; the frontend/engine
branch-history selection; and the SQL MERGE/PICK suites including the
checkpoint-catalog merge test. The previously reported larger
performance comparisons remain pinned to
`80708c0d8ebf4ec210596b2afa2b91e04effe51c`; they were not rerun for this
follow-up. Checkpoint object pruning is unchanged.
Protect hook installation and reset against background internal SQL reads reported by the CI race detector. Snapshot callbacks under the mutex and release it before nested SQL execution. Preserve all existing assertions and CI checks.
@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 →

@gouhongshen gouhongshen changed the title fix(branch): preserve PK pruning in historical catalog reads fix(branch): prune historical catalog replay and prefer snapshot reads Nov 19, 2026
Run global arena setup and cleanup outside the synctest bubble. Small off-heap buffers still exercise large-tier reuse and eviction without registering a virtual timer with the shared Linux allocator.
Stop the read window when a block or its metadata cannot be read. Drain submitted jobs and preserve the original error so snapshot fallback can still use the caller context.
…g-merge-opt-main

# Conflicts:
#	pkg/objectio/arena_pool_test.go
@mergify

mergify Bot commented Nov 20, 2026

Copy link
Copy Markdown
Contributor

✅ Merged into main as c33ce3f at 05:15 UTC

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

So far

  • ✅ Entered the queue Fri 20 Nov, 05:15 · rule main · triggered by rule Automatic queue on approval for main
  • ✅ Checks skipped · PR is already up-to-date
  • ✅ Merged 05:15 · c33ce3f · 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

This branch was previously deployed

1 inactive deployment
ci — 0dbf5f3e Deployed Nov 20, 2026 by gouhongshen
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind/bug Something isn't working kind/enhancement kind/test-ci size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: DATA BRANCH MERGE times out scanning unrelated catalog history after checkpoint recovery

3 participants