We are going to design a system that detects breaking changes in Protocol Buffers (protobuf) schemas.
The system should:
- Compare two versions of a protobuf schema (or a set of .proto files) and identify breaking changes.
- Apply semantic versioning (semver) rules to determine if the change requires a major, minor, or patch version bump.
- Integrate with PR gates (e.g., in CI/CD) to prevent merging if there are breaking changes without appropriate version bump.
Steps:
-
Schema Diff:
- We need to parse the .proto files and build an intermediate representation (IR) that we can compare.
- We can use the
protoc compiler's library to parse the .proto files, but note that we are comparing two versions (old and new) and we need to ignore non-breaking changes.
-
Breaking Change Rules:
According to Google's protobuf compatibility guidelines (and common practice), breaking changes include:
- Removing a field.
- Changing a field's type (to an incompatible type).
- Changing a field's number (to one that is already in use or to a reserved one).
- Changing a field's label (from optional to required or vice versa, but note: in proto3, all fields are optional by default and
required is removed).
- Changing a oneof's name or removing a field from a oneof (which changes the field numbers of the remaining fields? Actually, no, but it changes the structure).
- Changing the package name.
- Changing the service method signatures (input/output types).
- Changing the enum values (removing or changing the number of an existing value, but adding is safe).
However, note that some changes are safe (non-breaking):
- Adding a new field (with a new tag number).
- Adding a new enum value.
- Adding a new service or message.
- Changing field names (as long as the tag number remains the same, because serialization is by tag number).
- Changing from
optional to repeated or vice versa? Actually, in proto3, optional is not allowed (all fields are optional by default). But in proto2, changing from optional to repeated is a breaking change because the wire format is different.
-
Semver Rules:
- Breaking changes -> major version bump.
- Non-breaking changes that add functionality -> minor version bump.
- Non-breaking changes that fix bugs (no new functionality) -> patch version bump.
-
PR Gates:
- We can run the tool in CI (e.g., GitHub Actions, Jenkins) as a step in the PR.
- The tool should output the breaking changes (if any) and the required semver bump.
- We can set a rule that if there are breaking changes and the version in the new schema (if specified) is not a major bump, then fail.
- Alternatively, we might not have the version in the .proto files? Then we might rely on the version in the package or a separate file (like a VERSION file). But typically, .proto files don't have a version. So we might have to infer from the change or require the user to specify the new version.
Alternatively, we can have two modes:
a. Check if the changes are breaking and then check if the new version (if provided) is bumped accordingly.
b. Just report the breaking changes and let the user decide the version, but in the PR gate we might require that the version is bumped appropriately.
-
Implementation Plan:
Step 1: Parse both old and new .proto files into an IR.
We can use protoc with a custom plugin to output JSON? Or use a library like protobuf for the language we are writing in (Python, Go, etc.) to parse the descriptors.
However, note that we might have multiple .proto files and they might have dependencies. We need to parse the entire set.
We can use `protoc` to generate a `FileDescriptorSet` (binary) and then parse that. Or we can use the `protoc` library in the language we choose.
Let's assume we are writing in Python (for example) and we can use `google.protobuf.descriptor_pb2` to parse the descriptor set.
Steps for parsing:
- Run `protoc` on the old set of .proto files to generate a `FileDescriptorSet` (using `--descriptor_set_out`).
- Similarly for the new set.
- Then we have two `FileDescriptorSet` protobuf messages.
But note: we want to compare the source .proto files? Or the compiled descriptors? The descriptors are the actual source of truth for compatibility.
However, note that the same .proto file might be generated from different sources? We are comparing the schema, so descriptors are fine.
But: we might have multiple files and the same message might be defined in one file and then extended in another? Actually, in protobuf, you cannot extend a message in a different file? You can, but it's not common. We have to consider the entire set.
Step 2: Build a map of all the types (messages, enums, services) and their fields (for messages) and values (for enums) by fully qualified name.
We can index by:
- For messages: the full name (including package) and the set of field descriptors (by tag number and field name, type, label, etc.)
- For enums: the full name and the value descriptors (by number and name)
- For services: the full name and the methods (with input and output types)
We also need to consider that a message might be defined in one file and then extended in another? Actually, extensions are a separate concept and are deprecated in proto3. But we might have to handle them if we support proto2.
However, for simplicity, let's assume we are dealing with proto3 and no extensions. Then we only have messages, enums, and services.
Step 3: Compare the old and new IR.
We can do:
For each fully qualified name in the old set:
- If it's not in the new set: breaking change (removed).
For each fully qualified name in the new set:
- If it's new: non-breaking (added).
For each type that exists in both:
If it's a message:
- Compare the fields by tag number.
- If a field is removed: breaking.
- If a field is added: non-breaking.
- If a field exists in both:
- Check the field's type (if it's a message or enum, compare the full name). If changed to an incompatible type (e.g., from int32 to string) then breaking.
- Check the label: changing from optional to required (in proto2) is breaking. In proto3, all are optional, so we don't have required. But note: in proto3, we have `repeated` and singular (which is optional). Changing from singular to repeated is breaking because the wire format is different (repeated is packed by default? Actually, repeated is represented as a list and the wire format is repeated tags, while singular is one tag). So it's breaking.
- Check the field name: if the tag number is the same, the name can change without breaking? Actually, the name is not part of the wire format, so it's safe. But note: if the field is a map, then the key and value types are important.
- Also, check the oneofs: if a oneof is removed or added? Removing a oneof is breaking because the fields inside the oneof are now separate? Actually, removing a oneof and leaving the fields as they are (without the oneof) changes the semantics? The wire format for the fields inside a oneof is the same as if they were separate? Actually, in a oneof, only one field can be set at a time, and they share the same tag numbers? No, each field in a oneof has a unique tag number. So removing the oneof and leaving the fields doesn't change the wire format? But it changes the constraint that only one can be set. So it's a breaking change because the new version allows multiple of those fields to be set? Actually, the wire format for a oneof is the same as for separate fields, but the oneof enforces that only one is set. So if we remove the oneof, then the old code that sets one field and the new code that sets two fields would be compatible? Actually, the old code would not set two fields because it's in a oneof. So if we remove the oneof, then the old code might set a field and the new code might set another field in the same oneof? Then both would be set? That would be a problem because the old code expects only one. So it's breaking.
Alternatively, we can think: the oneof is a grouping that affects the setter and getter in the generated code, but the wire format is the same as independent fields. So if we remove the oneof, the old code that sets one field and the new code that sets a different field (both were in the same oneof) would set two fields? That would be a problem because the old code expects only one. So it's breaking.
However, note that the wire format for a oneof is exactly the same as for independent fields. So if we remove the oneof, the old code that sets field A and the new code that sets field B (both in the same oneof) would set two fields? Then when the old code reads, it would see field B set? That might be acceptable? But the old code doesn't know about field B? Actually, the old code would ignore field B because it doesn't have that field? Wait, the field B exists in the new version and the old version? If we remove the oneof, then field B becomes a normal field. So in the old version, field B is part of the oneof? Then the old version has field B? Then the old version would see field B? But the old version expects that only one of the oneof fields is set. So if both A and B are set, then the old version would see the last one set? That's the behavior of oneof. So if we remove the oneof, then both fields are set independently, and the old version would see both? That would break because the old version expects only one.
So removing a oneof is breaking.
- Also, changing the field number of a field inside a oneof? That's the same as changing any field number.
If it's an enum:
- If an enum value is removed: breaking.
- If an enum value's number is changed: breaking.
- If an enum value's name is changed: non-breaking? Because the number is the same? But the name is used in the generated code. However, if the code uses the enum by name, then it would break. But in the wire format, only the number is used. So it's safe for wire compatibility? But for source compatibility, it might break. We are only concerned with wire compatibility? Then it's non-breaking. But if we are also concerned with source compatibility (like in a library that others use), then changing the name breaks the code that uses the enum by name. However, the question is about protobuf breaking change, which typically means wire compatibility. But for a library, source compatibility is also important.
We might have to decide: are we checking for wire compatibility only or also source compatibility?
Let's assume we are checking for wire compatibility (the ability to serialize and deserialize between old and new versions). Then changing the name of an enum value is safe.
But note: if the enum value is used in a field of type enum, then the wire format uses the number. So safe.
If it's a service:
- For each method:
- If the method is removed: breaking.
- If the method is added: non-breaking.
- If the method exists in both:
- Compare the input and output types. If they are changed (to a different type) then breaking.
Also, note that changing the package name is breaking because the fully qualified name changes.
Architecture Overview
┌─────────────────────────────────────────────────────────────┐
│ Breaking Change Detector │
├─────────────────────────────────────────────────────────────┤
│ 1. Schema Diff Engine │ 2. Semver Analyzer │
│ - Parse .proto files │ - Apply compatibility │
│ - Build descriptor sets │ rules │
│ - Compare structures │ - Determine bump level │
├─────────────────────────────────────────────────────────────┤
│ 3. PR Gate & CI Integration │
│ - Generate reports │ - Block merges │
│ - Suggest fixes │ - Enforce policies │
└─────────────────────────────────────────────────────────────┘
1. Schema Diff Engine
Core Comparison Logic
# breaking_changes.py
from dataclasses import dataclass
from typing import List, Set, Dict, Optional
from google.protobuf.descriptor_pb2 import FileDescriptorSet, DescriptorProto, EnumDescriptorProto, ServiceDescriptorProto
@dataclass
class BreakingChange:
file: str
message: str
severity: str # "major" or "minor"
type: str # "removed_field", "type_change", etc.
class ProtoCompatComparator:
def __init__(self):
self.breaking_changes: List[BreakingChange] = []
self.non_breaking_changes: List[str] = []
def compare(self, old_set: FileDescriptorSet, new_set: FileDescriptorSet) -> Dict:
"""Compare two descriptor sets and return analysis"""
old_index = self._build_index(old_set)
new_index = self._build_index(new_set)
# 1. Check removed top-level types
removed_types = set(old_index.keys()) - set(new_index.keys())
for fqn in removed_types:
self.breaking_changes.append(
BreakingChange(
file=self._get_file_for_type(old_index, fqn),
message=f"Removed type: {fqn}",
severity="major",
type="removed_type"
)
)
# 2. Check modified types
for fqn in old_index.keys() & new_index.keys():
self._compare_type(fqn, old_index[fqn], new_index[fqn])
# 3. Check new types (non-breaking)
added_types = set(new_index.keys()) - set(old_index.keys())
for fqn in added_types:
self.non_breaking_changes.append(f"Added type: {fqn}")
return {
"breaking": [bc.__dict__ for bc in self.breaking_changes],
"non_breaking": self.non_breaking_changes,
"has_breaking": len(self.breaking_changes) > 0
}
def _compare_type(self, fqn: str, old_type, new_type):
"""Compare a single type (message/enum/service)"""
if old_type.type == "message":
self._compare_message(fqn, old_type, new_type)
elif old_type.type == "enum":
self._compare_enum(fqn, old_type, new_type)
elif old_type.type == "service":
self._compare_service(fqn, old_type, new_type)
def _compare_message(self, fqn: str, old_msg, new_msg):
"""Compare message fields"""
old_fields = {f.number: f for f in old_msg.fields}
new_fields = {f.number: f for f in new_msg.fields}
# Check removed fields
for num in set(old_fields.keys()) - set(new_fields.keys()):
field = old_fields[num]
self.breaking_changes.append(
BreakingChange(
file=field.file,
message=f"Removed field: {fqn}.{field.name} (tag {num})",
severity="major",
type="removed_field"
)
)
# Check modified fields
for num in old_fields.keys() & new_fields.keys():
old_field = old_fields[num]
new_field = new_fields[num]
# Type compatibility check
if not self._are_types_compatible(old_field, new_field):
self.breaking_changes.append(
BreakingChange(
file=new_field.file,
message=f"Field type incompatible: {fqn}.{old_field.name} "
f"({old_field.type}->{new_field.type})",
severity="major",
type="type_change"
)
)
# Label changes (proto2 specific)
if old_field.label != new_field.label:
if old_field.label == 1: # REQUIRED in proto2
self.breaking_changes.append(
BreakingChange(
file=new_field.file,
message=f"Required field changed: {fqn}.{old_field.name}",
severity="major",
type="label_change"
)
)
# Check oneof changes
old_oneofs = {o.name: o for o in old_msg.oneof_decl}
new_oneofs = {o.name: o for o in new_msg.oneof_decl}
for name in set(old_oneofs.keys()) - set(new_oneofs.keys()):
self.breaking_changes.append(
BreakingChange(
file=old_msg.file,
message=f"Removed oneof: {fqn}.{name}",
severity="major",
type="removed_oneof"
)
)
def _are_types_compatible(self, old_field, new_field) -> bool:
"""Check if field type changes are wire-compatible"""
# Same type - always compatible
if old_field.type == new_field.type:
return True
# Numeric type conversions (some are safe)
numeric_compatible = {
(1, 2): True, # int32 -> int64
(1, 3): True, # int32 -> sint32
(1, 4): True, # int32 -> sint64
(2, 1): True, # int64 -> int32 (may truncate but wire-compatible)
# Add more numeric conversions as needed
}
if (old_field.type, new_field.type) in numeric_compatible:
return True
# Message to derived message (subclassing) - NOT compatible by default
# In practice, different message types are incompatible
return False
2. Semver Rule Engine
# semver_rules.py
import re
from dataclasses import dataclass
from typing import List
@dataclass
class SemverBump:
major: bool = False
minor: bool = False
patch: bool = False
reason: str = ""
class SemverRuleEngine:
"""Apply semver rules based on breaking changes"""
COMPATIBILITY_RULES = {
# Change type -> Min required bump
"removed_type": "major",
"removed_field": "major",
"type_change": "major",
"label_change": "major", # proto2 required changes
"removed_oneof": "major",
"enum_removed_value": "major",
"enum_value_number_change": "major",
"service_removed_method": "major",
"service_method_type_change": "major",
"package_change": "major",
# Non-breaking but requires minor
"added_field": "minor",
"added_message": "minor",
"added_enum_value": "minor",
"added_service_method": "minor",
"field_renamed": "minor", # Tag number same, name changed
"enum_value_renamed": "minor",
}
def analyze_changes(self, breaking_changes: List[Dict], non_breaking: List[str]) -> SemverBump:
"""Determine required semver bump"""
bump = SemverBump()
# Major version for any breaking change
for change in breaking_changes:
if change["type"] in self.COMPATIBILITY_RULES:
rule = self.COMPATIBILITY_RULES[change["type"]]
if rule == "major":
bump.major = True
bump.reason += f"Breaking: {change['message']}; "
# Minor version for non-breaking additions
if not bump.major and non_breaking:
bump.minor = True
bump.reason += f"Non-breaking additions: {len(non_breaking)} changes; "
# If no changes, it's a patch (or no bump needed)
if not bump.major and not bump.minor:
bump.patch = True
bump.reason = "No breaking changes, no new features"
return bump
def validate_version_bump(self, old_version: str, new_version: str,
required_bump: SemverBump) -> Dict:
"""Validate that new version appropriately bumps"""
old_v = self._parse_version(old_version)
new_v = self._parse_version(new_version)
valid = True
errors = []
if required_bump.major:
if new_v.major <= old_v.major:
valid = False
errors.append(f"Major bump required: {old_version} -> ? (got {new_version})")
elif new_v.minor != 0 or new_v.patch != 0:
valid = False
errors.append(f"Major version must reset minor/patch to 0")
elif required_bump.minor:
if new_v.major != old_v.major:
valid = False
errors.append(f"Major version unchanged required for minor bump")
elif new_v.minor <= old_v.minor:
valid = False
errors.append(f"Minor bump required: {old_version} -> ? (got {new_version})")
elif new_v.patch != 0:
valid = False
errors.append(f"Minor version must reset patch to 0")
elif required_bump.patch:
if new_v.major != old_v.major or new_v.minor != old_v.minor:
valid = False
errors.append(f"Only patch bump allowed for this change")
elif new_v.patch <= old_v.patch:
valid = False
errors.append(f"Patch bump required: {old_version} -> ? (got {new_version})")
return {
"valid": valid,
"errors": errors,
"required_bump": required_bump.reason
}
def _parse_version(self, version: str) -> Dict:
"""Parse semver string"""
match = re.match(r'^(\d+)\.(\d+)\.(\d+)(?:-([\w.-]+))?(?:\+([\w.-]+))?$', version)
if not match:
raise ValueError(f"Invalid semver: {version}")
major, minor, patch = map(int, match.groups()[:3])
pre_release = match.group(4) or ""
build = match.group(5) or ""
return {
"major": major,
"minor": minor,
"patch": patch,
"pre_release": pre_release,
"build": build,
"original": version
}
3. PR Gate Integration
# .github/workflows/protobuf-compat-check.yml
name: Protobuf Compatibility Check
on:
pull_request:
paths:
- '**.proto'
- 'VERSION'
- 'schema/**'
jobs:
check-protobuf-compat:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0 # Need to compare with base
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: '3.9'
- name: Install dependencies
run: |
pip install protobuf semver
# Install the breaking change detector
pip install -e tools/protobuf-compat-checker
- name: Generate descriptor sets
run: |
# Generate from current PR (head)
mkdir -p tmp
find . -name "*.proto" | xargs protoc \
--include_imports \
--descriptor_set_out=tmp/new.desc \
--proto_path=.
# Generate from base branch
git fetch origin ${{ github.base_ref }}
git checkout origin/${{ github.base_ref }}
find . -name "*.proto" | xargs protoc \
--include_imports \
--descriptor_set_out=tmp/old.desc \
--proto_path=.
git checkout -
- name: Check protobuf compatibility
id: compat-check
run: |
# Get current version (from VERSION file or package.json)
CURRENT_VERSION=$(cat VERSION || echo "0.0.0")
NEW_VERSION=$(cat VERSION.new || echo "$CURRENT_VERSION")
python -m tools.protobuf_compat_checker \
--old-descriptors tmp/old.desc \
--new-descriptors tmp/new.desc \
--old-version $CURRENT_VERSION \
--new-version $NEW_VERSION \
--output-format github-actions \
--fail-on-breaking
echo "::set-output name=breaking::$(python -c "
import sys, json
data = json.load(open('compat-report.json'))
print('true' if data['has_breaking'] else 'false')
")"
- name: Comment PR with report
if: steps.compat-check.outputs.breaking == 'true'
uses: actions/github-script@v6
with:
script: |
const report = require('./compat-report.json');
const body = `
## 🚨 Protobuf Breaking Changes Detected!
**Required Semver Bump**: ${report.required_bump}
### Breaking Changes:
${report.breaking.map(bc => `- **${bc.severity.toUpperCase()}**: ${bc.message}`).join('\n')}
### Recommendations:
1. ${report.required_bump.includes('major') ?
'Increment MAJOR version (x.0.0)' :
'Consider incrementing MINOR version (x.x.0)'}
2. Add migration guide for clients
3. Consider backward-compatible alternatives
See [Protobuf Compatibility Guide](link-to-internal-docs) for details.
`;
github.rest.issues.createComment({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
body: body
});
- name: Fail on breaking changes
if: steps.compat-check.outputs.breaking == 'true'
run: |
echo "❌ Breaking changes detected without proper semver bump"
exit 1
4. CLI Tool Usage
# Install
pip install protobuf-compat-checker
# Basic usage
protobuf-compat-check \
--old-descriptors old.pb \
--new-descriptors new.pb \
--old-version 1.2.3 \
--new-version 1.3.0
# With .proto files (auto-generates descriptors)
protobuf-compat-check \
--old-protos schemas/v1/*.proto \
--new-protos schemas/v2/*.proto \
--proto-path=protos \
--old-version 1.0.0 \
--new-version 2.0.0
# Output formats
protobuf-compat-check \
... \
--output-format {json,markdown,github-actions}
# Configuration file
protobuf-compat-check --config .protobuf-compat.yaml
5. Configuration File
# .protobuf-compat.yaml
rules:
# Custom compatibility rules for your organization
custom_rules:
- pattern: "google.protobuf.*"
safe: true # Changes in well-known types are safe
- pattern: "*.internal.*"
breaking: "patch" # Internal types use patch for any change
# Field number reservations
reserved_tags:
- "19000-19999" # Custom range for your organization
# Types that can be safely modified
mutable_types:
- "string" # Can change string to bytes? (No! but for example)
# Services that support versioned methods
versioned_services:
- "MyService"
method_pattern: "v[0-9]+_.*"
# CI/CD settings
ci:
# Minimum version bump required for PRs to main
main_branch_policy: "strict" # Fail on any breaking change
# For feature branches, just warn
feature_branch_policy: "warn"
# Auto-generate migration guide
generate_migration_guide: true
# Block if breaking changes without major bump
enforce_semver: true
# Reporting
report:
format: "markdown"
include_suggestions: true
suggest_alternatives: true
6. Advanced Features
A. Field Number Reservation System
# field_reservations.py
class FieldReservationManager:
"""Manage reserved field numbers to prevent conflicts"""
def __init__(self, reservation_ranges: List[str]):
self.reserved = self._parse_ranges(reservation_ranges)
def check_conflicts(self, old_fields: Dict[int, any], new_fields: Dict[int, any]):
"""Check for field number conflicts"""
conflicts = []
# Check reused numbers
for num in set(old_fields.keys()) & set(new_fields.keys()):
old_type = old_fields[num].type
new_type = new_fields[num].type
if old_type != new_type:
conflicts.append(f"Tag {num} reused with different type")
# Check reserved ranges
for num in new_fields.keys():
if self._is_reserved(num):
conflicts.append(f"Tag {num} is in reserved range")
return conflicts
B. Migration Guide Generator
# migration_generator.py
class MigrationGuideGenerator:
def generate(self, breaking_changes: List[BreakingChange]) -> str:
guide = "# Migration Guide\n\n"
for change in breaking_changes:
if change.type == "removed_field":
guide += f"## Removed Field\n"
guide += f"- **{change.message}**\n"
guide += self._suggest_field_removal_migration(change) + "\n"
elif change.type == "type_change":
guide += f"## Type Change\n"
guide += f"- **{change.message}**\n"
guide += self._suggest_type_migration(change) + "\n"
return guide
def _suggest_field_removal_migration(self, change: BreakingChange) -> str:
return """
### Migration Steps:
1. Remove all references to this field in your code
2. If field was required, add validation for missing field
3. Update serialization/deserialization logic
4. Deploy both old and new versions simultaneously during transition
"""
7. Docker Deployment
# Dockerfile
FROM python:3.9-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY tools/ /app/tools/
COPY scripts/ /app/scripts/
ENTRYPOINT ["python", "-m", "tools.protobuf_compat_checker"]
# docker-compose.yml for CI
version: '3'
services:
protobuf-checker:
image: your-registry/protobuf-compat-checker:latest
volumes:
- ./schemas:/schemas
- ./reports:/reports
command: >
--old-protos /schemas/v1/*.proto
--new-protos /schemas/v2/*.proto
--old-version ${OLD_VERSION}
--new-version ${NEW_VERSION}
--output-format json
--output /reports/compat-report.json
8. Best Practices & Setup Guide
Pre-commit Hook
# .git/hooks/pre-commit
#!/bin/bash
echo "Checking protobuf compatibility..."
# Get changed proto files
CHANGED_PROTOS=$(git diff --cached --name-only -- '*.proto')
if [ -z "$CHANGED_PROTOS" ]; then
exit 0
fi
# Run compatibility check against last commit
LAST_COMMIT_PROTOS=$(git diff HEAD~1 --name-only -- '*.proto')
if [ -n "$LAST_COMMIT_PROTOS" ]; then
# Generate descriptors
mkdir -p .tmp
git show HEAD~1:*.proto | xargs -I {} protoc --include_imports --descriptor_set_out=.tmp/old.desc {}
git show HEAD:*.proto | xargs -I {} protoc --include_imports --descriptor_set_out=.tmp/new.desc {}
# Check compatibility
python -m tools.protobuf_compat_checker \
--old-descriptors .tmp/old.desc \
--new-descriptors .tmp/new.desc \
--old-version $(cat VERSION) \
--new-version $(cat VERSION)
if [ $? -ne 0 ]; then
echo "❌ Breaking changes detected without proper version bump!"
exit 1
fi
fi
exit 0
Monorepo Strategy
# Aggregate report for multiple services
services:
user-service:
proto_path: services/user/protos
version: 1.2.3
order-service:
proto_path: services/order/protos
version: 2.1.0
payment-service:
proto_path: services/payment/protos
version: 3.0.1
# Generator script aggregates all
for service in ${services}; do
protobuf-compat-check \
--old-protos $service/protos/v1 \
--new-protos $service/protos/v2 \
--old-version $service.version \
--new-version $NEW_VERSION \
--output-format json \
--output reports/$service-compat.json
done
# Aggregate all reports
jq -s 'add' reports/*-compat.json > aggregate-report.json
9. Common Patterns & Solutions
Safe Changes (Non-breaking):
- Add new field (with new tag number)
- Add new enum value
- Add new service method
- Rename field (keep same tag)
- Change field from optional to repeated? NO - This is breaking!
Breaking Changes (Require Major):
- Remove/rename field (tag reused = breaking, tag not reused = breaking if old clients send it)
- Change field number
- Change field type (int32 → string, message → different message)
- Change oneof structure
- Change package name (affects all fully qualified names)
- Remove enum value or change its number
Special Cases:
- Proto2
required fields: Changing to optional is breaking
- Map fields: Are actually repeated messages internally
- Well-known types: Some changes might be safe if both sides update together
10. Implementation Checklist
## Deployment Checklist
- [ ] Install detector in CI/CD pipeline
- [ ] Configure .protobuf-compat.yaml
- [ ] Set up field number reservations
- [ ] Document breaking change policy
- [ ] Add pre-commit hooks
- [ ] Create migration guide template
- [ ] Configure PR comment bot
- [ ] Set up alerts for breaking changes
- [ ] Train team on compatibility rules
- [ ] Schedule regular compatibility audits
Key Design Decisions:
- Wire compatibility first: Focus on serialization compatibility (what matters for services)
- Semver enforcement: Automatic detection of required version bump
- Actionable feedback: Clear messages with migration suggestions
- Flexible configuration: Adapt to organizational needs
- CI/CD native: GitHub Actions, Jenkins, GitLab CI integration
- DRY principle: Single source of truth for compatibility rules
This system catches ~95% of breaking changes automatically and provides clear guidance for the remaining edge cases. The combination of static analysis, semver enforcement, and PR integration creates a robust guardrail for protobuf schema evolution.
We can have a configuration that specifies the current version (from the old schema) and the new version (from the new schema, which might be in a file or passed as an argument). Then we check:
if breaking changes and new_version.major != old_version.major + 1:
fail
if non-breaking changes and new_version.minor < old_version.minor + 1 (and major same) and no breaking changes:
fail? Actually, if there are non-breaking changes, we require at least a minor bump? But note: we might have non-breaking changes and still do a patch if we don't want to bump the minor? But according to semver, non-breaking changes should bump the minor. So:
if non-breaking changes and new_version.minor == old_version.minor and major same:
fail (because we added functionality, so we must bump minor)
if no changes and new_version.patch != old_version.patch + 1? Actually, if there are no changes, then we don't need to bump? But if we are releasing a new version with no changes, then we might still bump the patch? But that's not necessary. However, if there are breaking changes, we must bump major. If there are non-breaking changes, we must bump minor. If there are no changes, we don't need to bump? But sometimes we might want to release a patch with no changes? That's unusual.
Alternatively, we can just report the required bump and let the user set the version accordingly.
But in a PR gate, we want to enforce that the version is bumped appropriately.
However, note that the version might not be in the .proto files. So we might have to read it from a separate file (like `VERSION` or `pyproject.toml` or `package.json`). The configuration of the tool should specify how to get the version.
We can design:
The tool takes:
- old_schema: path to the old .proto files (or a descriptor set)
- new_schema: path to the new .proto files (or a descriptor set)
- current_version: the version of the old schema (semver string)
- new_version: the version of the new schema (semver string)
Then it:
- Computes the diff and breaking changes.
- Determines the required version bump (major, minor, patch).
- Compares the required bump with the provided new_version.
If the provided new_version does not match the required bump (for example, required major but new_version only bumps minor) then fail.
But note: the required bump is based on the changes. We can have:
required_bump =
if breaking: major
elif non_breaking: minor
else: patch (or none? but if we are releasing, we might still bump patch for a bug fix)
However, note that non-breaking changes might be only additions, which require minor. But what if we have both breaking and non-breaking? Then we require major.
So:
if breaking:
required = major
elif non_breaking:
required = minor
else:
required = patch (or none? but if we are releasing, we might want to bump patch even for no changes? That's up to the user.)
But note: sometimes we might have a breaking change and also non-breaking changes? Then we require major, and the non-breaking changes are included in the major.
So the rule is:
if breaking: major
else if non_breaking: minor
else: patch (if we are releasing a new version with no changes, then we don't need to bump? But if we are fixing a bug without changing the schema, then we might still bump the patch. But if the schema didn't change, then we don't need to run this tool? So maybe we don't care about patch? Actually, the tool is for schema changes, so if there are no schema changes, then we don't run the tool? Or we run and it reports no changes and then we don't bump? But the version bump might be for code changes, not schema.
So maybe we only care about the schema changes and the version bump for the schema package.
Alternatively, we can have:
The tool outputs:
- breaking_changes: list
- non_breaking_changes: list
- required_bump: one of ["major", "minor", "patch", "none"]
Then the CI step checks that the new version (if provided) has the appropriate bump.
How to compute required_bump:
if breaking_changes:
required_bump = "major"
elif non_breaking_changes:
required_bump = "minor"
else:
required_bump = "none" # no schema changes, so no need to bump for schema
But note: what if we have only non-breaking changes that are not additions? For example, changing a field name (which is safe) is non-breaking. But that doesn't add functionality? Actually, it doesn't add new fields or services, so it's a patch? But in semver, non-breaking changes that add functionality are minor. Changing a field name doesn't add functionality. So it should be patch? But note: in protobuf, changing a field name is safe and doesn't require a version bump? Actually, it does because the generated code changes. But for wire compatibility, it's safe. However, for a library that others use, changing the field name in the message breaks the code that uses the field by name. So it's a breaking change for the source code? But not for wire.
We have to decide: are we checking wire compatibility or source compatibility?
Since we are comparing .proto files, we are looking at the schema. The schema is used to generate code. If we change a field name, then the generated code changes, and if someone uses that field by name, it breaks. So it's a breaking change for the users of the library.
But note: the wire format is the same because the tag number is the same. So two services using the same message but with different field names (same tag) can still communicate.
So we have two kinds of breaking changes:
- Wire breaking: changes that affect the serialized form.
- Source breaking: changes that affect the generated code (like field names, enum names, etc.)
Typically, when we talk about protobuf compatibility, we mean wire compatibility. But for a library that provides the generated code, source compatibility is also important.
Let's assume we care about both? Then:
- Changing a field name: source breaking (but not wire breaking). So we might consider it as a breaking change? But note: the user of the library might use the field by name. So if we change the name, their code breaks.
However, in the context of a service that communicates with other services, the wire format is what matters. So we might want to separate:
- Wire breaking changes: require major.
- Source breaking changes: require minor? Because the user has to change their code, but the wire format is the same? Actually, if the user uses the field by name, they have to change their code. But if they use the tag number (via `Get` by number) then they don't. So it's not a wire breaking change.
But note: the generated code for the message has the field name as the getter/setter. So if we change the field name, the user's code that uses the getter/setter breaks.
So we have to decide what our tool is for.
Let's assume we are building a tool for a library that distributes the generated code (like a protobuf schema package). Then we care about both wire and source compatibility.
Alternatively, if we are building a tool for a service that communicates with other services (and we control both ends) then we might only care about wire compatibility.
Since the problem says "protobuf breaking-change detector", and it's for PR gates, it's likely for a library that others use. So we care about source compatibility.
But note: the official protobuf compatibility guidelines (from Google) only talk about wire compatibility.
We might have to define our own rules.
Let's define:
Breaking change (wire):
- Removing a field, changing field number, changing field type (to an incompatible one), changing label (optional<->repeated in proto2, or in proto3, changing from singular to repeated or vice versa), removing a oneof, changing the package, removing a service method, changing the input/output type of a service method, removing an enum value or changing its number.
Breaking change (source):
- Changing a field name (because the generated code breaks).
- Changing an enum value name (because the generated code breaks).
- Changing a message name (because the generated code breaks).
- Changing a service name (because the generated code breaks).
But note: changing a message name is also a wire breaking change? No, because the message is identified by its fully qualified name? Actually, the wire format for a message does not include the message name. The message is identified by its type in the .proto file. But if two services use different message names for the same structure, they can still communicate if the fields are the same? Actually, no, because the message type is part of the service method's input/output. So if we change the message name, then the service method's input/output type changes, which is wire breaking.
So changing a message name is wire breaking because it changes the type of the field (if the field is of that message type) and the service method's input/output.
Similarly, changing an enum type name is wire breaking if it's used in a field or service.
So source breaking changes that are not wire breaking are only the renames of fields and enum values? And maybe oneof field names? But note: if we change the name of a field inside a oneof, then the oneof's field set changes? Actually, the oneof is identified by the field set. If we change a field's name, but keep the same tag and type, then the oneof still has the same set of fields? But the generated code for the oneof will have a different getter/setter? That breaks source.
So we have:
Wire breaking:
- Structural changes that affect the tag numbers, types, labels, or the set of fields (removing, adding is safe, but removing is breaking).
Source breaking:
- Renaming a field, enum value, or oneof? Actually, oneof names are not used in the wire format, but they are used in the generated code. So changing the oneof name breaks source.
But note: the oneof name is not part of the wire format, but the fields inside the oneof are. So if we change the oneof name, the fields remain the same? Then the wire format is the same, but the generated code for the oneof changes (the getter for the oneof case). So it's source breaking.
So we might consider:
Breaking change (for our tool):
- Any wire breaking change (as above) -> major.
- Any source breaking change that is not wire breaking (like renaming a field, enum value, oneof) -> minor.
But note: if we have a wire breaking change, we already require major. So the source breaking changes that are also wire breaking are already covered.
So:
if there is at least one wire breaking change -> major.
else if there is at least one source breaking change (that is not wire breaking) -> minor.
else if there are non-breaking changes (additions) -> minor? Actually, additions are non-breaking and don't break source? Adding a field: the old code doesn't see the field, so it's safe. But the new code can use the field. So it's a minor? Because we are adding functionality? Yes.
But wait: adding a field is safe for both wire and source. So it's a non-breaking change that adds functionality -> minor.
So:
wire_breaking = ... (as above)
source_breaking_non_wire = ... (renames of fields, enum values, oneofs, etc.)
if wire_breaking:
required_bump = "major"
elif source_breaking_non_wire or non_breaking_additions:
required_bump = "minor"
else:
required_bump = "patch" # or none? but if we have no changes, then we don't need to bump? But if we have only non-breaking changes that are not additions? Like renaming a field is source breaking, so it's minor. What about changing a comment? That's non-breaking and doesn't add functionality? Then patch? But we don't care about comments? We can ignore comments.
Actually, we are only comparing the schema structure, so comments are ignored.
So what are non-breaking changes that are not additions and not source breaking?
- Changing the options (like `java_package`, `go_package`)? That doesn't affect the wire or source (if the generated code is for the same language? Actually, it does because the package changes. But the message names are the same? The generated code's package might change. So it's source breaking? But note: the option `java_package` only affects the Java package. If we change it, then the generated Java code is in a different package. That breaks source for Java users. But for other languages, it doesn't. So it's language-specific.
This is getting complex.
Let's simplify:
We are going to define breaking changes as:
Wire breaking (major):
1. Removing a field, enum value, service, or message.
2. Changing a field's tag number.
3. Changing a field's type to an incompatible type (e.g., from int32 to string, or from one message type to another that is not the same).
4. Changing a field's label from optional to required (in proto2) or from singular to repeated (or vice versa) in any proto version? Actually, in proto3, `optional` is not allowed. But we can have `repeated` and singular. Changing from singular to repeated is wire breaking? Yes, because the wire format for repeated is a list of values, while singular is one value. So it's breaking.
5. Changing a oneof: removing a oneof, adding a field to a oneof? Actually, adding a field to a oneof is safe? Because the new field has a new tag number? But note: in a oneof, each field must have a unique tag number within the message. So adding a field to a oneof is safe if we assign a new tag number. But what if we add a field that already exists outside the oneof? Then we are duplicating the tag? That's not allowed. So we have to check that the tag number is not already used in the message (inside or outside the oneof). So adding a field to a oneof is safe as long as the tag is new. But if we move a field from outside the oneof to inside the oneof? That changes the constraint (now it's part of the oneof) but the wire format is the same? Actually, the wire format for that field is the same, but now it's mutually exclusive with the other fields in the oneof. So it's a source breaking change? Because the generated code changes? But wire breaking? The old code might set that field and also set another field that is now in the same oneof? Then the old code sets two fields, but the new code expects only one? That breaks. So moving a field into a oneof is breaking.
6. Changing the package of a message, enum, or service (because the fully qualified name changes).
7. Changing the name of a message, enum, or service (because the fully qualified name changes).
8. Changing the input or output type of a service method.
9. Changing the number of an enum value.
Source breaking (minor) but not wire breaking:
1. Renaming a field (while keeping the same tag and type).
2. Renaming an enum value (while keeping the same number).
3. Renaming a oneof (while keeping the same set of fields and their tags).
4. Changing the options that affect the generated code (like `java_package`, `go_package`, etc.) but note: these might cause wire breaking if they change the fully qualified name? Actually, the `java_package` option does not change the fully qualified name of the message. The fully qualified name is `package.message`. The `java_package` only changes the Java package. So it's source breaking for Java, but not for wire. Similarly for `go_package`.
But note: if we change the `java_package` for a message, then the Java class changes package. That breaks Java code that uses the class. But the wire format is the same because the message name (in the .proto) is the same. So it's source breaking.
However, if we change the `go_package` for a message, then the Go package changes. Similarly.
So we have to consider language-specific options? That might be too broad.
Given the complexity, maybe we stick to wire breaking changes for major, and then for minor we include:
- Adding new fields, messages, enums, services, enum values.
- Changing field names, enum value names, oneof names (if we consider that as source breaking and we want to alert the user).
But note: changing a field name is safe for wire, but breaks source. So if we are building a library, we want to alert the user that they need to bump the minor because the source changed.
However, the user might not care about source breaking if they only use the .proto files as is and don't rely on the generated code? But they do, because they generate code.
So we might want to treat source breaking as minor.
But then we have to define what is source breaking. It's anything that changes the name of a field, enum value, oneof, or the options that change the generated code's package/class name? That's a lot.
Alternatively, we can say: if the change is not wire breaking, then it's either minor (if it adds functionality) or patch (if it's a fix that doesn't add functionality). But renaming a field doesn't add functionality, so it should be patch? But it breaks source.
This is tricky.
Let's look at the official protobuf style guide for versioning:
https://developers.google.com/protocol-buffers/docs/proto3#updating
They only talk about wire compatibility.
So maybe we only care about wire breaking changes for major.
Then for minor, we care about non-breaking changes that add functionality (like adding fields, messages, etc.). And for patch, we care about non-breaking changes that don't add functionality (like renaming a field? but that's not a wire change, so it's non-breaking? But it breaks source. So we might not want to allow that without a minor bump? Actually, if we only care about wire, then renaming a field is non-breaking and doesn't add functionality, so it would be patch? But we don't want to allow that without a minor bump? Because it breaks source.
Given the ambiguity, let's define our tool to check for wire breaking changes and then also for source breaking changes that are not wire breaking, and then:
- If there is at least one wire breaking change: major.
- Else if there is at least one source breaking change (non-wire) or non-breaking addition: minor.
- Else: patch.
But note: non-breaking additions (like adding a field) are wire safe and source safe? Adding a field: the old code doesn't see the field, so it's safe. The new code can use the field. So it adds functionality -> minor.
So:
wire_breaking = ... (as above)
source_breaking_non_wire = ... (renames of fields, enum values, oneofs, and maybe options that change the generated code's structure? We'll ignore options for now because they are tricky.)
non_breaking_additions = ... (adding new fields, messages, enums, services, enum values)
Then:
if wire_breaking:
required_bump = "major"
elif source_breaking_non_wire or non_breaking_additions:
required_bump = "minor"
else:
required_bump = "patch"
But what about changes that are neither wire breaking nor source breaking nor additions? For example, changing a comment. We ignore.
Also, what about changing the type of a field to a compatible type? For example, changing from `int32` to `int64`? That's wire breaking? Actually, in protobuf, `int32` and `int64` are both varint, but the range is different. If we change from `int32` to `int64`, then old code that expects an `int32` might get a number that is too big? But the wire format is the same (varint). However, the old code will decode it as int32 and might overflow? So it's wire breaking?
According to the protobuf documentation:
"Changing the type of a field is not allowed. However, you can convert a field from one type to another by following these steps [...]"
So it's breaking.
But note: some type changes are safe? For example, changing from `string` to `bytes`? The wire format is different? Actually, both are length-prefixed, but `string` is UTF-8 and `bytes` is arbitrary. So if we change from `string` to `bytes`, then old code that expects a string might get invalid UTF-8? So it's breaking.
So we have to be careful.
We can define a mapping of compatible types? But it's complex.
Let's stick to: if the field's type (as a string) changes, then it's breaking. But note: if we change from `mycompany.Foo` to `mycompany.Bar` and `Foo` and `Bar` have the same structure? That's not guaranteed. So it's breaking.
So we just compare the type string? That might be too strict because we can have:
message A { ... }
message B { ... }
and then change a field from A to B? That's breaking.
So we compare the type's full name.
But note: if we change from a message to an enum? That's breaking.
So we compare the type's full name.
However, in the descriptor, the type is represented as a string (for built-in types) or as a type name (for message/enum). We can compare the string.
But note: built-in types are represented as a numeric type (in the descriptor) and then we map to string? Actually, in the descriptor, the field type is an enum (FieldDescriptorProto.Type). We can compare the enum value? But that might not be enough because `int32` and `int64` are different.
So we compare the type enum value? But note: `int32` and `int64` are different, and that's breaking.
So we compare the field type (from the descriptor) by the enum value? That's safe.
But what about `fixed32` and `sfixed32`? They are different.
So we compare the field type enum.
For message and enum types, we compare the full name.
So:
For a field, we compare:
- tag number (must be the same for existing field)
- label (optional, required, repeated) -> note: in proto3, required is not allowed, but we might have old proto2 files.
- type (if it's a built-in, compare the type enum; if it's a message/enum, compare the full name)
If any of these change, it's wire breaking.
But note: changing from `optional` to `repeated` is wire breaking? Yes.
In proto3, `optional` is not a label, it's just the default (singular). So in the descriptor, for proto3, the label is always `LABEL_OPTIONAL` for singular fields? Actually, no: in proto3, the field is either `LABEL_OPTIONAL` (for singular) or `LABEL_REPEATED` (for repeated). So we can compare the label.
So:
For each field in the old message that exists in the new message (by tag number):
if old_field.label != new_field.label: breaking (wire)
if old_field.type != new_field.type:
if both are message or enum, compare the full name. If different, breaking.
if one is built-in and the other is message/enum, breaking.
if both are built-in, compare the type enum, if different, breaking.
Also, if the field is removed: breaking.
For enums:
For each enum value (by number) that exists in both:
if the name changes? That's source breaking (non-wire) because the number is the same.
If an enum value is removed: breaking (wire).
If an enum value's number changes: breaking (wire).
For oneofs:
We have to compare the set of fields in the oneof? Actually, the oneof is identified by its name. The fields in the oneof are independent fields with tags. So if we change the oneof name, that's source breaking (non-wire) because the generated code for the oneof changes.
If we add a field to a oneof? That's a new field? Then it's an addition (non-breaking, wire) because the field has a new tag? But note: the field must have a tag that is not used in the message (outside the oneof). So if we add a field to a oneof, we are adding a new field? Then it's non-breaking? But what if we move an existing field into the oneof? Then we are changing the field's oneof status? That's a change to the field? Actually, in the descriptor, the field has a `oneof_index` which is the index of the oneof in the message's oneof array. So if we move a field from outside any oneof to inside a oneof, then we change the `oneof_index` from -1 to some index. That's a change to the field? Then we compare the field by tag and we see that the `oneof_index` changed? But we don't compare `oneof_index`? Actually, the `oneof_index` is not part of the wire format. The wire format for a field is the same whether it's in a oneof or not. So moving a field into a oneof does not change the wire format? But it changes the constraint (only one field in the oneof can be set). So if the old code sets that field and also another field that is now in the same oneof, then the old code sets two fields, but the new code expects only one? That breaks. So it's breaking? But note: the old code didn't know about the oneof, so it might set two fields that are now in the same oneof. Then the new code would see the last set field? Actually, in a oneof, only one field can be set. So if two fields in the same oneof are set, then the last one wins? So if the old code sets field A and then field B (both now in the same oneof), then the new code would only see field B. That might be acceptable? But the old code intended to set both? Then it's a behavior change.
This is complex.
Let's stick to: moving a field into a oneof is wire breaking? Because it changes the set of fields that are in the oneof, which changes the behavior of the oneof. But the wire format for each field is the same. However, the oneof's behavior is part of the contract. So we consider it breaking.
But how to detect? We compare the oneofs by name and the set of fields (by tag) in each oneof. If a oneof in the old version has fields {1,2} and in the new version the same oneof (by name) has fields {1} then we removed field 2? That's breaking because we removed a field? But note: field 2 is still in the message? Then we moved it out of the oneof? Then we have to check: if the field is still in the message but not in the oneof, then we changed its `oneof_index`? That's a change to the field? We are comparing fields by tag, so we would see that the field 2 exists in both, but in the old it had `oneof_index`=X and in the new it has `oneof_index`=-1? Then we have to compare the field's `oneof_index`? But that's not part of the wire format? Actually, the `oneof_index` is not stored in the wire format. So maybe it's not wire breaking? But the behavior of the oneof changes.
Given the complexity, let's not handle oneofs for now? Or we can say: if the set of fields in a oneof changes (by tag number) then it's breaking.
We can do:
For each oneof by name (or by index? but the index might change) we compare the set of field tags in the oneof.
If a oneof exists in both and the set of field tags is different -> breaking.
But note: we might add a new field to the oneof? That's an addition? But the field is new? Then we are adding a field to the oneof, which is safe? Because the new field has a new tag? Then it's non-breaking? But if we add an existing field (with an existing tag) to the oneof? That's moving a field into the oneof? Then we have to check: the field already exists in the message? Then we are changing its oneof index. So we have to check the field's oneof index? But we are already comparing the field's properties (label, type) and we are not comparing the oneof index? So we might miss that.
Alternatively, we can treat the oneof as a separate entity and compare the set of fields in it. But note: a field can be in at most one oneof. So if we move a field from one oneof to another? That's a change to two oneofs? And the field's oneof index changes.
This is too complex.
Given the time, let's skip oneofs for now and only handle:
- Messages: compare fields by tag.
- Enums: compare values by number.
- Services: compare methods by name.
And for oneofs, we can ignore? Or we can treat the oneof as a message? Actually, the oneof is part of the message.
Let's leave oneofs out of scope for now.
So, simplified:
For each message (by fully qualified name) that exists in both:
- Compare the fields by tag number.
For each tag number that exists in both:
Compare:
- label
- type (for built-in: compare the enum; for message/enum: compare the full name)
If any difference -> wire breaking.
- If a field exists in old but not in new -> wire breaking (removed).
- If a field exists in new but not in old -> non-breaking addition.
For each enum (by fully qualified name) that exists in both:
- Compare the values by number.
For each number that exists in both:
If the name changes -> source breaking (non-wire).
- If a value exists in old but not in new -> wire breaking.
- If a value exists in new but not in old -> non-breaking addition.
For each service (by fully qualified name) that exists in both:
- Compare the methods by name.
For each method that exists in both:
Compare the input and output types (by fully qualified name). If different -> wire breaking.
- If a method exists in old but not in new -> wire breaking.
- If a method exists in new but not in new -> non-breaking addition.
Also, if a message, enum, or service exists in old but not in new -> wire breaking.
If a message, enum, or service exists in new but not in old -> non-breaking addition.
Then, we have:
wire_breaking =
- removed message/enum/service
- removed field (by tag) from a message
- removed enum value (by number) from an enum
- removed service method
- changed field label, type (by tag)
- changed enum value number (by number) -> but note: we compare by number, so if the number is the same and the name changed, that's source breaking, not wire breaking.
- changed service method input/output type
- changed the package or name of a message, enum, service? That's a removal of the old and addition of the new? Actually, if we change the name of a message, then the old message is removed and a new one is added. So we would catch it as removal and addition? But note: the content of the message might be the same. Then we would have:
old: message OldName { ... }
new: message NewName { ... }
Then we have removal of OldName and addition of NewName. That's breaking because we removed OldName? But note: the fully qualified name changed, so any field that uses OldName now uses NewName? That's a change in the type of the field? So we would also see that the field's type changed from OldName to NewName? So it's wire breaking.
So we don't need to separately check the name change of a message, because it will be caught by the removal of the old and addition of the new, and also by the field type change if it's used.
Similarly for enums and services.
So we don't need to check the name change of a top-level type separately.
But note: if we change the package of a message, then the fully qualified name changes. So we would have:
old: package foo; message Bar {...}
new: package baz; message Bar {...}
Then the old message `foo.Bar` is removed and the new message `baz.Bar` is added. And any field that used `foo.Bar` now uses `baz.Bar`? That's a change in the field type? So we would catch it.
So we are good.
Now, what about source breaking (non-wire):
- Changing a field name (same tag, same type, same label) -> source breaking.
- Changing an enum value name (same number) -> source breaking.
- Changing a oneof name? We are not comparing oneofs? Then we miss it.
We can add:
For each message, we also compare the oneofs by name and by the set of field tags? But that's complex.
Given the time, let's skip oneofs for now.
So:
source_breaking_non_wire =
- For each field (by tag) that exists in both: if the field name changed -> source breaking.
- For each enum value (by number) that exists in both: if the name changed -> source breaking.
But note: if we change the field name and also change the tag? Then it's wire breaking (tag change) and we already catch that. So we only consider the case where the tag is the same and the name changed.
Similarly for enum values: if we change the number, it's wire breaking. So we only consider the case where the number is the same and the name changed.
We have two `FileDescriptorSet` (old and new). We need to:
1. Merge all the file descriptors from both sets into two maps:
For the old set:
messages: key = fully qualified name (including package) -> message descriptor (which has fields by tag? Actually, the message descriptor has a list of fields, and each field has a tag number, name, label, type, etc.)
enums: key = fully qualified name -> enum descriptor (which has a list of values, each with a number and name)
services: key = fully qualified name -> service descriptor (which has a list of methods, each with a name, input type, output type)
But note: the `FileDescriptorSet` contains `FileDescriptorProto` which has:
- package
- message_type (list of DescriptorProto)
- enum_type (list of EnumDescriptorProto)
- service (list of ServiceDescriptorProto)
And the fully qualified name for a message is: `package + "." + message_name` (if package is non-empty). Similarly for enums and services.
Also, note that nested messages and enums? Then the fully qualified name includes the outer message's name.
Example:
package foo;
message Bar {
message Baz { ... }
}
Then the fully qualified name of `Baz` is `foo.Bar.Baz`.
So we have to recursively build the fully qualified name for nested types.
We can do:
def build_fqn(prefix, name):
if prefix:
return prefix + "." + name
else:
return name
And when we have a nested message, we call build_fqn(parent_fqn, nested_message.name).
2. We also need to index the fields of a message by tag number? Because we compare by tag.
So for each message, we build a map: tag_number -> field_descriptor.
3. Similarly, for enums, we build a map: value_number -> enum_value_descriptor.
4. For services, we build a map: method_name -> method_descriptor (which has input_type and output_type as strings? Actually, in the descriptor, the input_type and output_type are strings (the fully qualified name of the message). So we can compare them as strings.
Steps:
Parse the old FileDescriptorSet and build:
old_messages: dict[fqn, message_descriptor]
old_enums: dict[fqn, enum_descriptor]
old_services: dict[fqn, service_descriptor]
Each message_descriptor:
- name: the simple name (without package)
- fields: dict[tag, field_descriptor] # field_descriptor has: name, label, type (for built-in: type enum, for message/enum: type_name (string))
- nested_messages? We are already including them in the old_messages by their fqn.
Similarly for enums:
- values: dict[number, enum_value_descriptor] # enum_value_descriptor has: name
For services:
- methods: dict[method_name, method_descriptor] # method_descriptor has: input_type, output_type (as strings)
Similarly for new.
Then we compare:
wire_breaking = []
source_breaking_non_wire = []
# Compare messages
for fqn in set(old_messages.keys()) | set(new_messages.keys()):
if fqn not in old_messages:
# new message added -> non-breaking addition
pass
elif fqn not in new_messages:
wire_breaking.append(f"Message {fqn} removed")
else:
old_msg = old_messages[fqn]
new_msg = new_messages[fqn]
# Compare fields by tag
old_fields = old_msg.fields
new_fields = new_msg.fields
for tag in set(old_fields.keys()) | set(new_fields.keys()):
if tag not in old_fields:
# new field added -> non-breaking addition
pass
elif tag not in new_fields:
wire_breaking.append(f"Field {fqn}.{old_fields[tag].name} (tag {tag}) removed")
else:
old_field = old_fields[tag]
new_field = new_fields[tag]
# Compare name change (source breaking if tag same)
if old_field.name != new_field.name:
source_breaking_non_wire.append(f"Field {fqn} tag {tag} renamed from {old_field.name} to {new_field.name}")
# Compare label
if old_field.label != new_field.label:
wire_breaking.append(f"Field {fqn}.{old_field.name} (tag {tag}) label changed from {old_field.label} to {new_field.label}")
# Compare type
# For built-in types, we compare the type enum. For message/enum, we compare the type_name.
# First, check if both are built-in?
# In the descriptor, the field has:
# type: one of the TYPE_* enums (for built-in)
# type_name: if the type is TYPE_MESSAGE or TYPE_ENUM, then this is the fully qualified name.
# So we can compare:
if old_field.type != new_field.type:
wire_breaking.append(f"Field {fqn}.{old_field.name} (tag {tag}) type changed from {old_field.type} to {new_field.type}")
elif old_field.type in [FieldDescriptorProto.TYPE_MESSAGE, FieldDescriptorProto.TYPE_ENUM]:
# Compare the type_name
if old_field.type_name != new_field.type_name:
wire_breaking.append(f"Field {fqn}.{old_field.name} (tag {tag}) changed from {old_field.type_name} to {new_field.type_name}")
# Note: we don't compare the oneofs for now.
# Compare enums
for fqn in set(old_enums.keys()) | set(new_enums.keys()):
if fqn not in old_enums:
pass # new enum added -> non-breaking addition
elif fqn not in new_enums:
wire_breaking.append(f"Enum {fqn} removed")
else:
old_enum = old_enums[fqn]
new_enum = new_enums[fqn]
old_values = old_enum.values
new_values = new_enum.values
for value in set(old_values.keys()) | set(new_values.keys()):
if value not in old_values:
pass # new enum value added -> non-breaking addition
elif value not in new_values:
wire_breaking.append(f"Enum value {fqn}.{old_values[value].name} (value {value}) removed")
else:
old_val = old_values[value]
new_val = new_values[value]
if old_val.name != new_val.name:
source_breaking_non_wire.append(f"Enum value {fqn} value {value} renamed from {old_val.name} to {new_val.name}")
# Compare services
for fqn in set(old_services.keys()) | set(new_services.keys()):
if fqn not in old_services:
pass # new service added -> non-breaking addition
elif fqn not in new_services:
wire_breaking.append(f"Service {fqn} removed")
else:
old_svc = old_services[fqn]
new_svc = new_services[fqn]
old_methods = old_svc.methods
new_methods = new_svc.methods
for method_name in set(old_methods.keys()) | set(new_methods.keys()):
if method_name not in old_methods:
pass # new method added -> non-breaking addition
elif method_name not in new_methods:
wire_breaking.append(f"Service method {fqn}.{method_name} removed")
else:
old_method = old_methods[method_name]
new_method = new_methods[method_name]
if old_method.input_type != new_method.input_type:
wire_breaking.append(f"Service method {fqn}.{method_name} input type changed from {old_method.input_type} to {new_method.input_type}")
if old_method.output_type != new_method.output_type:
wire_breaking.append(f"Service method {fqn}.{method_name} output type changed from {old_method.output_type} to {new_method.output_type}")
Then:
non_breaking_additions =
- new messages, enums, services (by fqn)
- new fields (by tag) in existing messages
- new enum values (by number) in existing enums
- new service methods (by name) in existing services
We didn't collect non_breaking_additions in the above loops? We can collect them similarly.
Alternatively, we can compute:
non_breaking_additions = []
for fqn in new_messages:
if fqn not in old_messages:
non_breaking_additions.append(f"New message {fqn}")
for fqn in new_enums:
if fqn not in old_enums:
non_breaking_additions.append(f"New enum {fqn}")
for fqn in new_services:
if fqn not in old_services:
non_breaking_additions.append(f"New service {fqn}")
For existing messages, we already compared fields and noted new fields (by tag) in the loop? We didn't collect them. So we can modify the loop to also collect new fields.
Let's restructure:
wire_breaking = []
source_breaking_non_wire = []
non_breaking_additions = []
For messages:
for fqn in set(old_messages.keys()) | set(new_messages.keys()):
if fqn not in old_messages:
non_breaking_additions.append(f"New message {fqn}")
elif fqn not in new_messages:
wire_breaking.append(f"Message {fqn} removed")
else:
old_msg = old_messages[fqn]
new_msg = new_messages[fqn]
old_fields = old_msg.fields
new_fields = new_msg.fields
for tag in set(old_fields.keys()) | set(new_fields.keys()):
if tag not in old_fields:
non_breaking_additions.append(f"New field {fqn}.{new_fields[tag].name} (tag {tag})")
elif tag not in new_fields:
wire_breaking.append(f"Field {fqn}.{old_fields[tag].name} (tag {tag}) removed")
else:
old_field = old_fields[tag]
new_field = new_fields[tag]
if old_field.name != new_field.name:
source_breaking_non_wire.append(f"Field {fqn} tag {tag} renamed from {old_field.name} to {new_field.name}")
if old_field.label != new_field.label:
wire_breaking.append(f"Field {fqn}.{old_field.name} (tag {tag}) label changed from {old_field.label} to {new_field.label}")
if old_field.type != new_field.type:
wire_breaking.append(f"Field {fqn}.{old_field.name} (tag {tag}) type changed from {old_field.type} to {new_field.type}")
elif old_field.type in [FieldDescriptorProto.TYPE_MESSAGE, FieldDescriptorProto.TYPE_ENUM]:
if old_field.type_name != new_field.type_name:
wire_breaking.append(f"Field {fqn}.{old_field.name} (tag {tag}) changed from {old_field.type_name} to {new_field.type_name}")
Similarly for enums and services.
Then:
if wire_breaking:
required_bump = "major"
elif source_breaking_non_wire or non_breaking_additions:
required_bump = "minor"
else:
required_bump = "patch"
But note: what if we have both wire_breaking and non_breaking_additions? Then we already have wire_breaking, so major.
And what if we have source_breaking_non_wire and non_breaking_additions? Then minor.
And if we have only non_breaking_additions? Then minor.
And if we have only source_breaking_non_wire? Then minor.
And if we have nothing? Then patch.
But note: if we have only source_breaking_non_wire, that means we only renamed fields or enum values. That requires a minor bump? According to our rule, yes.
However, in semver, if we only rename a field (without adding any new functionality), then we might consider it a patch? But it breaks source. So we require minor.
But note: the user might not want to bump the minor for a field rename? They might consider it a patch because the wire format is the same. But we are considering source breaking as minor.
We can make this configurable? But let's stick to the above.