CodeSampleX

Ejemplo

google.golang.org/protobuf v1.35.1: proto.Clone

Muestra verificada para golang google.golang.org/protobuf v1.35.1: proto.Clone. El contrato se ejecutó en go 1.26 · linux alpine/x64 · docker y pasó.

sha256:fee29872c83a67bcd2e5623869813d6169adf9d7136dbf90554732579a1a9662

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 alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26-alpine@sha256:28d89ee9cc0f…
2026-08-30

Caso

HOW
Objetivo
verify google.golang.org/protobuf/proto.Clone in pkg:golang/google.golang.org/protobuf@v1.35.1
Paquetes
Símbolos
  • google.golang.org/protobuf/proto.Clone
Entorno
go
Creado
2026-08-30T15:30:10Z

Contrato

  1. proto.Clone creates an isolated deep copy where mutating cloned repeated slices, maps, or nested messages does not affect the original message.
  2. proto.Clone(nil) returns untyped nil when given untyped nil, and returns a typed nil interface whose ProtoReflect().IsValid() is false when given a typed nil pointer.
  3. proto.Clone preserves explicit presence for proto3 optional fields set to default zero values while keeping unpopulated implicit fields unpopulated.
  4. proto.Clone produces semantically equal deep copies across static known types and dynamic message descriptors.

Archivos

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

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

Código fuente

NOTES.md
# Protocol Buffers Deep Copy Semantics and Isolation with proto.Clone

This sample verifies deep copy isolation, presence preservation, and nil handling behaviors of `proto.Clone` in `google.golang.org/protobuf` pinned to version `v1.35.1`.

## Observed Behavior

1. **Deep Copy Isolation for Repeated Fields, Maps, and Nested Messages**:
   - `proto.Clone` creates an independent deep copy of any `proto.Message`.
   - Mutating repeated slices (appending new items, modifying existing indices) on the cloned message does not mutate the source message.
   - Mutating protobuf maps (inserting new keys, deleting entries, or modifying nested messages inside map entries) on the cloned message does not affect the source message.
   - Modifying fields within singular nested submessages on the cloned message does not mutate the source message.

2. **Nil Message Handling**:
   - Passing an untyped `nil` (`var untypedNil proto.Message = nil`) to `proto.Clone(nil)` returns an untyped `nil`.
   - Passing a typed nil pointer implementing `proto.Message` (e.g., `(*timestamppb.Timestamp)(nil)`) returns a non-nil Go interface holding a typed nil pointer whose `ProtoReflect().IsValid()` evaluates to `false` and whose concrete value is nil (`reflect.ValueOf(res).IsNil() == true`).

3. **Proto3 Optional Presence Preservation**:
   - `proto.Clone` preserves field presence distinctions.
   - For `proto3_optional` fields explicitly populated with default/zero values (`0`, `""`, `false`), the cloned message retains explicit presence (`protoreflect.Message.Has` returns `true`).
   - Implicit-presence scalar fields that were unpopulated remain unpopulated on the cloned message (`protoreflect.Message.Has` returns `false`).

4. **Descriptor & Known Type Consistency**:
   - Deep copying works identically across statically generated message types (such as `timestamppb.Timestamp`) and dynamically constructed schemas (`dynamicpb.Message`).
   - Semantic message comparison (`proto.Equal`) evaluates `orig` and `cloned` as identical prior to mutation, properly handling IEEE 754 floating-point `NaN` values.
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 google.golang.org/protobuf/proto.Clone in pkg:golang/google.golang.org/protobuf@v1.35.1
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/google.golang.org/protobuf@v1.35.1
Demonstrate these symbols/APIs:
  - google.golang.org/protobuf/proto.Clone

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.
clone_test.go
package protoclone_test

import (
	"math"
	"reflect"
	"testing"

	"google.golang.org/protobuf/proto"
	"google.golang.org/protobuf/reflect/protodesc"
	"google.golang.org/protobuf/reflect/protoreflect"
	"google.golang.org/protobuf/reflect/protoregistry"
	"google.golang.org/protobuf/types/descriptorpb"
	"google.golang.org/protobuf/types/dynamicpb"
	"google.golang.org/protobuf/types/known/timestamppb"
)

// buildSchema constructs dynamic descriptors for testing proto.Clone across
// scalar types, proto3 optional presence, repeated lists, nested messages, and map fields.
func buildSchema(t *testing.T) (protoreflect.MessageDescriptor, protoreflect.MessageDescriptor) {
	t.Helper()

	fd := &descriptorpb.FileDescriptorProto{
		Name:    proto.String("clone_demo.proto"),
		Package: proto.String("example.clone"),
		Syntax:  proto.String("proto3"),
		MessageType: []*descriptorpb.DescriptorProto{
			{
				Name: proto.String("ChildRecord"),
				Field: []*descriptorpb.FieldDescriptorProto{
					{
						Name:     proto.String("tag"),
						Number:   proto.Int32(1),
						Type:     descriptorpb.FieldDescriptorProto_TYPE_STRING.Enum(),
						JsonName: proto.String("tag"),
					},
					{
						Name:     proto.String("weight"),
						Number:   proto.Int32(2),
						Type:     descriptorpb.FieldDescriptorProto_TYPE_INT32.Enum(),
						JsonName: proto.String("weight"),
					},
				},
			},
			{
				Name: proto.String("ParentRecord"),
				Field: []*descriptorpb.FieldDescriptorProto{
					{
						Name:     proto.String("title"),
						Number:   proto.Int32(1),
						Type:     descriptorpb.FieldDescriptorProto_TYPE_STRING.Enum(),
						JsonName: proto.String("title"),
					},
					{
						Name:           proto.String("optional_count"),
						Number:         proto.Int32(2),
						Type:           descriptorpb.FieldDescriptorProto_TYPE_INT32.Enum(),
						JsonName:       proto.String("optionalCount"),
						Proto3Optional: proto.Bool(true),
						OneofIndex:     proto.Int32(0),
					},
					{
						Name:     proto.String("items"),
						Number:   proto.Int32(3),
						Type:     descriptorpb.FieldDescriptorProto_TYPE_STRING.Enum(),
						Label:    descriptorpb.FieldDescriptorProto_LABEL_REPEATED.Enum(),
						JsonName: proto.String("items"),
					},
					{
						Name:     proto.String("child"),
						Number:   proto.Int32(4),
						Type:     descriptorpb.FieldDescriptorProto_TYPE_MESSAGE.Enum(),
						TypeName: proto.String(".example.clone.ChildRecord"),
						JsonName: proto.String("child"),
					},
					{
						Name:     proto.String("attributes"),
						Number:   proto.Int32(5),
						Type:     descriptorpb.FieldDescriptorProto_TYPE_MESSAGE.Enum(),
						TypeName: proto.String(".example.clone.ParentRecord.AttributesEntry"),
						Label:    descriptorpb.FieldDescriptorProto_LABEL_REPEATED.Enum(),
						JsonName: proto.String("attributes"),
					},
					{
						Name:     proto.String("score"),
						Number:   proto.Int32(6),
						Type:     descriptorpb.FieldDescriptorProto_TYPE_DOUBLE.Enum(),
						JsonName: proto.String("score"),
					},
				},
				NestedType: []*descriptorpb.DescriptorProto{
					{
						Name: proto.String("AttributesEntry"),
						Field: []*descriptorpb.FieldDescriptorProto{
							{
								Name:     proto.String("key"),
								Number:   proto.Int32(1),
								Type:     descriptorpb.FieldDescriptorProto_TYPE_STRING.Enum(),
								JsonName: proto.String("key"),
							},
							{
								Name:     proto.String("value"),
								Number:   proto.Int32(2),
								Type:     descriptorpb.FieldDescriptorProto_TYPE_MESSAGE.Enum(),
								TypeName: proto.String(".example.clone.ChildRecord"),
								JsonName: proto.String("value"),
							},
						},
						Options: &descriptorpb.MessageOptions{
							MapEntry: proto.Bool(true),
						},
					},
				},
				OneofDecl: []*descriptorpb.OneofDescriptorProto{
					{
						Name: proto.String("_optional_count"),
					},
				},
			},
		},
	}

	fileDesc, err := protodesc.NewFile(fd, protoregistry.GlobalFiles)
	if err != nil {
		t.Fatalf("protodesc.NewFile failed: %v", err)
	}

	parentDesc := fileDesc.Messages().ByName("ParentRecord")
	childDesc := fileDesc.Messages().ByName("ChildRecord")
	if parentDesc == nil || childDesc == nil {
		t.Fatalf("failed to resolve message descriptors")
	}

	return parentDesc, childDesc
}

func TestProtoCloneNilHandling(t *testing.T) {
	// 1. Untyped nil message returns untyped nil
	var untypedNil proto.Message = nil
	if res := proto.Clone(untypedNil); res != nil {
		t.Fatalf("proto.Clone(nil) must return nil, got %v", res)
	}

	// 2. Typed nil pointer returns typed nil proto.Message interface (non-nil interface holding nil pointer)
	var typedNil *timestamppb.Timestamp = nil
	res := proto.Clone(typedNil)
	if res == nil {
		t.Fatalf("proto.Clone(typedNil) returned untyped nil interface instead of typed nil interface")
	}
	if !reflect.ValueOf(res).IsNil() {
		t.Fatalf("proto.Clone(typedNil) concrete value is not nil")
	}
	if res.ProtoReflect().IsValid() {
		t.Fatalf("proto.Clone(typedNil) returned valid reflection message")
	}
}

func TestProtoCloneKnownTypes(t *testing.T) {
	orig := &timestamppb.Timestamp{
		Seconds: 1700000000,
		Nanos:   500,
	}

	cloned := proto.Clone(orig)
	clonedTs, ok := cloned.(*timestamppb.Timestamp)
	if !ok {
		t.Fatalf("cloned message is not *timestamppb.Timestamp")
	}

	if !proto.Equal(orig, clonedTs) {
		t.Fatalf("proto.Clone produced message unequal to original")
	}

	// Mutating cloned timestamp struct does not mutate original
	clonedTs.Seconds = 1700000001
	clonedTs.Nanos = 999
	if orig.Seconds != 1700000000 || orig.Nanos != 500 {
		t.Fatalf("mutating clone struct modified original timestamp: seconds=%d nanos=%d", orig.Seconds, orig.Nanos)
	}
}

func TestProtoCloneDeepIsolationRepeatedAndNested(t *testing.T) {
	parentDesc, childDesc := buildSchema(t)

	titleField := parentDesc.Fields().ByName("title")
	itemsField := parentDesc.Fields().ByName("items")
	childField := parentDesc.Fields().ByName("child")
	scoreField := parentDesc.Fields().ByName("score")
	tagField := childDesc.Fields().ByName("tag")
	weightField := childDesc.Fields().ByName("weight")

	orig := dynamicpb.NewMessage(parentDesc)
	orig.Set(titleField, protoreflect.ValueOfString("Original Title"))
	orig.Set(scoreField, protoreflect.ValueOfFloat64(math.NaN()))

	origItems := orig.Mutable(itemsField).List()
	origItems.Append(protoreflect.ValueOfString("item1"))
	origItems.Append(protoreflect.ValueOfString("item2"))

	origChild := orig.Mutable(childField).Message()
	origChild.Set(tagField, protoreflect.ValueOfString("child-v1"))
	origChild.Set(weightField, protoreflect.ValueOfInt32(10))

	// Clone the message
	clonedRaw := proto.Clone(orig)
	cloned, ok := clonedRaw.(*dynamicpb.Message)
	if !ok {
		t.Fatalf("cloned message is not *dynamicpb.Message")
	}

	// Verify semantic equality before mutations (proto.Equal handles NaN equality)
	if !proto.Equal(orig, cloned) {
		t.Fatalf("proto.Clone must produce semantically equal message")
	}

	// Verify deep isolation by mutating cloned fields
	clonedItems := cloned.Mutable(itemsField).List()
	clonedItems.Append(protoreflect.ValueOfString("item3"))
	clonedItems.Set(0, protoreflect.ValueOfString("mutated-item0"))

	clonedChild := cloned.Mutable(childField).Message()
	clonedChild.Set(tagField, protoreflect.ValueOfString("child-mutated"))
	clonedChild.Set(weightField, protoreflect.ValueOfInt32(99))

	cloned.Set(titleField, protoreflect.ValueOfString("Mutated Title"))

	// Assert original remains completely untouched
	if orig.Get(titleField).String() != "Original Title" {
		t.Fatalf("original title was modified: %s", orig.Get(titleField).String())
	}
	if origItems.Len() != 2 {
		t.Fatalf("original items list length modified: got %d, expected 2", origItems.Len())
	}
	if origItems.Get(0).String() != "item1" || origItems.Get(1).String() != "item2" {
		t.Fatalf("original items list content modified: %v", origItems)
	}
	if origChild.Get(tagField).String() != "child-v1" || origChild.Get(weightField).Int() != 10 {
		t.Fatalf("original child message modified: tag=%s, weight=%d", origChild.Get(tagField).String(), origChild.Get(weightField).Int())
	}
}

func TestProtoCloneMapDeepIsolation(t *testing.T) {
	parentDesc, childDesc := buildSchema(t)

	attrsField := parentDesc.Fields().ByName("attributes")
	tagField := childDesc.Fields().ByName("tag")
	weightField := childDesc.Fields().ByName("weight")

	orig := dynamicpb.NewMessage(parentDesc)
	origAttrs := orig.Mutable(attrsField).Map()

	child1 := dynamicpb.NewMessage(childDesc)
	child1.Set(tagField, protoreflect.ValueOfString("env-prod"))
	child1.Set(weightField, protoreflect.ValueOfInt32(100))
	origAttrs.Set(protoreflect.ValueOfString("env").MapKey(), protoreflect.ValueOfMessage(child1))

	// Clone message
	cloned := proto.Clone(orig).(*dynamicpb.Message)

	// Mutate cloned map: modify existing entry's child message, delete entry, add new entry
	clonedAttrs := cloned.Mutable(attrsField).Map()
	clonedChild := clonedAttrs.Get(protoreflect.ValueOfString("env").MapKey()).Message()
	clonedChild.Set(tagField, protoreflect.ValueOfString("env-staging"))

	child2 := dynamicpb.NewMessage(childDesc)
	child2.Set(tagField, protoreflect.ValueOfString("tier-frontend"))
	clonedAttrs.Set(protoreflect.ValueOfString("tier").MapKey(), protoreflect.ValueOfMessage(child2))

	// Assert original map and original child message inside map were not affected
	if origAttrs.Len() != 1 {
		t.Fatalf("original map size changed: got %d, expected 1", origAttrs.Len())
	}
	origChild := origAttrs.Get(protoreflect.ValueOfString("env").MapKey()).Message()
	if origChild.Get(tagField).String() != "env-prod" {
		t.Fatalf("nested message inside original map entry was modified: %s", origChild.Get(tagField).String())
	}
	if origAttrs.Has(protoreflect.ValueOfString("tier").MapKey()) {
		t.Fatalf("new entry added to cloned map leaked to original map")
	}
}

func TestProtoClonePresencePreservation(t *testing.T) {
	parentDesc, _ := buildSchema(t)

	titleField := parentDesc.Fields().ByName("title")
	optCountField := parentDesc.Fields().ByName("optional_count")

	// Message with explicit zero value for proto3 optional field
	orig := dynamicpb.NewMessage(parentDesc)
	orig.Set(optCountField, protoreflect.ValueOfInt32(0))
	// title is left unpopulated (implicit presence scalar default zero)

	if !orig.ProtoReflect().Has(optCountField) {
		t.Fatalf("expected optional_count with explicit 0 to have presence in orig")
	}
	if orig.ProtoReflect().Has(titleField) {
		t.Fatalf("expected unpopulated title to NOT have presence in orig")
	}

	cloned := proto.Clone(orig).(*dynamicpb.Message)

	// Cloned message must preserve presence distinction
	if !cloned.ProtoReflect().Has(optCountField) {
		t.Fatalf("proto.Clone lost presence for proto3 optional field explicitly set to 0")
	}
	if cloned.Get(optCountField).Int() != 0 {
		t.Fatalf("expected cloned optional_count value to be 0, got %d", cloned.Get(optCountField).Int())
	}
	if cloned.ProtoReflect().Has(titleField) {
		t.Fatalf("proto.Clone created presence for unpopulated implicit field")
	}
}
csx.json
{"case":{"caseId":"case:sha256:946fd3ba2e4d8673887eb7ed92ef854f1d22fae7efee9dedf90e270dc633973c","contract":["proto.Clone creates an isolated deep copy where mutating cloned repeated slices, maps, or nested messages does not affect the original message.","proto.Clone(nil) returns untyped nil when given untyped nil, and returns a typed nil interface whose ProtoReflect().IsValid() is false when given a typed nil pointer.","proto.Clone preserves explicit presence for proto3 optional fields set to default zero values while keeping unpopulated implicit fields unpopulated.","proto.Clone produces semantically equal deep copies across static known types and dynamic message descriptors."],"goal":"verify google.golang.org/protobuf/proto.Clone in pkg:golang/google.golang.org/protobuf@v1.35.1","kind":"HOW","packages":["pkg:golang/google.golang.org/protobuf@v1.35.1"],"schemaVersion":1,"symbols":["google.golang.org/protobuf/proto.Clone"]},"contractCommand":["go","test","./..."],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","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.35.1"],"schemaVersion":1,"subject":"pkg:golang/google.golang.org/protobuf@v1.35.1","symbols":["google.golang.org/protobuf/proto.Clone"],"verifierAdapter":"golang@1"}
go.mod
module example.com/protoclone

go 1.23

require google.golang.org/protobuf v1.35.1
go.sum
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/protobuf v1.35.1 h1:m3LfL6/Ca+fqnjnlqQXNpFPABW1UD7mjh8KO2mKFytA=
google.golang.org/protobuf v1.35.1/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE=
spec.json
{
  "schemaVersion": 1,
  "goal": "verify google.golang.org/protobuf/proto.Clone in pkg:golang/google.golang.org/protobuf@v1.35.1",
  "kind": "HOW",
  "packages": [
    "pkg:golang/google.golang.org/protobuf@v1.35.1"
  ],
  "symbols": [
    "google.golang.org/protobuf/proto.Clone"
  ]
}

Seeder de origen

anónimo