syntax = "proto3";
package schema_guard.v1;
option go_package = "github.com/trailblazer-labs/schema-guard/proto/gen/v1;schemarguard";
option java_package = "com.trailblazer.schema_guard.v1";
option java_multiple_files = true;
// EvolutionGuardService is a gRPC service for detecting breaking changes in protobuf schema evolution.
// It compares an old FileDescriptorSet (source schema) against a new one (target schema).
service EvolutionGuardService {
// DetectBreakingChanges analyzes the target schema against the source for breaking changes.
// Returns a report detailing any violations.
rpc DetectBreakingChanges(DetectBreakingChangesRequest) returns (DetectBreakingChangesResponse);
}
// DetectBreakingChangesRequest specifies the schemas to compare.
message DetectBreakingChangesRequest {
// source_schema is the baseline (old) schema. Must be a valid FileDescriptorSet.
bytes source_schema = 1; // google.protobuf.FileDescriptorSet
// target_schema is the evolved (new) schema to validate.
bytes target_schema = 2; // google.protobuf.FileDescriptorSet
// compatibility_mode specifies the compatibility level to enforce.
// Defaults to BACKWARD.
CompatibilityMode compatibility_mode = 3;
// ignore_paths is a list of JSONPaths to ignore during validation (e.g., ["foo.bar.baz"]).
repeated string ignore_paths = 4;
}
// DetectBreakingChangesResponse contains the validation results.
message DetectBreakingChangesResponse {
// is_valid indicates if the target schema is compatible with the source.
bool is_valid = 1;
// summary provides a high-level overview.
ValidationSummary summary = 2;
// violations lists all detected breaking changes, sorted by severity.
repeated Violation violations = 3;
}
// ValidationSummary aggregates violation stats.
message ValidationSummary {
int32 total_messages_validated = 1;
int32 total_enums_validated = 2;
int32 total_services_validated = 3;
int32 total_violations = 4;
int32 error_violations = 5; // Severity.ERROR
int32 warning_violations = 6; // Severity.WARNING
int32 info_violations = 7; // Severity.INFO
}
// Violation represents a single breaking change or issue.
message Violation {
Severity severity = 1;
// path is a JSONPath-like reference to the affected element (e.g., "package.Message.field").
string path = 2;
// description explains the issue.
string description = 3;
// suggestion provides remediation advice.
string suggestion = 4;
// source_value is the value/type in the source schema (for diff).
string source_value = 5;
// target_value is the value/type in the target schema.
string target_value = 6;
}
// Severity levels for violations.
enum Severity {
SEVERITY_UNSPECIFIED = 0;
INFO = 1;
WARNING = 2;
ERROR = 3;
}
// CompatibilityMode defines the evolution ruleset to apply.
enum CompatibilityMode {
COMPATIBILITY_MODE_UNSPECIFIED = 0;
// BACKWARD: New readers can read old data (additive changes only).
BACKWARD = 1;
// FORWARD: Old readers can read new data (no required additions).
FORWARD = 2;
// FULL: Both backward and forward compatible.
FULL = 3;
}
Design Overview
This design provides a Protobuf Schema Evolution Guard as a gRPC service (EvolutionGuardService) with a well-defined protobuf schema (schema_guard.v1). It detects breaking changes by comparing two FileDescriptorSets (serialized protobuf descriptors from .proto files), enabling CI/CD integration, schema registries, or API gateways.
Key Features
- Input: Binary
FileDescriptorSets (from protoc --descriptor_set_out), avoiding text parsing issues.
- Output: Structured
DetectBreakingChangesResponse with actionable violations.
- Extensible: JSONPath ignores, configurable modes (backward/forward/full compatibility).
- Comprehensive Detection Rules (implemented in server logic; see below):
| Category | Breaking Changes Detected (Examples) | Severity |
|---|
| Fields (Messages) | - Changed field number.- Incompatible type change (e.g., int32 → string).- Added required field (proto2).- Removed non-reserved field.- Changed oneof membership.- Changed default value incompatibly. | ERROR |
| Messages | - Changed message name without alias.- Removed message used in any field.- Changed to/from enum/service. | ERROR |
| Enums | - Removed value.- Changed value number.- Reordered values (gaps OK if additive).- Negative values added (proto3). | ERROR/WARNING |
| Services/RPCs | - Changed RPC input/output types incompatibly.- Removed RPC.- Changed streaming semantics. | ERROR |
| Packages/Files | - Changed package name.- Conflicting option java_package, etc. | WARNING |
| Any/All | - Tag collisions.- Exceeding max fields (536870911). | ERROR |
- Non-Breaking Allowed:
- Adding optional fields (new tags).
- Reserving old tags (
reserved).
- Adding enum values (high numbers).
- Deprecating fields.
- Modes:
| Mode | Rules |
|---|
| Backward | Target can read source data (no removals, additive only). |
| Forward | Source can read target data (no new required fields). |
| Full | Both. |
Implementation Guidance (Go Example)
Use google.golang.org/protobuf/reflect/protodesc and google.golang.org/protobuf/types/descriptorpb for parsing.
// Pseudocode for core logic in service impl.
func (s *EvolutionGuardService) DetectBreakingChanges(ctx context.Context, req *v1.DetectBreakingChangesRequest) (*v1.DetectBreakingChangesResponse, error) {
sourceFDs, err := protodesc.NewFileDescriptorsFromFileDescriptorSet(req.SourceSchema)
targetFDs, err := protodesc.NewFileDescriptorsFromFileDescriptorSet(req.TargetSchema)
var violations []*v1.Violation
for _, targetFile := range targetFDs.Files() {
sourceFile := findMatchingFile(sourceFDs.Files(), targetFile)
violations = append(violations, checkMessages(targetFile.Messages(), sourceFile.Messages())...)
violations = append(violations, checkEnums(targetFile.Enums(), sourceFile.Enums())...)
// ... services, packages
}
summary := computeSummary(violations)
isValid := len(getErrors(violations)) == 0
return &v1.DetectBreakingChangesResponse{IsValid: isValid, Summary: summary, Violations: violations}, nil
}
func checkFields(sourceMsg, targetMsg *desc.MessageDescriptor) []*v1.Violation {
var vs []*v1.Violation
targetFieldsByNum := mapFieldsByNumber(targetMsg.Fields())
for _, sf := range sourceMsg.Fields() {
tf, ok := targetFieldsByNum[sf.Number()]
if !ok {
if !isReserved(tf, sf.Number()) { // Check target reserved
vs = append(vs, violation("field_removed", path(sf), ERROR))
}
} else if !typesCompatible(sf.Type(), tf.Type()) {
vs = append(vs, violation("type_incompatible", path(sf), ERROR, sourceType(sf), targetType(tf)))
}
}
// Check new fields in target (additive OK unless FORWARD mode)
return vs
}
// Helper: typesCompatible (simplified)
func typesCompatible(s, t protoreflect.FieldDescriptor_Type) bool {
switch s {
case protoreflect.Int32Type, protoreflect.Int64Type: // Numeric family
return isNumeric(t)
case protoreflect.StringType, protoreflect.BytesType:
return t == protoreflect.StringType || t == protoreflect.BytesType
// Message subtypes, repeated/singleton, etc.
default:
return s == t
}
}
Usage Examples
- CLI Wrapper:
protoc --descriptor_set_out=old.desc old.proto
protoc --descriptor_set_out=new.desc new.proto
grpcurl -d '{"source_schema": "`cat old.desc`", "target_schema": "`cat new.desc`"}' localhost:8080 schema_guard.v1.EvolutionGuardService/DetectBreakingChanges
- CI Integration: Fail build if
is_valid=false.
- Schema Registry Hook: Validate PRs automatically.
Edge Cases Handled
- Cross-file dependencies (via FDS).
- Proto2 vs Proto3 (e.g.,
required deprecated in proto3).
- Extensions, groups (legacy).
- Unknown fields tolerated in unknown messages.
This guard ensures safe schema evolution, preventing outages in production systems. For full impl, extend with custom type hierarchies or plugin rules.