Skip to content

test(embed): cover data branch DIFF across GC, checkpoint, and restart (#27465) - #30410

Merged
mergify[bot] merged 5 commits into
matrixorigin:mainfrom
gouhongshen:agent/issue-27465-bc3435df
Oct 17, 2026
Merged

mergify[bot] merged 5 commits into
matrixorigin:mainfrom
gouhongshen:agent/issue-27465-bc3435df

Conversation

@gouhongshen

@gouhongshen gouhongshen commented Oct 16, 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 #27465 (regression coverage; the production fix landed in #29867)

What this PR does / why we need it:

Background and root cause

Issue #27465 reported that DATA BRANCH DIFF fails after storage GC and a
service restart with HY000 / 20101: internal error: cannot find database <id> (<db>) created_time at snapshot <ts>, even though both tables and the
branch protection record remained present.

Root cause: catalog tables such as mo_database are appendable. Before
#29867, handleDataObjectEntry in
pkg/vm/engine/disttae/logtailreplay/partition_state.go skipped any object
whose size was zero or which was appendable with an empty DeleteTime.
Checkpoint replay therefore dropped durable appendable catalog objects, the
post-restart mo_database partition state was empty, and
getDatabaseCreatedTimeLowerBoundByPK (pkg/frontend/data_branch.go) could
not find the database creation row at the branch fork snapshot, raising
20101. Commit 79d746a998 (PR #29867, already in main) narrowed the guard
to Size() == 0 and registers durable checkpoint creations.

Attribution was re-proven on this branch: reverting only that guard
reproduces the exact 20101 signature end to end, and the fix commit's own
unit test (TestCheckpointDurableAppendableObjectReplay/data) goes red
(expected: 1, actual: 0); both return to green after restore.

Exact changes (test-only, 2 files)

  • pkg/embed/branch_checkpoint_restart_test.go (new): regression test
    TestDataBranchDiffAcrossCheckpointGCAndRestart with three scenarios,
    each on its own dedicated embedded cluster so every named scenario
    also runs standalone under
    -run TestDataBranchDiffAcrossCheckpointGCAndRestart/<name>:
    • gc_checkpoint_restart replays the issue's exact one-edge lifecycle
      (root/leaf, 4 DIFF rows) with accelerated TN GC knobs (2s scans, 1ms
      TTLs, 2s incremental checkpoints — the same pattern as
      pkg/vm/engine/tae/testutils/config), then a reclamation probe:
      flush probe table, capture its objects with metadata_scan, stat them
      in the TN s3 storage root, drop the table, and alternately issue
      global checkpoints and re-check the files (with a small commit
      heartbeat) until the disk cleaner physically deletes them — bounded by
      a 6-minute deadline sized to this harness's roughly per-minute
      forced-checkpoint cadence. The scenario then survives two full
      restarts
      , asserting exact DIFF rows, output count, current rows,
      and the branch protection record after each.
    • checkpoint_restart (checkpoint-only trigger recorded on the issue on
      2026-10-09) and flush_only_restart (the published control) run on
      their own clusters with production 1h GC TTLs, so background
      reclamation cannot reach them; they are genuinely GC-free controls,
      each surviving one restart with the same assertions.
    • All setup/lifecycle/restart/assertion work is subtest-local; failures
      attach to the owning scenario, and no step depends on another
      scenario's output.
  • pkg/embed/upgrade_recovery_test.go: behavior-preserving extraction of
    newRecoveryClusterStarterWithBudget from newRecoveryClusterStarter
    (the existing 5-minute workload budget remains as a wrapper); each
    scenario's cluster uses a 15-minute budget so the reclaim wait fits the
    harness cadence. All SQL runs on the starter's per-generation context,
    refreshed after every restart, and each SQL client is closed via its own
    t.Cleanup.

Issue-to-test proof

Evidence Result
Final fixture, fixed tree --- PASS: TestDataBranchDiffAcrossCheckpointGCAndRestart (213.52s); gc 190.55s (probe reclaimed after 3 checkpoint rounds in 2m54.57s, two restarts asserted), checkpoint 11.75s, flush_only 11.22s
Same fixture, fix guard reverted FAIL 213.91s; checkpoint_restart failed post-restart with Error 20101 (HY000): internal error: cannot find database 272566 (db_checkpoint_restart) created_time at snapshot 1792148774686795999-0 on data branch diff db_checkpoint_restart.br against db_checkpoint_restart.base; gc and flush_only passed — pinning the failure to checkpoint replay rather than the GC leg
GC isolation of controls In the green log every GC-ExecDelete / DELETE-SNAPSHOT-FILES event occurs inside the gc scenario's window; zero deletion events occur inside either control window
Standalone subtests Anchored -run 'TestDataBranchDiffAcrossCheckpointGCAndRestart/^checkpoint_restart$' executes only that scenario, PASS 11.16s
Probe non-vacuity (control run) With the millisecond GCTTL knob removed the probe fails loudly at its deadline: zero ExecDelete lines and GC scan/GC watermarks stuck at nil
Fix commit unit tests TestCheckpointDurableAppendableObjectReplay and TestTombstoneReplayReclamationBoundaries PASS on the fixed tree

Test commands

go test ./pkg/embed/ -run TestDataBranchDiffAcrossCheckpointGCAndRestart -v -count=1 -timeout 25m
go test ./pkg/embed/ -run TestRecoveryClusterStartupBudget -v -count=1
go test ./pkg/vm/engine/disttae/logtailreplay/ -count=1
go vet ./pkg/embed/ && gofmt -l pkg/embed/

Residual risks

  • In this harness the quiet embedded cluster completes each forced global
    checkpoint on a roughly per-minute boundary (observed Force-GCKP-End
    costs of 54–58s with 54–59 ForceICKP no-progress retries), so the GC
    scenario takes about three minutes. The probe deadline and workload
    budget cover the slowest observed cadence with margin; the test asserts
    behavior only, never wall time.
  • With the fix guard reverted, the gc_checkpoint_restart scenario still
    passed (its many forced checkpoints keep the catalog creation row visible
    through another replay path); the checkpoint-only control is the
    sensitive detector for this regression, and the PR documents that split
    explicitly.
  • The regression runs against the embedded harness; equivalence with a
    real multi-process mo-service GC+restart remains asserted only through
    the same harness, matching the issue's own investigation trail.

Follow-up: SCA conformance fix (CI sqlclosecheck)

The SCA Test on Linux/arm64 job on the first head failed with two
sqlclosecheck findings in branch_checkpoint_restart_test.go (lines 354
and 482: Close should use defer), i.e. the failure was caused by this
PR's test code. Fixed by wrapping each metadata_scan / DIFF query in a
self-invoking closure that defers rows.Close() and returns the collected
rows; behavior and assertions are unchanged, including the explicit
rows.Err() checks.

Validation of the fix before pushing:

golangci-lint run -c .golangci.yml ./pkg/embed/...   # 0 issues
gofmt -l pkg/embed/                                   # clean
go test ./pkg/embed/ -run TestDataBranchDiffAcrossCheckpointGCAndRestart -v -count=1 -timeout 25m
# PASS 230.81s: gc_checkpoint_restart 195.33s (probe objects reclaimed
# after 3 checkpoint rounds in 2m2.125s), checkpoint_restart 16.53s,
# flush_only_restart 18.90s

The fix commit is rebased on the branch head that merged main, keeping
the PR's merge-history convention intact.

Related to #27465

Follow-up: heartbeat teardown fix (mo-bot review)

The mo-bot review of the SCA-conformance head requested changes for one
P2 finding: the GC probe's commit heartbeat released its goroutine only
via stopCh, so a DDL or INSERT blocked in ExecContext outlived the
probe's deferred join until the scenario context was cancelled (worst
case: the rest of the 15-minute workload budget), and the setup DDL loop
reported stop-initiated cancellation as a failure while the insert loop
treated it as a clean exit.

Fixed: the heartbeat now runs on its own context derived from the
caller; stop() closes stopCh and cancels that context so an
in-flight statement is released before the caller joins on done, and
both the setup DDL and the insert loop treat an error after stop as a
clean exit. Behavior of the probe itself is unchanged.

Validation of the fix before pushing:

gofmt -l pkg/embed/                                   # clean
go vet ./pkg/embed/                                   # pass
golangci-lint run -c .golangci.yml ./pkg/embed/...   # 0 issues
go test ./pkg/embed/ -run TestDataBranchDiffAcrossCheckpointGCAndRestart -v -count=1 -timeout 25m
# PASS 205.31s: gc_checkpoint_restart 188.76s (heartbeats exercised
# continuously across the whole reclamation window; stop+join returned
# cleanly), checkpoint_restart 10.03s, flush_only_restart 6.52s

Related to #27465

matrixorigin#27465)

Issue matrixorigin#27465 (DATA BRANCH DIFF failing after GC and restart with error
20101 "cannot find database ... created_time at snapshot") was fixed in
79d746a, which narrowed the checkpoint-replay guard for durable
appendable catalog objects. Add the executable regression guarding the
full lifecycle:

- gc_checkpoint_restart replays the issue's one-edge lifecycle on a
  private embedded cluster with accelerated TN GC knobs, proves with a
  reclamation probe that the disk cleaner physically deleted flushed
  probe objects before the restart, and survives two full restarts with
  exact DIFF rows, count, current rows, and branch protection asserted
  after each.
- checkpoint_restart and flush_only_restart are the published controls;
  each runs on its own cluster with production GC TTLs so background
  reclamation cannot reach it.
- Every scenario is subtest-scoped and runs standalone; each uses the
  recovery starter's per-generation context with a 15-minute workload
  budget (newRecoveryClusterStarterWithBudget, extracted in
  upgrade_recovery_test.go with the 5-minute behavior preserved).

Reverting the fix's appendable guard turns the checkpoint scenario red
with the exact 20101 error; restoring it returns all scenarios to
green.

Related to matrixorigin#27465
…rixorigin#27465)

The SCA job (sqlclosecheck in static-check-analysis) flagged the two
sites that queried and closed *sql.Rows in the same function body: a
require failure inside the scan loop would skip the close. Wrap each
query-and-scan in a closure whose rows are closed via defer, keeping
the explicit rows.Err() assertion. No behavior change; the full
regression passes unchanged.

Related to matrixorigin#27465
@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 →

@XuPeng-SH

XuPeng-SH commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: a7882344dde94ee4f054d284cb6519c84e5e02fd

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: a7882344dde94ee4f054d284cb6519c84e5e02fd

Assessment: request_changes

Reviewed the complete two-file delta. The isolated regression scenarios and reuse of the existing restart-budget helper are reasonable. One confirmed heartbeat teardown defect remains; production SQL paths are unchanged.

Model: gpt-6-astra / xhigh

Session: 01a13dcf-1586-7a01-9000-d45e20995cf8 · slot 1 · generation 1

  • P2 pkg/embed/branch_checkpoint_restart_test.go:463: The reclamation probe returns or fails while a heartbeat DDL or INSERT is blocked in ExecContext.
    Impact: stop() only closes stopCh, leaving the SQL request running. The deferred receive at line 373 then blocks before outer context cancellation and cluster cleanup can execute, potentially retaining the cluster and admission lease until the remaining 15-minute workload budget expires. Give the heartbeat its own cancellable context and cancel it before joining; handle intentional cancellation consistently during both initialization and inserts.
    Evidence: A race-enabled diagnostic using verbatim extracted helpers and a controlled database/sql driver reproduced this for both DDL and INSERT: stop() left the query context and worker alive; parent cancellation released them. See helper-probe.log, helper-probe-ledger.json and checks/1792170376899935029-32.json in the assigned attempt directory.

Validation:

  • Verified the frozen head and unchanged source; traced checkpoint error propagation, GC reclamation, restart generations, SQL resource cleanup and cluster admission ownership.

  • Isolation preflight passed: checks/1792170368546980255-3.json and preflight.log.

  • The standalone helper diagnostic completed with -race, exit 0. It confirmed the teardown defect and verified five-/fifteen-minute budget compatibility, generation cancellation and exhaustion behavior. Receipt and log contents were reconciled with source hashes.

  • Frozen evidence records successful Ubuntu/x86 UT and Linux/arm64 SCA. No substantive unresolved review comments were supplied. Detailed review evidence is retained in review-evidence.json.

Limitations:

  • The local diagnostic exercised extracted helpers, not a MatrixOne server. Native cluster tests were not rerun.

  • local_validation is empty; raw CI and author mutation/timing logs were unavailable. The reported 230.81-second regression runtime was not independently measured.

  • The linked issue's standalone contents were not supplied; its behavioral contract was reviewed as reproduced in the frozen PR description.

…ly (matrixorigin#27465)

mo-bot review on PR matrixorigin#30410 (XuPeng-SH) flagged that the GC probe's
commit heartbeat only closed stopCh on stop: a DDL or INSERT blocked
inside ExecContext kept the goroutine alive until the scenario context
was cancelled, so the probe's deferred join could retain the cluster and
admission lease until the 15-minute workload budget expired. The setup
DDL loop also reported stop-initiated cancellation as a heartbeat
failure, unlike the insert loop.

Give the heartbeat its own context derived from the caller's: stop()
closes stopCh and cancels it, releasing any in-flight statement before
the caller joins on done. Both the setup DDL and the insert loop now
treat an error after stop as a clean exit.

Related to matrixorigin#27465
@gouhongshen

Copy link
Copy Markdown
Contributor Author

Addressed the mo-bot P2 finding (heartbeat teardown) in 3365813223.

Valid, fixed. Reading startCommitHeartbeat confirmed the diagnosis: stop() closed only stopCh while every ExecContext ran on the shared scenario context, so a DDL/INSERT blocked in the driver kept the goroutine alive past the probe's deferred join until the scenario context was cancelled — and the setup DDL loop reported stop-initiated cancellation as a heartbeat failure, unlike the insert loop.

The heartbeat now runs on its own context derived from the caller's (hbCtx). stop() closes stopCh and cancels hbCtx, so an in-flight statement is released immediately and the join on done cannot outlive the stop. Both the setup DDL and the insert loop now treat an error after stop as a clean exit, making cancellation handling consistent across initialization and inserts.

Verification:

  • gofmt -l pkg/embed/ clean; go vet ./pkg/embed/ pass; golangci-lint run -c .golangci.yml ./pkg/embed/... — 0 issues
  • Full regression go test ./pkg/embed/ -run TestDataBranchDiffAcrossCheckpointGCAndRestart -v -count=1 -timeout 25m: PASS 205.31s — gc_checkpoint_restart 188.76s (heartbeat inserts run on a 50ms ticker across the entire reclamation window, so the stop-while-in-flight path is exercised on every run; the deferred join returned nil), checkpoint_restart 10.03s, flush_only_restart 6.52s

Related to #27465

@gouhongshen
gouhongshen requested a review from XuPeng-SH October 17, 2026 02:12

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

Reviewed exact head 3365813223fc9a938a497fe2bf694db9d48a07bb against 6b081a1fcfe60150a3bf61566352b58ed97e2f5c, including both changed files, issue #27465, the previous review, and the heartbeat fix. Test-only delta: +546/-1; production and separate documentation delta: zero.

No blocking finding. The three private clusters separate accelerated GC from checkpoint-only/flush-only controls. Public SQL drives actual flush/checkpoint/DIFF; physical deletion of a previously observed probe object prevents a vacuous “GC RPC returned OK” pass. Exact DIFF rows/count and protection metadata are checked before and after full restarts. The existing generation/budget owner is reused; no production execution path changes.

Independent validation on Go 1.27.1/darwin-arm64 with matching native build:

  • Unmodified full scenario passed: 203.03s total test time (GC 187.58s, checkpoint 9.00s, flush-only 6.45s). A separate correctly anchored checkpoint/flush-only run passed in 15.12s.
  • Reinstating only the old handleDataObjectEntry appendable-object guard made checkpoint/restart fail with the original 20101: cannot find database ... created_time at snapshot error; flush-only still passed. Source restored byte-for-byte afterwards. This proves the sensitive regression rather than just accepting another green test.
  • The exact heartbeat helper, extracted verbatim into a controlled database/sql driver diagnostic, passed -race: stop during first DDL, second DDL and INSERT cancels the in-flight context and joins without parent cancellation; a genuine SQL failure still propagates. This closes the previous review finding. It is a helper diagnostic, not a full-server race run.
  • Reused exact-head CI run 38994002471: SCA passes; retained UT artifacts record all three scenarios passing under the embedded race stage (241.98s total, GC 209.77s).

Cost is explicit: this adds roughly 3–4 minutes of integration coverage, mainly GC, plus bounded heartbeat writes; it adds no production/TP work. GC coverage and the short checkpoint regression test different lifecycle guarantees, so the heavier case has independent value. The original defect mutation does not make the GC case red; the checkpoint case is the sensitive detector.

Evidence limits: local GC logged transient sync-table-id missing-checkpoint-object retries after GC merge deletion, then recovered and completed; no causal production regression is attributed to this test PR. The initial full-run log was accidentally overwritten during a later control run, but its terminal JSON receipt was preserved; separate focused/control/mutation logs and the independent CI artifact are retained. This does not claim multi-process recovery equivalence.

@mergify mergify Bot added the queued label Oct 17, 2026
@mergify

mergify Bot commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-10-17 05:11 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • ✅ Checks passed · in-place
  • ✅ Merged — 2026-10-17 08:42 UTC · at d9cf2dd4e2b92e2193bb390115be624b76099764 · squash

This pull request spent 3 hours 31 minutes 20 seconds in the queue, including 53 minutes 17 seconds running CI.

Required conditions to merge

Copy link
Copy Markdown
Contributor

本轮实际执行验证(2026-10-17,main d9cf2dd4e2b92e2193bb390115be624b76099764,Linux/amd64、Go 1.27.1、匹配 make cgo 产物):

mo-cgo-test -p 2 -count=1 -tags matrixone_test -json -timeout=25m -run '^(TestDataBranchDiffAcrossCheckpointGCAndRestart|TestRecoveryClusterStartupBudget)$' ./pkg/embed 返回 PASS,生命周期根测试 219.80s:

  • gc_checkpoint_restart:200.60s,通过原 issue 的一边 branch SQL、完整 DIFF 行和 OUTPUT COUNT、当前表数据及 branch protection 检查;探针真实对象文件在 70 轮 checkpoint 检查后、2m57.824s 内被物理回收,随后两次完整集群 Close/Start 后的断言均通过。没有将 force_gc 返回 OK 当作 GC 完成证据。
  • checkpoint_restart:11.80s,通过;flush_only_restart:7.40s,通过。两项独立集群保留生产 1h GC TTL,对照结果未依赖 GC 场景状态。
  • TestRecoveryClusterStartupBudget 全部 6 个子场景通过,另外单独 -race -count=1 执行同一根测试也通过。
  • 完整 logtailreplay 包执行通过(360 个测试/子测试通过;现有 Requires real tombstone object files 的一项跳过,不计通过)。

#30410 是回归覆盖,生产修复此前由 #29867 落地;本轮实测证明当前 main 上报告的嵌入式恢复场景通过,不将测试代码描述成新的生产修复,也不扩展为未执行的多进程/远程部署验证。按约定将 #27465 转给 @Ariznawlll 继续测试确认。

This branch was previously deployed

1 inactive deployment
ci — a3ca1c4b Deployed Oct 17, 2026 by mergify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind/test-ci size/L Denotes a PR that changes [500,999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants