# Protobuf 反序列化静默地将未知枚举值转换为 0，导致逻辑错误

- **ID:** `data/protobuf-enum-value-out-of-range`
- **领域:** data
- **类别:** data_error
- **验证级别:** ai_generated
- **修复率:** 85%

## 根因

Protobuf 规范要求未知枚举值在导线格式中保留，但反序列化为 0（默认枚举值），导致在业务逻辑中使用时静默数据损坏。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| Protobuf 3.21.0+ | active | — | — |
| gRPC 1.50.0+ | active | — | — |
| Java Protobuf 3.21.0+ | active | — | — |
| Python protobuf 4.21.0+ | active | — | — |

## 解决方案

1. ```
   使用 `google.protobuf.EnumValueDescriptor` 检查值是否已知：`if not enum_descriptor.values_by_number.get(raw_value): raise ValueError('Unknown enum')`
   ```
2. ```
   将原始整数值存储在枚举旁边的单独字段中：`message Event { Status status = 1; int32 raw_status = 2; }`
   ```
3. ```
   使用自定义反序列化函数，在转换之前根据已知集合验证枚举值。
   ```

## 无效尝试

- **** — Protobuf treats 0 as the default even if named; unknown values still become 0, and logic cannot distinguish between 'intentional 0' and 'unknown'. (70% 失败率)
- **** — `allow_alias` is for multiple names mapping to same number, not for handling unknown values. (90% 失败率)
