Ejemplo
protobuf 7.35.1: google.protobuf.any_pb2 Any and Struct packing, unpacking, type URL handling, and JSON conversion
Muestra verificada para pypi protobuf 7.35.1: google.protobuf.any_pb2 Any and Struct packing, unpacking, type URL handling, and JSON conversion. El contrato…
sha256:4a5fde4311f0f3db5b6c7f575b45854ac4d367acc96b895513d1c2b14e8029ae
Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido.
Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas.
MIT-0
Evidencia de ejecución
El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.
- Base de evidencia
- Contrato firmado aprobado
- Recibos de verificación
- 1
- Claves de firma que lo compilaron
- 1
Entorno declarado
python 3.12 linux 24 · glibc x64 python 3.12 python 3.12 pip
Entornos de las ejecuciones de verificación
| Entorno | Contrato | Etapas | Ejecución |
|---|---|---|---|
| python 3.12 · linux alpine/x64 · docker ed25519:c1973797be207ac4 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · python@1python:3.12-alpine@sha256:d09d15e60962… |
2026-08-27 |
Caso
HOW- Objetivo
- google.protobuf.any_pb2 Any and Struct packing, unpacking, type URL handling, and JSON conversion
- Paquetes
- Símbolos
-
- google.protobuf.any_pb2.Any
- google.protobuf.any_pb2.Any.Pack
- google.protobuf.any_pb2.Any.Unpack
- google.protobuf.any_pb2.Any.Is
- google.protobuf.any_pb2.Any.TypeName
- google.protobuf.struct_pb2.Struct
- google.protobuf.struct_pb2.Value
- google.protobuf.struct_pb2.ListValue
- google.protobuf.json_format.MessageToDict
- google.protobuf.json_format.ParseDict
- Entorno
- python 3.12
- Creado
- 2026-08-27T19:21:38Z
Contrato
- Struct.update populates scalar, boolean, null, nested dict, and list fields with automatic Value and ListValue wrapping, while assigning unsupported types raises ValueError.
- Struct helper methods get_or_create_struct and get_or_create_list instantiate child containers in-place and support append, extend, and index mutation.
- Any.Pack serializes arbitrary protobuf messages including Struct with default type.googleapis.com URL prefix or explicit custom prefix, and TypeName extracts the clean message name.
- Any.Is verifies descriptor matching, while Any.Unpack deserializes the payload into matching message instances and safely returns False without modifying destination on type mismatch.
- MessageToDict and ParseDict round-trip Struct directly as native dictionaries and Any containers with @type discriminator metadata.
Archivos
- NOTES.md
- PROMPT.md
- csx.json
- requirements.lock
- requirements.txt
- spec.json
- test/contract.py
Código fuente
# google.protobuf Well-Known Types: Any and Struct
This sample proves the behavior of `google.protobuf.any_pb2.Any` and `google.protobuf.struct_pb2.Struct` in `protobuf` 7.35.1.
## Key Behaviors Proven
1. `Struct` represents dynamically typed JSON-like objects. `Struct.update(...)` accepts standard Python dictionaries, converting scalars, booleans, `None` (as `NullValue`), nested dicts, and lists into `Value` and `ListValue` wrappers. Assigning unsupported types (such as `set` or arbitrary custom objects) raises `ValueError`.
2. `get_or_create_struct` and `get_or_create_list` allow building structured trees dynamically without constructing intermediate messages.
3. `Any.Pack` encapsulates messages and sets `type_url` (with default `type.googleapis.com` or custom prefix). `Any.TypeName()` extracts the message type name.
4. `Any.Is(descriptor)` validates type agreement. `Any.Unpack(target)` returns `True` and populates `target` when the type matches, or returns `False` without altering `target` if descriptors mismatch. Unpacking corrupted byte payloads raises `DecodeError`.
5. `json_format.MessageToDict` and `json_format.ParseDict` handle seamless conversions: `Struct` fields are serialized as native dicts, while `Any` fields are serialized with `@type` discriminator fields.
Clean-room public code sample — generation instructions
Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.
A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.
Goal: google.protobuf.any_pb2 Any and Struct packing, unpacking, type URL handling, and JSON conversion
Kind: HOW
Use EXACTLY these public packages and versions:
- pkg:pypi/protobuf@7.35.1
Constraints:
- executionContext: node
Required runtime conditions:
- ecosystem: npm
- language: javascript
- moduleSystem: cjs
- packageManager: npm@10.9.8
- runtime: node@22.23.2
Rules:
- One focused purpose; the smallest project that proves the goal.
- Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
- Pin every dependency with a lockfile so resolution is reproducible.
- No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
- No personal names, emails, company names, or project identifiers of any kind.
- No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
- Keep it under 200 files and 256KB packed.
{"case":{"caseId":"case:sha256:217a6a986116c1e783467dfc5485b18401ba13506d294810d635a9fb54ffa078","contract":["Struct.update populates scalar, boolean, null, nested dict, and list fields with automatic Value and ListValue wrapping, while assigning unsupported types raises ValueError.","Struct helper methods get_or_create_struct and get_or_create_list instantiate child containers in-place and support append, extend, and index mutation.","Any.Pack serializes arbitrary protobuf messages including Struct with default type.googleapis.com URL prefix or explicit custom prefix, and TypeName extracts the clean message name.","Any.Is verifies descriptor matching, while Any.Unpack deserializes the payload into matching message instances and safely returns False without modifying destination on type mismatch.","MessageToDict and ParseDict round-trip Struct directly as native dictionaries and Any containers with @type discriminator metadata."],"goal":"google.protobuf.any_pb2 Any and Struct packing, unpacking, type URL handling, and JSON conversion","kind":"HOW","packages":["pkg:pypi/protobuf@7.35.1"],"schemaVersion":1,"symbols":["google.protobuf.any_pb2.Any","google.protobuf.any_pb2.Any.Pack","google.protobuf.any_pb2.Any.Unpack","google.protobuf.any_pb2.Any.Is","google.protobuf.any_pb2.Any.TypeName","google.protobuf.struct_pb2.Struct","google.protobuf.struct_pb2.Value","google.protobuf.struct_pb2.ListValue","google.protobuf.json_format.MessageToDict","google.protobuf.json_format.ParseDict"]},"contractCommand":["python","test/contract.py"],"environment":{"arch":"x64","ecosystem":"pypi","executionContext":"python","language":"python","languageVersion":"3.12","libc":"glibc","os":"linux","osVersionBucket":"24","packageManager":"pip","runtime":"python","runtimeVersion":"3.12","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/protobuf@7.35.1"],"schemaVersion":1,"subject":"pkg:pypi/protobuf@7.35.1","symbols":["google.protobuf.any_pb2.Any","google.protobuf.any_pb2.Any.Pack","google.protobuf.any_pb2.Any.Unpack","google.protobuf.any_pb2.Any.Is","google.protobuf.any_pb2.Any.TypeName","google.protobuf.struct_pb2.Struct","google.protobuf.struct_pb2.Value","google.protobuf.struct_pb2.ListValue","google.protobuf.json_format.MessageToDict","google.protobuf.json_format.ParseDict"],"verifierAdapter":"python@1"}
# Hashes are official PyPI release wheel hashes for protobuf 7.35.1
protobuf==7.35.1 \
--hash=sha256:74758715c53d7158fb76caf4f0cfdacc5329a4b1bb994f865d6cf302d413a1c4 \
--hash=sha256:230a75ddfc2de4806e56696ce9640c1cdfdb6543b7cfce98d42a4c0a0e7bdb87 \
--hash=sha256:4bc97768d8fe4ad6743c8a19403e314511ed9f6d13205b687e52421c023ac1b9 \
--hash=sha256:11d6b0ec246892d85215b0a13ca6e0233cf5284b68f0ac02646427f4ff88a799 \
--hash=sha256:ce115a26fe0c39a2c29973d914d327e516a6455464489fe3cd1e51a1b354f81a
protobuf==7.35.1
{
"schemaVersion": 1,
"goal": "google.protobuf.any_pb2 Any and Struct packing, unpacking, type URL handling, and JSON conversion",
"kind": "HOW",
"packages": [
"pkg:pypi/protobuf@7.35.1"
],
"constraints": {
"executionContext": "node"
},
"runtimeConditions": {
"ecosystem": "npm",
"language": "javascript",
"moduleSystem": "cjs",
"packageManager": "npm@10.9.8",
"runtime": "node@22.23.2"
}
}
from importlib.metadata import distribution
from pathlib import Path
import google.protobuf
from google.protobuf import any_pb2
from google.protobuf import struct_pb2
from google.protobuf import timestamp_pb2
from google.protobuf import json_format
from google.protobuf.message import DecodeError
EXPECTED_VERSION = "7.35.1"
def assert_official_distribution_import() -> None:
installed = distribution("protobuf")
package_file = Path(google.protobuf.__file__).resolve()
distribution_root = Path(installed.locate_file("")).resolve()
assert installed.version == EXPECTED_VERSION
assert google.protobuf.__version__ == EXPECTED_VERSION
assert package_file.is_relative_to(distribution_root), (
package_file,
distribution_root,
)
def assert_struct_contract() -> None:
s = struct_pb2.Struct()
payload = {
"string": "sample_text",
"integer": 42,
"float": 3.14,
"boolean": True,
"null_val": None,
"nested": {"key": "val"},
"items": [1, "two", False, None],
}
s.update(payload)
assert s["string"] == "sample_text"
assert s["integer"] == 42
assert s["float"] == 3.14
assert s["boolean"] is True
assert s["null_val"] is None
assert s["nested"]["key"] == "val"
assert s["items"] == [1, "two", False, None]
v_str = s.fields["string"]
assert v_str.WhichOneof("kind") == "string_value"
assert v_str.string_value == "sample_text"
v_null = s.fields["null_val"]
assert v_null.WhichOneof("kind") == "null_value"
assert v_null.null_value == struct_pb2.NULL_VALUE
try:
s["invalid"] = {1, 2, 3}
except (TypeError, ValueError):
pass
else:
raise AssertionError("Expected ValueError or TypeError when assigning set to Struct")
s2 = struct_pb2.Struct()
sub_struct = s2.get_or_create_struct("sub")
sub_struct["hello"] = "world"
assert s2["sub"]["hello"] == "world"
sub_list = s2.get_or_create_list("tags")
sub_list.append("tag1")
sub_list.extend([100, {"deep": True}])
assert s2["tags"] == ["tag1", 100, {"deep": True}]
try:
sub_list.append(object())
except (TypeError, ValueError):
pass
else:
raise AssertionError("Expected ValueError or TypeError when appending arbitrary object to ListValue")
def assert_any_contract() -> None:
s = struct_pb2.Struct()
s.update({"service": "codesamplex", "active": True})
any_default = any_pb2.Any()
any_default.Pack(s)
assert any_default.type_url == "type.googleapis.com/google.protobuf.Struct"
assert any_default.TypeName() == "google.protobuf.Struct"
assert any_default.Is(struct_pb2.Struct.DESCRIPTOR)
assert not any_default.Is(timestamp_pb2.Timestamp.DESCRIPTOR)
any_custom = any_pb2.Any()
any_custom.Pack(s, type_url_prefix="example.com/types")
assert any_custom.type_url == "example.com/types/google.protobuf.Struct"
assert any_custom.TypeName() == "google.protobuf.Struct"
assert any_custom.Is(struct_pb2.Struct.DESCRIPTOR)
target = struct_pb2.Struct()
success = any_custom.Unpack(target)
assert success is True
assert target == s
assert target["service"] == "codesamplex"
ts_target = timestamp_pb2.Timestamp()
ts_target.seconds = 999
ts_target.nanos = 500
mismatch_success = any_custom.Unpack(ts_target)
assert mismatch_success is False
assert ts_target.seconds == 999
assert ts_target.nanos == 500
corrupted = any_pb2.Any()
corrupted.type_url = "type.googleapis.com/google.protobuf.Struct"
corrupted.value = b"\xff\xff\xff\xff"
try:
corrupted.Unpack(struct_pb2.Struct())
except DecodeError:
pass
else:
raise AssertionError("Expected DecodeError when unpacking corrupted bytes")
def assert_json_format_contract() -> None:
s = struct_pb2.Struct()
s.update({
"id": "item-123",
"metrics": {"latency_ms": 12.5, "ok": True},
"tags": ["v1", "prod"],
})
as_dict = json_format.MessageToDict(s)
assert as_dict == {
"id": "item-123",
"metrics": {"latency_ms": 12.5, "ok": True},
"tags": ["v1", "prod"],
}
reconstructed_s = struct_pb2.Struct()
json_format.ParseDict(as_dict, reconstructed_s)
assert reconstructed_s == s
any_msg = any_pb2.Any()
any_msg.Pack(s)
any_dict = json_format.MessageToDict(any_msg)
assert any_dict["@type"] == "type.googleapis.com/google.protobuf.Struct"
assert any_dict["value"] == as_dict
reconstructed_any = any_pb2.Any()
json_format.ParseDict(any_dict, reconstructed_any)
assert reconstructed_any.type_url == any_msg.type_url
unpacked = struct_pb2.Struct()
assert reconstructed_any.Unpack(unpacked) is True
assert unpacked == s
def main() -> None:
assert_official_distribution_import()
assert_struct_contract()
assert_any_contract()
assert_json_format_contract()
print("CONTRACT PASS: protobuf 7.35.1 Any and Struct packing, unpacking, type URLs, and JSON roundtrip")
if __name__ == "__main__":
main()
Seeder de origen
anónimo