1# Application note: Field presence 2 3This application note explains the various presence tracking disciplines for protobuf fields. It also explains how to enable experimental support for explicit presence tracking for singular proto3 fields with basic types. 4 5## Background 6 7_Field presence_ is the notion of whether a protobuf field has a value. There are two different manifestations of presence for protobufs: _no presence_, where the generated message API stores field values (only), and _explicit presence_, where the API also stores whether or not a field has been set. 8 9Historically, proto2 has mostly followed _explicit presence_, while proto3 exposes only _no presence_ semantics. Singular proto3 fields of basic types (numeric, string, bytes, and enums) which are defined with the `optional` label have _explicit presence_, like proto2 (this is an experimental feature added as of release 3.12, and must be enabled by passing a flag to `protoc`). 10 11### Presence disciplines 12 13_Presence disciplines_ define the semantics for translating between the _API representation_ and the _serialized representation_. The _no presence_ discipline relies upon the field value itself to make decisions at (de)serialization time, while the _explicit presence_ discipline relies upon the explicit tracking state instead. 14 15### Presence in _tag-value stream_ (wire format) serialization 16 17The wire format is a stream of tagged, _self-delimiting_ values. By definition, the wire format represents a sequence of _present_ values. In other words, every value found within a serialization represents a _present_ field; furthermore, the serialization contains no information about not-present values. 18 19The generated API for a proto message includes (de)serialization definitions which translate between API types and a stream of definitionally _present_ (tag, value) pairs. This translation is designed to be forward- and backward-compatibile across changes to the message definition; however, this compatibility introduces some (perhaps surprising) considerations when deserializing wire-formatted messages: 20 21- When serializing, fields with _no presence_ are not serialized if they contain their default value. 22 - For numeric types, the default is 0. 23 - For enums, the default is the zero-valued enumerator. 24 - For strings, bytes, and repeated fields, the default is the zero-length value. 25 - For messages, the default is the language-specific null value. 26- "Empty" length-delimited values (such as empty strings) can be validly represented in serialized values: the field is "present," in the sense that it appears in the wire format. However, if the generated API does not track presence, then these values may not be re-serialized; i.e., the empty field may be "not present" after a serialization round-trip. 27- When deserializing, duplicate field values may be handled in different ways depending on the field definition. 28 - Duplicate `repeated` fields are typically appended to the field's API representation. (Note that serializing a _packed_ repeated field produces only one, length-delimited value in the tag stream.) 29 - Duplicate `optional` field values follow the rule that "the last one wins." 30- `oneof` fields expose the API-level invariant that only one field is set at a time. However, the wire format may include multiple (tag, value) pairs which notionally belong to the `oneof`. Similar to `optional` fields, the generated API follows the "last one wins" rule. 31- Out-of-range values are not returned for enum fields in generated proto2 APIs. However, out-of-range values may be stored as _unknown fields_ in the API, even though the wire-format tag was recognized. 32 33### Presence in _named-field mapping_ formats 34 35Protobufs can be represented in human-readable, textual forms. Two notable formats are TextFormat (the output format produced by generated message `DebugString` methods) and JSON. 36 37These formats have correctness requirements of their own, and are generally stricter than _tagged-value stream_ formats. However, TextFormat more closely mimics the semantics of the wire format, and does, in certain cases, provide similar semantics (for example, appending repeated name-value mappings to a repeated field). In particular, similar to the wire format, TextFormat only includes fields which are present. 38 39JSON is a much stricter format, however, and cannot validly represent some semantics of the wire format or TextFormat. 40 41- Notably, JSON _elements_ are semantically unordered, and each member must have a unique name. This is different from TextFormat rules for repeated fields. 42- JSON may include fields that are "not present," unlike the _no presence_ discipline for other formats: 43 - JSON defines a `null` value, which may be used to represent a _defined but not-present field_. 44 - Repeated field values may be included in the formatted output, even if they are equal to the default (an empty list). 45- Because JSON elements are unordered, there is no way to unambiguously interpret the "last one wins" rule. 46 - In most cases, this is fine: JSON elements must have unique names: repeated field values are not valid JSON, so they do not need to be resolved as they are for TextFormat. 47 - However, this means that it may not be possible to interpret `oneof` fields unambiguously: if multiple cases are present, they are unordered. 48 49In theory, JSON _can_ represent presence in a semantic-preserving fashion. In practice, however, presence correctness can vary depending upon implementation choices, especially if JSON was chosen as a means to interoperate with clients not using protobufs. 50 51### Presence in proto2 APIs 52 53This table outlines whether presence is tracked for fields in proto2 APIs (both for generated APIs and using dynamic reflection): 54 55Field type | Explicit Presence 56-------------------------------------------- | ----------------- 57Singular numeric (integer or floating point) | ✔️ 58Singular enum | ✔️ 59Singular string or bytes | ✔️ 60Singular message | ✔️ 61Repeated | 62Oneofs | ✔️ 63Maps | 64 65Singular fields (of all types) track presence explicitly in the generated API. The generated message interface includes methods to query presence of fields. For example, the field `foo` has a corresponding `has_foo` method. (The specific name follows the same language-specific naming convention as the field accessors.) These methods are sometimes referred to as "hazzers" within the protobuf implementation. 66 67Similar to singular fields, `oneof` fields explicitly track which one of the members, if any, contains a value. For example, consider this example `oneof`: 68 69``` 70oneof foo { 71 int32 a = 1; 72 float b = 2; 73} 74``` 75 76Depending on the target language, the generated API would generally include several methods: 77 78- A hazzer for the oneof: `has_foo` 79- A _oneof case_ method: `foo` 80- Hazzers for the members: `has_a`, `has_b` 81- Getters for the members: `a`, `b` 82 83Repeated fields and maps do not track presence: there is no distinction between an _empty_ and a _not-present_ repeated field. 84 85### Presence in proto3 APIs 86 87This table outlines whether presence is tracked for fields in proto3 APIs (both for generated APIs and using dynamic reflection): 88 89Field type | `optional` | Explicit Presence 90-------------------------------------------- | ---------- | ----------------- 91Singular numeric (integer or floating point) | No | 92Singular enum | No | 93Singular string or bytes | No | 94Singular numeric (integer or floating point) | Yes | ✔️ 95Singular enum | Yes | ✔️ 96Singular string or bytes | Yes | ✔️ 97Singular message | Yes | ✔️ 98Singular message | No | ✔️ 99Repeated | N/A | 100Oneofs | N/A | ✔️ 101Maps | N/A | 102 103Similar to proto2 APIs, proto3 does not track presence explicitly for repeated fields. Without the `optional` label, proto3 APIs do not track presence for basic types (numeric, string, bytes, and enums), either. (Note that `optional` for proto3 fields is only experimentally available as of release 3.12.) Oneof fields affirmatively expose presence, although the same set of hazzer methods may not generated as in proto2 APIs. 104 105Under the _no presence_ discipline, the default value is synonymous with "not present" for purposes of serialization. To notionally "clear" a field (so it won't be serialized), an API user would set it to the default value. 106 107The default value for enum-typed fields under _no presence_ is the corresponding 0-valued enumerator. Under proto3 syntax rules, all enum types are required to have an enumerator value which maps to 0. By convention, this is an `UNKNOWN` or similarly-named enumerator. If the zero value is notionally outside the domain of valid values for the application, this behavior can be thought of as tantamount to _explicit presence_. 108 109## Semantic differences 110 111The _no presence_ serialization discipline results in visible differences from the _explicit presence_ tracking discipline, when the default value is set. For a singular field with numeric, enum, or string type: 112 113- _No presence_ discipline: 114 - Default values are not serialized. 115 - Default values are _not_ merged-from. 116 - To "clear" a field, it is set to its default value. 117 - The default value may mean: 118 - the field was explicitly set to its default value, which is valid in the application-specific domain of values; 119 - the field was notionally "cleared" by setting its default; or 120 - the field was never set. 121- _Explicit presence_ discipline: 122 - Explicitly set values are always serialized, including default values. 123 - Un-set fields are never merged-from. 124 - Explicitly set fields -- including default values -- _are_ merged-from. 125 - A generated `has_foo` method indicates whether or not the field `foo` has been set (and not cleared). 126 - A generated `clear_foo` method must be used to clear (i.e., un-set) the value. 127 128### Considerations for merging 129 130Under the _no presence_ rules, it is effectively impossible for a target field to merge-from its default value (using the protobuf's API merging functions). This is because default values are skipped, simliar to the _no presence_ serialization discipline. Merging only updates the target (merged-to) message using the non-skipped values from the update (merged-from) message. 131 132The difference in merging behavior has further implications for protocols which rely on partial "patch" updates. If field presence is not tracked, then an update patch alone cannot represent an update to the default value, because only non-default values are merged-from. 133 134Updating to set a default value in this case requires some external mechanism, such as `FieldMask`. However, if presence _is_ tracked, then all explicitly-set values -- even default values -- will be merged into the target. 135 136### Considerations for change-compatibility 137 138Changing a field between _explicit presence_ and _no presence_ is a binary-compatible change for serialized values in wire format. However, the serialized representation of the message may differ, depending on which version of the message definition was used for serialization. Specifically, when a "sender" explicitly sets a field to its default value: 139 140- The serialized value following _no presence_ discipline does not contain the default value, even though it was explicitly set. 141- The serialized value following _explicit presence_ discipline contains every "present" field, even if it contains the default value. 142 143This change may or may not be safe, depending on the application's semantics. For example, consider two clients with different versions of a message definition. 144 145Client A uses this definition of the message, which follows the _explicit presence_ serialization discipline for field `foo`: 146 147``` 148syntax = "proto3"; 149message Msg { 150 optional int32 foo = 1; 151} 152``` 153 154Client B uses a definition of the same message, except that it follows the _no presence_ discipline: 155 156``` 157syntax = "proto3"; 158message Msg { 159 int32 foo = 1; 160} 161``` 162 163Now, consider a scenario where client A observes `foo`'s presence as the clients repeatedly exchange the "same" message by deserializing and reserializing: 164 165``` 166// Client A: 167Msg m_a; 168m_a.set_foo(1); // non-default value 169assert(m_a.has_foo()); // OK 170Send(m_a.SerializeAsString()); // to client B 171 172// Client B: 173Msg m_b; 174m_b.ParseFromString(Receive()); // from client A 175assert(m_b.foo() == 1); // OK 176Send(m_b.SerializeAsString()); // to client A 177 178// Client A: 179m_a.ParseFromString(Receive()); // from client B 180assert(m_a.foo() == 1); // OK 181assert(m_a.has_foo()); // OK 182m_a.set_foo(0); // default value 183Send(m_a.SerializeAsString()); // to client B 184 185// Client B: 186Msg m_b; 187m_b.ParseFromString(Receive()); // from client A 188assert(m_b.foo() == 0); // OK 189Send(m_b.SerializeAsString()); // to client A 190 191// Client A: 192m_a.ParseFromString(Receive()); // from client B 193assert(m_a.foo() == 0); // OK 194assert(m_a.has_foo()); // FAIL 195``` 196 197If client A depends on _explicit presence_ for `foo`, then a "round trip" through client B will be lossy from the perspective of client A. In the example, this is not a safe change: client A requires (by `assert`) that the field is present; even without any modifications through the API, that requirement fails in a value- and peer-dependent case. 198 199## How to enable _explicit presence_ in proto3 200 201These are the general steps to use the experimental field tracking support for proto3: 202 2031. Add an `optional` field to a `.proto` file. 2041. Run `protoc` (from release 3.12 or later) with an extra flag to recognize `optional` (i.e,. explicit presence) in proto3 files. 2051. Use the generated "hazzer" methods and "clear" methods in application code, instead of comparing or setting default values. 206 207### `.proto` file changes 208 209This is an example of a proto3 message with fields which follow both _no presence_ and _explicit presence_ semantics: 210 211``` 212syntax = "proto3"; 213package example; 214 215message MyMessage { 216 // No presence: 217 int32 not_tracked = 1; 218 219 // Explicit presence: 220 optional int32 tracked = 2; 221} 222``` 223 224### `protoc` invocation 225 226To enable presence tracking for proto3 messages, pass the `--experimental_allow_proto3_optional` flag to protoc. Without this flag, the `optional` label is an error in files using proto3 syntax. This flag is available in protobuf release 3.12 or later (or at HEAD, if you are reading this application note from Git). 227 228### Using the generated code 229 230The generated code for proto3 fields with _explicit presence_ (the `optional` label) will be the same as it would be in a proto2 file. 231 232This is the definition used in the "no presence" examples below: 233 234``` 235syntax = "proto3"; 236package example; 237message Msg { 238 int32 foo = 1; 239} 240``` 241 242This is the definition used in the "explicit presence" examples below: 243 244``` 245syntax = "proto3"; 246package example; 247message Msg { 248 optional int32 foo = 1; 249} 250``` 251 252In the examples, a function `GetProto` constructs and returns a message of type `Msg` with unspecified contents. 253 254#### C++ example 255 256No presence: 257 258``` 259Msg m = GetProto(); 260if (m.foo() != 0) { 261 // "Clear" the field: 262 m.set_foo(0); 263} else { 264 // Default value: field may not have been present. 265 m.set_foo(1); 266} 267``` 268 269Explicit presence: 270 271``` 272Msg m = GetProto(); 273if (m.has_foo()) { 274 // Clear the field: 275 m.clear_foo(); 276} else { 277 // Field is not present, so set it. 278 m.set_foo(1); 279} 280``` 281 282#### C# example 283 284No presence: 285 286``` 287var m = GetProto(); 288if (m.Foo != 0) { 289 // "Clear" the field: 290 m.Foo = 0; 291} else { 292 // Default value: field may not have been present. 293 m.Foo = 1; 294} 295``` 296 297Explicit presence: 298 299``` 300var m = GetProto(); 301if (m.HasFoo) { 302 // Clear the field: 303 m.ClearFoo(); 304} else { 305 // Field is not present, so set it. 306 m.Foo = 1; 307} 308``` 309 310#### Go example 311 312No presence: 313 314``` 315m := GetProto() 316if (m.GetFoo() != 0) { 317 // "Clear" the field: 318 m.Foo = 0; 319} else { 320 // Default value: field may not have been present. 321 m.Foo = 1; 322} 323``` 324 325Explicit presence: 326 327``` 328m := GetProto() 329if (m.HasFoo()) { 330 // Clear the field: 331 m.Foo = nil 332} else { 333 // Field is not present, so set it. 334 m.Foo = proto.Int32(1); 335} 336``` 337 338#### Java example 339 340These examples use a `Builder` to demonstrate clearing. Simply checking presence and getting values from a `Builder` follows the same API as the message type. 341 342No presence: 343 344``` 345Msg.Builder m = GetProto().toBuilder(); 346if (m.getFoo() != 0) { 347 // "Clear" the field: 348 m.setFoo(0); 349} else { 350 // Default value: field may not have been present. 351 m.setFoo(1); 352} 353``` 354 355Explicit presence: 356 357``` 358Msg.Builder m = GetProto().toBuilder(); 359if (m.hasFoo()) { 360 // Clear the field: 361 m.clearFoo() 362} else { 363 // Field is not present, so set it. 364 m.setFoo(1); 365} 366``` 367 368#### Python example 369 370No presence: 371 372``` 373m = example.Msg() 374if m.foo != 0: 375 // "Clear" the field: 376 m.foo = 0 377else: 378 // Default value: field may not have been present. 379 m.foo = 1 380``` 381 382Explicit presence: 383 384``` 385m = example.Msg() 386if m.HasField('foo'): 387 // Clear the field: 388 m.ClearField('foo') 389else: 390 // Field is not present, so set it. 391 m.foo = 1 392``` 393 394#### Ruby example 395 396No presence: 397 398``` 399m = Msg.new 400if m.foo != 0 401 // "Clear" the field: 402 m.foo = 0 403else 404 // Default value: field may not have been present. 405 m.foo = 1 406end 407``` 408 409Explicit presence: 410 411``` 412m = Msg.new 413if m.has_foo? 414 // Clear the field: 415 m.clear_foo 416else 417 // Field is not present, so set it. 418 m.foo = 1 419end 420``` 421 422#### Javascript example 423 424No presence: 425 426``` 427var m = new Msg(); 428if (m.getFoo() != 0) { 429 // "Clear" the field: 430 m.setFoo(0); 431} else { 432 // Default value: field may not have been present. 433 m.setFoo(1); 434} 435``` 436 437Explicit presence: 438 439``` 440var m = new Msg(); 441if (m.hasFoo()) { 442 // Clear the field: 443 m.clearFoo() 444} else { 445 // Field is not present, so set it. 446 m.setFoo(1); 447} 448``` 449 450#### Objective C example 451 452No presence: 453 454``` 455Msg *m = [[Msg alloc] init]; 456if (m.foo != 0) { 457 // "Clear" the field: 458 m.foo = 0; 459} else { 460 // Default value: field may not have been present. 461 m.foo = 1; 462} 463``` 464 465Explicit presence: 466 467``` 468Msg *m = [[Msg alloc] init]; 469if (m.hasFoo()) { 470 // Clear the field: 471 [m clearFoo]; 472} else { 473 // Field is not present, so set it. 474 [m setFoo:1]; 475} 476``` 477