CodeSampleX

Ejemplo

google.golang.org/protobuf v1.36.11: proto.UnmarshalOptions

Muestra verificada para golang google.golang.org/protobuf v1.36.11: proto.UnmarshalOptions. El contrato se ejecutó en go 1.26 · linux debian/x64 · docker y…

sha256:796769bc1a4802de6f41d2311b336e65d3de9be6c1df97bfe07450e5bc5f4564

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 go linux 24 · ubuntu · glibc 2.39 x64 go go go

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
go 1.26 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26@sha256:e30143be198a…
2026-09-02

Caso

HOW
Objetivo
verify proto.UnmarshalOptions in pkg:golang/google.golang.org/protobuf@v1.36.11
Paquetes
Símbolos
  • proto.UnmarshalOptions
Entorno
go
Creado
2026-09-02T08:45:00Z

Contrato

  1. proto.UnmarshalOptions.Unmarshal parses wire-format bytes into a destination protobuf message.
  2. proto.UnmarshalOptions with DiscardUnknown controls whether unknown wire fields are preserved in message reflection or discarded.
  3. proto.UnmarshalOptions with Merge controls whether repeated fields in wire bytes replace or append to existing message fields.
  4. proto.UnmarshalOptions with RecursionLimit limits maximum message nesting depth and fails when exceeded.
  5. proto.UnmarshalOptions with AllowPartial permits deserialization of partial protobuf messages.
  6. proto.UnmarshalOptions with Resolver specifies a custom type resolver such as protoregistry.GlobalTypes to resolve anypb.Any messages.
  7. proto.UnmarshalOptions supports combining DiscardUnknown, AllowPartial, RecursionLimit, and Resolver for complex message unmarshaling.

Archivos

  • NOTES.md
  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • spec.json
  • unmarshal_options_test.go

Descargar el artefacto de código fuente (tar.gz)

Código fuente

NOTES.md
# Protocol Buffers proto.UnmarshalOptions Deserialization Semantics

A search for `proto.UnmarshalOptions` in `pkg:golang/google.golang.org/protobuf@v1.36.11` returned `NO_SAFE_MATCH`.

This sample verifies the unmarshaling options and behavior provided by `proto.UnmarshalOptions`.

## Observed Behavior

1. **Basic Unmarshaling (`Unmarshal`)**:
   - `UnmarshalOptions.Unmarshal(b, m)` unmarshals wire-format bytes into a destination protobuf message.

2. **Handling Unknown Fields (`DiscardUnknown`)**:
   - When `DiscardUnknown: false` (default), unknown wire fields are preserved in the message reflection unknown fields buffer (`m.ProtoReflect().GetUnknown()`).
   - When `DiscardUnknown: true`, unknown wire fields are ignored and stripped during deserialization.

3. **Merging vs Replacement (`Merge`)**:
   - When `Merge: false` (default), repeated fields in wire bytes replace existing repeated slices in destination message.
   - When `Merge: true`, repeated fields in wire bytes are appended to existing repeated slices in destination message.

4. **Recursion Depth Limit (`RecursionLimit`)**:
   - Setting `RecursionLimit` restricts maximum message nesting depth. Parsing nested structures that exceed this limit fails with a recursion limit error.

5. **Allowing Partial Messages (`AllowPartial`)**:
   - Setting `AllowPartial: true` permits deserialization of messages without requiring all mandatory fields.

6. **Custom Resolvers (`Resolver`)**:
   - `Resolver` specifies a custom `protoregistry.ExtensionTypeResolver` and `protoregistry.MessageTypeResolver` (such as `protoregistry.GlobalTypes`) for dynamically resolving types (e.g. `anypb.Any`).
PROMPT.md
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: verify proto.UnmarshalOptions in pkg:golang/google.golang.org/protobuf@v1.36.11
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/google.golang.org/protobuf@v1.36.11
Demonstrate these symbols/APIs:
  - proto.UnmarshalOptions
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.
csx.json
{"case":{"caseId":"case:sha256:6f1c7a01bef89ebcdfa839626d25077258e207c8216d1c0695b8d5dd2c42dbe2","contract":["proto.UnmarshalOptions.Unmarshal parses wire-format bytes into a destination protobuf message.","proto.UnmarshalOptions with DiscardUnknown controls whether unknown wire fields are preserved in message reflection or discarded.","proto.UnmarshalOptions with Merge controls whether repeated fields in wire bytes replace or append to existing message fields.","proto.UnmarshalOptions with RecursionLimit limits maximum message nesting depth and fails when exceeded.","proto.UnmarshalOptions with AllowPartial permits deserialization of partial protobuf messages.","proto.UnmarshalOptions with Resolver specifies a custom type resolver such as protoregistry.GlobalTypes to resolve anypb.Any messages.","proto.UnmarshalOptions supports combining DiscardUnknown, AllowPartial, RecursionLimit, and Resolver for complex message unmarshaling."],"goal":"verify proto.UnmarshalOptions in pkg:golang/google.golang.org/protobuf@v1.36.11","kind":"HOW","packages":["pkg:golang/google.golang.org/protobuf@v1.36.11"],"schemaVersion":1,"symbols":["proto.UnmarshalOptions"]},"contractCommand":["go","test","./..."],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","executionContext":"go","language":"go","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"go","runtime":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/google.golang.org/protobuf@v1.36.11"],"schemaVersion":1,"subject":"pkg:golang/google.golang.org/protobuf@v1.36.11","symbols":["proto.UnmarshalOptions"],"verifierAdapter":"golang@1"}
go.mod
module example.com/protounmarshaldemo

go 1.23

require google.golang.org/protobuf v1.36.11
go.sum
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
spec.json
{
  "schemaVersion": 1,
  "goal": "verify proto.UnmarshalOptions in pkg:golang/google.golang.org/protobuf@v1.36.11",
  "kind": "HOW",
  "packages": [
    "pkg:golang/google.golang.org/protobuf@v1.36.11"
  ],
  "symbols": [
    "proto.UnmarshalOptions"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
unmarshal_options_test.go
package protounmarshaldemo_test

import (
	"bytes"
	"testing"

	"google.golang.org/protobuf/encoding/protowire"
	"google.golang.org/protobuf/proto"
	"google.golang.org/protobuf/reflect/protoregistry"
	"google.golang.org/protobuf/types/known/anypb"
	"google.golang.org/protobuf/types/known/apipb"
	"google.golang.org/protobuf/types/known/sourcecontextpb"
	"google.golang.org/protobuf/types/known/structpb"
	"google.golang.org/protobuf/types/known/typepb"
)

// TestUnmarshalOptionsBasic verifies basic unmarshaling using proto.UnmarshalOptions.
func TestUnmarshalOptionsBasic(t *testing.T) {
	orig := &sourcecontextpb.SourceContext{
		FileName: "service/schema.proto",
	}
	data, err := proto.Marshal(orig)
	if err != nil {
		t.Fatalf("proto.Marshal failed: %v", err)
	}

	opts := proto.UnmarshalOptions{}
	var msg sourcecontextpb.SourceContext
	if err := opts.Unmarshal(data, &msg); err != nil {
		t.Fatalf("opts.Unmarshal failed: %v", err)
	}

	if msg.FileName != "service/schema.proto" {
		t.Fatalf("expected FileName %q, got %q", "service/schema.proto", msg.FileName)
	}
}

// TestUnmarshalOptionsDiscardUnknown verifies DiscardUnknown controls whether unknown fields
// are preserved in message reflection or discarded.
func TestUnmarshalOptionsDiscardUnknown(t *testing.T) {
	orig := &sourcecontextpb.SourceContext{
		FileName: "main.proto",
	}
	knownBytes, err := proto.Marshal(orig)
	if err != nil {
		t.Fatalf("Marshal failed: %v", err)
	}

	// Append an unknown field (tag 99, varint value 42) to the wire bytes
	unknownField := protowire.AppendTag(nil, 99, protowire.VarintType)
	unknownField = protowire.AppendVarint(unknownField, 42)
	wireWithUnknown := append(knownBytes, unknownField...)

	// 1. Default (DiscardUnknown: false): unknown fields are preserved
	optsKeep := proto.UnmarshalOptions{
		DiscardUnknown: false,
	}
	var msgKeep sourcecontextpb.SourceContext
	if err := optsKeep.Unmarshal(wireWithUnknown, &msgKeep); err != nil {
		t.Fatalf("Unmarshal with DiscardUnknown: false failed: %v", err)
	}
	unknownBytes := msgKeep.ProtoReflect().GetUnknown()
	if len(unknownBytes) == 0 {
		t.Fatalf("expected unknown fields to be preserved, got 0 bytes")
	}
	if !bytes.Equal(unknownBytes, unknownField) {
		t.Fatalf("preserved unknown bytes mismatch: got %v, want %v", unknownBytes, unknownField)
	}

	// 2. DiscardUnknown: true -> unknown fields are discarded
	optsDiscard := proto.UnmarshalOptions{
		DiscardUnknown: true,
	}
	var msgDiscard sourcecontextpb.SourceContext
	if err := optsDiscard.Unmarshal(wireWithUnknown, &msgDiscard); err != nil {
		t.Fatalf("Unmarshal with DiscardUnknown: true failed: %v", err)
	}
	if len(msgDiscard.ProtoReflect().GetUnknown()) != 0 {
		t.Fatalf("expected 0 unknown bytes with DiscardUnknown: true, got %d", len(msgDiscard.ProtoReflect().GetUnknown()))
	}
	if msgDiscard.FileName != "main.proto" {
		t.Fatalf("expected FileName 'main.proto', got %q", msgDiscard.FileName)
	}
}

// TestUnmarshalOptionsMerge verifies Merge behavior when unmarshaling into non-empty messages.
func TestUnmarshalOptionsMerge(t *testing.T) {
	// Source message with repeated fields
	updateMsg := &typepb.Type{
		Name: "UpdatedType",
		Fields: []*typepb.Field{
			{Name: "field2", Number: 2},
		},
	}
	wireBytes, err := proto.Marshal(updateMsg)
	if err != nil {
		t.Fatalf("Marshal failed: %v", err)
	}

	// 1. Merge: false (default) -> repeated fields in wire replace existing repeated fields
	targetNoMerge := &typepb.Type{
		Name: "InitialType",
		Fields: []*typepb.Field{
			{Name: "field1", Number: 1},
		},
	}
	optsNoMerge := proto.UnmarshalOptions{
		Merge: false,
	}
	if err := optsNoMerge.Unmarshal(wireBytes, targetNoMerge); err != nil {
		t.Fatalf("Unmarshal with Merge: false failed: %v", err)
	}
	if targetNoMerge.Name != "UpdatedType" {
		t.Fatalf("expected Name 'UpdatedType', got %q", targetNoMerge.Name)
	}
	if len(targetNoMerge.Fields) != 1 || targetNoMerge.Fields[0].Name != "field2" {
		t.Fatalf("expected Fields to be replaced with field2, got: %+v", targetNoMerge.Fields)
	}

	// 2. Merge: true -> repeated fields in wire are appended to existing repeated fields
	targetMerge := &typepb.Type{
		Name: "InitialType",
		Fields: []*typepb.Field{
			{Name: "field1", Number: 1},
		},
	}
	optsMerge := proto.UnmarshalOptions{
		Merge: true,
	}
	if err := optsMerge.Unmarshal(wireBytes, targetMerge); err != nil {
		t.Fatalf("Unmarshal with Merge: true failed: %v", err)
	}
	if targetMerge.Name != "UpdatedType" {
		t.Fatalf("expected Name 'UpdatedType', got %q", targetMerge.Name)
	}
	if len(targetMerge.Fields) != 2 {
		t.Fatalf("expected 2 fields after merge, got %d", len(targetMerge.Fields))
	}
	if targetMerge.Fields[0].Name != "field1" || targetMerge.Fields[1].Name != "field2" {
		t.Fatalf("expected fields [field1, field2], got: %+v, %+v", targetMerge.Fields[0], targetMerge.Fields[1])
	}
}

// TestUnmarshalOptionsRecursionLimit verifies RecursionLimit halts deeply nested parsing.
func TestUnmarshalOptionsRecursionLimit(t *testing.T) {
	// Build a deeply nested Struct/Value (depth = 6)
	current := &structpb.Value{
		Kind: &structpb.Value_StringValue{StringValue: "innermost"},
	}
	for i := 0; i < 5; i++ {
		current = &structpb.Value{
			Kind: &structpb.Value_ListValue{
				ListValue: &structpb.ListValue{
					Values: []*structpb.Value{current},
				},
			},
		}
	}

	wireBytes, err := proto.Marshal(current)
	if err != nil {
		t.Fatalf("Marshal nested message failed: %v", err)
	}

	// 1. With RecursionLimit: 2, parsing deeply nested payload should fail
	optsLimited := proto.UnmarshalOptions{
		RecursionLimit: 2,
	}
	var msgLimited structpb.Value
	errLimited := optsLimited.Unmarshal(wireBytes, &msgLimited)
	if errLimited == nil {
		t.Fatalf("expected error due to RecursionLimit: 2, but unmarshal succeeded")
	}

	// 2. With default/adequate RecursionLimit, parsing succeeds
	optsAdequate := proto.UnmarshalOptions{
		RecursionLimit: 20,
	}
	var msgAdequate structpb.Value
	if err := optsAdequate.Unmarshal(wireBytes, &msgAdequate); err != nil {
		t.Fatalf("Unmarshal with RecursionLimit: 20 failed: %v", err)
	}
}

// TestUnmarshalOptionsAllowPartial verifies AllowPartial option accepts messages.
func TestUnmarshalOptionsAllowPartial(t *testing.T) {
	msg := &sourcecontextpb.SourceContext{
		FileName: "partial.proto",
	}
	wireBytes, err := proto.Marshal(msg)
	if err != nil {
		t.Fatalf("Marshal failed: %v", err)
	}

	opts := proto.UnmarshalOptions{
		AllowPartial: true,
	}
	var target sourcecontextpb.SourceContext
	if err := opts.Unmarshal(wireBytes, &target); err != nil {
		t.Fatalf("Unmarshal with AllowPartial: true failed: %v", err)
	}
	if target.FileName != "partial.proto" {
		t.Fatalf("expected 'partial.proto', got %q", target.FileName)
	}
}

// TestUnmarshalOptionsResolver verifies Resolver option resolves message types and extensions.
func TestUnmarshalOptionsResolver(t *testing.T) {
	inner := &sourcecontextpb.SourceContext{
		FileName: "resolver_test.proto",
	}
	anyMsg, err := anypb.New(inner)
	if err != nil {
		t.Fatalf("anypb.New failed: %v", err)
	}

	wireBytes, err := proto.Marshal(anyMsg)
	if err != nil {
		t.Fatalf("Marshal failed: %v", err)
	}

	// Custom resolver explicitly using protoregistry.GlobalTypes
	opts := proto.UnmarshalOptions{
		Resolver: protoregistry.GlobalTypes,
	}
	var target anypb.Any
	if err := opts.Unmarshal(wireBytes, &target); err != nil {
		t.Fatalf("Unmarshal with Resolver failed: %v", err)
	}

	unpacked, err := target.UnmarshalNew()
	if err != nil {
		t.Fatalf("target.UnmarshalNew failed: %v", err)
	}
	sc, ok := unpacked.(*sourcecontextpb.SourceContext)
	if !ok {
		t.Fatalf("expected *sourcecontextpb.SourceContext, got %T", unpacked)
	}
	if sc.FileName != "resolver_test.proto" {
		t.Fatalf("expected FileName 'resolver_test.proto', got %q", sc.FileName)
	}
}

// TestUnmarshalOptionsComposition verifies combining multiple UnmarshalOptions with complex messages.
func TestUnmarshalOptionsComposition(t *testing.T) {
	api := &apipb.Api{
		Name:    "v1.Service",
		Version: "v1.0",
		SourceContext: &sourcecontextpb.SourceContext{
			FileName: "service.proto",
		},
	}
	apiBytes, err := proto.Marshal(api)
	if err != nil {
		t.Fatalf("Marshal failed: %v", err)
	}

	// Append unknown tag
	unknownTag := protowire.AppendTag(nil, 888, protowire.VarintType)
	unknownTag = protowire.AppendVarint(unknownTag, 100)
	wireBytes := append(apiBytes, unknownTag...)

	opts := proto.UnmarshalOptions{
		DiscardUnknown: true,
		AllowPartial:   true,
		RecursionLimit: 50,
		Resolver:       protoregistry.GlobalTypes,
	}

	var target apipb.Api
	if err := opts.Unmarshal(wireBytes, &target); err != nil {
		t.Fatalf("Unmarshal composition failed: %v", err)
	}

	if target.Name != "v1.Service" || target.Version != "v1.0" {
		t.Fatalf("unexpected API data: %+v", target)
	}
	if target.SourceContext == nil || target.SourceContext.FileName != "service.proto" {
		t.Fatalf("unexpected SourceContext: %+v", target.SourceContext)
	}
	if len(target.ProtoReflect().GetUnknown()) != 0 {
		t.Fatalf("expected unknown fields to be discarded, got %d bytes", len(target.ProtoReflect().GetUnknown()))
	}
}

Seeder de origen

anónimo