I renumbered a field and the old client silently read the wrong value
Read and write the bytes by hand
Goal
In a Pod with neither protoc nor the protobuf package, you build a protobuf wire-format encoder and decoder yourself using only the Python standard library. You stack them up in the order varint → tag → signed integer → field → message, and finally decode a submessage and a packed repeated field. You will use the tool you build in the next lab as well.
Why it matters
Half of gRPC outages come from not knowing that "bytes have no names". The wire carries only
the field number and the wire type, and the names and declared types are attached by the reader's .proto.
If you encode by hand once, the calculations show why you must not change a number, why a negative
int32 takes as many as 10 bytes, and why an old client skips a new field
without error. Someone who has opened up once what the library hides
sees different things in a schema review.
Steps
- Create
/root/grpc/pb.pyand implementencode_varint(n) -> bytesanddecode_varint(data, pos=0) -> (value, next_pos). Write the hex encodings of 1, 150, 300, and 16384 to/root/grpc/01-varint.txt, one per line, as<value>=<hex>. - Add
encode_tag(field, wire_type) -> bytesanddecode_tag(data, pos=0) -> (field, wire_type, next_pos). Write the hex of the four tags1:0,2:2,3:2, and16:0to/root/grpc/02-tag.txtas<field>:<wire_type>=<hex>. - Add
zigzag_encode(n) -> intandzigzag_decode(u) -> int, actually encodeint32 -1,sint32 -1,int32 -150, andsint32 -150, and write them to/root/grpc/03-signed.txtas<type> <value> = <hex> (<N> bytes). int32 sends the 64-bit two's complement as a varint, and sint32 sends the value that went through ZigZag as a varint. - Add
encode_field(field, kind, value) -> bytes. kind is one ofint32 int64 uint32 uint64 sint32 sint64 bool string bytes. Using that function, create an order withid(1)=4242, qty(2)=17, note(3)="한글 메모"by writing/root/grpc/04-make.py, run it, and leave/root/grpc/04-order.bin. - Add
decode_message(data) -> [(field, wire_type, raw), ...]. VARINT is an int, LEN is bytes, and I32/I64 are the 4- and 8-byte bytes as they are. Decode/opt/app/grpc/order_v1.binand write it to/root/grpc/05-decode.txt, one line each, asfield=N wire=W value=V(LEN values in hex). - Add
encode_records(records) -> bytes(the inverse function of decode_message). Decode/opt/app/grpc/order_v2.binand, for each record, record whether the number is known to the v1 schema (/opt/app/grpc/order_v1.proto) in/root/grpc/06-unknown.txt, asfield=N wire=W knownorunknown. - Field 6 of
/opt/app/grpc/nested.binis aCustomersubmessage. Decode its payload again with decode_message and write three lines to/root/grpc/07-nested.txt:customer.bytes=<hex>customer.name=<name>customer.tier=<number>. - Add
decode_packed_varints(raw) -> [int, ...], unpack field 7 (packed repeated int32) of/opt/app/grpc/packed.bin, and write three lines to/root/grpc/08-packed.txt:tags=<comma-list>packed_record=<hex>expanded_record=<hex>.
Notes
- The source of the rules is the Protocol Buffers encoding document. The tag is
(field_number << 3) | wire_type, and the wire types are 0 VARINT · 1 I64 · 2 LEN · 5 I32. - There is a reference implementation,
/opt/app/grpc/pbmini.py. Read it if you get stuck, but this lab's grader imports your/root/grpc/pb.pyand runs it with random values that are not in the instructions as well. If you hard-code the answers, you fail on the spot. - You can view the fixture bytes with
python3 -c "print(open('/opt/app/grpc/order_v1.bin','rb').read().hex())". - Common mistakes:
decode_varintignoring theposargument, counting the string length in characters (it must be the number of UTF-8 bytes), and truncating a negativeint32to 32 bits (it is 64 bits).
Build and read a varint
In /root/grpc/pb.py, implement encode_varint(n) and decode_varint(data, pos=0), and write the hex of 1, 150, 300, and 16384 to /root/grpc/01-varint.txt as <value>=<hex>.
Direction: cut the integer into 7-bit groups and emit them from the lowest, and if more follows, set the most significant bit (0x80) of that byte. When reading, stop at the byte where that bit is 0.
Tools: the bit operations & 0x7F, >>= 7, | 0x80, and a loop that also returns the position read up to.
Specifics: 150 is 10010110 in binary → the lower 7 bits with the continuation mark give 0x96, and the remaining 1 is 0x01, so it is 96 01 (300 is ac02). decode_varint must read from pos and return (value, next_pos) — the grader also calls it from positions in the middle.
Put the number and wire type in a tag
Add encode_tag(field, wire_type) and decode_tag(data, pos=0) to /root/grpc/pb.py, and write the hex of 1:0 2:2 3:2 16:0 to /root/grpc/02-tag.txt as <field>:<wire_type>=<hex>.
Direction: a tag is also just one varint — it holds the field number and the wire type in a single integer.
Tools: (field << 3) | wire_type and its inverse (the lower 3 bits & 0x7, the rest >> 3), plus encode_varint and decode_varint from step 1.
Specifics: 1:0 is 8, so 08, and 2:2 is 18, so 12. Numbers 1–15 take a one-byte tag, and from 16 on it becomes two bytes — this is where the recommendation to give small numbers to frequently used fields comes from.
A negative int32 is 10 bytes, a sint32 is one or two
Add zigzag_encode(n) and zigzag_decode(u), actually encode int32 -1 sint32 -1 int32 -150 sint32 -150, and write them to /root/grpc/03-signed.txt as <type> <value> = <hex> (<N> bytes).
Direction: the same -1 is 10 bytes as int32 and 1 byte as sint32. The former sends the 64-bit two's complement as a varint; the latter sends the value after ZigZag as a varint.
Tools: the 64-bit mask n & 0xFFFFFFFFFFFFFFFF, the document's ZigZag formula (n << 1) ^ (n >> 31) and the inverse formula (u >> 1) ^ -(u & 1) (Python's >> is an arithmetic shift).
Specifics: ZigZag alternates 0→0, -1→1, 1→2, -2→3. In the line format, write the hex and the byte count together, as in sint32 -1 = 01 (1 bytes).
Turn one field into a record
Add encode_field(field, kind, value) (kind: int32 int64 uint32 uint64 sint32 sint64 bool string bytes). In /root/grpc/04-make.py, use that function to concatenate id(1)=4242, qty(2)=17, note(3)="한글 메모" and save it as /root/grpc/04-order.bin.
Direction: a record is a tag + a value, and a message is nothing more than records concatenated (no header, no delimiter).
Tools: encode_tag from step 2, encode_varint from step 1, the mask and ZigZag from step 3 (for 64 bits, n >> 63), and .encode("utf-8") for strings.
Specifics: the numeric family is wire type 0, string and bytes are 2, and type 2 has a length varint before the value. The length is the number of UTF-8 bytes, not the number of characters — "한글 메모" is 5 characters but 13 bytes in UTF-8 (this string is not translated).
Turn the bytes back into a list of records
Add decode_message(data) so that it returns [(field, wire_type, raw), ...]. Decode /opt/app/grpc/order_v1.bin and write it to /root/grpc/05-decode.txt as field=N wire=W value=V (LEN values in hex).
Direction: repeat until the end — read a tag, then read as much value as the wire type tells you. At this step you know neither the name nor the declared type, so do not interpret the value.
Tools: decode_tag, decode_varint, and byte slicing. Wire type 0 is a varint, 2 is a length varint followed by that many bytes, 5 is 4 bytes, and 1 is 8 bytes.
Specifics: if you do not advance the position (pos) exactly, you read the next tag from the wrong place — the grader runs it on 12 random messages. Write LEN values in hex.
Skip unknown fields without losing them
Add encode_records(records) (the inverse of decode_message). Decode /opt/app/grpc/order_v2.bin and, for each record, write to /root/grpc/06-unknown.txt whether its number is known to the v1 schema (/opt/app/grpc/order_v1.proto), as field=N wire=W known or unknown.
Direction: an old parser skips a new field without error because the wire type tells it the length, and a proto3 parser does not discard that unknown field but emits it when serializing again.
Tools: the inverse of decode_message — for each record, write the tag again and attach the value according to the wire type. The v1 schema is /opt/app/grpc/order_v1.proto.
Specifics: the grader round-trips random messages through decode_message → encode_records and checks that the result equals the original down to the byte. Only numbers declared by v1 are known.
A submessage is another message inside a LEN
Decode the payload of field 6 (the Customer submessage) of /opt/app/grpc/nested.bin again with decode_message, and write three lines to /root/grpc/07-nested.txt: customer.bytes=<hex> customer.name=<name> customer.tier=<number>.
Direction: a submessage is a LEN record, just like a string — only its bytes are another message, so you decode them once more with the same function.
Tools: decode_message twice, and the Customer numbers written in /opt/app/grpc/nested.proto.
Specifics: customer.bytes is the raw value of field 6, that is, the hex of the payload without the tag and length.
Unpack a packed repeated field
Add decode_packed_varints(raw), unpack field 7 (packed repeated int32) of /opt/app/grpc/packed.bin, and write three lines to /root/grpc/08-packed.txt: tags=<comma-list> packed_record=<hex> expanded_record=<hex>.
Direction: packed means varints concatenated inside a single-tag LEN record.
Tools: a loop that repeats decode_varint until the payload ends, and encode_records and encode_field for comparison.
Specifics: packed_record is the whole field 7 record (tag + length + payload), and expanded_record is the same list with a tag attached to each element, concatenated. Comparing the two lengths shows the cost of the tags.