CodeSampleX

Exemple

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

Échantillon vérifié pour golang google.golang.org/protobuf v1.26.0-rc.1: proto.Merge. Le contrat s'est exécuté sur go 1.26 · linux debian/x64 · docker et a…

sha256:e3cfe4d7927bfae564e9f7ab0cbe61324605da887860db287cdcc88a620fea4f

Ce réseau offre une seule chose : un échantillon qui compile. Il l'a exécuté dans un bac à sable et conservé le reçu signé. Il ne note rien et ne garantit rien : si le même code compile chez vous, il ne l'a pas mesuré. Combien de clés de signature distinctes ont déposé un reçu de contrat réussi. Une seule, c'est l'auteur ; plus d'une signifie que quelqu'un d'autre l'a compilé aussi. Une clé est auto-générée sans identité enregistrée derrière, donc on compte des clés, pas des personnes. MIT-0

Preuves d'exécution

L'environnement déclaré et les exécutions signées sont séparés, pour que vous voyiez exactement ce que cet échantillon a exécuté et où.

Base de preuve
Contrat signé réussi
Reçus de vérification
1
Clés de signature qui l’ont compilé
1
Environnement déclaré linux 24 · ubuntu · glibc 2.39 x64 go

Environnements des exécutions de vérification

Environnement Contrat Étapes Exécution
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

Cas

HOW
Objectif
verify proto.Merge in pkg:golang/google.golang.org/protobuf@v1.26.0-rc.1
Paquets
Symboles
  • proto.Merge
Créé
2026-09-04T23:37:43Z

Contrat

  1. proto.Merge overwrites populated scalar fields from src into dst while preserving untouched fields in dst
  2. proto.Merge appends repeated list elements from src to dst without clearing existing elements
  3. proto.Merge recursively merges nested messages while replacing matching map entry keys
  4. proto.Merge panics with descriptor mismatch when message types differ

Fichiers

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

Télécharger l’artefact source (tar.gz)

Code source

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.Merge 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.Merge

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:ca53790c292f1df9e9038017a5f9a8374977b90da7b46301383fb99d6c2c2dff","contract":["proto.Merge overwrites populated scalar fields from src into dst while preserving untouched fields in dst","proto.Merge appends repeated list elements from src to dst without clearing existing elements","proto.Merge recursively merges nested messages while replacing matching map entry keys","proto.Merge panics with descriptor mismatch when message types differ"],"goal":"verify proto.Merge 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.Merge"]},"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.Merge"],"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() {
	dst := &timestamppb.Timestamp{
		Seconds: 100,
		Nanos:   200,
	}
	src := &timestamppb.Timestamp{
		Seconds: 500,
	}

	fmt.Printf("Before Merge: dst={Seconds:%d, Nanos:%d}\n", dst.Seconds, dst.Nanos)
	proto.Merge(dst, src)
	fmt.Printf("After Merge:  dst={Seconds:%d, Nanos:%d}\n", dst.Seconds, dst.Nanos)
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify proto.Merge 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.Merge"
  ]
}
test/contract.go
package main

import (
	"fmt"
	"os"

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

func buildSchema() (protoreflect.MessageDescriptor, protoreflect.MessageDescriptor, error) {
	fd := &descriptorpb.FileDescriptorProto{
		Name:    proto.String("merge_demo.proto"),
		Package: proto.String("example.merge"),
		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("count"),
						Number:   proto.Int32(2),
						Type:     descriptorpb.FieldDescriptorProto_TYPE_INT32.Enum(),
						JsonName: proto.String("count"),
					},
					{
						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.merge.ChildRecord"),
						JsonName: proto.String("child"),
					},
					{
						Name:     proto.String("attributes"),
						Number:   proto.Int32(5),
						Type:     descriptorpb.FieldDescriptorProto_TYPE_MESSAGE.Enum(),
						TypeName: proto.String(".example.merge.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.merge.ChildRecord"),
								JsonName: proto.String("value"),
							},
						},
						Options: &descriptorpb.MessageOptions{
							MapEntry: proto.Bool(true),
						},
					},
				},
			},
		},
	}

	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")
	countField := parentDesc.Fields().ByName("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.Merge overwrites populated scalar fields from src into dst while preserving untouched fields in dst
	{
		dst := dynamicpb.NewMessage(parentDesc)
		dst.Set(titleField, protoreflect.ValueOfString("Initial Title"))
		dst.Set(countField, protoreflect.ValueOfInt32(42))

		src := dynamicpb.NewMessage(parentDesc)
		src.Set(titleField, protoreflect.ValueOfString("Updated Title"))

		proto.Merge(dst, src)

		if dst.Get(titleField).String() != "Updated Title" {
			fmt.Fprintf(os.Stderr, "FAIL: expected title to be overwritten to 'Updated Title', got '%s'\n", dst.Get(titleField).String())
			os.Exit(1)
		}
		if dst.Get(countField).Int() != 42 {
			fmt.Fprintf(os.Stderr, "FAIL: expected count to remain 42, got %d\n", dst.Get(countField).Int())
			os.Exit(1)
		}
	}

	// Assertion 2: proto.Merge appends repeated list elements from src to dst without clearing existing elements
	{
		dst := dynamicpb.NewMessage(parentDesc)
		dstItems := dst.Mutable(itemsField).List()
		dstItems.Append(protoreflect.ValueOfString("item1"))
		dstItems.Append(protoreflect.ValueOfString("item2"))

		src := dynamicpb.NewMessage(parentDesc)
		srcItems := src.Mutable(itemsField).List()
		srcItems.Append(protoreflect.ValueOfString("item3"))
		srcItems.Append(protoreflect.ValueOfString("item4"))

		proto.Merge(dst, src)

		resItems := dst.Get(itemsField).List()
		if resItems.Len() != 4 {
			fmt.Fprintf(os.Stderr, "FAIL: expected 4 items after merge, got %d\n", resItems.Len())
			os.Exit(1)
		}
		expected := []string{"item1", "item2", "item3", "item4"}
		for i, exp := range expected {
			if resItems.Get(i).String() != exp {
				fmt.Fprintf(os.Stderr, "FAIL: expected item[%d] == %s, got %s\n", i, exp, resItems.Get(i).String())
				os.Exit(1)
			}
		}
	}

	// Assertion 3: proto.Merge recursively merges nested messages while replacing matching map entry keys
	{
		dst := dynamicpb.NewMessage(parentDesc)
		dstChild := dst.Mutable(childField).Message()
		dstChild.Set(tagField, protoreflect.ValueOfString("childDst"))
		dstChild.Set(weightField, protoreflect.ValueOfInt32(10))

		dstAttrs := dst.Mutable(attrsField).Map()
		m1 := dynamicpb.NewMessage(childDesc)
		m1.Set(tagField, protoreflect.ValueOfString("map1"))
		m1.Set(weightField, protoreflect.ValueOfInt32(100))
		dstAttrs.Set(protoreflect.ValueOfString("k1").MapKey(), protoreflect.ValueOfMessage(m1))

		m2 := dynamicpb.NewMessage(childDesc)
		m2.Set(tagField, protoreflect.ValueOfString("map2"))
		m2.Set(weightField, protoreflect.ValueOfInt32(200))
		dstAttrs.Set(protoreflect.ValueOfString("k2").MapKey(), protoreflect.ValueOfMessage(m2))

		src := dynamicpb.NewMessage(parentDesc)
		srcChild := src.Mutable(childField).Message()
		srcChild.Set(weightField, protoreflect.ValueOfInt32(20))

		srcAttrs := src.Mutable(attrsField).Map()
		m1Src := dynamicpb.NewMessage(childDesc)
		m1Src.Set(weightField, protoreflect.ValueOfInt32(150))
		srcAttrs.Set(protoreflect.ValueOfString("k1").MapKey(), protoreflect.ValueOfMessage(m1Src))

		m3 := dynamicpb.NewMessage(childDesc)
		m3.Set(tagField, protoreflect.ValueOfString("map3"))
		m3.Set(weightField, protoreflect.ValueOfInt32(300))
		srcAttrs.Set(protoreflect.ValueOfString("k3").MapKey(), protoreflect.ValueOfMessage(m3))

		proto.Merge(dst, src)

		// Check nested message recursive merge (dst tag preserved, weight updated)
		resChild := dst.Get(childField).Message()
		if resChild.Get(tagField).String() != "childDst" {
			fmt.Fprintf(os.Stderr, "FAIL: expected nested child tag to remain 'childDst', got '%s'\n", resChild.Get(tagField).String())
			os.Exit(1)
		}
		if resChild.Get(weightField).Int() != 20 {
			fmt.Fprintf(os.Stderr, "FAIL: expected nested child weight to be updated to 20, got %d\n", resChild.Get(weightField).Int())
			os.Exit(1)
		}

		// Check map merge
		resAttrs := dst.Get(attrsField).Map()
		if resAttrs.Len() != 3 {
			fmt.Fprintf(os.Stderr, "FAIL: expected 3 map entries, got %d\n", resAttrs.Len())
			os.Exit(1)
		}

		// k1: replaced by src entry (tag is empty because src didn't set tag, weight is 150)
		k1Val := resAttrs.Get(protoreflect.ValueOfString("k1").MapKey()).Message()
		if k1Val.Get(tagField).String() != "" || k1Val.Get(weightField).Int() != 150 {
			fmt.Fprintf(os.Stderr, "FAIL: expected k1 message overwritten with tag='', weight=150, got tag='%s', weight=%d\n", k1Val.Get(tagField).String(), k1Val.Get(weightField).Int())
			os.Exit(1)
		}

		// k2: untouched
		k2Val := resAttrs.Get(protoreflect.ValueOfString("k2").MapKey()).Message()
		if k2Val.Get(tagField).String() != "map2" || k2Val.Get(weightField).Int() != 200 {
			fmt.Fprintf(os.Stderr, "FAIL: expected k2 message preserved tag='map2', weight=200, got tag='%s', weight=%d\n", k2Val.Get(tagField).String(), k2Val.Get(weightField).Int())
			os.Exit(1)
		}

		// k3: newly inserted
		k3Val := resAttrs.Get(protoreflect.ValueOfString("k3").MapKey()).Message()
		if k3Val.Get(tagField).String() != "map3" || k3Val.Get(weightField).Int() != 300 {
			fmt.Fprintf(os.Stderr, "FAIL: expected k3 message added tag='map3', weight=300, got tag='%s', weight=%d\n", k3Val.Get(tagField).String(), k3Val.Get(weightField).Int())
			os.Exit(1)
		}
	}

	// Assertion 4: proto.Merge panics with descriptor mismatch when message types differ
	{
		parent := dynamicpb.NewMessage(parentDesc)
		child := dynamicpb.NewMessage(childDesc)

		var recovered any
		func() {
			defer func() {
				recovered = recover()
			}()
			proto.Merge(parent, child)
		}()

		if recovered == nil {
			fmt.Fprintf(os.Stderr, "FAIL: expected proto.Merge to panic on descriptor mismatch\n")
			os.Exit(1)
		}
	}

	fmt.Println("CONTRACT_PASS")
}

Seeder d'origine

anonyme