Skip to content

fix: harden async lifecycle and CI test contracts - #26546

Merged
XuPeng-SH merged 20 commits into
mainfrom
fix/systematic-async-flake-contracts
Aug 2, 2026
Merged

XuPeng-SH merged 20 commits into
mainfrom
fix/systematic-async-flake-contracts

Conversation

@XuPeng-SH

@XuPeng-SH XuPeng-SH commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

What changed

This fixes the shared asynchronous lifecycle contracts behind the recent CI flakes instead of relaxing individual assertions:

  • checkpoint durable progress and GC use only finished entries; a pending GCKP intent cannot advance the GC boundary
  • checkpoint data and table-ID objects remain rollback-owned until checkpoint metadata is durable: sinkers delete partial spills on internal failure, while ICKP/GCKP delete all successfully returned objects on an explicit pre-publication failure
  • unpublished-object cleanup deduplicates names and uses the established checkpoint-GC policy of at most 1,000 objects with an independent 10-minute bound per batch; the original and cleanup errors are both preserved
  • the existing single ICKP/GCKP error event records the rollback object count and one aggregate cleanup error; there are no per-file logs or dynamic metric labels
  • a forced GCKP may summarize only the exact finished ICKP that provides its data boundary, never another GCKP's synthetic successor boundary; an in-flight force request reserves the fresh ICKP from an automatic GCKP and hands any suppressed automatic trigger back when it finishes
  • table-ID history continuity is validated fail-closed while the predecessor is streamed, so the normal GCKP path reads the predecessor index once rather than first validating and then merging it in a second scan
  • forced-checkpoint retries use bounded, context-cancelable backoff; one aggregate log records retry counts and costs, while mo_task_checkpoint_retry_total exposes three fixed reasons without dynamic label cardinality
  • embedded test clusters own cross-process port-range leases for their full lifetime, bound startup admission while bootstrapping HAKeeper, clean partial initialization, and expose one error-aware shared-cluster helper to all real consumers; direct partition/shard callers retain a non-nil cleanup owner before asserting a startup error
  • ISCP tests synchronize at actual injected executor phases and assert exact committed watermark targets; snapshot/merge/catalog-GC tests use commit/checkpoint/cleaner state rather than wall-clock ordering
  • MORPC tests distinguish probe observation from durable draining, and Darwin Unix sockets use a bounded short path with fail-fast setup
  • JSON_OVERLAPS verifies result-frame wrapper ownership and evaluates a real 8,192-row batch under normal, race, and repo-wide coverage instrumentation; the process-wide allocation-count oracle was removed because instrumentation makes it nondeterministic

No test sleeps, skips, race exclusions, reduced row/cardinality assertions, or raised allocation thresholds were introduced. Normal checkpoint publication does not perform cleanup scans or file-service calls; deduplication, batching, and rollback logs run only after an explicit pre-publication failure.

Validation

  • original PR gate: make static-check (package graph, err-check, molint, license checks, golangci-lint): 0 issues
  • full normal owning packages, including checkpoint, logtail, TAE DB, tae/db/test, metric, partition, and shard
  • full -race checkpoint/logtail/TAE DB/metric packages and full tae/db/test; partition and shard also pass their complete race suites
  • adaptive race stress after the final cleanup semantics: table-ID spill/batching 14x, ICKP/GCKP save-failure and fail-closed lifecycle 5x, and JSON wrapper/8,192-row evaluation 16x
  • final full owning-package race: objectio/ioutil, logtail, checkpoint, tae/db/test (114.604s), and SQL function (38.262s)
  • fault injection proves failed ICKP and GCKP metadata publication leave the file-service object set unchanged; three consecutive fail-closed GCKP attempts also leave it unchanged
  • a table-ID predecessor larger than the 8,192-row flush threshold proves partial spills are deleted; injected delete failure proves both the original validation error and cleanup error remain observable
  • cleanup batching/deduplication is covered at the 1,000/1 boundary, including parent-context cancellation
  • targeted checkpoint coverage passes for objectio/ioutil, logtail, and checkpoint; JSON passes with repo-wide -coverpkg=./...
  • final go build, go vet, gofmt, and full-PR git diff --check pass
  • prior full owning-package validation remains green for MORPC, embed, ISCP, TAE RPC, and engine integration; coverage did not decrease (embed 82.0% -> 82.3%, ISCP 39.6% -> 39.7%)

Fixes #26519
Fixes #26529
Fixes #26530
Fixes #26542
Fixes #26543
Fixes #26544
Fixes #26545

@qodo-code-review

qodo-code-review Bot commented Aug 1, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (1) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)

Grey Divider


Remediation recommended

1. Flock not closed on error 🐞 Bug ☼ Reliability
Description
tryAcquireClusterPortLease returns when fl.TryLock() errors without closing the *flock.Flock,
leaking a file descriptor and potentially destabilizing long-running test processes under repeated
lock/FS failures. The surrounding lease code closes the flock on other failure paths, so this is an
inconsistent cleanup path introduced by this PR.
Code

pkg/embed/cluster.go[R529-533]

+	fl := flock.New(filepath.Join(dir, fmt.Sprintf("%d.lock", base)))
+	locked, err := fl.TryLock()
+	if err != nil {
+		return nil, false, err
+	}
Evidence
The port-lease helper returns immediately on TryLock error without calling Close(), unlike other
paths in the same file that explicitly close the flock on failure.

pkg/embed/cluster.go[524-536]
pkg/embed/cluster.go[542-559]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
`tryAcquireClusterPortLease` returns on `fl.TryLock()` error without closing the `flock.Flock`, leaking a file descriptor.

### Issue Context
The non-locked path already calls `fl.Close()`, and `acquireClusterStartupLease` joins `fl.Close()` on error, so the missing close in the TryLock error path is inconsistent and can accumulate FDs when `TryLock` repeatedly errors.

### Fix Focus Areas
- pkg/embed/cluster.go[524-536]

### Suggested change
Close `fl` before returning on `TryLock` error, e.g.:

```go
locked, err := fl.TryLock()
if err != nil {
   return nil, false, errors.Join(err, fl.Close())
}
```

(Or `_ = fl.Close()` and return the original error if you prefer not to mask errors with a join.)

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

To customize comments, go to the Qodo configuration screen, or learn more in the docs.

Qodo Logo

Comment thread pkg/embed/cluster.go Resolved
@qodo-code-review

Copy link
Copy Markdown

PR Summary by Qodo

Harden async lifecycle contracts (checkpoint GC, embed clusters, ISCP/MORPC tests)

🐞 Bug fix 🧪 Tests ✨ Enhancement 🕐 40+ Minutes

Grey Divider

AI Description

• Make checkpoint/GC progress use newest finished checkpoint and pin GCKP predecessors.
• Add cross-process port-range & startup leases for embedded test clusters, with shared helper.
• Replace timing/sleep-based flakes with phase/commit-TS assertions in ISCP, TAE, MORPC, and SQL
 tests.
Diagram

graph TD
  T("CI tests") --> E["embed.StartTestCluster"] --> L[("Port/startup leases")] --> C["Embedded cluster"]
  T --> B["SharedTestCluster"] --> C
  T --> I["ISCP fault barriers"] --> X["ISCP executor"]
  X --> R["Checkpoint runner"] --> S["runnerStore MaxCheckpoint"] --> G["GC / backup / snapshot"]
  T --> O["JSON_OVERLAPS test"] --> F["jsonOverlaps operands"]
  T --> M["MORPC backend tests"]
  subgraph Legend
    direction LR
    _test("Test") ~~~ _comp["Component"] ~~~ _lock[("State/Lock")]
  end
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Use OS-assigned ephemeral ports instead of leasing ranges
  • ➕ Avoids maintaining a custom port allocator/lease state
  • ➕ Reduces need for temp-dir lockfiles
  • ➖ Harder to keep deterministic multi-service port-base config templates
  • ➖ Still needs cross-process coordination to avoid collisions in multi-cluster tests
  • ➖ May not work with components that require contiguous/derived port bases
2. Track a separate persisted “durable checkpoint watermark”
  • ➕ Explicitly separates “intent/pending” vs “durable finished” checkpoint boundaries
  • ➕ Could simplify some call sites that currently choose between global vs incremental
  • ➖ Adds another persisted state surface to maintain and validate
  • ➖ Still requires predecessor pinning for metadata consumption during GCKP commit
3. Relax assertions / add sleeps in flaky tests
  • ➕ Lower implementation effort short-term
  • ➖ Hides real lifecycle races and increases CI time
  • ➖ Does not enforce durability contracts; flakes often return later under load

Recommendation: The PR’s approach is the right direction: (1) make production logic expose an explicit durable boundary (MaxCheckpoint and finished-only GC watermarking) and (2) make tests synchronize on real lifecycle phases (fault barriers, commit TS targets, and cluster leases). This fixes the root contract issues without adding sleeps or weakening coverage, while keeping the changes localized to the checkpoint store/GC boundary and the embedded-test harness.

Files changed (30) +1438 / -985

Enhancement (3) +55 / -19
options.goDefine test-mode HAKeeper default timeouts +11/-0

Define test-mode HAKeeper default timeouts

• Adds test-only default heartbeat/store timeouts and ensures WithTesting sets coherent defaults when callers do not override them.

pkg/embed/options.go

testing.goIntroduce SharedTestCluster and StartTestCluster helper +39/-19

Introduce SharedTestCluster and StartTestCluster helper

• Replaces the old onceCluster/mutex pattern with SharedTestCluster that serializes shared-cluster usage, preserves the first init result, and reports init failures consistently. Adds StartTestCluster which starts a cluster in test mode and closes on startup failure.

pkg/embed/testing.go

info.goExpose MaxCheckpoint via RunnerReader and runner +5/-0

Expose MaxCheckpoint via RunnerReader and runner

• Extends RunnerReader with MaxCheckpoint and implements it in runner by delegating to the store, enabling call sites to use a single durable progress API.

pkg/vm/engine/tae/db/checkpoint/info.go

Bug fix (9) +291 / -127
cluster.goAdd cross-process port-range leasing and startup admission for test clusters +186/-30

Add cross-process port-range leasing and startup admission for test clusters

• Introduces port-range leases (file locks) held for the cluster lifetime, plus a test-only startup lease to serialize bootstrap admission when multiple Raft/HAKeeper control planes start concurrently. Refactors cluster adjustment to return errors (no panics), ensures partial init releases leases, and threads a per-cluster NextBasePort generator into config templates.

pkg/embed/cluster.go

executor.goAdd phase barriers for injected executor faults +3/-0

Add phase barriers for injected executor faults

• When ISCP fault injection triggers specific failure branches, the executor now signals a phase barrier (WaitForISCPExecutorFault) so tests can deterministically observe the injected phase before asserting watermark behavior.

pkg/iscp/executor.go

executor.goPin finished incremental predecessor for global checkpoint commits +14/-13

Pin finished incremental predecessor for global checkpoint commits

• Threads a predecessor CheckpointEntry through the GCKP request path and validates it is finished and matches the intended end boundary. Uses the pinned predecessor for table-ID batch sync so GC cannot delete required metadata mid-commit.

pkg/vm/engine/tae/db/checkpoint/executor.go

runner.goCarry pinned predecessor in gckpContext merges +5/-0

Carry pinned predecessor in gckpContext merges

• Adds predecessor field to gckpContext and includes it in Merge so coalesced requests keep the metadata pin needed to commit global checkpoints safely.

pkg/vm/engine/tae/db/checkpoint/runner.go

store.goCompute durable boundaries from newest finished checkpoints only +58/-46

Compute durable boundaries from newest finished checkpoints only

• Implements MaxCheckpoint (newest finished global or incremental), fixes MaxIncrementalCheckpoint to return the newest finished incremental, and makes safe-GC timestamp advance only from finished global checkpoints (not intents). Improves iteration logic for finding the last finished global checkpoint.

pkg/vm/engine/tae/db/checkpoint/store.go

testutils.goForceGCKP uses MaxCheckpoint and handles already-covered targets +8/-2

ForceGCKP uses MaxCheckpoint and handles already-covered targets

• Updates ForceGCKP to use MaxCheckpoint and to no-op when a finished global checkpoint already covers the requested end. Ensures GCKP requests pin their predecessor entry.

pkg/vm/engine/tae/db/checkpoint/testutils.go

cronjobs.goCatalog/Checkpoint GC cronjobs use MaxCheckpoint durable watermark +9/-9

Catalog/Checkpoint GC cronjobs use MaxCheckpoint durable watermark

• Replaces MaxIncrementalCheckpoint usage with MaxCheckpoint so GC watermarks follow the newest finished checkpoint (global or incremental) and never advance based on pending intents.

pkg/vm/engine/tae/db/cronjobs.go

db.goBackup force-checkpoint reads durable boundary via MaxCheckpoint +5/-1

Backup force-checkpoint reads durable boundary via MaxCheckpoint

• Uses MaxCheckpoint to select the latest finished checkpoint for backup orchestration and returns an explicit error if the force-checkpoint path completes without producing a finished checkpoint.

pkg/vm/engine/tae/db/db.go

handle_debug.goUse MaxCheckpoint for snapshot read and changed-table list selection +3/-26

Use MaxCheckpoint for snapshot read and changed-table list selection

• Simplifies checkpoint selection by relying on MaxCheckpoint in snapshot read validation and changed-list extraction, ensuring the chosen boundary is the newest finished checkpoint.

pkg/vm/engine/tae/rpc/handle_debug.go

Refactor (2) +28 / -23
template.goMake port-base allocation cluster-scoped in templates +11/-14

Make port-base allocation cluster-scoped in templates

• Removes the global template function and instead passes a NextBasePort closure via template arguments, using {{call .NextBasePort}} to allocate ports deterministically per cluster lease.

pkg/embed/template.go

func_builtin_json_overlap.goFactor JSON_OVERLAPS operand wrapper setup into helper +17/-9

Factor JSON_OVERLAPS operand wrapper setup into helper

• Extracts operand construction into newJSONOverlapOperands to centralize UseOptFunctionParamFrame usage and wrapper acquisition, improving testability of result-scoped wrapper ownership.

pkg/sql/plan/function/func_builtin_json_overlap.go

Tests (16) +1064 / -816
backend_test.goStabilize draining/probe assertions and Darwin unix-socket setup +36/-6

Stabilize draining/probe assertions and Darwin unix-socket setup

• Separates “probe observed” from “durably draining” to avoid racey expectations while still asserting the final drained state rejects new traffic. Uses a short, unique temp directory for unix sockets on Darwin and upgrades critical assertions to require for fail-fast behavior.

pkg/common/morpc/backend_test.go

cluster_test.goAdopt StartTestCluster and add lease exclusivity coverage +120/-24

Adopt StartTestCluster and add lease exclusivity coverage

• Switches tests to StartTestCluster/WithTesting and validates multi-cluster uniqueness (IDs, datapaths, port-lease bases). Adds explicit tests for port-range lease exclusivity, startup lease exclusivity, coherent testing timeouts, and ensures rollback paths release leases.

pkg/embed/cluster_test.go

testing_test.goExtend SharedTestCluster behavioral tests +49/-4

Extend SharedTestCluster behavioral tests

• Renames tests for SharedTestCluster and adds coverage for nil initialization rejection and cleanup-on-failed-init (ensuring resources like port leases are released).

pkg/embed/testing_test.go

func_builtin_json_overlap_alloc_test.goReplace allocation-only check with race-safe wrapper and batch test +30/-36

Replace allocation-only check with race-safe wrapper and batch test

• Removes the non-race build tag and replaces allocation-scaling assertions with a stronger invariant: wrapper ownership is result-scoped and stable across calls. Executes a real 8,192-row batch and validates all results under both normal and race instrumentation.

pkg/sql/plan/function/func_builtin_json_overlap_alloc_test.go

table_features_test.goUse embed.SharedTestCluster for shared features cluster +4/-24

Use embed.SharedTestCluster for shared features cluster

• Replaces custom sync.Once/mutex shared cluster logic with embed.SharedTestCluster.Run and uses StartTestCluster to ensure the cluster is started (and cleaned up on failure) deterministically.

pkg/tests/features/table_features_test.go

issue_test.goSwitch issue test cluster creation to StartTestCluster +1/-2

Switch issue test cluster creation to StartTestCluster

• Uses StartTestCluster so the returned cluster is already running and consistently configured for test mode.

pkg/tests/issues/issue_test.go

partition_test.goRefactor partition tests to SharedTestCluster + started cluster helper +20/-35

Refactor partition tests to SharedTestCluster + started cluster helper

• Consolidates cluster reuse via embed.SharedTestCluster and StartTestCluster, and moves schema initialization under the shared run callback to avoid ordering races across reuse/no-reuse paths.

pkg/tests/partition/partition_test.go

shard_test.goRefactor shard tests to SharedTestCluster + started cluster helper +21/-35

Refactor shard tests to SharedTestCluster + started cluster helper

• Eliminates bespoke sync.Once reuse logic, uses SharedTestCluster for reuse mode, and ensures initialization SQL is executed based on catalog state within the run callback.

pkg/tests/shard/shard_test.go

txn_executor_test.goUse StartTestCluster for txnexecutor integration test +1/-2

Use StartTestCluster for txnexecutor integration test

• Constructs a running test cluster via StartTestCluster and removes the separate Start call.

pkg/tests/txnexecutor/txn_executor_test.go

upgrade_v1_2_3_test.goStart upgrade test cluster via StartTestCluster and ensure cleanup +2/-2

Start upgrade test cluster via StartTestCluster and ensure cleanup

• Uses StartTestCluster and registers cleanup immediately to reduce leaked clusters on early failures.

pkg/tests/upgrade/upgrade_v1_2_3_test.go

flusher_test.goUpdate scheduler stub to satisfy new RunnerReader contract +3/-0

Update scheduler stub to satisfy new RunnerReader contract

• Adds MaxCheckpoint stub method to the triggerJobCheckpointScheduler test implementation.

pkg/vm/engine/tae/db/checkpoint/flusher_test.go

runner_test.goAdd MaxCheckpoint behavior tests and predecessor merge assertion +51/-0

Add MaxCheckpoint behavior tests and predecessor merge assertion

• Introduces TestRunnerStoreMaxCheckpoint to verify pending global intents don’t advance durable GC boundaries and that finished checkpoints do. Extends gckpContext merge tests to include predecessor propagation.

pkg/vm/engine/tae/db/checkpoint/runner_test.go

db_test.goRewrite checkpoint/GC tests to use commit/checkpoint state, not wall time +217/-213

Rewrite checkpoint/GC tests to use commit/checkpoint state, not wall time

• Replaces timing-based waits with explicit commit/checkpoint targets and bounded Eventually assertions for snapshot GC, merge GC, checkpoint leak checks, and checkpoint reading after restart. Adds helpers to wait for disk-cleaner merged checkpoints and to force catalog-GC eligibility beyond TTL boundaries with better failure diagnostics.

pkg/vm/engine/tae/db/test/db_test.go

funcs.goAdd helpers for catalog-GC boundary checkpoints and commit-TS returns +47/-5

Add helpers for catalog-GC boundary checkpoints and commit-TS returns

• Adds ForceCheckpointBeyondCatalogGCBoundary to create checkpoints that make catalog GC eligible beyond TTL offsets. Introduces AppendWithCommitTS/DeleteAllWithCommitTS helpers returning commit timestamps and tightens assertions with require for deterministic failures.

pkg/vm/engine/tae/db/testutil/funcs.go

handle_debug_test.goRemove machine-speed deadline from backup test; assert checkpoint output +8/-4

Remove machine-speed deadline from backup test; assert checkpoint output

• Bounds the test with an outer context timeout instead of encoding a short FlushDuration deadline, and asserts that successful backup returns a non-empty checkpoint location.

pkg/vm/engine/tae/rpc/handle_debug_test.go

change_handle_test.goMake ISCP executor tests phase-accurate and commit-TS targeted +454/-424

Make ISCP executor tests phase-accurate and commit-TS targeted

• Unskips and strengthens ISCP register/unregister tests, adds watermark wait helpers with detailed diagnostics, and introduces an iscpFaultBarrier utility to deterministically synchronize injected fault phases. Updates multiple ISCP tests to assert exact commit-TS watermark targets, distinguish observation vs durable draining/removal, and harden fault-injection enable/cleanup contracts.

pkg/vm/engine/test/change_handle_test.go

@LeftHandCold LeftHandCold left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Deep review completed at d2d841e. One production-reachable data-correctness blocker is reported inline: the new ForceGCKP fast path treats durable coverage as if it also satisfied the caller-specific history-retention contract, allowing the administrative ForceGC path to fail open. The remaining checkpoint durable-boundary/predecessor changes, embed lease lifecycle, ISCP/MORPC synchronization, JSON_OVERLAPS extraction, and test migrations did not reveal another blocker. The reported gofrs/flock TryLock FD leak does not apply to the pinned v0.8.1 implementation because unheld handles are closed by ensureFhState on every error path. Targeted checkpoint, MORPC, and JSON tests passed. CI coverage and BVT passed; the Ubuntu UT job failed in the untouched logservicedriver TestReplay1 due a reused Dragonboat data directory/NodeHostID mismatch.

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

Deep review findings on exact head 5656c92c8362530382bab3082b16d30cff1c9f5f:

[P1] Do not let a pending GCKP become the table-ID predecessor of the next ICKP

The new fail-closed validation in doGlobalCheckpoint assumes that the predecessor's table-ID index still proves the full retention window. However, RunICKP first searches every global checkpoint for ckp.end == entry.start and accepts the match without checking IsFinished() or whether GetTableIDLocation() is authoritative. It only falls back to the incremental checkpoint ending at entry.start.Prev() when no global entry was found.

This permits the following normal scheduling sequence:

  1. An ICKP completes and a GCKP intent is published.
  2. While that GCKP is still writing its table-ID index, the next ICKP starts.
  3. The ICKP selects the pending GCKP and inherits an empty table-ID location.
  4. Its table-ID history is restarted at the current ICKP start.
  5. The following GCKP is rejected by the new 24h history validation.

This is deterministic, not a hypothetical race. Local normal/race runs of TestReadCheckpoint reproduce it, and the current Ubuntu UT job fails with the same error:

internal error: global checkpoint table-ID history is incomplete:
covered from 1785582218601103569-1,
required from 1785495818640602819-0

The CI timeline also confirms the overlap: the first GCKP ran from 11:03:38.636 to 11:03:38.658; the next ICKP completed at 11:03:38.660 after taking 19ms, so it built its table-ID index while that GCKP was pending.

Please only accept a finished global checkpoint with authoritative table-ID history. If the exact-end global is pending, empty, unreadable, or lacks a valid coverage row, fall back to the finished ICKP ending at entry.start.Prev(). A deterministic regression should block GCKP after intent publication, run the next ICKP, then verify that the later GCKP succeeds and retains the required history.

Relevant code: executor.go GCKP validation, RunICKP predecessor selection, and the failed Ubuntu UT job.

[P1] The gossip-port collision test does not reserve memberlist's wildcard address on Darwin

TestNewTestServiceRetriesGossipPortCollisionWithStableIdentity reserves 127.0.0.1:port, while memberlist binds 0.0.0.0:port. On Darwin, two SO_REUSEADDR listeners on those addresses can coexist, so the first service attempt does not receive EADDRINUSE. The self-join is captured by the test listener, which never accepts; the test waits about 30 seconds and then fails because attempts == 1.

I reproduced this independently and in the package run:

TestNewTestServiceRetriesGossipPortCollisionWithStableIdentity
"1" is not greater than or equal to "2"
elapsed: 30.4s

Please reserve 0.0.0.0:0, matching memberlist's actual bind address, or inject a deterministic bind failure. Darwin UT is currently skipped in CI, so the pipeline does not expose this deterministic local failure.

Relevant test: testclient_test.go.

[P2] Preserve a cleanup owner when startup rollback also fails

StartTestCluster returns nil, errors.Join(startErr, c.Close()) after a startup failure. Start() has already attempted rollback; a service whose Close() fails remains attached to its operator for retry. If the helper's second c.Close() also fails, cluster.Close() does not release the port lease, but the helper discards the only cluster handle. The caller can no longer retry cleanup, leaving a service/FD/port-range flock alive for the process lifetime. SharedTestCluster.Run has the same issue when it unconditionally clears c.cluster after a failed cleanup.

Please retain a retryable owner until cleanup succeeds; joining the cleanup error and returning a nil handle does not close the ownership lifecycle.

Relevant code: testing.go and cluster.Close.

I also rechecked the earlier checkpoint review threads: the force-retention, legacy-index authority, durable fallback, and multi-block coverage issues are fixed in this head. The reported flock.TryLock() error-path FD leak is not present with the pinned gofrs/flock implementation, which closes the unheld file handle on error.

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

已在 0cc789a9b 完成 first-principles 修复并合入最新 main(含 #26472、#26553)。

本轮对 review findings 的处理:

  1. Ubuntu UT / TestReadCheckpoint 根因与修复

    • 根因:GCKP intent 在 table-ID metadata 持久化前已进入 global tree;下一 ICKP 按 exact end 选中这个 pending GCKP,继承空 index,截断 24h history,随后 GCKP 以 table-ID history is incomplete 失败。
    • 修复:ICKP predecessor 只接受 finished checkpoint;finished global 还必须证明 table-ID history 连续覆盖到交接边界,否则回退到精确相邻的 finished ICKP。没有可信来源时只建立显式 partial range,GCKP 在完整窗口恢复前保持 fail-closed。
    • 连续性校验放在 SyncTableIDBatch 已有流式 merge 中,避免每个 ICKP 重读 predecessor index;consumer 同时验证 history 下界和 checkpoint coverage 上界,不跨 gap 制造 authority。
    • 新回归通过真实 fault barrier 停在 “intent published / metadata unset”,并发完成下一 ICKP,再证明后续 GCKP 成功。legacy/global-only 用例也改为先走真实 checkpoint GC 移除 ICKP,而不是靠手工构造不真实状态。
  2. Darwin port-collision 测试

    • 接受原测试不确定的 review 结论,但没有采用 wildcard gossip 的场景化修补:Darwin 上该方案仍会因 socket reuse 进入 30s self-join。
    • 改为占用 Dragonboat 将绑定的精确 raft endpoint,确定性触发同一个 EADDRINUSE -> NewServiceWithRetry 契约,并验证所有 retry 保持同一 NodeHost identity。
  3. cleanup owner

    • NewCluster / StartTestCluster rollback 只有在 Close 成功后才返回 nil;cleanup 失败返回非 nil、仅用于重试 Close 的 owner。所有直接 caller 都在断言 error 前注册 cleanup。
    • SharedTestCluster cleanup 失败时保留 owner,后续 Run/Close 可重试;成功 Close 是 terminal state,避免后续把 nil cluster 交给 callback。
    • startup flock 自身释放失败也保留在 cluster owner 中,不再丢失 FD/lock;service cleanup 完成前 port-range lease 不释放。
  4. Qodo flock comment

    • 未采纳重复 Close:pinned gofrs/flock v0.8.1 的 TryLock error path 通过 ensureFhState 关闭未持锁 handle;额外 Close 不是缺失修复。

验证(最终 head / 最新 main):

  • adaptive focused race:pending GCKP count=22、原 TestReadCheckpoint count=50、legacy/global-only count=35;embed ownership、raft collision、writer/consumer coverage 各 count=100,全部通过。
  • full -race -count=1:objectio、embed、logservice、common/morpc、iscp、SQL function、checkpoint、logtail、rpc、db/test、vm/engine/test、logservicedriver、features、partition、shard 全部通过。
  • StartTestCluster 直接 caller:issues / txnexecutor / upgrade targeted race 通过。
  • production owning packages build + vet 通过;git diff --check 通过。

关联 #26526。

@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

Copy link
Copy Markdown
Contributor Author

@LeftHandCold @aunjgr @gouhongshen @aptend @jiangxinmeng1 @volgariver6 麻烦 review 最新 head 0cc789a9b。现有 request-changes 已逐条按最终实现回复并关闭:pending GCKP/table-ID authority、retention fail-closed、legacy/partial history、Darwin 确定性 collision,以及 cleanup owner 生命周期均已修复并补充无 sleep 的确定性回归;Qodo flock 条目也已依据 pinned dependency 的真实实现说明不采纳。当前新一轮 CI 正在运行。

@LeftHandCold LeftHandCold left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review completed at exact head 0cc789a.

The previous production correctness blocker is closed: an ICKP now selects only a finished, boundary-adjacent predecessor; current-format GCKP metadata must prove continuous table-ID history, pending GCKP intents are excluded, and legacy/global-only recovery rebuilds an explicit partial range while GCKP publication remains fail-closed until the retention window is authoritative. Changed-table consumers validate both history bounds.

I also rechecked the zero/idle-LSN WAL path, checkpoint replay, catalog-GC boundary, embedded-cluster cleanup ownership, startup/port lease retries, Darwin raft-port collision test, fault-barrier cleanup, and final main merge. No further production-reachable correctness, regression, resource-lifecycle, or performance blocker was found.

Focused tests passed for checkpoint predecessor/retention, table-ID gap and multi-block consumption, changed-list bounds, pending-GCKP concurrency, legacy/global-only GC, zero-LSN and fully-reserved WAL restart, cluster cleanup-owner retries, and stable-identity port collision. The normal Ubuntu UT job is green. The coverage run had one TestBasicCluster TN-ready timeout under instrumentation; based on the passing normal UT and the reviewed state machine, I do not consider that single flake a code-review blocker.

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

Follow-up for the new UT Coverage failure (pkg/embed.TestBasicCluster): the failure was not a port collision. Its HAKeeper/TN timeline shows the D/Start schedule command was issued but never applied before CN shard-readiness timed out. WithTesting() had implicitly extended the serial CN/TN heartbeat RPC deadline from the service default (3s) to 30s; an unavailable startup heartbeat could therefore hold the only command-delivery loop long enough to miss that readiness window.\n\nThis update removes only that implicit override. It preserves the 60s HAKeeper store-liveness grace needed for embedded tests, keeps explicit WithHAKeeperHeartbeatTimeout callers unchanged, and adds a contract test documenting the distinction. Local validation after the final edit: targeted regression, 5x TestBasicCluster, full pkg/embed, go build, go vet, focused race stress (config 100x, BasicCluster 2x), and full pkg/embed race.

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

@ck89119 please help to review

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

REQUEST_CHANGES-equivalent review at exact head 24cd00a. GitHub does not allow the PR author account to formally request changes on its own PR.

[Blocker][SCA] Replace both newly added production fmt.Errorf calls with moerr.

  • pkg/vm/engine/tae/logtail/ckp_writer.go:870 constructs the table-ID predecessor continuity error with fmt.Errorf.
  • pkg/vm/engine/tae/db/db.go:276 constructs the exhausted fresh-ICKP retry error with fmt.Errorf and wraps ErrGCKPNeedsFreshICKP.

The repository err-check scans non-test files under pkg and rejects fmt.Errorf. Exact-head make err-check fails deterministically, and the arm64 SCA job is now failed. Please use context-aware moerr construction at both sites; where preserving errors.Is identity is intentional, combine the moerr context with the original cause via errors.Join or the repository equivalent.

The rest of the production closure is sound in this head: only finished checkpoints advance durable/GC boundaries; forced GCKP requests reserve a real ICKP, merge with maximum requested retention, receive their exact execution result, retry with bounded cancelable backoff, and hand suppressed automatic work back; table-ID history remains fail-closed across GC/restart/legacy gaps; embed port/startup/service ownership has retryable terminal cleanup; retry metrics have three fixed reasons. No additional correctness, resource-lifecycle, compatibility, or hot-path performance blocker was found.

Fresh local evidence: the five checkpoint state-machine tests passed under race 100x each; embed heartbeat contract 100x; table-ID single-pass validation 100x; real force-GC-fresh-ICKP lifecycle 50x; legacy/partial-history fail-closed 49x; full checkpoint and logtail packages passed race count=1. The PR head remained unchanged throughout review.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

APPROVE-equivalent review at exact head 38c61ef. GitHub does not allow the PR author account to formally approve its own PR.

The prior SCA blocker is closed. Both new production fmt.Errorf sites now use context-aware moerr construction, and the exhausted fresh-ICKP retry uses errors.Join so errors.Is still reaches ErrGCKPNeedsFreshICKP while preserving the contextual MO error. Exact-head make err-check passes.

I re-reviewed the complete 43-file diff rather than only the two-line fix. No remaining merge blocker was found:

  • Correctness/closure: only finished checkpoints advance durable, catalog-GC, logtail-GC, and snapshot boundaries; forced GCKP has an exact result, fresh finished ICKP predecessor, maximum merged retention, bounded retry, and suppressed automatic-work handback; table-ID history stays fail-closed across pending GCKP, GC, restart, legacy metadata, partial ranges, malformed coverage, and multi-block readers.
  • Unhappy paths: checkpoint intents and embedded services/leases retain exactly one cleanup owner; waits observe caller/runner cancellation or a hard timeout; queues, retries, port ranges, sinkers, and metric labels are bounded.
  • Performance/compatibility: no query hot path is changed. The table-ID merge remains single-pass and now releases each batch promptly; extra retries occur only on rare forced-checkpoint contention. No disk/wire format change is introduced; legacy checkpoints recover conservatively without mandatory conversion.
  • Observability: force-checkpoint logs include requested/checkpoint TS, retention, retry counts, and errors; the retry counter has three fixed reasons.

Fresh exact-head evidence: modified production packages build and vet; focused selection is non-empty; TestForceGCKPRequiresFreshICKPAfterGlobal, TestSyncTableIDBatchValidatesPredecessorInSinglePass, and TestForceGCKPRetryBackoffIsBoundedAndCancelable each pass under -race -count=100 (T=0/0.02/0s, B=30s, N=100); full db, checkpoint, and logtail packages pass both race and normal count=1. All four inline review threads are resolved. GitHub SCA/UT/coverage/BVT jobs were still running when this review was submitted; no CI failure was present.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Deep re-review of 38c61efbc81f9e7939db79c0c6cc56954019f479 against 06004087353d58094c14080cc122e5681ed590d0. This is a blocking review; GitHub does not allow the PR author to submit REQUEST_CHANGES on their own PR.

I found two confirmed blockers: an unbounded object-ownership gap on failed GCKP publication, and the unchanged coverage-sensitive allocation oracle from #26543. Both have inline details and local reproduction evidence below.

Validation performed on the exact clean head:

  • reproduced the GCKP orphan growth with the existing fail-closed integration scenario: 5 failed attempts produced 5 unreachable table-ID objects; the temporary diagnostic patch was removed
  • exact allocation test under repo-wide -coverpkg=./...: 20x; full function package under the same instrumentation: 10x (passes locally, but proves the test still participates in coverage)
  • full -race -count=1 suites: checkpoint, logtail, TAE DB, MORPC, embed, logservice, and SQL function
  • adaptive race stress: history fallback/fail-closed 29x; repeated force->GCKP->GC lifecycle 34x; fast checkpoint/logtail/embed/MORPC/logservice/JSON invariants 100x; affected ISCP success and unhappy paths 4x-37x according to measured duration

No additional confirmed blocker emerged from the lifecycle, wait-for, retry/cancellation, port-lease, ISCP, or plan/performance audit.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review after 5480ada and the latest main merge: the two previously blocking findings are closed, and I found no remaining blocking correctness issue in the updated diff.

The checkpoint fix now follows one publication invariant across both ICKP and GCKP: successful sinker writes have exactly one owner until durable checkpoint metadata exists. Internal sinker failures roll back partial spills; explicit failures after helper success roll back checkpoint-data and table-ID objects. Cleanup is deduplicated, bounded per 1,000-object batch, preserves both error chains, and adds fields to the existing aggregate checkpoint error event rather than emitting per-file logs. The normal success path performs no delete, deduplication, or file listing.

The coverage-sensitive AllocsPerRun oracle is removed rather than weakened. Its intended contract remains covered deterministically by stable wrapper identity plus a real 8,192-row result verification under race and repo-wide coverage instrumentation.

Unhappy-path evidence includes partial spill before validation failure, injected cleanup failure, failed ICKP/GCKP metadata publication, repeated fail-closed GCKP attempts, parent cancellation, and the 1,000/1 batching boundary. Final adaptive race repetitions (14x/5x/16x), complete owning-package race suites, targeted and repo-wide coverage, build, vet, gofmt, and diff checks all pass locally.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

APPROVE-equivalent review for exact head c1ca6ec (GitHub does not allow the PR author to formally approve their own PR).

Re-reviewed the complete 43-file diff, the latest cleanup-error delta, all six review threads, and the relevant producer/consumer and failure paths. I found no remaining blocking issue.

  • Correctness/lifecycle: checkpoint publication remains the linearization point; pre-publication ICKP/GCKP data and table-ID objects are rollback-owned, cleanup is bounded/deduplicated/cancelable, and the original error remains reachable through errors.Join. Embedded-cluster service/lease ownership is retained until cleanup succeeds, including partial startup and added-CN rollback.
  • Completeness/compatibility: forced GCKP keeps a finished fresh ICKP predecessor and requested retention; legacy/missing table-ID history fails closed and restarts from a real boundary without a disk/wire-format change. All review threads are resolved.
  • Performance/design: added work is confined to checkpoint/test lifecycle paths; the JSON hot path still uses result-scoped wrappers, fixed-label retry metrics are low-cardinality, and there is no new non-spill/query hot-path cost.
  • Observability: retry reason counters and retry counts are bounded/fixed; rollback object count and cleanup error are preserved separately in logs.

Exact-head validation passed:

  • git diff --check, gofmt -d, make err-check
  • go vet for all modified production owner packages
  • focused normal and -race tests for embed leases/rollback, checkpoint cleanup/table-ID/forced-GCKP, logservice retry identity, and JSON wrapper reuse
  • real ICKP/GCKP save-failure tests proving the file-service object snapshot is unchanged after failed publication and recovery succeeds after fault removal

Completed CI checks are green with no failures observed; the still-running UT/SCA/coverage/CodeQL/BVT jobs remain the merge gate.

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

size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

3 participants