Can a proto3 optional field be changed to repeated without breaking wire compatibility?
Asked Answered
S

1

11

Let's say that I have a proto3 message defined as follows, for use as a gRPC request (i.e. using protobuf's binary encoding):

message MyRequest {
  string name = 1;
}

Can I change my server (i.e. the reader of the message) to use the following definition without breaking wire compatibility for existing clients (i.e. writers)?

message MyRequest {
  repeated string names = 1;
}

In the proto2 language guide, I see the following:

optional is compatible with repeated. Given serialized data of a repeated field as input, clients that expect this field to be optional will take the last input value if it's a primitive type field or merge all input elements if it's a message type field.

However, the proto3 documentation does not contain an equivalent statement. I think that this may be related to the use of the packed encoding for repeated fields in proto3.

Springhouse answered 23/8, 2017 at 21:57 Comment(0)
S
8

Yes, this is possible as the binary encoding for an optional string and for a repeated string with a single element are the same. However, this change may be confusing to readers of the code because it is not immediately obvious that a message can be reinterpreted in this way.

Springhouse answered 7/9, 2017 at 14:24 Comment(1)
Hi, i was wondering if a repeated field can be changed to optional (which is default for proto3) without breaking compatability, the language guide only give a example of client expect optional can parse repeated field correctly, but doesn't mention if it's also compatible for client expect repeated but get optional field.Folketing

© 2022 - 2025 — McMap. All rights reserved.