Skip to content

vtctl: fix nil pointer dereference in SNAPSHOT keyspace creation#19120

Merged
nickvanw merged 1 commit intomainfrom
fix-vtctl-snapshot-vschema-nil-panic
Jan 13, 2026
Merged

vtctl: fix nil pointer dereference in SNAPSHOT keyspace creation#19120
nickvanw merged 1 commit intomainfrom
fix-vtctl-snapshot-vschema-nil-panic

Conversation

@nickvanw
Copy link
Copy Markdown
Collaborator

@nickvanw nickvanw commented Jan 10, 2026

Description

When creating a SNAPSHOT keyspace, if the base keyspace has no VSchema (NoNode error), the code would set ksvs.Keyspace to an empty vschema, but then unconditionally try to clone from bksvs.Keyspace. Since bksvs is nil when GetVSchema returns an error, this causes a panic.

Fix by moving the clone into an else block so it only runs when GetVSchema succeeds. This matches the correct pattern already used in grpcvtctldserver/server.go.

Related Issue(s)

Fixes #19134

Checklist

  • "Backport to:" labels have been added if this change should be back-ported to release branches
  • If this change is to be back-ported to previous releases, a justification is included in the PR description
  • Tests were added or are not required
  • Did the new or modified tests pass consistently locally and on CI?
  • Documentation was added or is not required

Deployment Notes

AI Disclosure

This was discovered by doing some thorough analyses with AI and then validating the findings.

When creating a SNAPSHOT keyspace, if the base keyspace has no VSchema
(NoNode error), the code would set ksvs.Keyspace to an empty vschema,
but then unconditionally try to clone from bksvs.Keyspace. Since bksvs
is nil when GetVSchema returns an error, this causes a panic.

Fix by moving the clone into an else block so it only runs when
GetVSchema succeeds. This matches the correct pattern already used
in grpcvtctldserver/server.go.

Signed-off-by: Nick Van Wiggeren <nick@planetscale.com>
@vitess-bot
Copy link
Copy Markdown
Contributor

vitess-bot Bot commented Jan 10, 2026

Review Checklist

Hello reviewers! 👋 Please follow this checklist when reviewing this Pull Request.

General

  • Ensure that the Pull Request has a descriptive title.
  • Ensure there is a link to an issue (except for internal cleanup and flaky test fixes), new features should have an RFC that documents use cases and test cases.

Tests

  • Bug fixes should have at least one unit or end-to-end test, enhancement and new features should have a sufficient number of tests.

Documentation

  • Apply the release notes (needs details) label if users need to know about this change.
  • New features should be documented.
  • There should be some code comments as to why things are implemented the way they are.
  • There should be a comment at the top of each new or modified test to explain what the test does.

New flags

  • Is this flag really necessary?
  • Flag names must be clear and intuitive, use dashes (-), and have a clear help text.

If a workflow is added or modified:

  • Each item in Jobs should be named in order to mark it as required.
  • If the workflow needs to be marked as required, the maintainer team must be notified.

Backward compatibility

  • Protobuf changes should be wire-compatible.
  • Changes to _vt tables and RPCs need to be backward compatible.
  • RPC changes should be compatible with vitess-operator
  • If a flag is removed, then it should also be removed from vitess-operator and arewefastyet, if used there.
  • vtctl command output order should be stable and awk-able.

@vitess-bot vitess-bot Bot added NeedsBackportReason If backport labels have been applied to a PR, a justification is required NeedsDescriptionUpdate The description is not clear or comprehensive enough, and needs work NeedsIssue A linked issue is missing for this Pull Request NeedsWebsiteDocsUpdate What it says labels Jan 10, 2026
@github-actions github-actions Bot added this to the v24.0.0 milestone Jan 10, 2026
@vitess-bot
Copy link
Copy Markdown
Contributor

vitess-bot Bot commented Jan 10, 2026

Review Checklist

Hello reviewers! 👋 Please follow this checklist when reviewing this Pull Request.

General

  • Ensure that the Pull Request has a descriptive title.
  • Ensure there is a link to an issue (except for internal cleanup and flaky test fixes), new features should have an RFC that documents use cases and test cases.

Tests

  • Bug fixes should have at least one unit or end-to-end test, enhancement and new features should have a sufficient number of tests.

Documentation

  • Apply the release notes (needs details) label if users need to know about this change.
  • New features should be documented.
  • There should be some code comments as to why things are implemented the way they are.
  • There should be a comment at the top of each new or modified test to explain what the test does.

New flags

  • Is this flag really necessary?
  • Flag names must be clear and intuitive, use dashes (-), and have a clear help text.

If a workflow is added or modified:

  • Each item in Jobs should be named in order to mark it as required.
  • If the workflow needs to be marked as required, the maintainer team must be notified.

Backward compatibility

  • Protobuf changes should be wire-compatible.
  • Changes to _vt tables and RPCs need to be backward compatible.
  • RPC changes should be compatible with vitess-operator
  • If a flag is removed, then it should also be removed from vitess-operator and arewefastyet, if used there.
  • vtctl command output order should be stable and awk-able.

@codecov
Copy link
Copy Markdown

codecov Bot commented Jan 10, 2026

Codecov Report

❌ Patch coverage is 0% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 69.88%. Comparing base (fa770f9) to head (3e6b259).
⚠️ Report is 9 commits behind head on main.

Files with missing lines Patch % Lines
go/vt/vtctl/vtctl.go 0.00% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #19120      +/-   ##
==========================================
+ Coverage   69.87%   69.88%   +0.01%     
==========================================
  Files        1613     1613              
  Lines      216002   216024      +22     
==========================================
+ Hits       150939   150978      +39     
+ Misses      65063    65046      -17     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@nickvanw nickvanw added Type: Bug Component: vtctl and removed NeedsDescriptionUpdate The description is not clear or comprehensive enough, and needs work NeedsWebsiteDocsUpdate What it says NeedsIssue A linked issue is missing for this Pull Request NeedsBackportReason If backport labels have been applied to a PR, a justification is required labels Jan 13, 2026
@nickvanw nickvanw marked this pull request as ready for review January 13, 2026 00:35
Copy link
Copy Markdown
Member

@mattlord mattlord left a comment

Choose a reason for hiding this comment

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

The legacy vtctl[client] client has been deprecated since v18.0 (I would like to remove it entirely in v24 or v25). It's fine to fix this, I suppose... but does this same issue exist in vtctldclient?

The current/supported client implementation is here:

var createKeyspaceOptions = struct {
Force bool
AllowEmptyVSchema bool
KeyspaceType cli.KeyspaceTypeFlag
BaseKeyspace string
SnapshotTimestamp string
DurabilityPolicy string
SidecarDBName string
}{
KeyspaceType: cli.KeyspaceTypeFlag(topodatapb.KeyspaceType_NORMAL),
}
func commandCreateKeyspace(cmd *cobra.Command, args []string) error {
name := cmd.Flags().Arg(0)
switch topodatapb.KeyspaceType(createKeyspaceOptions.KeyspaceType) {
case topodatapb.KeyspaceType_NORMAL, topodatapb.KeyspaceType_SNAPSHOT:
default:
return fmt.Errorf("invalid keyspace type passed to --type: %v", createKeyspaceOptions.KeyspaceType)
}
var snapshotTime *vttime.Time
if topodatapb.KeyspaceType(createKeyspaceOptions.KeyspaceType) == topodatapb.KeyspaceType_SNAPSHOT {
if createKeyspaceOptions.DurabilityPolicy != policy.DurabilityNone {
return errors.New("--durability-policy cannot be specified while creating a snapshot keyspace")
}
if createKeyspaceOptions.BaseKeyspace == "" {
return errors.New("--base-keyspace is required for a snapshot keyspace")
}
if createKeyspaceOptions.SnapshotTimestamp == "" {
return errors.New("--snapshot-timestamp is required for a snapshot keyspace")
}
t, err := time.Parse(time.RFC3339, createKeyspaceOptions.SnapshotTimestamp)
if err != nil {
return fmt.Errorf("cannot parse --snapshot-timestamp as RFC3339: %w", err)
}
if now := time.Now(); t.After(now) {
return fmt.Errorf("--snapshot-time cannot be in the future; snapshot = %v, now = %v", t, now)
}
snapshotTime = protoutil.TimeToProto(t)
}
createKeyspaceOptions.SidecarDBName = strings.TrimSpace(createKeyspaceOptions.SidecarDBName)
if createKeyspaceOptions.SidecarDBName == "" {
return errors.New("--sidecar-db-name cannot be empty when creating a keyspace")
}
if len(createKeyspaceOptions.SidecarDBName) > mysql.MaxIdentifierLength {
return sqlerror.NewSQLErrorf(sqlerror.ERTooLongIdent, sqlerror.SSDataTooLong, "--sidecar-db-name identifier value of %q is too long (%d chars), max length for database identifiers is %d characters",
createKeyspaceOptions.SidecarDBName, len(createKeyspaceOptions.SidecarDBName), mysql.MaxIdentifierLength)
}
cli.FinishedParsing(cmd)
req := &vtctldatapb.CreateKeyspaceRequest{
Name: name,
Force: createKeyspaceOptions.Force,
AllowEmptyVSchema: createKeyspaceOptions.AllowEmptyVSchema,
Type: topodatapb.KeyspaceType(createKeyspaceOptions.KeyspaceType),
BaseKeyspace: createKeyspaceOptions.BaseKeyspace,
SnapshotTime: snapshotTime,
DurabilityPolicy: createKeyspaceOptions.DurabilityPolicy,
SidecarDbName: createKeyspaceOptions.SidecarDBName,
}
resp, err := client.CreateKeyspace(commandCtx, req)
if err != nil {
return err
}
data, err := cli.MarshalJSON(resp.Keyspace)
if err != nil {
return err
}
fmt.Printf("Successfully created keyspace %s. Result:\n%s\n", name, data)
return nil
}

And the server side implementation for the current/supported client/server implementation is here:

// CreateKeyspace is part of the vtctlservicepb.VtctldServer interface.
func (s *VtctldServer) CreateKeyspace(ctx context.Context, req *vtctldatapb.CreateKeyspaceRequest) (resp *vtctldatapb.CreateKeyspaceResponse, err error) {
span, ctx := trace.NewSpan(ctx, "VtctldServer.CreateKeyspace")
defer span.Finish()
defer panicHandler(&err)
span.Annotate("keyspace", req.Name)
span.Annotate("keyspace_type", topoproto.KeyspaceTypeLString(req.Type))
span.Annotate("force", req.Force)
span.Annotate("allow_empty_vschema", req.AllowEmptyVSchema)
span.Annotate("durability_policy", req.DurabilityPolicy)
switch req.Type {
case topodatapb.KeyspaceType_NORMAL:
case topodatapb.KeyspaceType_SNAPSHOT:
if req.BaseKeyspace == "" {
err = errors.New("BaseKeyspace is required for SNAPSHOT keyspaces")
return nil, err
}
if req.SnapshotTime == nil {
err = errors.New("SnapshotTime is required for SNAPSHOT keyspaces")
return nil, err
}
span.Annotate("base_keyspace", req.BaseKeyspace)
span.Annotate("snapshot_time", protoutil.TimeFromProto(req.SnapshotTime).String())
default:
return nil, fmt.Errorf("unknown keyspace type %v", req.Type)
}
ki := &topodatapb.Keyspace{
KeyspaceType: req.Type,
BaseKeyspace: req.BaseKeyspace,
SnapshotTime: req.SnapshotTime,
DurabilityPolicy: req.DurabilityPolicy,
SidecarDbName: req.SidecarDbName,
}
err = s.ts.CreateKeyspace(ctx, req.Name, ki)
if req.Force && topo.IsErrType(err, topo.NodeExists) {
log.Infof("keyspace %v already exists (ignoring error with Force=true)", req.Name)
err = nil
// Get the actual keyspace out of the topo; it may differ in structure,
// and we want to return the authoritative version as the "created" one
// to the client.
var ks *topo.KeyspaceInfo
ks, _ = s.ts.GetKeyspace(ctx, req.Name)
ki = ks.Keyspace
}
if err != nil {
return nil, err
}
if !req.AllowEmptyVSchema {
if err = s.ts.EnsureVSchema(ctx, req.Name); err != nil {
return nil, err
}
}
if req.Type == topodatapb.KeyspaceType_SNAPSHOT {
bksvs, err := s.ts.GetVSchema(ctx, req.BaseKeyspace)
if err != nil {
log.Infof("error from GetVSchema(%v) = %v", req.BaseKeyspace, err)
if topo.IsErrType(err, topo.NoNode) {
log.Infof("base keyspace %v does not exist; continuing with bare, unsharded vschema", req.BaseKeyspace)
bksvs = &topo.KeyspaceVSchemaInfo{
Name: req.Name,
Keyspace: &vschemapb.Keyspace{
Sharded: false,
Tables: map[string]*vschemapb.Table{},
Vindexes: map[string]*vschemapb.Vindex{},
},
}
} else {
return nil, err
}
}
// We don't want to clone the base keyspace's key version
// so we do NOT call bksvs.CloneVT() here. We instead only
// clone the vschemapb.Keyspace field for the new snapshot
// keyspace.
sksvs := &topo.KeyspaceVSchemaInfo{
Name: req.Name,
Keyspace: bksvs.Keyspace.CloneVT(),
}
// SNAPSHOT keyspaces are excluded from global routing.
sksvs.RequireExplicitRouting = true
if err = s.ts.SaveVSchema(ctx, sksvs); err != nil {
return nil, fmt.Errorf("SaveVSchema(%v) = %w", sksvs, err)
}
}
cells := []string{}
err = s.ts.RebuildSrvVSchema(ctx, cells)
if err != nil {
return nil, fmt.Errorf("RebuildSrvVSchema(%v) = %w", cells, err)
}
return &vtctldatapb.CreateKeyspaceResponse{
Keyspace: &vtctldatapb.Keyspace{
Name: req.Name,
Keyspace: ki,
},
}, nil
}

I'm guessing that by this comment:

This matches the correct pattern already used in grpcvtctldserver/server.go.

The issue does not exist in the current/supported client/server implementation. 🙂

@nickvanw
Copy link
Copy Markdown
Collaborator Author

The issue does not exist in the current/supported client/server implementation. 🙂

yep! I debated not opening this at all since it's deprecated, but once I knew it was a problem I couldn't stop myself.

@nickvanw nickvanw merged commit 3700c70 into main Jan 13, 2026
119 of 134 checks passed
@nickvanw nickvanw deleted the fix-vtctl-snapshot-vschema-nil-panic branch January 13, 2026 04:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug Report: Nil pointer panic in vtctl CreateKeyspace for SNAPSHOT keyspace when base keyspace has no VSchema

3 participants