Skip to content

feat: add opt-in table-owned AUTO_ID_CACHE - #28528

Merged
mergify[bot] merged 28 commits into
matrixorigin:mainfrom
ck89119:issue-23371-main
Sep 16, 2026
Merged

mergify[bot] merged 28 commits into
matrixorigin:mainfrom
ck89119:issue-23371-main

Conversation

@ck89119

@ck89119 ck89119 commented Sep 9, 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 #23371

What this PR does / why we need it:

Adds opt-in, table-owned AUTO_ID_CACHE support while reusing the existing ALTER TABLE ... AUTO_INCREMENT and session increment/offset implementations.

Behavior

  • CREATE TABLE ... AUTO_ID_CACHE=0 (or omitted) inherits the existing CN allocation policy.
  • AUTO_ID_CACHE=1 reserves only actual automatic-row demand, with no constructor, estimate, low-water, or concurrency-driven speculative reservation. It does not promise globally monotonic or gapless IDs.
  • Values 2..1000000 override the base raw reservation span; larger actual demand can enlarge a reservation. Non-default session series still do not background-prefetch.
  • Reject invalid, duplicate, out-of-range options and nonzero policies without a visible auto-increment column. ALTER ... AUTO_ID_CACHE is not supported.
  • Persist the policy in SchemaExtra, project it through TableDef and allocator columns, and preserve it across cold CN loading, SHOW CREATE, LIKE/COPY/CLONE, rename, TRUNCATE, dump/load, and restart.
  • Keep demand-only CurrentValue observation non-reserving and preserve the existing pre-generation allocation-timestamp probe and deferred generated-ID publication.

Rollout boundary — approved option A

The production configuration defaults to disabled:

[cn.auto-increment]
enable-auto-id-cache = true

Enable only after draining workloads, stopping all old CN/TN processes, and upgrading every role. Mixed-version operation and old-node reentry are unsupported. The new V67 check and appended PRE_INSERT wire marker provide local/transport rejection, not cluster-wide admission or proof of upgrade completion.

Disabled nodes reject nonzero CREATE and allocator-cache construction/use instead of silently applying their defaults. SHOW retains the persisted policy. Existing independent ALTER AUTO_INCREMENT offset/epoch maintenance remains available and preserves the policy. Disabling is not data rollback; in-place downgrade with nonzero-policy tables is unsupported.

The standalone, multi-CN, compose BVT examples and shared feature-test fixture explicitly opt in for fresh, same-version test clusters. No platform admission state machine, additional allocator table, background worker, or per-row capability RPC is introduced. This PR does not independently fix or close the separate REPLACE/IGNORE issues.

Design and review

The allocator/metadata design and rollout option A were approved before their respective implementation phases. Exact delivered revisions:

Self-review covered the complete change map, metadata readers/writers and recovery paths, ownership/cancellation/retirement, bounds, protocol rejection, and delivery artifacts. Generated parser/protobuf files were regenerated with repository tools and reproduced identical SHA256 hashes; most diff volume is generated parser tables.

Validation

Local validation used darwin/arm64, Go 1.26.4, and the repository mo-cgo-test wrapper with matching native artifacts.

  • Owning packages passed: incrservice, sql/plan, sql/parsers/..., sql/compile, pb/api, pb/plan, vm, vm/engine, the entire disttae package, disttae/cache, tae/catalog, cnservice, and embed.
  • Five individually selected race tests each passed 100 repetitions after duration-based budget selection: concurrent cache demand, cancellation/retirement, concurrent session series, cold services/probes, and runtime gate cleanup. Entire incrservice and sql/compile packages also passed once under -race.
  • Changed-line coverage: 250/271 = 92.25%, mapped from Go coverage blocks, excluding generated files and tests; this is not whole-package or branch coverage.
  • TestAutoIDCachePublicLifecycle: real two-CN cold loading, DDL lifecycle, rename, and public stage/object dump/load passed.
  • TestAutoIDCacheRestartAndDisabledNode: permanent isolated-cluster test passed through full shutdown, disabled restart, rejection/no-partial-DDL checks, and enabled restart with the expected next ID.
  • Real mo-tester BVT: generated/reviewed .result, then 67/67 twice on the same instance, with zero failures/ignored/abnormal statements and independently verified database teardown between runs. Test services were closed.
  • Default one-row allocation benchmark, upstream vs feature, five 2-second samples each: median 1248 vs 1234 ns/op; both 0 B/op, 0 allocs/op, approximately 0.0001 reservations/op. No material default hot-path regression observed; no claim of statistically significant speedup or zero cold-catalog overhead.
  • Before submission, synchronized mo/main through 3d22c694a8 and reran plan/compile owning tests and the public lifecycle test successfully. Other evidence is reused from cd04bb4c1a because the intervening SET/FIND_IN_SET change does not alter the validated CACHE protocol, allocator, or recovery paths.
  • git diff --check passed. TODOs, local logs, caches, and temporary harnesses are excluded.

Review follow-up — transaction-owned observation and ALTER normalization

Fixed in 5d72ca9e9d, after merging upstream through d3794ea964:

  • Demand-only observation now runs in the actual table-cache owner: uncommitted CREATE uses its transaction, while committed caches use a fresh committed read. The lazy wrapper retains the delegate for the entire observation. No IDs are reserved by SHOW/information_schema queries.
  • After all ALTER COPY clauses are applied, clear the inherited policy only if the final definition has no visible auto-increment column. MODIFY/DROP now succeed; keeping or transferring the auto-increment attribute preserves the policy. Direct CREATE validation and truthful SHOW rendering remain unchanged.
  • Added pre-fix failing regressions, commit/rollback and lazy-owner coverage, final-definition/internal-CREATE controls, and real SHOW TABLE STATUS/information_schema plus MODIFY/DROP controls for policies 0/1/8.
  • Updated owning incrservice/plan/compile tests and public lifecycle passed. The two affected observation tests each passed 100 individually selected race repetitions; the entire incrservice package passed once under race.
  • Follow-up changed-line coverage: 19/22 = 86.36% (Go block mapping, excluding generated files/tests). The earlier 92.25% above records the initial implementation, not this incremental fix.
  • Updated mo-tester result was regenerated and reviewed; normal comparison passed 89/89 twice on the same instance, with zero ignored/abnormal statements and verified teardown. Services were closed.
  • The generated plan protobuf merge conflict was resolved by repository tooling; regeneration reproduced the same SHA256. No TODOs or local validation artifacts were committed.

Upstream conflict resolution

Merged mo/main@d3e8aced87 in 27707b0f93. Preserve upstream V58 for binary-string/runtime-domain semantics; AUTO_ID_CACHE now requires V59, with unchanged wire opcodes, field numbers, and rollout contract. Both independent remote-pipeline gates remain intact. Tests explicitly reject CACHE at V58 and accept it at V59.

Focused gates, complete incrservice/compile/process/plan/frontend tests, and the real two-CN public lifecycle all passed on this merge. The two executable lines changed by the manual conflict resolution are covered (2/2); this is not a coverage claim for all incoming upstream code. Earlier unchanged allocator/race/BVT evidence is reused rather than reported as newly executed.

The updated rollout document records the protocol-number reassignment; the earlier design links above preserve the original approved revision.

SCA follow-up (535269d)

Merged upstream through 401b967dc1, including #28555, which removes the unused CDC helper reported by SCA. No lint suppression was added. Upstream now owns V59 for FORMAT; AUTO_ID_CACHE therefore requires V60, with unchanged opcode/field numbers and rollout contract. Latest-version and dedicated boundary assertions were updated together. The rewritten remote branch was merged without force-pushing; its merge tree is identical to the locally validated tree.

Repository-configured golangci-lint 2.6.2 passed for issues/incrservice/compile/queryservice-client. Complete incrservice/compile/queryservice-client/embed tests, the public AUTO_ID_CACHE lifecycle, and both CDC watermark ordering scenarios passed. This records targeted local validation, not a claim that the new full SCA run has passed.

Latest review follow-up (089c2e68cb)

Current protocol requirement is V64; earlier version numbers in the historical follow-ups are superseded.

  • Reject AUTO_ID_CACHE in PARTITION/SUBPARTITION option lists, including zero, at the shared parser boundary. Table-level placement and existing partition options remain supported. Added 12 parser counterexamples/controls, public SQL rejection with no published table, and BVT cases; regenerated the parser using repository tooling with repeatable SHA256.
  • Cold PRE_INSERT and internal_auto_increment now carry policy from their already-resolved TableDef/relation. A physical-table-ID-bound hint avoids re-reading mo_tables for those paths, including default policy. A stale/mismatched hint (including table-ID refresh/TRUNCATE) falls back to durable discovery; size/config/protocol checks remain. Table-ID-only callers without authoritative metadata still use the catalog lookup.
  • Empty-cache observation deliberately retains a fresh allocator offset read. Another CN can advance the watermark without changing local cache state; caching the last local offset would break the existing cross-CN observation regression. We do not introduce a distributed invalidation protocol or claim all observation SQL has been eliminated.
  • Real SQL cold metadata comparison: 1024 empty default-policy tables, three passes through GetColumns without allocator-cache reuse, median 2.977s without typed policy → 0.516s with typed policy (~82.7% lower). DDL excluded; same embedded fixture, not an isolated production or full end-to-end benchmark. Unknown-ID fallback costs remain. No permanent heavyweight test fixture or benchmark scratch source added.
  • Complete incrservice/preinsert/function/mysql owning tests, incrservice/preinsert race, changed-package lint and two-CN public lifecycle passed. Handwritten Go changed-line coverage 15/15 (100%), combining owning/public profiles; grammar rejection is separately covered by parser/public SQL tests. Real mo-tester comparison passed 92/92 twice, with zero ignored/abnormal statements and verified teardown.

Latest merge and test follow-up

Merged upstream through 77dbf54644. Upstream V64 now belongs to typed BIN/CONV; AUTO_ID_CACHE requires V65. Parser conflict resolved by reproducible repository regeneration. A locally reproduced cross-CN lifecycle assertion read stale metadata immediately after ALTER; the test now waits for the writer commit to be replayed on the reader and advances the reader transaction frontier. Assertions are unchanged; no sleeps, retries, skips or timeout increases.

Complete incrservice/compile/mysql/queryservice-client/optools tests and targeted lint passed. Public lifecycle passed normally and under race after the causal fence. Manual production gate changes have 2/2 executable lines covered. The failed Linux run hit its overall race-suite budget; upstream fixture/tooling improvements are included, but a successful new full CI run is still needed to establish that the budget is met.

CI wait-budget regression follow-up

Merged upstream through 4f9d170a22; CACHE remains V65. Regenerated the parser conflict with repository tooling (repeatable SHA256). Run 34605879932 failed in TestDiskCacheReadSharesWaitBudgetAcrossEntries/distinct_ranges, not at the overall runner budget. Its 500ms wall-clock assertion expired under race load.

The test now owns its entire fixture/channels/timers inside testing/synctest, retains both 64-entry scenarios and the 500ms deadline, and additionally asserts exactly one shared 20ms virtual wait budget. A temporary per-path-budget-reset mutation failed both scenarios and was reverted; no product wait behavior was changed. The exact test passed 100 race repetitions, the complete fileservice package passed normally and under race, and fileservice lint plus mysql/compile owning tests and public AUTO_ID_CACHE lifecycle passed. No sleeps, skips, retries, or deadline increases were introduced.

Latest conflict/CI follow-up (e7837e0b32)

Merged main through 887576e6b8; upstream owns V65/V66, so the current AUTO_ID_CACHE gate is V67. Protobuf conflicts were resolved by repeatable repository generation. Upstream #28769 fixes the JSON ColumnBuffer fixture that failed UT/coverage. Complete vectorindex tests and race, incrservice/compile/plan/pb-plan owning tests and public AUTO_ID_CACHE lifecycle passed.

Unresolved CI diagnostic: the proxy ALTER BVT originally failed because deleteTable received two catalog rowids for one account/database/name during repeated ALTER COPY in a transaction. The unchanged original case passes 95/95 twice on a local two-CN direct-connection fixture, but that does not establish the proxy failure is fixed. No expected-result changes, retries or arbitrary row selection were introduced; this root cause remains open.

Latest follow-up (79efd5ed10)

Merged main through be30a70fe5. The current AUTO_ID_CACHE gate is V69, preserving upstream V67 timezone and V68 GROUP_CONCAT contracts. Parser regeneration is reproducible; the equivalent upstream port-probe fix replaces duplicate local fixtures. Complete incrservice/compile/mysql tests with coverage, port race tests x100, and public AUTO_ID_CACHE lifecycle passed.

Run 34807638541 passed UT, SCA, UT coverage and Proxy BVT. Its Pessimistic BVT never started: setup-java exhausted its existing attempts downloading Java with HTTP 500. Aggregate coverage was blocked by that missing producer, not by a coverage threshold. No product/workflow workarounds or weakened tests were introduced. This push triggers a fresh run; fresh CI results have not been monitored or claimed.

Latest conflict-only follow-up (32374c048d)

Merged main through a72a224ce8. The current AUTO_ID_CACHE gate is V70, preserving upstream V69 bounded RANK. Protobuf was regenerated twice with identical hashes. AUTO_ID_CACHE gate tests, complete incrservice/compile/pb-plan tests, and public lifecycle passed. Compilation initially exceeded the local command budget; lowering parallelism unblocked validation. Existing Parquet fanout tests failed with GOMAXPROCS=2 and the complete compile package passed with GOMAXPROCS=4; no assertions were changed. No CI checks were queried or monitored in this conflict-only follow-up.

Latest review follow-up (7bbab4c1cf)

Addresses the two P2 performance comments in review 5197965391:

  • All definition-owning Reset/SetOffset production callers (TRUNCATE, in-place/copy ALTER, CLONE and LOAD TABLE) now carry physically bound policy hints. Truly unknown or mismatched table IDs retain durable fallback; no global metadata cache is added.
  • Empty demand-only observations use a fresh (table_id, col_name) offset/step point query rather than reading policy and the complete column list. Private transaction ownership, committed fresh snapshots, errors/overflow and no-reservation semantics remain intact. No stale observation cache or distributed invalidation protocol is introduced.

Validation: complete incrservice/compile/table_clone/frontend tests with coverage; complete incrservice race; strict DDL context and fresh-observation SQL regressions; public two-CN lifecycle; incremental lint and diff check. Handwritten changed-code coverage: 51/52 = 98.08%. Mock generation is reproducible.

Real 1024-empty-table store-read benchmark, three-pass medians: catalog fallback 951.706ms, policy hint 204.496ms, offset/step point query 133.514ms. DDL/cleanup excluded, no allocator reservation/cache reuse. This is store-read cost, not end-to-end DDL/SHOW throughput. Every empty observation intentionally still executes one fresh SQL query. Fresh CI has not been monitored; no reviewer replies or Resolve actions were posted.

Latest conflict-only follow-up (02dde94931)

Merged main through 2ea4ec2e6e. AUTO_ID_CACHE now uses V73, preserving upstream V70 row-dependent CONV bases, V71 checked integer arithmetic, and V72 corrected IP semantics. The CREATE conflict retains both the AUTO_ID_CACHE publication gate and upstream persisted-IP gates for main/index table definitions. Wire opcode and protobuf field numbers are unchanged.

Complete incrservice and compile tests, V72-reject/V73-accept sender/receiver boundaries, incremental lint, and the public two-CN AUTO_ID_CACHE lifecycle passed. Initial compile and lifecycle attempts hit local temporary-directory capacity/path-length environment failures; both passed using task-owned temporary directories, which were removed. No tests were weakened. Fresh CI has not been monitored.

Cross-CN observation follow-up (0dd58f854a)

Addresses review 5205129331. A committed empty demand-only observation now acquires the engine TN-ordered LogtailReadBarrier, then starts the allocator point-read transaction with the returned applied frontier as MinCommittedTS. This prevents default sacrificing-freshness from selecting a pre-frontier snapshot on the observing CN. Private uncommitted CREATE observations continue to use their owner transaction and do not acquire an external barrier. Missing capability, cancellation and barrier errors fail closed; there are no sleeps, retries, stale caches or allocator reservations.

Deterministic tests block the barrier and prove SQL cannot start before release, verify the exact frontier is carried into executor options, preserve private/committed transaction behavior, and cover cancellation/missing capability plus the CN adapter. Complete incrservice/cnservice tests, focused race, incremental lint, and the public immediate cross-CN lifecycle passed. Handwritten changed-code coverage: 24/26 = 92.31%. The earlier point-query benchmark is now documented only as pre-barrier SQL-shape evidence, not current end-to-end latency. Fresh CI has not been monitored; no review reply or Resolve mutation was posted.

Metadata observation follow-up (965157e10b)

Addresses review 5208589585. One vectorized internal_auto_increment evaluation now owns a statement-local observation scope: all table point reads share one TN-ordered frontier and retain that frontier as MinCommittedTS, while allocator offsets are never cached. Distinct evaluations acquire new frontiers. The scope is concurrency-safe and retains a barrier error consistently without starting SQL. This reduces the external barrier count from O(tables) to one per vector evaluation; point queries remain keyed by (table_id, col_name) rather than introducing dynamic batch SQL.

Reset also safely rebinds a known policy from the exact old physical ID to its replacement ID. A hint already bound to the replacement remains valid; unrelated hints are not trusted and retain durable fallback.

Complete incrservice/function tests, public two-CN SQL lifecycle with dependency coverage, focused concurrent race, incremental lint and diff checks passed. Combined handwritten changed-code coverage: 16/20 = 80%; the rebinding helper itself and old/new/unrelated cases are covered. No sleeps, retries, stale caches or review-thread mutations were introduced. Fresh CI has not been monitored.

Latest conflict-only follow-up (bf613fb0f1)

Merged main through 4cd720e0ce. AUTO_ID_CACHE now uses V74, preserving upstream V73 widened DECIMAL SUM partial state. Local and remote sender/receiver gates reject V73 and accept V74; wire opcode and protobuf field numbers remain unchanged. This merge had only the protocol constant conflict and no generated-file conflict.

Complete incrservice/compile tests, public two-CN lifecycle, incremental lint and diff checks passed. Fresh CI has not been monitored.

Latest conflict/CI follow-up (d45dc8cce9)

Merged main through 091825aac2. AUTO_ID_CACHE now uses V76, preserving upstream V74 corrected numeric HEX identities and V75 persistent data-branch identity. The MySQL parser conflict was resolved by reproducible repository regeneration; local and remote AUTO_ID_CACHE boundaries reject V75 and accept V76, while wire opcode and protobuf field numbers remain unchanged.

Run 34990282101 exposed a real empty-result cleanup race rather than a slow test: a drain-all Shuffle that never reached Prepare could still publish a shared-pool stopper. Under parallel cleanup this produced shuffle pool too many stoppers! panics, killed worker goroutines, and stranded the query until its 180-second deadline. Cleanup now publishes a stopper only for an operator that owns a holder acquired by Prepare. The regression fails with the ownership guard removed, passes under race 100 times, and TestIssue28313EmptyRemoteDispatch passes under race 5 times. Complete shuffle/incrservice/compile/parser owning tests, AUTO_ID_CACHE public lifecycle, targeted lint, coverage and diff checks passed. No timeout increase, retry, skip, or assertion weakening was introduced. Fresh CI has not been monitored.

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

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

Re-review completed at exact head 089c2e68cb712116cc584e6a3456dd782b321ef0 against exact base 061ee00f8c4f2de130c0b7495e16b80a150dbba3.

I read the complete review, inline-comment, reply, and thread state, then checked the delta since my previous reviewed head ee2ddcb1e9e7cf3b330688148e739ba222e2deca together with the full PR diff. My previous blocker is closed in code: the partition/subpartition grammar boundary now rejects AUTO_ID_CACHE (including zero) instead of accepting and silently discarding it, with parser and public-SQL counterexamples covering both placements. I also verified the latest cold-metadata change: known policy is bound to the physical table ID, stale/mismatched/TRUNCATE identities fall back to durable discovery, and PRE_INSERT, internal_auto_increment, plus existing-cache observation carry policy from authoritative metadata.

The full re-review also rechecked the table-owned policy propagation, CACHE=1 demand-only allocation and mixed explicit/automatic ordering, session-series arithmetic, allocator timestamp probes, CREATE/ALTER/LIKE/CLONE/TRUNCATE/dump-load lifecycle, disabled-node behavior, and V64 sender/receiver marker gates. I found no blocking code issue within the documented all-role-upgrade rollout boundary. The outstanding session-semantics objection is a product decision and is not overridden by this technical approval.

Exact-head validation:

  • git diff --check; forced MySQL parser regeneration produced no diff.
  • Full packages: incrservice, MySQL parser, plan, preinsert, compile, cnservice, pb/api, disttae/cache, and tae/catalog.
  • Focused race runs: all TestAutoIDCache* incrservice tests, plus AUTO_ID_CACHE and refreshed-table-ID paths in compile/preinsert.
  • Current exact-head SCA, coverage, shared build, and multi-CN BVT checks are green.

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

OK. Even though using a session variable on this sounds crazy to me.

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

Re-review completed at the exact head below. I found one new blocking protocol-version collision after main advanced. The previously reviewed AUTO_ID_CACHE implementation and partition-placement fix remain sound in the inspected diff, and focused exact-head tests passed.

Comment thread pkg/defines/const.go Resolved

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

Re-review completed at exact head 32374c0 against exact base a72a224.

I read the complete review history, inline comments, author replies, and resolved/unresolved thread state, then inspected the delta since my previous reviewed head 79efd5e together with the full PR diff.

My previous protocol-version blocker is closed in code: MORPCVersion69 remains assigned to exact bounded per-partition RANK, AUTO_ID_CACHE moves consistently to MORPCVersion70, MORPCLatestVersion advances to V70, and the service plus remote sender/receiver gates reject V69 and accept V70. The design and rollout documents describe the same boundary. Current origin/main still ends at V69, so there is no remaining version collision.

The earlier partition/subpartition placement blocker remains closed, and the complete-diff review found no regression in policy propagation, demand-only allocation, mixed explicit/automatic ordering, CREATE/ALTER/LIKE/CLONE/TRUNCATE lifecycle, metadata observation, or fail-closed rollout handling.

Exact-head validation passed:

  • make thirdparties
  • go test ./pkg/incrservice -count=1
  • go test ./pkg/sql/compile -run ^TestAutoIDCacheRemoteWireGate$ -count=1
  • go test ./pkg/pb/plan -count=1
  • git diff --check

All required exact-head GitHub CI is green, including Ubuntu/x86 UT, SCA, coverage, shared build, proxy/pessimistic BVT, and CI Required.

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

复审结论

审查基于 exact head 32374c048dea25cb8385b1a1a743ae15f0f8c874,base a72a224ce85fd13aa919fb56dab58b8c60b366dc。完整 diff、调用链和相关测试已复核;未确认 P0/P1,当前确认以下两个 P2。上轮 Codex review 5175986176 的 P1 是针对旧 head 的无条件 fallback 回归;当前 PRE_INSERT 和 internal_auto_increment 主路径已传递 typed policy hint,因此不再按旧范围判定为 P1。上轮 P2 未收到作者针对性回复,故本次按规则提交 COMMENT。

P2 — 无 policy hint 的 GetColumns fallback 使用无索引目录查找

  • 位置:pkg/incrservice/store_sql.go:500-506。
  • 触发:Reset、SetOffset 或其他仅携带 tableID 的冷加载调用 GetColumns 时,hasKnownPolicy=false,SQL 为 (select extra_info from mo_tables where rel_id = ...)。
  • 证据/影响:mo_tables 在 pkg/catalog/catalog.go:103-132 的主键是复合 cpkey,现有二级索引是 rel_logical_id,没有 rel_id 索引;因此每次 fallback 都可能扫描目录。当前 hint 覆盖的主要路径不受此影响,但批量 DDL 或重启后的 tableID-only 冷加载会随目录规模产生额外扫描成本。
  • 建议:继续扩展 typed policy 传递,或改用有索引/缓存的策略读取;补充大目录 cold-load 基准。

P2 — demand-only 空段观测重复读取 allocator

  • 位置:pkg/incrservice/table_cache.go:178-195。
  • 触发:AUTO_ID_CACHE=1 新建或本地 range 耗尽后,cc.current 返回 0,CurrentValue 每次再调用 store.GetColumns。
  • 证据/影响:known policy 只绕过 mo_tables 子查询,仍会读取 mo_increment_columns;重复执行 SHOW TABLE STATUS 或 information_schema.tables 会为每个空段观测重复发起 allocator SQL。这样保持跨 CN 高水位观测的正确性,但会增加元数据查询开销。
  • 建议:引入可正确失效的观测缓存,或更窄的 offset/step 点查;补充空段重复观测的读取次数/性能回归测试。

验证

  • go test -run '^TestAutoIDCache' ./pkg/incrservice 通过。
  • go test -race ./pkg/incrservice 通过。
  • MySQL partition rejection、plan、compile 的 AUTO_ID_CACHE 定向用例通过。
  • git diff --check 通过。
  • 未修改代码、未 push、未创建 PR、未 merge。

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

Codex review

Reviewed the complete PR diff at exact head 02dde94931708f17ee3edff3bb86a0b31a1762a0 (the PR advanced from the watcher-reported 7bbab4c1 during this review). No P0/P1 found. The two P2s from review 5197965391 are addressed: typed policy hints remove the fallback catalog lookup from authoritative paths, and empty demand-only observations now use a single allocator point read.

P2 — empty AUTO_ID_CACHE=1 observation can be stale across CNs

Location: pkg/incrservice/store_sql.go:564-581, especially autoColumnReadOptions at :572 and its use at :581; reached by pkg/incrservice/table_cache.go:167-192 at :185 when a committed demand-only cache is empty.

autoColumnReadOptions(nil) opens the point query with only WithEnableTrace().WithDisableWaitPaused(). It does not establish a logtail/visibility barrier before the SELECT. This matters in the default CN configuration: EnableSacrificingFreshness is normalized to 1 (pkg/cnservice/types.go:433-439), so a new SQL transaction uses the CN current applied logtail snapshot. If CN-B allocates or advances the allocator and commits, then CN-A calls internal_auto_increment while that commit is still unapplied on CN-A, the SELECT can read the previous offset and return a stale next value. That contradicts the new method stated cross-CN freshness guarantee (store_sql.go:575-577), even though allocator uniqueness is preserved.

Please add a visibility fence or snapshot guarantee before this read and a regression that delays CN-A logtail after a CN-B allocator commit. The existing point-observation mock test does not assert this, and the two-CN test does not fence immediately before the CurrentValue assertion.

No current P0/P1 remains. Because this P2 has no author-targeted reply in the review threads or PR conversation, the required event is COMMENT. Current CI has several pending jobs after the new head; merge state is blocked.

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

Codex review

审查基于 exact head 0dd58f854a99ca66e30fed2924523fe38c5def93,base 2ea4ec2e6ef4b20321a235ef416228506813e39b。

结论:未确认 P0/P1;当前仍有以下两个非阻塞 P2,因此按规则提交 COMMENT。上一轮关于跨 CN stale observation 的 P2 已由当前 head 的 LogtailReadBarrier(pkg/cnservice/server.go:1301-1327、pkg/incrservice/store_sql.go:590-600)修复。检查 review threads 和 PR conversation 未发现作者针对这些 P2 的明确回复;新 commit、机器人留言和无关回复不计。

P2 — CACHE=1 空缓存观测每次执行 barrier 和 allocator 点查

  • 位置:pkg/incrservice/table_cache.go:178-192;SQL 实现在 pkg/incrservice/store_sql.go:583-600。
  • 触发:已提交的 AUTO_ID_CACHE=1 cache 没有本地 range(冷加载或本批精确号段已消费)时,CurrentValue 每次都调用 GetColumnValue;该函数对 nil txn 每次取得 TN 有序 logtail frontier,再执行一次 mo_increment_columns 点查。
  • 调用链:internal_auto_increment 对可见表逐行调用 CurrentValue(pkg/sql/plan/function/auto_increase.go:36-66),它被 information_schema.TABLES/SHOW TABLE STATUS 使用(pkg/util/sysview/predefined.go:510、pkg/sql/plan/build_show.go:721)。
  • 影响:一次包含 N 个空 CACHE=1 表的元数据查询会产生 N 次外部 barrier 等待和 N 次 allocator SQL;重复 SHOW/info-schema 查询会重复该成本,延迟与 TN/logtail 负载按表数放大。该问题不破坏唯一性,但属于可观的元数据性能回退。
  • 建议:在不返回过期值的前提下,按一次元数据语句共享 frontier/快照并批量点查,或增加可按 allocator epoch 正确失效的合并机制。

P2 — Reset/未知调用的 GetColumns fallback 仍按无索引 rel_id 查 mo_tables

  • 位置:pkg/incrservice/store_sql.go:500-515,尤其 :508 的 (select extra_info from mo_tables where rel_id = ...)。
  • 触发:Reset 的 old/new physical table ID 不同时,pkg/incrservice/service.go:243-246 将 policy owner 改为 replacement ID,但已有 known policy 仍绑定 old ID,hasKnownPolicy 为 false,于是每次 Reset 走该 fallback;任何没有匹配 typed policy 的冷加载也会走同一路径。
  • 证据/影响:mo_tables 的主键/现有索引并不覆盖 rel_id(pkg/catalog/catalog.go:103-132),因此 fallback 可能扫描整个目录。批量 TRUNCATE/Reset 或大目录下的 tableID-only 冷加载会增加目录规模相关的延迟。
  • 建议:把已知 cache size 重新绑定到 replacement ID,或改用有索引/缓存的策略读取;补充 Reset/unknown-caller 的大目录基准。

Validation

  • 完整 diff 已按上述 base/head 复核,git diff --check 通过。
  • 当前 PR 的 29 个 check 均已结束且无失败,CI Required 通过;GitHub 报告 mergeable=true、mergeable_state=behind。
  • 未修改代码、未 push、未创建 PR、未 merge。

ck89119 and others added 6 commits September 15, 2026 18:52
# Conflicts:
#	pkg/defines/const.go
#	pkg/sql/parsers/dialect/mysql/mysql_sql.go
# Conflicts:
#	pkg/sql/colexec/shuffle/shuffle.go
#	pkg/sql/colexec/shuffle/shuffle_test.go
# Conflicts:
#	pkg/defines/const.go
#	pkg/sql/compile/ddl.go
@mergify

mergify Bot commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-09-16 10:02 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • ✅ Checks skipped · PR is already up-to-date
  • ✅ Merged — 2026-09-16 10:02 UTC · at 2b56f0d5e11b7af0b29cf91bd1d0f03430da3f75 · squash

This pull request spent 13 seconds in the queue, including 1 second running CI.

Required conditions to merge

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/feature size/XL Denotes a PR that changes [1000, 1999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature Request]: Enhanced AUTO_INCREMENT Support

8 participants