Skip to content

keyspace: get keyspace name from env#68103

Open
ystaticy wants to merge 7 commits into
pingcap:masterfrom
ystaticy:keyspace_env
Open

keyspace: get keyspace name from env#68103
ystaticy wants to merge 7 commits into
pingcap:masterfrom
ystaticy:keyspace_env

Conversation

@ystaticy
Copy link
Copy Markdown
Contributor

@ystaticy ystaticy commented Apr 29, 2026

What problem does this PR solve?

Issue Number: close #xxx

Problem Summary:

What changed and how does it work?

Check List

Tests

  • Unit test
  • Integration test
  • Manual test (add detailed scripts or steps below)
  • No need to test
    • I checked and no code files have been changed.

Side effects

  • Performance regression: Consumes more CPU
  • Performance regression: Consumes more Memory
  • Breaking backward compatibility

Documentation

  • Affects user behaviors
  • Contains syntax changes
  • Contains variable changes
  • Contains experimental features
  • Changes MySQL compatibility

Release note

Please refer to Release Notes Language Style Guide to write a quality release note.

None

Summary by CodeRabbit

  • New Features

    • Keyspace name now falls back to an environment variable when not set and the resolved value is persisted to global settings for consistent retrieval.
    • Byte-returning keyspace accessor now uses the same resolved setting as the string accessor for consistent behavior.
  • Tests

    • Expanded tests covering empty, env-fallback, deploy-mode, and accessor-order scenarios.

Review Change Stack

Cherry-pick the behavior from tidbcloud/tidb-cse#1909 and adapt it to the current TiDB tree. Also cover the env fallback in pkg/keyspace tests.
@ti-chi-bot ti-chi-bot Bot added do-not-merge/needs-linked-issue do-not-merge/needs-tests-checked release-note-none Denotes a PR that doesn't merit a release note. size/M Denotes a PR that changes 30-99 lines, ignoring generated files. labels Apr 29, 2026
@ystaticy ystaticy changed the title keyspace: get keyspace name from env when config is empty keyspace: get keyspace name from env Apr 29, 2026
@ti-chi-bot
Copy link
Copy Markdown

ti-chi-bot Bot commented Apr 29, 2026

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by:
Once this PR has been reviewed and has the lgtm label, please assign hongyunyan for approval. For more information see the Code Review Process.
Please ensure that each of them provides their approval before proceeding.

The full list of commands accepted by this bot can be found here.

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@tiprow
Copy link
Copy Markdown

tiprow Bot commented Apr 29, 2026

Hi @ystaticy. Thanks for your PR.

PRs from untrusted users cannot be marked as trusted with /ok-to-test in this repo meaning untrusted PR authors can never trigger tests themselves. Collaborators can still trigger tests on the PR using /test all.

I understand the commands that are listed here.

Details

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 29, 2026

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 4dfcbf1a-0f6d-4b8b-9eb6-dee91621e3eb

📥 Commits

Reviewing files that changed from the base of the PR and between 8f41b0f and 7d6cd80.

📒 Files selected for processing (1)
  • pkg/keyspace/keyspace_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • pkg/keyspace/keyspace_test.go

📝 Walkthrough

Walkthrough

GetKeyspaceNameBySettings returns the global keyspace name when set; otherwise, if in starter mode it reads config.EnvVarKeyspaceName from the environment, persists it via config.UpdateGlobal, and returns it. GetKeyspaceNameBytesBySettings now calls GetKeyspaceNameBySettings().

Changes

Keyspace name resolution

Layer / File(s) Summary
Resolve and persist keyspace name
pkg/keyspace/keyspace.go, pkg/keyspace/BUILD.bazel
Adds os and config/deploymode imports; GetKeyspaceNameBySettings short-circuits on a non-empty global name, returns empty when not in starter mode, otherwise reads config.EnvVarKeyspaceName from the environment and persists it via config.UpdateGlobal. Updates Bazel deps to include //pkg/config/deploymode. GetKeyspaceNameBytesBySettings now calls GetKeyspaceNameBySettings() for consistent behavior.
Tests: cache reset and env/config scenarios
pkg/keyspace/keyspace_test.go
Adds deploymode import and helpers to reset keyspace-name caches and snapshot/restore global config; splits TestNoKeyspaceNameSet into subtests covering empty env/config, env fallback persistence, config-over-env precedence, bytes-first behavior, and non-starter mode.
sequenceDiagram
  participant Caller
  participant GetKeyspaceNameBySettings
  participant OS as os.Getenv
  participant Config as config.UpdateGlobal
  Caller->>GetKeyspaceNameBySettings: request keyspace name
  GetKeyspaceNameBySettings-->>Config: config.GetGlobalKeyspaceName() (check)
  alt global empty
    GetKeyspaceNameBySettings->>OS: os.Getenv(config.EnvVarKeyspaceName)
    OS-->>GetKeyspaceNameBySettings: env value
    GetKeyspaceNameBySettings->>Config: config.UpdateGlobal(conf.KeyspaceName = env value)
    GetKeyspaceNameBySettings-->>Caller: return env value
  else global set
    GetKeyspaceNameBySettings-->>Caller: return global value
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐰 I sniff the env for names at dawn,
If config sleeps, I bring it on;
I write it down and tuck it tight,
Reset the cache and test by night,
Hop back—your keyspace is not gone.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The PR description is largely incomplete; it contains only the template with empty/unchecked sections and placeholder values like 'close #xxx', with no actual problem statement, implementation details, or rationale provided. Fill in the description with: a valid issue number, a clear problem statement, explanation of the changes and how they work, check the appropriate test checklist items, and update the release note if applicable.
Docstring Coverage ⚠️ Warning Docstring coverage is 40.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely summarizes the main change: enabling keyspace name to be read from an environment variable, which matches the implementation in the raw_summary.
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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 and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@pkg/keyspace/keyspace_test.go`:
- Around line 55-99: Before mutating global state with config.UpdateGlobal in
the subtests, capture a snapshot copy of the current global config (e.g., copy
the config.Config struct) and register a t.Cleanup that restores it by calling
config.UpdateGlobal(func(conf *config.Config){ *conf = savedCopy }) and also
invokes resetKeyspaceNameCache to clear the cached bytes; apply this to both
subtests that call config.UpdateGlobal so GetKeyspaceNameBySettings,
GetKeyspaceNameBytesBySettings and IsKeyspaceNameEmpty do not leave process-wide
state changed for later tests.

In `@pkg/keyspace/keyspace.go`:
- Around line 61-68: GetKeyspaceNameBytesBySettings currently reads
config.GetGlobalKeyspaceName() directly and caches that value with sync.Once,
which can permanently cache an empty string and bypass the env fallback
implemented by GetKeyspaceNameBySettings; update GetKeyspaceNameBytesBySettings
to call GetKeyspaceNameBySettings() (the string getter) and then convert that
returned string to []byte for caching, ensuring the env var fallback
(config.EnvVarKeyspaceName) is respected and avoiding a stale empty cache;
retain the sync.Once caching but base it on the string getter's result so
callers like pkg/sessionctx/stmtctx and pkg/executor get the correct value.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: ed711854-42c3-415a-a99f-e64ff2fed247

📥 Commits

Reviewing files that changed from the base of the PR and between 49c7713 and af69cd5.

📒 Files selected for processing (2)
  • pkg/keyspace/keyspace.go
  • pkg/keyspace/keyspace_test.go

Comment thread pkg/keyspace/keyspace_test.go
Comment thread pkg/keyspace/keyspace.go
@codecov
Copy link
Copy Markdown

codecov Bot commented Apr 29, 2026

Codecov Report

❌ Patch coverage is 33.33333% with 8 lines in your changes missing coverage. Please review.
✅ Project coverage is 75.7524%. Comparing base (5ffa989) to head (7d6cd80).
⚠️ Report is 11 commits behind head on master.

Additional details and impacted files
@@               Coverage Diff                @@
##             master     #68103        +/-   ##
================================================
- Coverage   77.2803%   75.7524%   -1.5279%     
================================================
  Files          2010       2008         -2     
  Lines        555624     565159      +9535     
================================================
- Hits         429388     428122      -1266     
- Misses       125316     136797     +11481     
+ Partials        920        240       -680     
Flag Coverage Δ
integration 41.5153% <33.3333%> (+1.7212%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

Components Coverage Δ
dumpling 60.4888% <ø> (ø)
parser ∅ <ø> (∅)
br 49.9725% <ø> (-13.0354%) ⬇️
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@ystaticy
Copy link
Copy Markdown
Contributor Author

/test check-dev2

@tiprow
Copy link
Copy Markdown

tiprow Bot commented May 13, 2026

@ystaticy: PRs from untrusted users cannot be marked as trusted with /ok-to-test in this repo meaning untrusted PR authors can never trigger tests themselves. Collaborators can still trigger tests on the PR using /test.

Details

In response to this:

/test check-dev2

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository.

ystaticy added 2 commits May 13, 2026 12:12
Signed-off-by: ystaticy <y_static_y@sina.com>
Signed-off-by: ystaticy <y_static_y@sina.com>
@ti-chi-bot ti-chi-bot Bot added size/L Denotes a PR that changes 100-499 lines, ignoring generated files. and removed size/M Denotes a PR that changes 30-99 lines, ignoring generated files. labels May 13, 2026
ystaticy added 3 commits May 18, 2026 18:36
Signed-off-by: ystaticy <y_static_y@sina.com>
Signed-off-by: ystaticy <y_static_y@sina.com>
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
pkg/keyspace/keyspace.go (1)

66-73: ⚡ Quick win

Gate the starter/env fallback on NextGen too.

This path now consults deploymode.IsStarter() even when kerneltype.IsNextGen() is false, while the new tests explicitly treat deploy mode as nextgen-only. Leaving it like this makes non-nextgen behavior depend on the deploy-mode default and can still pull KEYSPACE_NAME into GetKeyspaceNameBySettings() unexpectedly.

Suggested change
-	if !deploymode.IsStarter() {
+	if !kerneltype.IsNextGen() || !deploymode.IsStarter() {
 		return ""
 	}
🤖 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 `@pkg/keyspace/keyspace.go` around lines 66 - 73, The current guard only checks
deploymode.IsStarter() before reading KEYSPACE_NAME and updating the global
config; change the condition to require both deploymode.IsStarter() and
kerneltype.IsNextGen() so the starter/env fallback is only applied for NextGen
kernels. Modify the conditional around the os.Getenv(config.EnvVarKeyspaceName)
and config.UpdateGlobal(...) in keyspace.go (the block that currently checks
deploymode.IsStarter()) to also call kerneltype.IsNextGen(), ensuring
GetKeyspaceNameBySettings() no longer picks up KEYSPACE_NAME in non-NextGen
modes.
🤖 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 `@pkg/keyspace/keyspace.go`:
- Around line 66-73: The current guard only checks deploymode.IsStarter() before
reading KEYSPACE_NAME and updating the global config; change the condition to
require both deploymode.IsStarter() and kerneltype.IsNextGen() so the
starter/env fallback is only applied for NextGen kernels. Modify the conditional
around the os.Getenv(config.EnvVarKeyspaceName) and config.UpdateGlobal(...) in
keyspace.go (the block that currently checks deploymode.IsStarter()) to also
call kerneltype.IsNextGen(), ensuring GetKeyspaceNameBySettings() no longer
picks up KEYSPACE_NAME in non-NextGen modes.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 021c0df6-da09-47a7-9c2c-e99984886709

📥 Commits

Reviewing files that changed from the base of the PR and between 36f060e and 8f41b0f.

📒 Files selected for processing (3)
  • pkg/keyspace/BUILD.bazel
  • pkg/keyspace/keyspace.go
  • pkg/keyspace/keyspace_test.go
✅ Files skipped from review due to trivial changes (1)
  • pkg/keyspace/BUILD.bazel

Signed-off-by: ystaticy <y_static_y@sina.com>
@ti-chi-bot
Copy link
Copy Markdown

ti-chi-bot Bot commented May 18, 2026

[FORMAT CHECKER NOTIFICATION]

Notice: To remove the do-not-merge/needs-linked-issue label, please provide the linked issue number on one line in the PR body, for example: Issue Number: close #123 or Issue Number: ref #456.

📖 For more info, you can check the "Contribute Code" section in the development guide.


Notice: To remove the do-not-merge/needs-tests-checked label, please finished the tests then check the finished items in description.

For example:

Tests <!-- At least one of them must be included. -->

- [x] Unit test
- [ ] Integration test
- [ ] Manual test (add detailed scripts or steps below)
- [ ] No code

‼️ Must keep the HTML comments <!-- At least one of them must be included. -->

📖 For more info, you can check the "Contribute Code" section in the development guide.

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

Labels

do-not-merge/needs-linked-issue do-not-merge/needs-tests-checked release-note-none Denotes a PR that doesn't merit a release note. size/L Denotes a PR that changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant