CodeSampleX

Exemplo

google.golang.org/protobuf v1.35.2

Amostra verificada para golang google.golang.org/protobuf v1.35.2. O contrato rodou em go 1.26 · linux debian/x64 · docker e passou.

sha256:c1125ede659b0d88ff31a7294c912735078c7dcf14b4cdce909f58034b6ef92e

Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu. Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas. MIT-0

Evidência de execução

O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.

Base da evidência
Contrato assinado aprovado
Recibos de verificação
1
Chaves de assinatura que o compilaram
1
Ambiente declarado go linux 24 · ubuntu · glibc 2.39 x64 go go go

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
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-10-15

Caso

HOW
Objetivo
verify pkg:golang/google.golang.org/protobuf@v1.35.2
Pacotes
Ambiente
go
Criado
2026-10-15T02:27:56Z

Contrato

  1. proto.Marshal and proto.Unmarshal round-trip dynamic and well-known protobuf messages while preserving proto.Equal equivalence, proto.Size accuracy, and explicit proto3_optional zero-value presence.
  2. proto.Clone produces an isolated deep copy where mutations to scalar and repeated fields do not affect the original message, and proto.Merge combines fields into a target message.
  3. protojson.Marshal and protojson.Unmarshal round-trip messages using camelCase keys, string 64-bit integers, and string enum names by default, while protojson.MarshalOptions supports UseProtoNames and UseEnumNumbers.
  4. Google well-known types (timestamppb.Timestamp, durationpb.Duration, structpb.Struct, wrapperspb.StringValue, and anypb.Any) construct, validate, pack, and unpack via anypb.New and anypb.UnmarshalNew.

Arquivos

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

Baixar o artefato de código-fonte (tar.gz)

Código-fonte

NOTES.md
# Verifying google.golang.org/protobuf v1.35.2

This sample verifies core wire format serialization, reflection-based dynamic messages, deep cloning, JSON encoding, and well-known types in `google.golang.org/protobuf` pinned to version `v1.35.2`.

## Verified Contract Assertions

1. **Binary Wire Format & Presence (`proto.Marshal`, `proto.Unmarshal`, `proto.Size`, `proto.Equal`)**:
   - `proto.Marshal` encodes messages to binary wire format whose byte length matches `proto.Size`.
   - `proto.Unmarshal` decodes wire bytes back into target messages with `proto.Equal` confirming semantic equality.
   - Explicit `proto3_optional` fields set to zero values retain field presence (`Has` returns `true`) across wire round-trips.

2. **Deep Copy Isolation & Merging (`proto.Clone`, `proto.Merge`)**:
   - `proto.Clone` creates an independent deep copy; mutating scalar or repeated list fields on the clone leaves the source message unchanged.
   - `proto.Merge` copies populated scalar fields and appends repeated elements into a destination message.

3. **JSON Mapping (`protojson.Marshal`, `protojson.Unmarshal`, `protojson.MarshalOptions`)**:
   - Default `protojson.Marshal` uses `camelCase` field names, formats `int64` values as strings, and outputs enum names as strings.
   - `protojson.MarshalOptions` with `UseProtoNames: true` and `UseEnumNumbers: true` emits `snake_case` keys and numeric enum values.
   - `protojson.Unmarshal` parses JSON back into a message equal to the original.

4. **Well-Known Types (`timestamppb`, `durationpb`, `structpb`, `wrapperspb`, `anypb`)**:
   - Constructs and validates `Timestamp`, `Duration`, `Struct`, and `StringValue` wrappers, and packs/unpacks messages using `anypb.New` and `anypb.UnmarshalNew`.
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 pkg:golang/google.golang.org/protobuf@v1.35.2
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/google.golang.org/protobuf@v1.35.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:5cfddb95891031348cdacea2c512646cb109675e17f9ebfa8e4e39910197e3c9","contract":["proto.Marshal and proto.Unmarshal round-trip dynamic and well-known protobuf messages while preserving proto.Equal equivalence, proto.Size accuracy, and explicit proto3_optional zero-value presence.","proto.Clone produces an isolated deep copy where mutations to scalar and repeated fields do not affect the original message, and proto.Merge combines fields into a target message.","protojson.Marshal and protojson.Unmarshal round-trip messages using camelCase keys, string 64-bit integers, and string enum names by default, while protojson.MarshalOptions supports UseProtoNames and UseEnumNumbers.","Google well-known types (timestamppb.Timestamp, durationpb.Duration, structpb.Struct, wrapperspb.StringValue, and anypb.Any) construct, validate, pack, and unpack via anypb.New and anypb.UnmarshalNew."],"goal":"verify pkg:golang/google.golang.org/protobuf@v1.35.2","kind":"HOW","packages":["pkg:golang/google.golang.org/protobuf@v1.35.2"],"schemaVersion":1},"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.2"],"schemaVersion":1,"subject":"pkg:golang/google.golang.org/protobuf@v1.35.2","verifierAdapter":"golang@1"}
go.mod
module example.com/protobuf-sample

go 1.23

require google.golang.org/protobuf v1.35.2
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.2 h1:8Ar7bF+apOIoThw1EdZl0p1oWvMqTHmpA2fRTyZO8io=
google.golang.org/protobuf v1.35.2/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE=
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:golang/google.golang.org/protobuf@v1.35.2",
  "kind": "HOW",
  "packages": [
    "pkg:golang/google.golang.org/protobuf@v1.35.2"
  ]
}
test/contract.go
package contract

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

// BuildDynamicSchema constructs an EventRecord message descriptor and Status enum descriptor
// at runtime using descriptorpb and protodesc.NewFile.
func BuildDynamicSchema() (protoreflect.MessageDescriptor, protoreflect.EnumDescriptor, error) {
	fd := &descriptorpb.FileDescriptorProto{
		Name:    proto.String("event.proto"),
		Package: proto.String("example.event"),
		Syntax:  proto.String("proto3"),
		MessageType: []*descriptorpb.DescriptorProto{
			{
				Name: proto.String("EventRecord"),
				Field: []*descriptorpb.FieldDescriptorProto{
					{
						Name:     proto.String("event_id"),
						Number:   proto.Int32(1),
						Label:    descriptorpb.FieldDescriptorProto_LABEL_OPTIONAL.Enum(),
						Type:     descriptorpb.FieldDescriptorProto_TYPE_INT64.Enum(),
						JsonName: proto.String("eventId"),
					},
					{
						Name:     proto.String("name"),
						Number:   proto.Int32(2),
						Label:    descriptorpb.FieldDescriptorProto_LABEL_OPTIONAL.Enum(),
						Type:     descriptorpb.FieldDescriptorProto_TYPE_STRING.Enum(),
						JsonName: proto.String("name"),
					},
					{
						Name:     proto.String("status"),
						Number:   proto.Int32(3),
						Label:    descriptorpb.FieldDescriptorProto_LABEL_OPTIONAL.Enum(),
						Type:     descriptorpb.FieldDescriptorProto_TYPE_ENUM.Enum(),
						TypeName: proto.String(".example.event.Status"),
						JsonName: proto.String("status"),
					},
					{
						Name:     proto.String("labels"),
						Number:   proto.Int32(4),
						Label:    descriptorpb.FieldDescriptorProto_LABEL_REPEATED.Enum(),
						Type:     descriptorpb.FieldDescriptorProto_TYPE_STRING.Enum(),
						JsonName: proto.String("labels"),
					},
					{
						Name:           proto.String("retry_count"),
						Number:         proto.Int32(5),
						Label:          descriptorpb.FieldDescriptorProto_LABEL_OPTIONAL.Enum(),
						Type:           descriptorpb.FieldDescriptorProto_TYPE_INT32.Enum(),
						JsonName:       proto.String("retryCount"),
						Proto3Optional: proto.Bool(true),
						OneofIndex:     proto.Int32(0),
					},
				},
				OneofDecl: []*descriptorpb.OneofDescriptorProto{
					{
						Name: proto.String("_retry_count"),
					},
				},
			},
		},
		EnumType: []*descriptorpb.EnumDescriptorProto{
			{
				Name: proto.String("Status"),
				Value: []*descriptorpb.EnumValueDescriptorProto{
					{
						Name:   proto.String("STATUS_UNSPECIFIED"),
						Number: proto.Int32(0),
					},
					{
						Name:   proto.String("STATUS_ACTIVE"),
						Number: proto.Int32(1),
					},
					{
						Name:   proto.String("STATUS_ARCHIVED"),
						Number: proto.Int32(2),
					},
				},
			},
		},
	}

	fileDesc, err := protodesc.NewFile(fd, protoregistry.GlobalFiles)
	if err != nil {
		return nil, nil, err
	}

	msgDesc := fileDesc.Messages().ByName("EventRecord")
	enumDesc := fileDesc.Enums().ByName("Status")
	return msgDesc, enumDesc, nil
}
test/contract_test.go
package contract

import (
	"encoding/json"
	"testing"
	"time"

	"google.golang.org/protobuf/encoding/protojson"
	"google.golang.org/protobuf/proto"
	"google.golang.org/protobuf/reflect/protoreflect"
	"google.golang.org/protobuf/types/dynamicpb"
	"google.golang.org/protobuf/types/known/anypb"
	"google.golang.org/protobuf/types/known/durationpb"
	"google.golang.org/protobuf/types/known/structpb"
	"google.golang.org/protobuf/types/known/timestamppb"
	"google.golang.org/protobuf/types/known/wrapperspb"
)

func TestProtobufContract(t *testing.T) {
	msgDesc, enumDesc, err := BuildDynamicSchema()
	if err != nil {
		t.Fatalf("BuildDynamicSchema failed: %v", err)
	}
	if msgDesc == nil || enumDesc == nil {
		t.Fatalf("expected non-nil message and enum descriptors")
	}

	eventIDField := msgDesc.Fields().ByName("event_id")
	nameField := msgDesc.Fields().ByName("name")
	statusField := msgDesc.Fields().ByName("status")
	labelsField := msgDesc.Fields().ByName("labels")
	retryField := msgDesc.Fields().ByName("retry_count")

	// 1. Wire Marshal, Size, Unmarshal, and Equal with explicit proto3_optional presence
	orig := dynamicpb.NewMessage(msgDesc)
	orig.Set(eventIDField, protoreflect.ValueOfInt64(9001))
	orig.Set(nameField, protoreflect.ValueOfString("deploy"))
	orig.Set(statusField, protoreflect.ValueOfEnum(enumDesc.Values().ByName("STATUS_ACTIVE").Number()))
	orig.Set(retryField, protoreflect.ValueOfInt32(0)) // explicit zero presence

	labels := orig.Mutable(labelsField).List()
	labels.Append(protoreflect.ValueOfString("prod"))
	labels.Append(protoreflect.ValueOfString("eu"))

	wireBytes, err := proto.Marshal(orig)
	if err != nil {
		t.Fatalf("proto.Marshal failed: %v", err)
	}
	if len(wireBytes) == 0 || len(wireBytes) != proto.Size(orig) {
		t.Fatalf("proto.Size mismatch: len=%d size=%d", len(wireBytes), proto.Size(orig))
	}

	decoded := dynamicpb.NewMessage(msgDesc)
	if err := proto.Unmarshal(wireBytes, decoded); err != nil {
		t.Fatalf("proto.Unmarshal failed: %v", err)
	}
	if !proto.Equal(orig, decoded) {
		t.Fatalf("proto.Equal returned false after Marshal/Unmarshal round-trip")
	}
	if !decoded.Has(retryField) || decoded.Get(retryField).Int() != 0 {
		t.Fatalf("proto3_optional explicit zero presence lost after round-trip")
	}

	// 2. Deep copy isolation with proto.Clone and message combination with proto.Merge
	cloned := proto.Clone(orig).(*dynamicpb.Message)
	cloned.Set(nameField, protoreflect.ValueOfString("rollback"))
	cloned.Mutable(labelsField).List().Append(protoreflect.ValueOfString("canary"))

	if orig.Get(nameField).String() != "deploy" || orig.Get(labelsField).List().Len() != 2 {
		t.Fatalf("proto.Clone did not isolate mutations from original message")
	}

	mergeTarget := dynamicpb.NewMessage(msgDesc)
	mergeTarget.Set(nameField, protoreflect.ValueOfString("initial"))
	proto.Merge(mergeTarget, orig)
	if mergeTarget.Get(eventIDField).Int() != 9001 || mergeTarget.Get(nameField).String() != "deploy" {
		t.Fatalf("proto.Merge did not overwrite scalar fields or append repeated lists properly")
	}

	// 3. JSON encoding and decoding with protojson
	jsonBytes, err := protojson.Marshal(orig)
	if err != nil {
		t.Fatalf("protojson.Marshal failed: %v", err)
	}
	var parsed map[string]any
	if err := json.Unmarshal(jsonBytes, &parsed); err != nil {
		t.Fatalf("json.Unmarshal of protojson output failed: %v", err)
	}
	if parsed["eventId"] != "9001" || parsed["status"] != "STATUS_ACTIVE" {
		t.Fatalf("unexpected default protojson fields: %v", parsed)
	}

	snakeBytes, err := (protojson.MarshalOptions{
		UseProtoNames:  true,
		UseEnumNumbers: true,
	}).Marshal(orig)
	if err != nil {
		t.Fatalf("protojson.MarshalOptions.Marshal failed: %v", err)
	}
	var snakeParsed map[string]any
	if err := json.Unmarshal(snakeBytes, &snakeParsed); err != nil {
		t.Fatalf("json.Unmarshal of snake_case protojson failed: %v", err)
	}
	if snakeParsed["event_id"] != "9001" || snakeParsed["status"] != float64(1) {
		t.Fatalf("unexpected UseProtoNames/UseEnumNumbers output: %v", snakeParsed)
	}

	fromJSON := dynamicpb.NewMessage(msgDesc)
	if err := protojson.Unmarshal(jsonBytes, fromJSON); err != nil {
		t.Fatalf("protojson.Unmarshal failed: %v", err)
	}
	if !proto.Equal(orig, fromJSON) {
		t.Fatalf("proto.Equal returned false after protojson Marshal/Unmarshal round-trip")
	}

	// 4. Well-Known Types (Timestamp, Duration, Struct, Wrapper, Any)
	ts := timestamppb.New(time.Date(2026, time.January, 15, 10, 30, 0, 0, time.UTC))
	if err := ts.CheckValid(); err != nil {
		t.Fatalf("timestamppb.CheckValid failed: %v", err)
	}
	dur := durationpb.New(45 * time.Second)
	if dur.AsDuration() != 45*time.Second {
		t.Fatalf("durationpb.AsDuration mismatch: %v", dur.AsDuration())
	}

	st, err := structpb.NewStruct(map[string]any{
		"env":     "production",
		"enabled": true,
		"count":   3,
	})
	if err != nil {
		t.Fatalf("structpb.NewStruct failed: %v", err)
	}
	if st.GetFields()["env"].GetStringValue() != "production" {
		t.Fatalf("structpb field lookup mismatch")
	}

	wrap := wrapperspb.String("wrapped-value")
	anyMsg, err := anypb.New(wrap)
	if err != nil {
		t.Fatalf("anypb.New failed: %v", err)
	}
	unpacked, err := anyMsg.UnmarshalNew()
	if err != nil {
		t.Fatalf("anypb.UnmarshalNew failed: %v", err)
	}
	if !proto.Equal(wrap, unpacked) {
		t.Fatalf("anypb.UnmarshalNew did not round-trip wrapped message")
	}
}

Seeder de origem

anônimo