1. Analyze the Request:
* Topic: Protobuf (Protocol Buffers) Schema Evolution.
* Goal: Design a "guard" (a mechanism/tool/process) to detect breaking changes.
* Key Components:
* Understanding Protobuf compatibility rules.
* Defining what constitutes a "breaking change."
* Designing the architecture of the guard (linting, CI/CD integration, comparison logic).
* Providing code/configuration examples (likely using Buf or protoc plugins).
Deconstruct "Breaking Changes" in Protobuf:
Wire compatibility: Does it break binary deserialization?
Source compatibility: Does it break generated code compilation?
Logical/Behavioral compatibility: Does it break the business logic (e.g., changing a field type from int to string might be wire-compatible in some contexts but logically wrong; renaming a field might break JSON mapping)?
Standard rules (Proto2 vs Proto3):
Deleting fields (safe if reserved).
Renaming fields/fields (safe on wire, unsafe for JSON/Source).
Changing field numbers (major break).
Changing types (usually breaking).
Changing required vs optional (complex).
Moving fields into oneof (can break).
Select the Best Tool for the Job:
Writing a custom linter from scratch is hard and error-prone.
Buf is the industry standard for this. It has built-in breaking change detection (buf breaking).
Prototool is deprecated/maintenance mode.
Custom implementation: I should outline how one would build this if they had to, but strongly recommend Buf. The prompt asks to "Design," so I should provide an architectural overview and a practical implementation using the best tool (Buf).
Input: Previous schema (Git commit, stored file) vs. Current schema (Pull Request).
Parser: Reads .proto files into an Abstract Syntax Tree (AST) or FileDescriptorSet.
Comparator: Walks the two trees and compares nodes.
Reporter: Outputs errors/warnings.
Phase 3: Implementation Strategy (The Code):
Option A (Best Practice): Use Buf. It's the gold standard.
Option B (Custom): Python/Go script using protoc to generate descriptors and comparing them.
Phase 4: CI/CD Integration:
This is crucial for a "guard." It needs to run on Pull Requests.
Refining the Design (Self-Correction/Detailing):
Refinement: Just listing rules is boring. I should structure the answer as a "Solution Design."
Constraint Check: The user asked for a design, not just "use Buf." So I need to explain the logic behind the detection, then offer Buf as the implementation.
Detailed Logic for the Comparator:
Map fields by ID (number), not name (since names don't exist on wire).
Check for overlaps.
Check type safety.
Structuring the Output:
Introduction: Define Protobuf compatibility (Wire vs. Source vs. Logical).
The Rules Matrix: A table/list of safe vs. unsafe operations.
Architectural Design: A diagram (mental or ASCII) of the Guard.
Implementation (The "Buf" Approach): Configuration and usage.
Implementation (The "Custom" Approach - Logic): Pseudocode for the comparison engine.
CI/CD Integration: How to lock it down.
Drafting Content (Iterative):
Wire vs Source: Crucial distinction. Changing a field name is wire-safe but source-breaking. I should default to checking for wire safety but allow strictness for source safety.
The "Guard" Concept: It implies a gatekeeper. Git hooks or CI pipelines are the place.
(Self-Correction during drafting): Make sure to mention reserved fields. That's a common pitfall.
Final Polish:
Use clear headings.
Use code blocks for YAML/Buf configuration.
Add a "Decision Matrix" for users to choose strictness levels.
Final Output Generation: (This matches the provided good response, following the structure: Concept -> Rules -> Tooling -> CI/CD).
Designing a robust protobuf schema evolution guard requires a multi-layered approach. You need to enforce rules at three distinct levels: Wire Compatibility (will the app crash?), Source Compatibility (will the code compile?), and Logical Compatibility (will the data be misinterpreted?).
Here is a comprehensive design for a Protobuf Schema Evolution Guard, including the logical rules, an architectural design, and a practical implementation using the industry-standard buf CLI.
1. The Rules of Engagement
Before building the tool, we must define what constitutes a "Breaking Change." We categorize these into Safe (Non-Breaking) and Unsafe (Breaking) changes.
Wire & Source Safety Matrix
Action
Verdict
Reason
Add Field
✅ SAFE
Old clients ignore new fields; new clients see default values.
Rename Field
✅ SAFE (Wire) / ❌ UNSAFE (Code)
Wire format uses numbers. However, this breaks source code referencing the old name.
Rename Package
❌ UNSAFE
Changes the fully qualified path, breaking reflection and gRPC routing.
Remove Field
❌ UNSAFE
Old clients sending this field may cause errors or be rejected by new servers.
Change Field Type
❌ UNSAFE
Usually causes data corruption or parsing errors (e.g., int64 to string).
Change Field Number
❌ UNSAFE
This is equivalent to deleting a field and reusing its ID, causing data corruption.
Reuse Field Number
❌ UNSAFE
Never reuse a tag number within the same message, even if the field was deleted.
The "Retention" Trap (Logical Safety)
A critical, often missed edge case is JSON/Struct serialization.
Scenario: You rename a field user_id to uid.
Wire: Safe (uses tag 1).
Database/JSON:Breaking. If you serialize Proto to JSON (common in ElasticSearch or REST gateways), the key changes, causing data loss. The Guard must treat renames as breaking unless explicitly ignored.
2. System Architecture
The Guard acts as a gatekeeper in your CI/CD pipeline. It does not look at files in isolation; it compares the Current Proposed Schema against a Baseline Schema (the version currently in production).
mermaid
graph LR
A[Git Push / PR] --> B(CI Pipeline)
B --> C{Evolution Guard}
C --> D[Checkout 'main' proto files]
D --> E[Parser: Create Baseline AST]
C --> F[Parse Current Changes]
F --> G[Comparator Engine]
E --> G
G --> H{Check Rules}
H -- Violation Found --> I[Fail Build & Report]
H -- No Violations --> J[Allow Merge]
Core Components:
Parser: Reads .proto files into a manipulatable object (AST or FileDescriptor). Tools: protoc or protoreflect.
Snapshot Storage: Where the "Known Good State" lives. Usually the main branch of the git repo.
Comparator: Iterates through the old vs. new descriptors to find drift.
3. Implementation Strategy
While you can write a custom Python/Go script to parse protos, the industry standard is Buf CLI. It is faster, handles edge cases (like imports) correctly, and has a built-in breaking change detector.
The Configuration (buf.yaml)
Create a buf.yaml in the root of your project. This file defines the strictness of your guard.
yaml
# buf.yaml
version: v1
breaking:
use:
- FILE
- WIRE_JSON
except:
# Allow renaming fields if you strictly use binary gRPC and never JSON.
# This is risky, so we leave it commented out by default.
# - FIELD_NO_DELETE
ignore:
# Ignore legacy protos that are too messy to fix yet
- proto/legacy
lint:
use:
- DEFAULT
except:
- PACKAGE_VERSION_SUFFIX
The Guard Logic (CI Script)
Here is a design for a CI workflow script (e.g., GitHub Actions) that implements the guard.
Conceptual Logic (Pseudo-code):
python
def run_evolution_guard():
# 1. Get the reference (Baseline)
# Usually 'origin/main' or a specific git tag
baseline_ref = get_default_branch()
# 2. Build the current state
current_protos = compile_protos("./src")
# 3. Compare
# The tool outputs a list of violations
violations = compare_schemas(
current=current_protos,
against=baseline_ref
)
# 4. Enforce
if violations:
for v in violations:
print(f"ERROR: {v.file}:{v.line} - {v.message}")
print(f"Change ID: {v.field_id}")
exit(1) # Block the merge
else:
exit(0)
Actual Implementation (GitHub Actions):
yaml
# .github/workflows/proto-guard.yml
name: Proto Breaking Change Guard
on: [pull_request]
jobs:
buf-breaking:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: bufbuild/buf-setup-action@v1
- name: Breaking Change Detection
uses: bufbuild/buf-breaking-action@v1
with:
# The 'against' input creates the Baseline.
# It checks out the input_ref and compares it to the PR files.
against: 'https://github.com/${{ github.repository }}.git#branch=main'
4. Advanced Guard Features (The "Custom" Layer)
Standard tools check syntax. A robust Guard checks semantics. If you are building a custom internal tool, implement these specific validators:
A. The "Reserved" Enforcer
If a developer deletes a field, the guard must verify they added it to the reserved list.
Logic:
Detect Field deletion in message M.
Check if Field.Number exists in M.ReservedRange in the new schema.
Error: "Field 5 was deleted from Message A but not reserved. Reuse of tag 5 will cause wire corruption."
B. The "OneOf" Wire Safety
Moving a field into a OneOf is generally safe, but moving it out or moving it betweenOneOfs is often breaking depending on the language implementation (e.g., C++ oneof memory management).
Logic:
Check field parents.
If OldField.OneOf != NewField.OneOf, fail.
C. The SQL/Proto Correlation Guard
If your protobufs map directly to Database schemas (e.g., via ORM or Trino):
Logic:
Integrate with your DB schema loader.
If ProtoField is renamed, check if DatabaseColumn is renamed.
If DB is unchanged but Proto is, fail (logical mismatch).
5. Summary of Recommendations
To implement this successfully:
Enforce buf breaking in CI on every Pull Request.
Use WIRE_JSON lint category. It is stricter and safer than just WIRE. It treats field renames as breaking changes, preventing data loss in JSON-based microservices or logs.
Enforce "Reserve on Delete". Make it a policy that git rm on a proto field is invalid unless a reserved tag is added simultaneously.
Tag your releases. Do not compare against main forever. Compare against the last released artifact (e.g., git tag v1.2.0) to allow non-breaking changes on main to accumulate without blocking feature branches.