Skip to content

vschema: Let a table declare its primary key - #50

Merged
morgo merged 6 commits into
release-24.0from
mtocker/vschema-primary-key
Nov 27, 2026
Merged

morgo merged 6 commits into
release-24.0from
mtocker/vschema-primary-key

Conversation

@morgo

@morgo morgo commented Nov 27, 2026 •

Copy link
Copy Markdown
Collaborator

Why

The planner plans a multi-shard DELETE ... LIMIT n or UPDATE ... LIMIT n as DML with input: it selects the primary keys of the matching rows, then deletes or updates by primary key.

That needs BaseTable.PrimaryKey, which is only filled in by vtgate's schema tracker today. When it is empty the planner returns VT09015: schema tracking required.

A deployment without schema tracking can already declare columns in the VSchema (columns, column_list_authoritative), but it cannot declare a primary key, so these statements can never be planned there. This adds the declarative equivalent.

What

  • proto/vschema.proto: Table gets repeated string primary_key = 8, the ordered primary-key columns. The generated Go code is regenerated. The comment states that the list must be exactly the table's primary key (or another unique key whose columns are NOT NULL in every row), because vtgate trusts it as unique and DML planned by key, such as a multi-shard DELETE/UPDATE with LIMIT, relies on it for correctness. The vtadmin web types are unchanged by the comment.
  • Field number 8 is used by this fork only. There is no upstream equivalent at the time of writing, so an upstream sync must check for a conflicting field 8 on Table. The proto comment says so.
  • vindexes.BuildVSchema copies primary_key into BaseTable.PrimaryKey. The same builder is used by ApplyVSchema validation, so no other validation path needed a change.
  • Validation: an empty column name is an error, a duplicate column name is an error (compared case-insensitively), and when column_list_authoritative is true every primary-key column must be in columns. When the column list is not authoritative, primary-key columns are not checked against it.
  • The field is accepted for every table type (including reference tables and tables with a source), in the same way columns is.
  • Schema tracking wins: when the tracker knows a table, its primary key replaces the declared one instead of being appended to it. A tracked table that has no primary key ends up with none.
  • BaseTable.PrimaryKeyTracked records the provenance: it is true only when schema tracking handled the table. It is tagged json:"-", so the JSON rendering of BaseTable does not change.
  • createOperatorFromInsert only rewrites a sharded (or foreign-key) REPLACE into delete-then-insert when index metadata came from schema tracking (PrimaryKeyTracked) or unique keys are known. A declared primary key says nothing about the table's other unique keys, so a sharded REPLACE without tracked index metadata keeps returning VT12001.

How

The builder change is in buildTables, next to the column handling. It leaves PrimaryKeyTracked false. The tracker change in VSchemaManager.updateTableInfo resets PrimaryKey before it applies the tracked primary index, and sets PrimaryKeyTracked. Without the reset the declared columns and the tracked columns would be concatenated. The AddPrimaryKey test helper stands in for schema tracking, so it sets PrimaryKeyTracked too.

Risk

Low. The field is new and optional, so existing VSchemas build exactly as before. The behavior changes for existing deployments are in updateTableInfo, where PrimaryKey is reset before the tracked primary key is applied (previously it was always empty at that point, because the VSchema builder never set it), and in createOperatorFromInsert, where the REPLACE rewrite now requires PrimaryKeyTracked (or known unique keys). Tracked tables are marked tracked, so their REPLACE planning is unchanged.

A wrong or stale declared key can make a LIMIT statement touch rows beyond the limit, because vtgate cannot validate the declaration against the database. Before this change such a table failed closed with VT09015. This is the same kind of trust the VSchema already places in column_vindexes, and it is documented on the proto field.

Rollout: a binary built before this change ignores a declared primary_key as an unknown field, so planning behaves as it did before. A client built before this change that reads a VSchema with GetVSchema and re-applies its JSON output drops primary_key, because unknown fields are discarded. New vtgates then plan with VT09015 again, so this fails closed.

Testing

  • vindexes: the field is copied in the declared order, including on a reference table with a source. Each validation error is covered, and the field round-trips through JSON ("primary_key": ["a", "b"]) and through BuildKeyspace.
  • vtgate: TestDeclaredPrimaryKeyAndSchemaTracking covers declared-only (not tracked), tracked-equal, tracked-overrides-declared and tracked-without-primary-key (tracked). It fails without the reset.
  • planbuilder: primary_key_cases.json with a dedicated test VSchema. Scatter DELETE ... LIMIT and UPDATE ... LIMIT on tables whose primary key (single and composite) comes only from the VSchema plan as DMLWithInput, and a table without a declared primary key still gives VT09015. A sharded REPLACE on a table with a declared key still gives VT12001. Unsharded DELETE/UPDATE ... LIMIT on tables with and without a declared key are passed through.
  • go build ./go/vt/vtgate/..., go vet and gofmt on the touched packages are clean. go test ./go/vt/vtgate/vindexes/... ./go/vt/vtgate/planbuilder/... ./go/vt/vtgate/ passes except as noted below.
  • TestSelectDateTypes in go/vt/vtgate fails today because it depends on the current date (a month-end rollover), and the vtgate end-to-end packages need a local MySQL. Both are unrelated to this change.

🤖 Generated with Claude Code

morgo and others added 2 commits November 27, 2026 16:50
Add a repeated string primary_key field to vschema.Table, listing in order
the columns that make up the table's primary key. It is regenerated with the
pinned protoc 3.21.3 and the repo's pinned protoc-gen-go and vtprotobuf
(Go outputs) and with pbjs/pbts (vtadmin web types).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Morgan Tocker <mtocker@squareup.com>
The planner plans a multi-shard DELETE or UPDATE with a LIMIT as DML with
input: it selects the primary keys of the matching rows, then deletes or
updates by primary key. That needs BaseTable.PrimaryKey, which today is only
filled in by schema tracking. A deployment without schema tracking can
already declare columns in the VSchema, but cannot declare a primary key, so
these statements fail to plan with VT09015.

Build BaseTable.PrimaryKey from the new primary_key field of the VSchema
table. Empty names, duplicate names (case-insensitively) and, when
column_list_authoritative is set, names missing from columns are rejected.
The field is accepted for every table type, as columns are.

When schema tracking knows the table, its primary key replaces the declared
one rather than being appended to it. A tracked table without a primary key
therefore ends up without one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Morgan Tocker <mtocker@squareup.com>

Copilot AI 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.

🟡 Changes recommended

The sharded REPLACE rewrite can run without complete index metadata when schema tracking is disabled, causing secondary unique-key conflicts to fail instead of replacing the existing row.

1 open issue
2 files not reviewed
  • go/vt/proto/vschema/vschema.pb.go: Generated file
  • go/vt/proto/vschema/vschema_vtproto.pb.go: Generated file
What changed in this PR

Adds declarative primary keys to VSchema so vtgate can plan multi-shard DELETE ... LIMIT and UPDATE ... LIMIT without schema tracking.

Changes:

  • Adds an ordered primary_key field and regenerates Go and vtadmin bindings.
  • Validates declared keys while preserving schema-tracker precedence.
  • Adds builder, serialization, tracker-override, and planner regression tests.
File Description
web/​vtadmin/​src/​proto/​vtadmin.js Adds generated primary-key serialization support.
web/​vtadmin/​src/​proto/​vtadmin.d.ts Adds generated primary-key type declarations.
proto/​vschema.proto Defines the ordered primary-key field and precedence.
go/​vt/​vtgate/​vschema_manager.go Replaces declared keys with tracked metadata.
go/​vt/​vtgate/​vschema_manager_test.go Tests declared keys and tracker overrides.
go/​vt/​vtgate/​vindexes/​vschema.go Validates and copies declared primary keys.
go/​vt/​vtgate/​vindexes/​vschema_test.go Tests validation, ordering, and JSON round trips.
go/​vt/​vtgate/​planbuilder/​testdata/​vschemas/​primary_key_schema.json Provides declarative-key planner fixtures.
go/​vt/​vtgate/​planbuilder/​testdata/​primary_key_cases.json Adds expected DML plans and missing-key errors.
go/​vt/​vtgate/​planbuilder/​plan_test.go Registers the declarative primary-key planning tests.
go/​vt/​proto/​vschema/​vschema.pb.go Adds the generated Go field and descriptor.
go/​vt/​proto/​vschema/​vschema_vtproto.pb.go Adds generated cloning and wire-format support.

Review effort: Balanced

Comment thread go/vt/vtgate/vindexes/vschema.go Resolved
A primary key declared in the VSchema says nothing about the table's
other unique keys. The sharded REPLACE rewrite (DELETE by primary key
and unique keys, then INSERT) needs the full set. With only a declared
primary key it would miss a row that clashes on a secondary unique key,
and the INSERT would fail after the DELETE had already run.

Mark a primary key that comes only from the VSchema with
BaseTable.PrimaryKeyDeclared. Schema tracking clears the mark when it
supplies the table's indexes. The REPLACE rewrite now ignores a declared
primary key, so a sharded REPLACE without tracked index metadata keeps
returning VT12001, as it did before the field existed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Morgan Tocker <mtocker@squareup.com>
@aparajon

Copy link
Copy Markdown
Collaborator

🤖 Review of 99628f9: 0 blocking, 5 non-blocking.

Inspected the full diff (13 files) and the code around each change at the head: BuildVSchema/buildTables in vindexes/vschema.go, VSchemaManager.updateTableInfo and setColumns, createOperatorFromInsert with its pkCompExpression/findPKIndexes helpers, every other reader of BaseTable.PrimaryKey (operators/delete.go, operators/update.go, operators/phases.go createDMLWithInput, vindexes/foreign_keys.go), the generated vschema.pb.go / vschema_vtproto.pb.go / vtadmin JS and TS against the .proto, and upstream vitessio/vitess main for an equivalent field. Review was API-only (no clone, no build, no tests run).

Blocking

None. The declared key only takes effect where schema tracking has no entry for the table, tracking replaces it cleanly, and the one planner path where a declared key is not equivalent to a tracked one (REPLACE) is gated off.

Non-blocking

  1. A declared key is trusted as unique, so a wrong or stale declaration turns a LIMIT statement into an over-delete or over-update. DELETE ... LIMIT n and UPDATE ... LIMIT n select the key columns of the first n matching rows and then run delete ... where <key> in ::dml_vals (createDMLWithInput). If the declared columns are a strict subset of the real primary key, or are not unique, every row that shares those values is touched, including rows beyond the limit and rows the where did not match. Before this change that table failed closed with VT09015; now it succeeds with the wrong row set. Nothing in the diff can validate the declaration, and a later schema change to the real key leaves the declaration stale where tracking is off. That is inherent to a declarative field and the same trust the VSchema already places in column_vindexes, so not a defect in the diff, but the .proto comment only says when the list is used. It should say the list must be exactly the table's primary key (or another unique, non-null key covering every row), and that LIMIT DML relies on it for correctness, not just for planning.

  2. The unsafe direction is the zero value of PrimaryKeyDeclared. trackedPK := len(vTbl.PrimaryKey) > 0 && !vTbl.PrimaryKeyDeclared treats any key whose flag was never set as tracked. Today the only producers are buildTables (sets the flag), updateTableInfo (clears it) and the test helper AddPrimaryKey in foreign_keys.go, so the gating is correct. Latent only: it fires if a future code path sets PrimaryKey without touching the flag, for example another metadata source, and then REPLACE is rewritten to delete-then-insert on a key that says nothing about secondary unique keys. Recording the provenance the other way round (a flag that is true only when the tracker supplied the key) would make a forgotten assignment fail closed. The new exported field and its primary_key_declared JSON tag also change the JSON rendering of BaseTable wherever it is dumped, which is worth a line in the description.

  3. Proto field 8 is a fork-only field number. I found no equivalent upstream: vitessio/vitess main Table still ends at source = 7, and a search of upstream PRs and issues for a declared primary key returned nothing. If upstream later adds its own field 8 to Table, topo data written by this fork would decode as the wrong field, and the reverse. Options are to open the same change upstream first, or to leave a note on the field so the number is claimed deliberately when the next upstream sync is done. The generated code itself checks out against the .proto: the Table length byte in rawDesc moves from \xb1\x02 (305) to \xd2\x02 (338), a delta of 33, which is exactly the added field descriptor (tag, length byte, 31 bytes); the vtproto marshal tag 0x42 is (8<<3)|2; CloneVT, SizeVT, MarshalToSizedBufferVT and UnmarshalVT agree with each other; the vtadmin JS writes uint32(66) and the TypeScript types carry the field.

  4. Test gaps against the description's claims. (a) The description says the field is accepted for tables with a source, but TestVSchemaPrimaryKey only declares it on a reference table with no source. (b) The unsharded_declared_pk and unsharded_no_pk fixtures in primary_key_schema.json are not queried by any case in primary_key_cases.json. (c) The "run twice" loop in TestDeclaredPrimaryKeyAndSchemaTracking cannot catch accumulation across rebuilds: VSchemaUpdate calls BuildVSchema, which creates fresh BaseTable values every time, so the second pass starts from the same state as the first. Accumulation inside one rebuild is already caught by the first pass. (d) There is no case for a delete or update with a declared key on a table that also has a tracked entry in the planner suite; the manager test covers it at the VSchema level only.

  5. Description and rollout notes are incomplete. The Risk section says the only behavior change for existing deployments is in updateTableInfo, but the diff also changes createOperatorFromInsert and adds an exported BaseTable field; neither is mentioned, and the REPLACE case in the test file is only explained by a comment. Separately, "a binary built before this change ignores a declared primary_key" holds for planning, but the JSON path is lossy in one direction: json2.UnmarshalPB uses DiscardUnknown, so an older client that reads a keyspace with GetVSchema and re-applies its JSON output silently drops every declared key, after which new vtgates answer VT09015 again. That fails closed, so it is only a note for the rollout.

Verified

  • CI (gh pr checks): 83 checks success, 1 skipped (labels), 0 failing, 12 still pending when I looked (Unit Test (Race), vtgate_queries, vtgate_transaction, cluster 21, the two Upgrade Downgrade query-serving variants, two example jobs and three online DDL / general suites). Unit Test (mysql80) and Unit Test (mysql84) passed, which run vindexes and planbuilder; Static Code Checks Etc, Check Make VTAdmin Web Proto and lint passed, which is the generated-code sync check.
  • The tracked override is complete. updateTableInfo resets PrimaryKey and PrimaryKeyDeclared only after the two continue branches (routed table not found, table routed elsewhere), so a table that gets no tracked key keeps its declared one, and a table that does get one never sees both concatenated. A tracked table with no primary index ends with an empty key, as described.
  • Validation is reached on every write path. buildTables (L809-L841) runs from BuildKeyspace, which VSchemaManager.UpdateVSchema calls before SaveVSchema. The case-insensitive duplicate check and the authoritative-list check use Lowered() consistently with how column names are de-duplicated just above.
  • No other reader is affected by a declared key. The remaining readers of PrimaryKey are createDMLWithInput, createDeleteOpWithTarget, createUpdateOpWithTarget (all intended consumers) and REPLACE, which the PR gates. Foreign key metadata and UniqueKeys come only from the tracker, which also clears the declared key, so a declared key and a non-empty UniqueKeys cannot both be present, and pkCompExpression is only reached with a tracked key. The ALTER VSCHEMA and workflow code that builds vschemapb.Table values creates empty tables or edits existing ones in place, so the new field is not dropped there.
  • Mutation testing and test runs were not possible API-only (no clone, no build). Reasoned from the test files, each mutant against the case that should fail:
Mutant Caught by
trackedPK ignores the flag (len(PrimaryKey) > 0) the REPLACE case in primary_key_cases.json (plan becomes delete plus insert instead of VT12001)
trackedPK always false the foreign key planning suite, whose tables get their keys from AddPrimaryKey (plan_test.go L257-L269), for any REPLACE case in it that relies on the rewrite (not checked case by case)
Drop rTbl.PrimaryKey = nil in updateTableInfo tracked_same, tracked_override, tracked_no_pk in TestDeclaredPrimaryKeyAndSchemaTracking
Drop rTbl.PrimaryKeyDeclared = false the pkDeclared assertions for the four tracked tables
Drop t.PrimaryKeyDeclared = len(...) > 0 assert.True(t1.PrimaryKeyDeclared) and the declared_only assertion
Do not copy declared columns into BaseTable.PrimaryKey TestVSchemaPrimaryKey and all four DML cases
Reverse or sort the declared order ["b", "A"] assertion and the composite-key plan cases
Remove the empty-name, duplicate or authoritative-list check the matching subtest of TestVSchemaPrimaryKeyFail
Compare duplicates case-sensitively the ["a", "A"] subtest
Apply the authoritative check when the list is not authoritative "column not in non-authoritative list is accepted"
Remove the new UnmarshalVT case 8 or marshal code not caught by a unit test (the JSON round trip goes through protoreflect, not vtproto); covered by the regeneration check in CI

This review was generated by Claude Code (claude-sonnet-5-5).

@aparajon aparajon left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🤖 Stamping with comments: 0 blocking, 5 non-blocking (see the review comment above).

This stamp was left by Claude Code (claude-sonnet-5-5).

morgo and others added 3 commits November 27, 2026 17:26
State that the primary_key list must be exactly the table's primary key (or
another unique key whose columns are NOT NULL in every row), that vtgate
trusts it as unique, and that DML planned by key, such as a multi-shard
DELETE or UPDATE with a LIMIT, relies on it for correctness. Note that field
number 8 is used by this fork only, so an upstream sync must check it for a
conflict.

Only comments change. The generated Go code differs by the comment text, and
the vtproto and vtadmin web outputs and the descriptor bytes are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Morgan Tocker <mtocker@squareup.com>
Replace BaseTable.PrimaryKeyDeclared with PrimaryKeyTracked, which is true only
when schema tracking handled the table. The REPLACE rewrite in
createOperatorFromInsert now requires it, so a code path that sets PrimaryKey
without setting the flag fails closed: a sharded REPLACE keeps returning
VT12001. The field is tagged json:"-", so the JSON rendering of BaseTable does
not change.

VSchemaManager.updateTableInfo sets the flag whenever tracking handled the
table, including a table with no primary key. buildTables leaves it false, and
the AddPrimaryKey test helper, which stands in for schema tracking, sets it.

Update the tests to assert the new flag. TestDeclaredPrimaryKeyAndSchemaTracking
no longer runs twice, since BuildVSchema builds fresh tables on every call, so
a second pass cannot detect accumulation. The VSchema comparison tests ignore
PrimaryKeyTracked, which they do not cover.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Morgan Tocker <mtocker@squareup.com>
Add planner cases that query the unsharded fixtures that declare a primary key
and that have none. Declare a primary key on a reference table that has a
source in TestVSchemaPrimaryKey.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Morgan Tocker <mtocker@squareup.com>
@morgo

morgo commented Nov 27, 2026

Copy link
Copy Markdown
Collaborator Author

🤖 Thanks. Addressed in 99628f9..1fdb57f:

  1. Trust: the primary_key comment in vschema.proto now says the list must be exactly the table's primary key (or a unique key whose columns are NOT NULL in every row), that vtgate trusts it as unique, and that keyed DML such as multi-shard DELETE/UPDATE with LIMIT relies on it for correctness. A wrong or stale key makes such a statement touch rows beyond the LIMIT or rows the WHERE did not match.
  2. Provenance: PrimaryKeyDeclared is replaced by PrimaryKeyTracked, which only schema tracking sets (and the AddPrimaryKey test helper, which stands in for it). A code path that sets PrimaryKey without the flag now fails closed for REPLACE. The field is tagged json:"-", so the JSON rendering of BaseTable does not change.
  3. Field 8: the proto comment notes the number is used by this fork only, so an upstream sync must check for a conflicting field 8. Generated code changed in comments only.
  4. Tests: (a) TestVSchemaPrimaryKey declares a key on a reference table with a source. (b) primary_key_cases.json now queries unsharded_declared_pk and unsharded_no_pk. (c) The run-twice loop is removed. (d) Not added: the planner reads only BaseTable.PrimaryKey, and TestDeclaredPrimaryKeyAndSchemaTracking covers which key wins.
  5. Description: Risk now covers the REPLACE gate in createOperatorFromInsert and the new BaseTable field. There is a rollout note that an older client re-applying GetVSchema JSON drops primary_key and planning falls back to VT09015.

🤖 Addressed by Claude Code

@morgo
morgo merged commit fd1e737 into release-24.0 Nov 27, 2026
97 checks passed
morgo added a commit that referenced this pull request Nov 28, 2026
This reverts commit fd1e737 (#50).

No user of this fork needs a declared primary key. The planner reads it
only for two-phase DML (a multi-shard DELETE or UPDATE with LIMIT, and a
multi-table DELETE or UPDATE). Those shapes stay unsupported without
schema tracking.

Signed-off-by: Morgan Tocker <mtocker@squareup.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
@morgo
morgo deleted the mtocker/vschema-primary-key branch November 28, 2026 01:02
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.

3 participants