Skip to content

Reserve dedicated TSO raft group#1064

Open
bootjp wants to merge 5 commits into
mainfrom
design/dedicated-tso-group
Open

Reserve dedicated TSO raft group#1064
bootjp wants to merge 5 commits into
mainfrom
design/dedicated-tso-group

Conversation

@bootjp

@bootjp bootjp commented Jul 11, 2026

Copy link
Copy Markdown
Owner

Summary

  • Reserve Raft group 0 for the dedicated TSO group and keep user-data shard ranges on group IDs 1 and above.
  • Pin --tsoEnabled timestamp issuance leadership to group 0 when that group is configured, while preserving the existing any-led-shard bridge when it is absent.
  • Update the centralized TSO design doc to mark the reserved-group bootstrap bridge as implemented and keep the minimal TSO-only FSM / follower redirect work explicit.

Tests

  • go test . -run 'TestDefaultGroupID|TestParseRuntimeConfigAllowsDedicatedTSOGroupWithoutDataRoute|TestValidateShardRanges'
  • go test ./kv -run 'TestShardedCoordinatorReportsAnyShardAsTimestampLeader|TestShardedCoordinatorUsesDedicatedTimestampGroupLeader|TestLocalTSOAllocator|TestBatchAllocator'
  • go test ./store -count=1
  • go test ./... currently fails in adapter: Test_grpc_transaction and Test_consistency_satisfy_write_after_read_sequence time out. Test_grpc_transaction also times out on a clean origin/main worktree under the same local conditions, so this is not introduced by this branch.

Summary by CodeRabbit

  • 新機能
    • 専用TSOグループ(group 0)を基準にタイムスタンプ・リーダ判定を制御できるようになりました。
  • 改善
    • 設定済みの全シャードグループを対象に、リース検証やブロードキャスト動作が正しく反映されます。
    • 予約TSOグループに関するシャード範囲・FIFO設定・データディレクトリを分離/検証し、誤設定は明確なエラーで中断します。
  • ドキュメント
    • TSO設計の進捗とマイルストーン、残課題を更新しました。
  • テスト
    • 予約TSOグループの取り扱いに関する検証を追加しました。

@coderabbitai

coderabbitai Bot commented Jul 11, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

TSO用Raft group ID 0を予約し、データルートやSQS FIFO割り当てから除外する検証を追加した。専用グループへのリーダー固定、全グループ操作、ランタイムディレクトリ配置、関連テストと設計文書を更新した。

Changes

専用TSOグループ対応

Layer / File(s) Summary
TSOグループの予約とルート検証
shard_config.go, shard_config_test.go, main.go
group ID 0をTSO専用として定義し、データグループ選択、シャード範囲、SQS FIFOパーティション割り当てから除外した。
TSOリーダーと全グループ操作の固定
kv/sharded_coordinator.go, kv/*test.go
WithTimestampGroupでTSOリーダー判定対象を固定し、lease読み取りとブロードキャストを設定済みの全シャードグループへ適用する処理とテストを追加した。
ランタイム構成とディレクトリ配置
main.go, main_encryption_startup_guard.go, multiraft_runtime.go, multiraft_runtime_test.go
データグループに基づくmulti判定を構成・暗号化起動ガードへ適用し、単一データグループ時もTSO group 0を個別ディレクトリへ配置するよう変更した。
TSO設計ステータス更新
docs/design/...
M1〜M5の実装状況、M2 dual-write bridgeの条件、残作業を更新した。

Estimated code review effort: 3 (Moderate) | ~25 minutes

Sequence Diagram(s)

sequenceDiagram
  participant RuntimeConfig
  participant configureCoordinatorTSO
  participant ShardedCoordinator
  participant TimestampGroupEngine
  participant DataGroupEngine
  RuntimeConfig->>configureCoordinatorTSO: groups構成を渡す
  configureCoordinatorTSO->>ShardedCoordinator: group 0と全データグループを設定
  ShardedCoordinator->>TimestampGroupEngine: group 0のリーダー状態を確認
  TimestampGroupEngine-->>ShardedCoordinator: リーダー判定結果
  ShardedCoordinator->>DataGroupEngine: 設定済みグループへlease・ブロードキャストを実行
Loading

Possibly related PRs

  • bootjp/elastickv#952: LeaseReadAllGroupsの設定済みシャードグループ走査に関連する変更。

Suggested reviewers: copilot

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 6.25% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed 専用TSO用のRaft group 0を予約する変更を端的に表しており、主要な変更内容と一致しています。
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@github-actions

Copy link
Copy Markdown
Contributor

TLA+ spec divergence review (auto-triggered)

This PR touches files that the TLA+ safety spec has an anchor on (per
docs/design/2026_05_28_implemented_tla_safety_spec.md §3),
so an AI review is requested below to verify the implementation has not drifted
from the model.

Anchored files changed in this PR head (296fe03):

  • kv/sharded_coordinator.go

What to check, by subsystem:

  • kv/hlc*.goNext() must respect the HLC-4 preconditions (i)/(ii)/(iii) from the design doc: bounded skew, logical-counter handoff on leader change (strategy (c) Observe(MaxAppliedHLC)), and the commit-time ceiling fence (fail-closed when wall_now >= physicalCeiling). Any change to the bit layout (48/16), the CAS loop, or the ceiling getter/setter is in scope.
  • kv/coordinator.go, kv/sharded_coordinator.goRunHLCLeaseRenewal, hlcRenewalInterval, hlcPhysicalWindowMs constants, and the new-term detection that calls Observe(fsm.MaxAppliedHLC()) (strategy (c)). Any change to renewal cadence, group selection, or fail-closed behaviour is in scope.
  • kv/transaction.go, kv/lock_resolver.go — OCC commit-ts assignment, lock-map encoding (key, lock_ts) -> start_ts, and the LockResolver action OCC-3 depends on. (M2 spec will land OCC-1..OCC-5; until then the spec doc §5.2 is the contract.)
  • kv/fsm.go — FSM apply of HLC lease entries (SetPhysicalCeiling), and any future MaxAppliedHLC() accessor that strategy (c) needs.
  • store/mvcc_store.go — version visibility, snapshot install, and the MVCC-1..MVCC-4 invariants (M3 scope).
  • distribution/** — route catalog versioning, SplitRange atomicity, and CatalogWatcher async fan-out (M4 scope).

If the change is correct but requires a spec update, edit tla/hlc/HLC.tla (or the corresponding M2..M5 module once landed) and the design doc in the same PR. The tla-check workflow runs the TLC model check on the same paths.


@claude review please verify TLA+ spec divergence per the checklist above.

@codex review please verify TLA+ spec divergence per the checklist above.

@chatgpt-codex-connector

Copy link
Copy Markdown

To use Codex here, create a Codex account and connect to github.

@bootjp bootjp marked this pull request as ready for review July 11, 2026 04:15
@github-actions

Copy link
Copy Markdown
Contributor

TLA+ spec divergence review (auto-triggered)

This PR touches files that the TLA+ safety spec has an anchor on (per
docs/design/2026_05_28_implemented_tla_safety_spec.md §3),
so an AI review is requested below to verify the implementation has not drifted
from the model.

Anchored files changed in this PR head (296fe03):

  • kv/sharded_coordinator.go

What to check, by subsystem:

  • kv/hlc*.goNext() must respect the HLC-4 preconditions (i)/(ii)/(iii) from the design doc: bounded skew, logical-counter handoff on leader change (strategy (c) Observe(MaxAppliedHLC)), and the commit-time ceiling fence (fail-closed when wall_now >= physicalCeiling). Any change to the bit layout (48/16), the CAS loop, or the ceiling getter/setter is in scope.
  • kv/coordinator.go, kv/sharded_coordinator.goRunHLCLeaseRenewal, hlcRenewalInterval, hlcPhysicalWindowMs constants, and the new-term detection that calls Observe(fsm.MaxAppliedHLC()) (strategy (c)). Any change to renewal cadence, group selection, or fail-closed behaviour is in scope.
  • kv/transaction.go, kv/lock_resolver.go — OCC commit-ts assignment, lock-map encoding (key, lock_ts) -> start_ts, and the LockResolver action OCC-3 depends on. (M2 spec will land OCC-1..OCC-5; until then the spec doc §5.2 is the contract.)
  • kv/fsm.go — FSM apply of HLC lease entries (SetPhysicalCeiling), and any future MaxAppliedHLC() accessor that strategy (c) needs.
  • store/mvcc_store.go — version visibility, snapshot install, and the MVCC-1..MVCC-4 invariants (M3 scope).
  • distribution/** — route catalog versioning, SplitRange atomicity, and CatalogWatcher async fan-out (M4 scope).

If the change is correct but requires a spec update, edit tla/hlc/HLC.tla (or the corresponding M2..M5 module once landed) and the design doc in the same PR. The tla-check workflow runs the TLC model check on the same paths.


@claude review please verify TLA+ spec divergence per the checklist above.

@codex review please verify TLA+ spec divergence per the checklist above.

@chatgpt-codex-connector

Copy link
Copy Markdown

To use Codex here, create a Codex account and connect to github.

@gemini-code-assist gemini-code-assist Bot 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.

Code Review

This pull request reserves and bootstraps a dedicated Raft group (ID 0) for the Centralized Timestamp Oracle (TSO). It updates the ShardedCoordinator to pin timestamp issuance leadership to this dedicated group when configured, ensures that shard ranges cannot route user data to group 0, and updates the design documentation and tests accordingly. There are no review comments, so we have no additional feedback to provide.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 296fe03024

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread shard_config.go
Comment thread shard_config.go
Comment thread main.go Outdated
@bootjp

bootjp commented Jul 11, 2026

Copy link
Copy Markdown
Owner Author

Addressed the current-head dedicated TSO group findings.

Changes:

  • Exclude the reserved TSO group from configured all-shard data paths, so LeaseReadAllGroups and DEL_PREFIX broadcasts only touch data groups.
  • Reject --sqsFifoPartitionMap entries that route a partition to reserved group 0.
  • Keep data-shard leaders eligible to issue local timestamps until a TSO-leader redirect path exists.

Caller audit:

  • WithAllShardGroups is wired only from runtime config using dataGroupIDs(cfg.groups), which excludes group 0.
  • LeaseReadAllGroups and DEL_PREFIX broadcast are the only all-shard coordinator paths using the configured all-shard group set.
  • WithTimestampGroup remains available for future redirected TSO serving but is no longer wired by configureCoordinatorTSO.

Verification:

  • go test . -run 'Test(BuildSQSFifoPartitionMapRejectsDedicatedTSOGroup|DataGroupIDsExcludeDedicatedTSOGroup|ParseRuntimeConfigAllowsDedicatedTSOGroupWithoutDataRoute|DefaultGroupID|ValidateShardRanges)' -count=1 -timeout=120s\n- go test ./kv -run 'TestShardedCoordinator(LeaseReadAllGroups_UsesConfiguredAllShardGroups|DelPrefixBroadcast_UsesConfiguredAllShardGroups|DedicatedGroupDoesNotBlockDataLeaderTimestampBridge|UsesDedicatedTimestampGroupLeader)' -count=1 -timeout=120s\n- go test . -count=1 -timeout=180s\n- go test ./kv -count=1 -timeout=240s\n- go test ./... -run '^$' -count=1 -timeout=300s\n- golangci-lint run --timeout=5m\n- git diff --check\n- git verify-commit HEAD\n\n@codex review

@github-actions

Copy link
Copy Markdown
Contributor

TLA+ spec divergence review (auto-triggered)

This PR touches files that the TLA+ safety spec has an anchor on (per
docs/design/2026_05_28_implemented_tla_safety_spec.md §3),
so an AI review is requested below to verify the implementation has not drifted
from the model.

Anchored files changed in this PR head (333d12a):

  • kv/sharded_coordinator.go

What to check, by subsystem:

  • kv/hlc*.goNext() must respect the HLC-4 preconditions (i)/(ii)/(iii) from the design doc: bounded skew, logical-counter handoff on leader change (strategy (c) Observe(MaxAppliedHLC)), and the commit-time ceiling fence (fail-closed when wall_now >= physicalCeiling). Any change to the bit layout (48/16), the CAS loop, or the ceiling getter/setter is in scope.
  • kv/coordinator.go, kv/sharded_coordinator.goRunHLCLeaseRenewal, hlcRenewalInterval, hlcPhysicalWindowMs constants, and the new-term detection that calls Observe(fsm.MaxAppliedHLC()) (strategy (c)). Any change to renewal cadence, group selection, or fail-closed behaviour is in scope.
  • kv/transaction.go, kv/lock_resolver.go — OCC commit-ts assignment, lock-map encoding (key, lock_ts) -> start_ts, and the LockResolver action OCC-3 depends on. (M2 spec will land OCC-1..OCC-5; until then the spec doc §5.2 is the contract.)
  • kv/fsm.go — FSM apply of HLC lease entries (SetPhysicalCeiling), and any future MaxAppliedHLC() accessor that strategy (c) needs.
  • store/mvcc_store.go — version visibility, snapshot install, and the MVCC-1..MVCC-4 invariants (M3 scope).
  • distribution/** — route catalog versioning, SplitRange atomicity, and CatalogWatcher async fan-out (M4 scope).

If the change is correct but requires a spec update, edit tla/hlc/HLC.tla (or the corresponding M2..M5 module once landed) and the design doc in the same PR. The tla-check workflow runs the TLC model check on the same paths.


@claude review please verify TLA+ spec divergence per the checklist above.

@codex review please verify TLA+ spec divergence per the checklist above.

@chatgpt-codex-connector

Copy link
Copy Markdown

To use Codex here, create a Codex account and connect to github.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 333d12a022

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +38 to +39
and `--tsoEnabled` pins timestamp issuance leadership to group 0 when that
group is present. Existing `--raftGroups` / `--raftGroupPeers` bootstrap the

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3 Badge Align TSO docs with bridge leadership behavior

This says --tsoEnabled pins timestamp leadership to group 0 when that group is present, but this commit deliberately leaves WithTimestampGroup(0) unwired in configureCoordinatorTSO, so LocalTSOAllocator still accepts any locally-led data shard via IsTimestampLeader. For deployments adding reserved group 0, the doc now describes a stricter timestamp authority than the code actually enforces, which can mislead rollout planning and incident diagnosis until the redirect path exists.

Useful? React with 👍 / 👎.

Comment thread main.go Outdated
}

func validateSQSFifoPartitionMapNoDedicatedTSOGroup(partitionMap map[string]sqsFifoQueueRouting) error {
for queue, routing := range partitionMap {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3 Badge Sort queues before validating reserved TSO routes

When a config contains more than one queue that routes a partition to group 0, this new validation returns whichever queue Go's randomized map iteration visits first. The existing validateSQSFifoPartitionMap sorts queue names specifically to keep operator diagnostics and golden-test assertions deterministic, so multi-error configs can become flaky here; iterate over sorted queue keys before checking the reserved group.

Useful? React with 👍 / 👎.

@bootjp

bootjp commented Jul 13, 2026

Copy link
Copy Markdown
Owner Author

@codex review

対応しました。

  • group 0 reserved TSO validation for SQS FIFO partition maps now sorts queue names before returning the first error, matching the deterministic diagnostics used by validateSQSFifoPartitionMap.
  • The centralized TSO design doc now reflects the current bridge behavior: group 0 is reserved and warmed, but --tsoEnabled still issues timestamps from locally led data shards until TSO-leader redirect exists.

検証:

  • go test . -run 'TestBuildSQSFifoPartitionMapRejectsDedicatedTSOGroup|TestParseRuntimeConfigAllowsDedicatedTSOGroupWithoutDataRoute|TestDataGroupIDsExcludeDedicatedTSOGroup' -count=1 -timeout=180s
  • go test . -count=1 -timeout=300s
  • go test ./... -run '^$' -count=1 -timeout=300s
  • golangci-lint run . --timeout=5m
  • git diff --check
  • git verify-commit HEAD

@github-actions

Copy link
Copy Markdown
Contributor

TLA+ spec divergence review (auto-triggered)

This PR touches files that the TLA+ safety spec has an anchor on (per
docs/design/2026_05_28_implemented_tla_safety_spec.md §3),
so an AI review is requested below to verify the implementation has not drifted
from the model.

Anchored files changed in this PR head (e776b16):

  • kv/sharded_coordinator.go

What to check, by subsystem:

  • kv/hlc*.goNext() must respect the HLC-4 preconditions (i)/(ii)/(iii) from the design doc: bounded skew, logical-counter handoff on leader change (strategy (c) Observe(MaxAppliedHLC)), and the commit-time ceiling fence (fail-closed when wall_now >= physicalCeiling). Any change to the bit layout (48/16), the CAS loop, or the ceiling getter/setter is in scope.
  • kv/coordinator.go, kv/sharded_coordinator.goRunHLCLeaseRenewal, hlcRenewalInterval, hlcPhysicalWindowMs constants, and the new-term detection that calls Observe(fsm.MaxAppliedHLC()) (strategy (c)). Any change to renewal cadence, group selection, or fail-closed behaviour is in scope.
  • kv/transaction.go, kv/lock_resolver.go — OCC commit-ts assignment, lock-map encoding (key, lock_ts) -> start_ts, and the LockResolver action OCC-3 depends on. (M2 spec will land OCC-1..OCC-5; until then the spec doc §5.2 is the contract.)
  • kv/fsm.go — FSM apply of HLC lease entries (SetPhysicalCeiling), and any future MaxAppliedHLC() accessor that strategy (c) needs.
  • store/mvcc_store.go — version visibility, snapshot install, and the MVCC-1..MVCC-4 invariants (M3 scope).
  • distribution/** — route catalog versioning, SplitRange atomicity, and CatalogWatcher async fan-out (M4 scope).

If the change is correct but requires a spec update, edit tla/hlc/HLC.tla (or the corresponding M2..M5 module once landed) and the design doc in the same PR. The tla-check workflow runs the TLC model check on the same paths.


@claude review please verify TLA+ spec divergence per the checklist above.

@codex review please verify TLA+ spec divergence per the checklist above.

@chatgpt-codex-connector

Copy link
Copy Markdown

To use Codex here, create a Codex account and connect to github.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e776b16e62

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread kv/sharded_coordinator.go Outdated
Comment on lines 1623 to 1627
if c.timestampGroupConfigured {
return isLeaderEngine(engineForGroup(c.groups[c.timestampGroup]))
}
for _, g := range c.groups {
if isLeaderEngine(engineForGroup(g)) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Exclude reserved TSO group from bridge leader checks

When --tsoEnabled is used in the current bridge path, configureCoordinatorTSO deliberately does not call WithTimestampGroup, so LocalTSOAllocator.IsLeader falls through to this method's unpinned scan. Because that scan still considers every entry in c.groups, a process that leads only reserved group 0 now reports itself as a timestamp leader and can serve timestamps before the TSO-leader redirect path exists, adding group 0 as another independent issuer despite the bridge being intended to use locally led data shards only. Filter the fallback to the configured data groups (or otherwise skip group 0) when timestampGroupConfigured is false.

Useful? React with 👍 / 👎.

Comment thread shard_config.go
Comment on lines +486 to +487
if g.id == dedicatedTSORaftGroupID {
continue

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Preserve single-group data dir when adding reserved TSO group

When an existing single-group deployment adds only the reserved group 0 (for example changing from group 1 to groups 0+1), this new acceptance path makes the config valid but runtimeConfig.multi is still computed from len(groups) > 1; buildShardGroups then passes multi=true to groupDataDir, moving group 1 from the existing base/raftID store to base/raftID/group-1. That makes the upgraded data group start from an empty/new directory instead of its existing Raft/MVCC state. Derive multi from data groups or otherwise keep group 1 on the legacy path when group 0 is the only added group.

Useful? React with 👍 / 👎.

@github-actions

Copy link
Copy Markdown
Contributor

TLA+ spec divergence review (auto-triggered)

This PR touches files that the TLA+ safety spec has an anchor on (per
docs/design/2026_05_28_implemented_tla_safety_spec.md §3),
so an AI review is requested below to verify the implementation has not drifted
from the model.

Anchored files changed in this PR head (438fa9d):

  • kv/sharded_coordinator.go

What to check, by subsystem:

  • kv/hlc*.goNext() must respect the HLC-4 preconditions (i)/(ii)/(iii) from the design doc: bounded skew, logical-counter handoff on leader change (strategy (c) Observe(MaxAppliedHLC)), and the commit-time ceiling fence (fail-closed when wall_now >= physicalCeiling). Any change to the bit layout (48/16), the CAS loop, or the ceiling getter/setter is in scope.
  • kv/coordinator.go, kv/sharded_coordinator.goRunHLCLeaseRenewal, hlcRenewalInterval, hlcPhysicalWindowMs constants, and the new-term detection that calls Observe(fsm.MaxAppliedHLC()) (strategy (c)). Any change to renewal cadence, group selection, or fail-closed behaviour is in scope.
  • kv/transaction.go, kv/lock_resolver.go — OCC commit-ts assignment, lock-map encoding (key, lock_ts) -> start_ts, and the LockResolver action OCC-3 depends on. (M2 spec will land OCC-1..OCC-5; until then the spec doc §5.2 is the contract.)
  • kv/fsm.go — FSM apply of HLC lease entries (SetPhysicalCeiling), and any future MaxAppliedHLC() accessor that strategy (c) needs.
  • store/mvcc_store.go — version visibility, snapshot install, and the MVCC-1..MVCC-4 invariants (M3 scope).
  • distribution/** — route catalog versioning, SplitRange atomicity, and CatalogWatcher async fan-out (M4 scope).

If the change is correct but requires a spec update, edit tla/hlc/HLC.tla (or the corresponding M2..M5 module once landed) and the design doc in the same PR. The tla-check workflow runs the TLC model check on the same paths.


@claude review please verify TLA+ spec divergence per the checklist above.

@codex review please verify TLA+ spec divergence per the checklist above.

@bootjp

bootjp commented Jul 13, 2026

Copy link
Copy Markdown
Owner Author

@codex review

対応しました。

  • group 0 を IsTimestampLeader の bridge fallback から除外し、WithAllShardGroups 設定済みの場合も data group だけを timestamp bridge 候補にしました。
  • runtimeConfig.multi を全 group 数ではなく data group 数から導出し、group 0 だけを追加する既存 single-data-group deployment では data group の legacy base/raftID path を維持します。
  • group 0 自体は single-data-group mode でも base/raftID/group-0 に隔離し、legacy data dir との衝突を避けます。
  • design doc の実装ステータスもこの data-dir 互換性に合わせました。

Caller audit:

  • rg -n "groupDataDir\(" .
  • rg -n "IsTimestampLeader\(|timestampBridgeCandidateGroupIDs\(|WithTimestampGroup\(|WithAllShardGroups\(" .

検証:

  • go test . -run 'TestGroupDataDir|TestParseRuntimeConfigAllowsDedicatedTSOGroupWithoutDataRoute|TestParseRuntimeConfigMultipleDataGroupsEnableMultiDataDirs|TestDataGroupIDsExcludeDedicatedTSOGroup|TestBuildSQSFifoPartitionMapRejectsDedicatedTSOGroup' -count=1 -timeout=180s
  • go test ./kv -run 'TestShardedCoordinatorReportsAnyShardAsTimestampLeader|TestShardedCoordinatorDedicatedGroupDoesNotBlockDataLeaderTimestampBridge|TestShardedCoordinatorTimestampBridgeIgnoresReservedGroupLeader|TestShardedCoordinatorUsesDedicatedTimestampGroupLeader' -count=1 -timeout=180s
  • go test . ./kv -count=1 -timeout=300s
  • go test ./... -run '^$' -count=1 -timeout=300s
  • golangci-lint run . ./kv --timeout=5m
  • git diff --check
  • git verify-commit HEAD

@chatgpt-codex-connector

Copy link
Copy Markdown

To use Codex here, create a Codex account and connect to github.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

Reviewed commit: 438fa9dab6

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@github-actions

Copy link
Copy Markdown
Contributor

TLA+ spec divergence review (auto-triggered)

This PR touches files that the TLA+ safety spec has an anchor on (per
docs/design/2026_05_28_implemented_tla_safety_spec.md §3),
so an AI review is requested below to verify the implementation has not drifted
from the model.

Anchored files changed in this PR head (7c12731):

  • kv/sharded_coordinator.go

What to check, by subsystem:

  • kv/hlc*.goNext() must respect the HLC-4 preconditions (i)/(ii)/(iii) from the design doc: bounded skew, logical-counter handoff on leader change (strategy (c) Observe(MaxAppliedHLC)), and the commit-time ceiling fence (fail-closed when wall_now >= physicalCeiling). Any change to the bit layout (48/16), the CAS loop, or the ceiling getter/setter is in scope.
  • kv/coordinator.go, kv/sharded_coordinator.goRunHLCLeaseRenewal, hlcRenewalInterval, hlcPhysicalWindowMs constants, and the new-term detection that calls Observe(fsm.MaxAppliedHLC()) (strategy (c)). Any change to renewal cadence, group selection, or fail-closed behaviour is in scope.
  • kv/transaction.go, kv/lock_resolver.go — OCC commit-ts assignment, lock-map encoding (key, lock_ts) -> start_ts, and the LockResolver action OCC-3 depends on. (M2 spec will land OCC-1..OCC-5; until then the spec doc §5.2 is the contract.)
  • kv/fsm.go — FSM apply of HLC lease entries (SetPhysicalCeiling), and any future MaxAppliedHLC() accessor that strategy (c) needs.
  • store/mvcc_store.go — version visibility, snapshot install, and the MVCC-1..MVCC-4 invariants (M3 scope).
  • distribution/** — route catalog versioning, SplitRange atomicity, and CatalogWatcher async fan-out (M4 scope).

If the change is correct but requires a spec update, edit tla/hlc/HLC.tla (or the corresponding M2..M5 module once landed) and the design doc in the same PR. The tla-check workflow runs the TLC model check on the same paths.


@claude review please verify TLA+ spec divergence per the checklist above.

@codex review please verify TLA+ spec divergence per the checklist above.

@chatgpt-codex-connector

Copy link
Copy Markdown

To use Codex here, create a Codex account and connect to github.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick comments (4)
kv/sharded_coordinator.go (2)

478-484: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

スライスのコピーに slices.Clone を使用する

Go 1.21以降では、append を用いたコピーの代わりに slices.Clone を使用することで、スライスの複製をより意図が明確で簡潔に記述できます。

♻️ 修正案
 func (c *ShardedCoordinator) WithAllShardGroups(groupIDs ...uint64) *ShardedCoordinator {
-	c.allShardGroupIDs = append([]uint64(nil), groupIDs...)
+	c.allShardGroupIDs = slices.Clone(groupIDs)
 	slices.Sort(c.allShardGroupIDs)
 	c.allShardGroupIDs = slices.Compact(c.allShardGroupIDs)
 	c.allShardGroupsConfigured = true
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@kv/sharded_coordinator.go` around lines 478 - 484, WithAllShardGroups should
use slices.Clone(groupIDs) instead of append([]uint64(nil), groupIDs...) when
copying the input slice, while preserving the existing sorting, compaction,
configuration flag, and return behavior.

1794-1810: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

マップキーの抽出とソートを簡略化する

Go 1.23以降で利用可能な slices.Sortedmaps.Keys を活用することで、手動で行っているキーの抽出とソート処理を1行で簡潔に記述できます。

※ 適用する場合は、importブロックに "maps" パッケージの追加が必要です。

♻️ 修正案
 func (c *ShardedCoordinator) ownedAllShardGroups() ([]*ShardGroup, error) {
-	gids := make([]uint64, 0, len(c.groups))
-	for gid := range c.groups {
-		gids = append(gids, gid)
-	}
-	slices.Sort(gids)
+	gids := slices.Sorted(maps.Keys(c.groups))
 	out := make([]*ShardGroup, 0, len(gids))
 	for _, gid := range gids {
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@kv/sharded_coordinator.go` around lines 1794 - 1810, In ownedAllShardGroups,
replace the manual gid collection and sorting with maps.Keys followed by
slices.Sorted, adding the maps import if needed. Preserve the existing iteration
order, nil-group ErrLeaderNotFound handling, and returned shard groups.
multiraft_runtime_test.go (1)

75-78: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

require.NoDirExists の使用を検討してください。

os.Statos.IsNotExist を用いた冗長なエラーチェックの代わりに、Testifyの require.NoDirExists を使用することで、アサーションの意図を明確にしつつ記述を簡潔にできます。

♻️ 提案するリファクタリング
-	if _, err := os.Stat(filepath.Join(legacyDir, "group-1")); !os.IsNotExist(err) {
-		require.NoError(t, err)
-		t.Fatalf("group 1 should stay in legacy dir, but group-1 dir exists")
-	}
+	require.NoDirExists(t, filepath.Join(legacyDir, "group-1"), "group 1 should stay in legacy dir")
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@multiraft_runtime_test.go` around lines 75 - 78, Replace the manual
os.Stat/os.IsNotExist check for filepath.Join(legacyDir, "group-1") with
Testify’s require.NoDirExists assertion, preserving the test’s expectation that
the directory does not exist and removing the redundant failure handling.
shard_config_test.go (1)

308-331: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

テーブル駆動テスト (Table-driven tests) の活用を検討してください。

コーディングガイドラインにて「Goのユニットテストではテーブル駆動テストを優先すること」が定められています。以下の箇所において、複数のケースが独立したテスト関数や個別の t.Run として列挙されています。テストケースを構造体のスライス(テーブル)としてまとめ、ループ処理で実行するようにリファクタリングすることで、今後のケース追加や保守が容易になります。

  • shard_config_test.go#L308-L331: TestBuildSQSFifoPartitionMap... の2つのテスト関数を、1つのテーブル駆動テストに統合してください。
  • multiraft_runtime_test.go#L23-L30: TestGroupDataDir 内の個別の t.Run 呼び出しを、スライスを用いたテーブル駆動テストの形式へ変更してください。
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@shard_config_test.go` around lines 308 - 331, Refactor the two SQS FIFO
partition-map tests in shard_config_test.go (lines 308-331) into one
table-driven TestBuildSQSFifoPartitionMap test, preserving each case’s input and
assertions while running them through subtests. Also update TestGroupDataDir in
multiraft_runtime_test.go (lines 23-30) to define its cases in a slice and
iterate over them with t.Run; both sites require direct changes.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@kv/sharded_coordinator.go`:
- Around line 478-484: WithAllShardGroups should use slices.Clone(groupIDs)
instead of append([]uint64(nil), groupIDs...) when copying the input slice,
while preserving the existing sorting, compaction, configuration flag, and
return behavior.
- Around line 1794-1810: In ownedAllShardGroups, replace the manual gid
collection and sorting with maps.Keys followed by slices.Sorted, adding the maps
import if needed. Preserve the existing iteration order, nil-group
ErrLeaderNotFound handling, and returned shard groups.

In `@multiraft_runtime_test.go`:
- Around line 75-78: Replace the manual os.Stat/os.IsNotExist check for
filepath.Join(legacyDir, "group-1") with Testify’s require.NoDirExists
assertion, preserving the test’s expectation that the directory does not exist
and removing the redundant failure handling.

In `@shard_config_test.go`:
- Around line 308-331: Refactor the two SQS FIFO partition-map tests in
shard_config_test.go (lines 308-331) into one table-driven
TestBuildSQSFifoPartitionMap test, preserving each case’s input and assertions
while running them through subtests. Also update TestGroupDataDir in
multiraft_runtime_test.go (lines 23-30) to define its cases in a slice and
iterate over them with t.Run; both sites require direct changes.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 446a4707-ef50-47fe-9996-a7612e07637b

📥 Commits

Reviewing files that changed from the base of the PR and between 296fe03 and 7c12731.

📒 Files selected for processing (11)
  • docs/design/2026_04_16_partial_centralized_tso.md
  • kv/sharded_coordinator.go
  • kv/sharded_coordinator_leader_test.go
  • kv/sharded_coordinator_txn_test.go
  • kv/tso_test.go
  • main.go
  • main_encryption_startup_guard.go
  • multiraft_runtime.go
  • multiraft_runtime_test.go
  • shard_config.go
  • shard_config_test.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • shard_config.go
  • docs/design/2026_04_16_partial_centralized_tso.md

@bootjp

bootjp commented Jul 14, 2026

Copy link
Copy Markdown
Owner Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. More of your lovely PRs please.

Reviewed commit: 7c12731f90

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant