CodeSampleX

Пример

google.golang.org/protobuf v1.26.0-rc.1: proto.Clone

Проверенный пример — golang google.golang.org/protobuf v1.26.0-rc.1: proto.Clone. Контракт выполнен на go 1.26 · linux debian/x64 · docker и пройден.

sha256:fb45bd5c2b2f280b7d0991e3216a72866de7034c2dd1972bb3c94124c9936f63

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда linux 24 · ubuntu · glibc 2.39 x64 go

Среды запусков проверки

Окружение Контракт Этапы Запуск
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-04

Кейс

HOW
Цель
verify proto.Clone in pkg:golang/google.golang.org/protobuf@v1.26.0-rc.1
Пакеты
Символы
  • proto.Clone
Создан
2026-09-04T23:32:53Z

Контракт

  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

Файлы

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • main.go
  • spec.json
  • test/contract.go

Скачать артефакт с исходным кодом (tar.gz)

Исходный код

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.Clone in pkg:golang/google.golang.org/protobuf@v1.26.0-rc.1
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/google.golang.org/protobuf@v1.26.0-rc.1
Demonstrate these symbols/APIs:
  - 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.
csx.json
{"case":{"caseId":"case:sha256:08c0a71d623333dcb1f70e4dcc0b156d2a8e2bef8912e7f13d769b382d937729","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 proto.Clone in pkg:golang/google.golang.org/protobuf@v1.26.0-rc.1","kind":"HOW","packages":["pkg:golang/google.golang.org/protobuf@v1.26.0-rc.1"],"schemaVersion":1,"symbols":["proto.Clone"]},"contractCommand":["go","run","./test"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/google.golang.org/protobuf@v1.26.0-rc.1"],"schemaVersion":1,"subject":"pkg:golang/google.golang.org/protobuf@v1.26.0-rc.1","symbols":["proto.Clone"],"verifierAdapter":"golang@1"}
go.mod
module sample

go 1.23

require google.golang.org/protobuf v1.26.0-rc.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.26.0-rc.1 h1:7QnIQpGRHE5RnLKnESfDoxm2dTapTZua5a0kS0A+VXQ=
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
main.go
package main

import (
	"fmt"

	"google.golang.org/protobuf/proto"
	"google.golang.org/protobuf/types/known/timestamppb"
)

func main() {
	orig := &timestamppb.Timestamp{
		Seconds: 1700000000,
		Nanos:   123456,
	}

	cloned := proto.Clone(orig).(*timestamppb.Timestamp)
	fmt.Printf("Cloned timestamp equals original: %t\n", proto.Equal(orig, cloned))

	cloned.Seconds = 1700000001
	cloned.Nanos = 999999

	fmt.Printf("Original seconds after mutating clone: %d\n", orig.Seconds)
	fmt.Printf("Cloned seconds: %d\n", cloned.Seconds)
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify proto.Clone in pkg:golang/google.golang.org/protobuf@v1.26.0-rc.1",
  "kind": "HOW",
  "packages": [
    "pkg:golang/google.golang.org/protobuf@v1.26.0-rc.1"
  ],
  "symbols": [
    "proto.Clone"
  ]
}
test/contract.go
package main

import (
	"fmt"
	"os"
	"reflect"

	"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"
)

func buildSchema() (protoreflect.MessageDescriptor, protoreflect.MessageDescriptor, error) {
	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"),
					},
				},
				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 {
		return nil, nil, fmt.Errorf("protodesc.NewFile failed: %w", err)
	}

	parentDesc := fileDesc.Messages().ByName("ParentRecord")
	childDesc := fileDesc.Messages().ByName("ChildRecord")
	if parentDesc == nil || childDesc == nil {
		return nil, nil, fmt.Errorf("failed to resolve message descriptors")
	}

	return parentDesc, childDesc, nil
}

func main() {
	parentDesc, childDesc, err := buildSchema()
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: schema build error: %v\n", err)
		os.Exit(1)
	}

	titleField := parentDesc.Fields().ByName("title")
	optCountField := parentDesc.Fields().ByName("optional_count")
	itemsField := parentDesc.Fields().ByName("items")
	childField := parentDesc.Fields().ByName("child")
	attrsField := parentDesc.Fields().ByName("attributes")
	tagField := childDesc.Fields().ByName("tag")
	weightField := childDesc.Fields().ByName("weight")

	// Assertion 1: proto.Clone creates an isolated deep copy where mutating cloned repeated slices, maps, or nested messages does not affect the original message
	{
		orig := dynamicpb.NewMessage(parentDesc)
		orig.Set(titleField, protoreflect.ValueOfString("Initial Title"))

		origItems := orig.Mutable(itemsField).List()
		origItems.Append(protoreflect.ValueOfString("v1"))
		origItems.Append(protoreflect.ValueOfString("v2"))

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

		origAttrs := orig.Mutable(attrsField).Map()
		nestedChild := dynamicpb.NewMessage(childDesc)
		nestedChild.Set(tagField, protoreflect.ValueOfString("mapChildA"))
		nestedChild.Set(weightField, protoreflect.ValueOfInt32(20))
		origAttrs.Set(protoreflect.ValueOfString("k1").MapKey(), protoreflect.ValueOfMessage(nestedChild))

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

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

		clonedItems := cloned.Mutable(itemsField).List()
		clonedItems.Append(protoreflect.ValueOfString("v3"))
		clonedItems.Set(0, protoreflect.ValueOfString("mutated-v1"))

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

		clonedAttrs := cloned.Mutable(attrsField).Map()
		clonedNested := clonedAttrs.Get(protoreflect.ValueOfString("k1").MapKey()).Message()
		clonedNested.Set(tagField, protoreflect.ValueOfString("mapChildMutated"))

		newChild := dynamicpb.NewMessage(childDesc)
		newChild.Set(tagField, protoreflect.ValueOfString("mapChildB"))
		clonedAttrs.Set(protoreflect.ValueOfString("k2").MapKey(), protoreflect.ValueOfMessage(newChild))

		// Check original isolation
		if orig.Get(titleField).String() != "Initial Title" {
			fmt.Fprintf(os.Stderr, "FAIL: original title mutated: %s\n", orig.Get(titleField).String())
			os.Exit(1)
		}
		if origItems.Len() != 2 || origItems.Get(0).String() != "v1" || origItems.Get(1).String() != "v2" {
			fmt.Fprintf(os.Stderr, "FAIL: original repeated items mutated\n")
			os.Exit(1)
		}
		if origChild.Get(tagField).String() != "tagA" || origChild.Get(weightField).Int() != 10 {
			fmt.Fprintf(os.Stderr, "FAIL: original child message mutated\n")
			os.Exit(1)
		}
		if origAttrs.Len() != 1 || origAttrs.Has(protoreflect.ValueOfString("k2").MapKey()) {
			fmt.Fprintf(os.Stderr, "FAIL: original map mutated: len=%d\n", origAttrs.Len())
			os.Exit(1)
		}
		mapChildInOrig := origAttrs.Get(protoreflect.ValueOfString("k1").MapKey()).Message()
		if mapChildInOrig.Get(tagField).String() != "mapChildA" {
			fmt.Fprintf(os.Stderr, "FAIL: nested message in original map mutated\n")
			os.Exit(1)
		}
	}

	// Assertion 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
	{
		var untypedNil proto.Message = nil
		if res := proto.Clone(untypedNil); res != nil {
			fmt.Fprintf(os.Stderr, "FAIL: proto.Clone(nil) must return nil, got %v\n", res)
			os.Exit(1)
		}

		var typedNil *timestamppb.Timestamp = nil
		res := proto.Clone(typedNil)
		if res == nil {
			fmt.Fprintf(os.Stderr, "FAIL: proto.Clone(typedNil) returned untyped nil interface\n")
			os.Exit(1)
		}
		if !reflect.ValueOf(res).IsNil() {
			fmt.Fprintf(os.Stderr, "FAIL: proto.Clone(typedNil) concrete value is not nil\n")
			os.Exit(1)
		}
		if res.ProtoReflect().IsValid() {
			fmt.Fprintf(os.Stderr, "FAIL: proto.Clone(typedNil) returned valid reflection message\n")
			os.Exit(1)
		}
	}

	// Assertion 3: proto.Clone preserves explicit presence for proto3 optional fields set to default zero values while keeping unpopulated implicit fields unpopulated
	{
		orig := dynamicpb.NewMessage(parentDesc)
		orig.Set(optCountField, protoreflect.ValueOfInt32(0))

		if !orig.ProtoReflect().Has(optCountField) {
			fmt.Fprintf(os.Stderr, "FAIL: expected optional_count with explicit 0 to have presence in orig\n")
			os.Exit(1)
		}
		if orig.ProtoReflect().Has(titleField) {
			fmt.Fprintf(os.Stderr, "FAIL: expected unpopulated title to NOT have presence in orig\n")
			os.Exit(1)
		}

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

		if !cloned.ProtoReflect().Has(optCountField) {
			fmt.Fprintf(os.Stderr, "FAIL: proto.Clone lost presence for proto3 optional field explicitly set to 0\n")
			os.Exit(1)
		}
		if cloned.Get(optCountField).Int() != 0 {
			fmt.Fprintf(os.Stderr, "FAIL: expected cloned optional_count value to be 0, got %d\n", cloned.Get(optCountField).Int())
			os.Exit(1)
		}
		if cloned.ProtoReflect().Has(titleField) {
			fmt.Fprintf(os.Stderr, "FAIL: proto.Clone created presence for unpopulated implicit field\n")
			os.Exit(1)
		}
	}

	// Assertion 4: proto.Clone produces semantically equal deep copies across static known types and dynamic message descriptors
	{
		// Static known type
		origTs := &timestamppb.Timestamp{
			Seconds: 1700000000,
			Nanos:   500,
		}
		clonedTsRaw := proto.Clone(origTs)
		clonedTs, ok := clonedTsRaw.(*timestamppb.Timestamp)
		if !ok {
			fmt.Fprintf(os.Stderr, "FAIL: cloned static type is not *timestamppb.Timestamp\n")
			os.Exit(1)
		}
		if !proto.Equal(origTs, clonedTs) {
			fmt.Fprintf(os.Stderr, "FAIL: static cloned message does not equal original\n")
			os.Exit(1)
		}

		// Dynamic type
		dynOrig := dynamicpb.NewMessage(parentDesc)
		dynOrig.Set(titleField, protoreflect.ValueOfString("Dynamic Equivalence Test"))
		dynItems := dynOrig.Mutable(itemsField).List()
		dynItems.Append(protoreflect.ValueOfString("alpha"))
		dynItems.Append(protoreflect.ValueOfString("beta"))

		clonedDynRaw := proto.Clone(dynOrig)
		clonedDyn, ok := clonedDynRaw.(*dynamicpb.Message)
		if !ok {
			fmt.Fprintf(os.Stderr, "FAIL: cloned dynamic type is not *dynamicpb.Message\n")
			os.Exit(1)
		}
		if !proto.Equal(dynOrig, clonedDyn) {
			fmt.Fprintf(os.Stderr, "FAIL: dynamic cloned message does not equal original\n")
			os.Exit(1)
		}
	}

	fmt.Println("CONTRACT_PASS")
}

Исходный сидер

аноним