Skip to content

fix: data branch diff returns wrong results after GC+restart - #24010

Merged
mergify[bot] merged 24 commits into
matrixorigin:mainfrom
gouhongshen:fix/branch-diff-snapshot-range-zm
Mar 31, 2026
Merged

mergify[bot] merged 24 commits into
matrixorigin:mainfrom
gouhongshen:fix/branch-diff-snapshot-range-zm

Conversation

@gouhongshen

@gouhongshen gouhongshen commented Mar 29, 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:

issue #23820

What this PR does / why we need it:

After flush + global checkpoint + GC + restart, data branch diff t1 against t0 output summary returns incorrect results:

  • Shows INSERTED instead of UPDATED
  • Or shows DELETED instead of UPDATED
  • Takes 25s instead of ~1s

Root Causes

  1. VisibleStateChangesHandle (Path 3) silently swallows GC errors: After GC, getRelationAt() fails with "can not find table by id" but the code treats it as "table didn't exist", returning empty "before" rows → all rows classified as INSERT.

  2. TN merge objects unreachable after GC: When appendable predecessors are GC'd, delete-chain has no starting point → TN data objects not read → rows classified as DELETED.

  3. SnapshotStateRange stale read too conservative: The stale-read guard rejects valid post-restart partition states that cover the needed objects.

  4. Snapshot scan missing in-memory rows: ScanSnapshotWithCurrentRanges used RemoteDataSource (disk-only) in serial path, missing unflushed rows.

Fixes

  • Remove VisibleStateChangesHandle (Path 3) entirely — it had a known GC bug and is now unnecessary
  • Add orphan sweep in resolveVisibleObjectsByDeleteChain to find TN objects whose appendable predecessors were GC'd
  • Relax stale-read check in NewChangesHandlerWithPartitionStateRange (log instead of error)
  • Use LocalDataSource in serial snapshot scan path to include in-memory rows
  • Fix early-return in delete-chain resolution that skipped orphan sweep

Tests

  • BVT diff_9.sql: 56/56 PASS
  • BVT diff_10.sql (new): 75/75 PASS — snapshot-based diff after table drop
  • Manual: verified correct UPDATED 275361 across 4 consecutive GC+restart cycles

Cleanup

  • Removed dead code: swapCurrentHandleToVisibleState, swapCurrentHandleToCheckpointRange, diagnostic helpers
  • Extracted readSnapshotWithSource to deduplicate snapshot scan read loop
  • Upgraded 25 rare diagnostic logs from Debug to Info for production visibility
  • Removed 6 verbose diagnostic functions (~320 lines)

Copilot AI review requested due to automatic review settings March 29, 2026 05:53
@gouhongshen
gouhongshen requested a review from aunjgr as a code owner March 29, 2026 05:53
@gouhongshen
gouhongshen requested a review from a user March 29, 2026 05:53
@matrix-meow matrix-meow added the size/XXL Denotes a PR that changes 2000+ lines label Mar 29, 2026
@mergify mergify Bot added the kind/bug Something isn't working label Mar 29, 2026
gouhongshen and others added 23 commits March 29, 2026 14:25
Bug fixes:
- Fix getTableCreationCommitTSByCollectChanges: use positional column
  fallback when ChangeHandler.Next() returns empty Attrs
- Fix change_handle: bound currentPSTo to maxCkpTS in checkpoint range
- Fix hashdiff dedup: handle single-tombstone keys for real PK tables
  and enable dedup for fake PK tables
- Fix shouldUseLCAReaderFallback: add ErrParseError to trigger
  reader-based fallback when catalog name lookup fails at old snapshots
- Use getTableCreationCommitTSByID as primary method to avoid
  checkpoint fallback returning constant commit TS

Tests:
- Add diff_9.sql BVT covering flush+checkpoint+GC scenarios

Co-authored-by: Copilot <[email protected]>
When handleDelsOnLCA uses the reader fallback path, the result includes
all columns (including __cpkey__/__mo_fake_pk_col). The loop fills all
dBat vectors, then the pkKind != normalKind block fills Vecs[endIdx]
again from the tombstone batch, doubling the PK vector length. This
causes an index-out-of-range panic in findDeleteAndUpdateBat where
seen[] is sized by RowCount() but PopByVectorsStream iterates by the
(2x) vector length.

Fix: skip the extra UnionOne when the loop already covered endIdx
(len(cols)-2 >= endIdx). Add diagnostic logging for future debugging.

Co-authored-by: Copilot <[email protected]>
Bug #8: VisibleState checkpoint-range recovery picks up CN-created
objects with constant commit_ts, producing phantom INSERTs. Fix:
skip checkpoint-range fallback for VisibleState policy in both
getNextChangeHandle and bufferCurrentRange.

Bug #9: After GC+restart, table creation CTS becomes unreliable
(synthetic = snapshot end from VisibleState). Fix: introduce
lcaFullStateFallback mode that compares full visible state of both
tables without relying on CTS-based incremental ranges.

lcaFullStateFallback handles:
- Same PK + different value → UPDATE (target side)
- PK only in target → INSERT (target side)
- PK only in base → DELETE (target side)
- Skip tombstone processing (compacted data is already correct)

CTS resolution now has 3 tiers:
1. getTableCreationCommitTSByID (snapshot scan, real CTS)
2. CollectChanges without VisibleState (real CTS from logtail)
3. CollectChanges with VisibleState (synthetic CTS, last resort)

Tier 2 ensures fresh tables created after restart get real CTS
and avoid lcaFullStateFallback, which is critical for fake-PK
tables where UPDATE detection requires incremental change data.

Co-authored-by: Copilot <[email protected]>
…pshot scan

- Swap CTS resolution order: CollectChanges (primary) → Reader (fallback)
- Replace readutil.NewReader with SimpleReaderWithDataSource + WithColumns
- Remove snapshot partition state (getOrCreateSnapPartBy) from Reader path
  → Use RemoteDataSource with CollectTombstones instead
- Strip EmptyBlockInfo marker before RemoteDataSource to fix 'invalid file path'
- Clean up CTS resolution: flatten closures, extract locateColumnsInChangeBatch
- Remove unused: ScanWithCurrentPartitionState, newSnapshotScanDataSource,
  lcaFullStateFallback branches
- Net reduction: ~200 lines

Co-authored-by: Copilot <[email protected]>
ScanSnapshotWithCurrentRanges previously used RemoteDataSource which
only reads persisted S3 blocks.  Newly created table catalog entries
still in partition-state memory were invisible, causing
getTableCreationCommitTSByID (ReaderFallback) to fail with
'cannot find table ... commit ts at snapshot ...'

Serial path now uses LocalDataSource which reads both in-memory
partition-state rows and persisted blocks.  Parallel path keeps
RemoteDataSource for disk-only reads (large tables are typically
flushed already).

Co-authored-by: Copilot <[email protected]>
…ding aobj

The previous fix unconditionally added alive TN merge objects to the aobj
list in getObjectEntries(). This caused double-counting when
enableDeleteChainResolve was false (Path 1 / NewChangesHandler), because
both the appendable predecessor and its TN replacement were read without
deduplication.

Move the orphan detection into resolveVisibleObjectsByDeleteChain: after
the main chain-walking loop, sweep tnByCreateTS for TN objects never
reached by any chain (predecessors GC'd) and add them to the resolved
set. The visited map prevents duplicates.

Co-authored-by: Copilot <[email protected]>
Add diff_10.sql testing data branch diff via snapshot references after
the base and target tables have been dropped. Covers 4 cases:
- Case 1: PK table with updates
- Case 2: PK table with inserts and deletes
- Case 3: PK table with mixed insert + update + delete
- Case 4: Non-PK table with updates

Co-authored-by: Copilot <[email protected]>
The full-table-diff fallback (read table at start.Prev() and end, then
compute set difference) had a known bug where getRelationAt silently
returned nil after GC, causing all rows to appear as INSERTs. Now that
SnapshotStateRange (Path 2a) handles post-GC scenarios correctly, this
fallback is no longer needed.

- Delete change_handle_visible_state.go and its tests
- Remove swapCurrentHandleToVisibleState method
- Let SnapshotStateRange errors propagate directly

Co-authored-by: Copilot <[email protected]>
- Remove logSnapshotCheckpointPlan, logSnapshotPartitionSummary,
  collectVisibleObjectSamples from db.go
- Remove shouldTraceCatalogSnapshotSQL and related tracing from util.go
- Remove CKPReader-MoDatabase-ObjectEntries tracing wrapper from ckp_reader.go
- Downgrade per-item/per-table Info logs to Debug across data_branch,
  change_handle, snapshot_scan, and engine files
- Fix fmt.Sprintf table-id patterns to use zap.Uint64
- Fix copyright year 2026 → 2025 in snapshot_scan.go

Co-authored-by: Copilot <[email protected]>
- Remove unused swapCurrentHandleToCheckpointRange function
- Extract readSnapshotWithSource to deduplicate scanSnapshotShard
  and scanSnapshotShardLocal (shared reader creation + read loop)
- Rename nextWithVisibleState → nextWithSnapshotRecovery
- Update stale comments referencing removed VisibleState fallback

Co-authored-by: Copilot <[email protected]>
Logs that fire once or a few times per diff operation and help
post-mortem debugging are upgraded to Info so they remain visible
in production. Per-batch/per-object logs stay at Debug.

Also removes logSnapshotCheckpointSelection and reverts redundant
execReadSql wrapper.

Co-authored-by: Copilot <[email protected]>
- copyloopvar: remove redundant shard := shard (Go 1.22+)
- ineffassign: declare minTS/maxTS without unused initial values
- staticcheck SA6001: inline string() into map access for efficiency
- TestCollectChangesRange: remove Debug log with GetTableID call that
  the mock didn't expect

Co-authored-by: Copilot <[email protected]>
- TestHashDiff_NoLCAWithStubHandles: protect shared 'got' slice with
  mutex since emit callback is invoked from ForEachShardParallel
- TestCollectTableStats_ShuffleRanges_DynamicCreation: release the
  global ants pool created by snapshot_scan tests so leaktest does
  not detect lingering purge/ticktock goroutines

Co-authored-by: Copilot <[email protected]>
Add comprehensive tests covering pure/near-pure functions in
change_handle.go to raise PR coverage from 62.5% to 76.5%:

- batchesShareAppendSchema, blockCommitTSOverlapsRange, calcPruneRate
- lookupDeleteChainSuccessor, classifyResolvedObjects
- resolveVisibleObjectsByDeleteChain (multiple scenarios)
- objectFileExists, classifyCheckpointObject, checkpointObjectMapToSlice
- baseHandle.Close/less, checkTS, fillInSkipTS*
- NewBaseHandlerWithObjEntries, IsEmpty/IsSmall, getObjectEntries
- shouldReadBlock (all paths including buildBlockPlan integration)
- nextPrefetchTarget, buildBlockPlan success/prune paths
- blockCommitTSOverlapsRange with real zonemap metadata

Uses in-memory FileService (MemoryFS) and ioutil.ConstructWriter to
create real object files with commit-TS columns for end-to-end
buildBlockPlan and zonemap overlap testing.

Co-authored-by: Copilot <[email protected]>
@mergify

mergify Bot commented Mar 31, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-03-31 07:33 UTC · Rule: main
  • ✅ Checks passed · in-place
  • ✅ Merged — 2026-03-31 08:32 UTC · at 4e1b030e5b6319ad0cea0873f091ff72e5a83994

This pull request spent 58 minutes 17 seconds in the queue, including 58 minutes 1 second running CI.

Required conditions to merge
  • #approved-reviews-by >= 1 [🛡 GitHub branch protection]
  • #changes-requested-reviews-by = 0 [🛡 GitHub branch protection]
  • #review-threads-unresolved = 0 [🛡 GitHub branch protection]
  • branch-protection-review-decision = APPROVED [🛡 GitHub branch protection]
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Compose CI / multi cn e2e bvt test docker compose(PESSIMISTIC)
    • check-neutral = Matrixone Compose CI / multi cn e2e bvt test docker compose(PESSIMISTIC)
    • check-skipped = Matrixone Compose CI / multi cn e2e bvt test docker compose(PESSIMISTIC)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Standlone CI / Multi-CN e2e BVT Test on Linux/x64(LAUNCH, PROXY)
    • check-neutral = Matrixone Standlone CI / Multi-CN e2e BVT Test on Linux/x64(LAUNCH, PROXY)
    • check-skipped = Matrixone Standlone CI / Multi-CN e2e BVT Test on Linux/x64(LAUNCH, PROXY)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
    • check-neutral = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
    • check-skipped = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone CI / SCA Test on Ubuntu/x86
    • check-neutral = Matrixone CI / SCA Test on Ubuntu/x86
    • check-skipped = Matrixone CI / SCA Test on Ubuntu/x86
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone CI / UT Test on Ubuntu/x86
    • check-neutral = Matrixone CI / UT Test on Ubuntu/x86
    • check-skipped = Matrixone CI / UT Test on Ubuntu/x86
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Compose CI / multi cn e2e bvt test docker compose(Optimistic/PUSH)
    • check-neutral = Matrixone Compose CI / multi cn e2e bvt test docker compose(Optimistic/PUSH)
    • check-skipped = Matrixone Compose CI / multi cn e2e bvt test docker compose(Optimistic/PUSH)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH,Optimistic)
    • check-neutral = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH,Optimistic)
    • check-skipped = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH,Optimistic)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Upgrade CI / Compatibility Test With Target on Linux/x64(LAUNCH)
    • check-neutral = Matrixone Upgrade CI / Compatibility Test With Target on Linux/x64(LAUNCH)
    • check-skipped = Matrixone Upgrade CI / Compatibility Test With Target on Linux/x64(LAUNCH)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Utils CI / Coverage
    • check-neutral = Matrixone Utils CI / Coverage
    • check-skipped = Matrixone Utils CI / Coverage

This branch was previously deployed

1 inactive deployment
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/refactor Code refactor size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants