Repository navigation
fix: data branch diff returns wrong results after GC+restart - #24010
Merged
mergify[bot] merged 24 commits intoMar 31, 2026
Merged
mergify[bot] merged 24 commits into
mergify[bot] merged 24 commits into
Conversation
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]>
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]>
Co-authored-by: Copilot <[email protected]>
XuPeng-SH
approved these changes
Mar 31, 2026
aunjgr
approved these changes
Mar 31, 2026
ghost
approved these changes
Mar 31, 2026
Contributor
Merge Queue Status
This pull request spent 58 minutes 17 seconds in the queue, including 58 minutes 1 second running CI. Required conditions to merge
|
This was referenced Aug 21, 2026
This branch was previously deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What type of PR is this?
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 summaryreturns incorrect results:INSERTEDinstead ofUPDATEDDELETEDinstead ofUPDATEDRoot Causes
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.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.
SnapshotStateRange stale read too conservative: The stale-read guard rejects valid post-restart partition states that cover the needed objects.
Snapshot scan missing in-memory rows:
ScanSnapshotWithCurrentRangesusedRemoteDataSource(disk-only) in serial path, missing unflushed rows.Fixes
resolveVisibleObjectsByDeleteChainto find TN objects whose appendable predecessors were GC'dNewChangesHandlerWithPartitionStateRange(log instead of error)Tests
diff_9.sql: 56/56 PASSdiff_10.sql(new): 75/75 PASS — snapshot-based diff after table dropUPDATED 275361across 4 consecutive GC+restart cyclesCleanup
swapCurrentHandleToVisibleState,swapCurrentHandleToCheckpointRange, diagnostic helpersreadSnapshotWithSourceto deduplicate snapshot scan read loop