CodeSampleX

샘플

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

검증된 샘플 — golang google.golang.org/protobuf v1.35.1: proto.Equal. go 1.26 · linux alpine/x64 · docker에서 contract를 실행해 통과했습니다: proto.Equal returns true when…

sha256:5abbd12c05db97460964dc331edca15b92f1cec567e902f8354d097d4d07d4fe

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. MIT-0

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
2
빌드한 서명 키
1
선언된 환경 go linux x64 go go go

검증 실행 환경

환경 컨트랙트 단계 실행일
go 1.26 · linux alpine/x64 · docker ed25519:c1973797be207ac4 FAIL compile:SKIPPED · contract:FAIL · load:SKIPPED · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26-alpine@sha256:28d89ee9cc0f…
2026-08-30
go 1.26 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26-alpine@sha256:28d89ee9cc0f…
2026-08-30

케이스

HOW
목표
verify google.golang.org/protobuf/proto.Equal in pkg:golang/google.golang.org/protobuf@v1.35.1
패키지
심벌
  • google.golang.org/protobuf/proto.Equal
환경
go
생성일
2026-08-30T15:12:36Z

컨트랙트

  1. proto.Equal returns true when comparing two nil proto.Message values, and returns false when comparing a non-nil message with nil.
  2. proto.Equal evaluates semantic equality of populated scalar and string fields across separate message instances.
  3. proto.Equal distinguishes between unpopulated proto3 optional fields and explicitly set zero-value optional fields, while treating unpopulated implicit-presence scalars and default zero values as equal.
  4. proto.Equal evaluates repeated slice fields as equal only when all elements match strictly in identical index order, and treats unpopulated repeated slices and empty slices as equal.
  5. proto.Equal recursively evaluates nested message fields for equality.
  6. proto.Equal compares raw unknown field bytes across messages, returning true only when unknown field byte payloads match.

파일

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

소스 아티팩트 내려받기 (tar.gz)

소스

NOTES.md
# Protocol Buffers proto.Equal Semantic Equality

A known-solution search for `pkg:golang/google.golang.org/protobuf@v1.35.1` and `google.golang.org/protobuf/proto.Equal` demonstrated core equality comparison semantics.

This sample tests and verifies `proto.Equal` behaviors in `google.golang.org/protobuf` pinned to release `v1.35.1`.

## Observed Behavior

1. **Nil Handling (`proto.Equal`)**:
   `proto.Equal(nil, nil)` returns `true`. Comparing any non-nil message with `nil` (e.g. `proto.Equal(msg, nil)` or `proto.Equal(nil, msg)`) evaluates to `false`.

2. **Populated Field Equality Across Separate Instances**:
   `proto.Equal` performs descriptor-aware semantic comparisons. Two independently instantiated dynamic or generated messages with identical field populations evaluate to `true`, regardless of distinct memory pointer addresses.

3. **Field Presence Semantics**:
   - For fields with explicit presence (`proto3_optional`), an unset field is not equal to an explicitly populated field set to `0`.
   - For implicit-presence scalars in proto3, an unpopulated default zero value and an explicitly set `0` are semantically equal.

4. **Repeated Fields and Slice Ordering**:
   `proto.Equal` requires repeated field slices to have identical lengths and elements matching strictly by index. Different element ordering evaluates to `false`. An unpopulated repeated field and an allocated empty repeated slice evaluate as equal.

5. **Nested Messages**:
   `proto.Equal` recursively compares child message fields, returning `true` only when all nested submessages match semantically.

6. **Unknown Fields Comparison**:
   `proto.Equal` compares raw unknown field byte slices, returning `true` only when unknown field byte payloads match identically across messages.
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.Equal 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.Equal
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":{"believed":"reflect.DeepEqual safely compares protobuf messages while proto.Equal behaves identically to standard struct comparisons.","caseId":"case:sha256:76d2ff106b948b7d22e7ecac06d7f4173278dd4bd414235e492c835df3fd7f51","contract":["proto.Equal returns true when comparing two nil proto.Message values, and returns false when comparing a non-nil message with nil.","proto.Equal evaluates semantic equality of populated scalar and string fields across separate message instances.","proto.Equal distinguishes between unpopulated proto3 optional fields and explicitly set zero-value optional fields, while treating unpopulated implicit-presence scalars and default zero values as equal.","proto.Equal evaluates repeated slice fields as equal only when all elements match strictly in identical index order, and treats unpopulated repeated slices and empty slices as equal.","proto.Equal recursively evaluates nested message fields for equality.","proto.Equal compares raw unknown field bytes across messages, returning true only when unknown field byte payloads match."],"goal":"verify google.golang.org/protobuf/proto.Equal 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.Equal"]},"contractCommand":["go","test","./..."],"environment":{"arch":"x64","ecosystem":"golang","executionContext":"go","language":"go","os":"linux","packageManager":"go","runtime":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/google.golang.org/protobuf@v1.35.1"],"schemaVersion":1,"symbols":["google.golang.org/protobuf/proto.Equal"],"verifierAdapter":"golang@1"}
go.mod
module example.com/protoequal

go 1.26.6

require google.golang.org/protobuf v1.35.1

go.sum
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=
proto_equal_test.go
package protoequal_test

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

func buildSchema(t *testing.T) (*descriptorpb.FileDescriptorProto, protoreflect.MessageDescriptor, protoreflect.MessageDescriptor) {
	t.Helper()

	fd := &descriptorpb.FileDescriptorProto{
		Name:    proto.String("service_registry.proto"),
		Package: proto.String("example.registry"),
		Syntax:  proto.String("proto3"),
		MessageType: []*descriptorpb.DescriptorProto{
			{
				Name: proto.String("Endpoint"),
				Field: []*descriptorpb.FieldDescriptorProto{
					{
						Name:     proto.String("host"),
						Number:   proto.Int32(1),
						Type:     descriptorpb.FieldDescriptorProto_TYPE_STRING.Enum(),
						JsonName: proto.String("host"),
					},
					{
						Name:     proto.String("port"),
						Number:   proto.Int32(2),
						Type:     descriptorpb.FieldDescriptorProto_TYPE_INT32.Enum(),
						JsonName: proto.String("port"),
					},
				},
			},
			{
				Name: proto.String("ServiceEntry"),
				Field: []*descriptorpb.FieldDescriptorProto{
					{
						Name:     proto.String("service_name"),
						Number:   proto.Int32(1),
						Type:     descriptorpb.FieldDescriptorProto_TYPE_STRING.Enum(),
						JsonName: proto.String("serviceName"),
					},
					{
						Name:     proto.String("instance_count"),
						Number:   proto.Int32(2),
						Type:     descriptorpb.FieldDescriptorProto_TYPE_INT32.Enum(),
						JsonName: proto.String("instanceCount"),
					},
					{
						Name:           proto.String("priority"),
						Number:         proto.Int32(3),
						Type:           descriptorpb.FieldDescriptorProto_TYPE_INT32.Enum(),
						JsonName:       proto.String("priority"),
						Proto3Optional: proto.Bool(true),
						OneofIndex:     proto.Int32(0),
					},
					{
						Name:     proto.String("tags"),
						Number:   proto.Int32(4),
						Type:     descriptorpb.FieldDescriptorProto_TYPE_STRING.Enum(),
						Label:    descriptorpb.FieldDescriptorProto_LABEL_REPEATED.Enum(),
						JsonName: proto.String("tags"),
					},
					{
						Name:     proto.String("endpoint"),
						Number:   proto.Int32(5),
						Type:     descriptorpb.FieldDescriptorProto_TYPE_MESSAGE.Enum(),
						TypeName: proto.String(".example.registry.Endpoint"),
						JsonName: proto.String("endpoint"),
					},
				},
				OneofDecl: []*descriptorpb.OneofDescriptorProto{
					{
						Name: proto.String("_priority"),
					},
				},
			},
		},
	}

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

	entryDesc := fileDesc.Messages().ByName("ServiceEntry")
	endpointDesc := fileDesc.Messages().ByName("Endpoint")
	if entryDesc == nil || endpointDesc == nil {
		t.Fatalf("failed to resolve message descriptors")
	}

	return fd, entryDesc, endpointDesc
}

func TestProtoEqualNilHandling(t *testing.T) {
	_, entryDesc, _ := buildSchema(t)

	msg := dynamicpb.NewMessage(entryDesc)
	msg.Set(entryDesc.Fields().ByName("service_name"), protoreflect.ValueOfString("auth-service"))

	// 1. Two untyped nil proto.Message values are equal
	if !proto.Equal(nil, nil) {
		t.Fatalf("expected proto.Equal(nil, nil) to be true")
	}

	// 2. Comparing non-nil message with nil returns false
	if proto.Equal(msg, nil) {
		t.Fatalf("expected proto.Equal(msg, nil) to be false")
	}
	if proto.Equal(nil, msg) {
		t.Fatalf("expected proto.Equal(nil, msg) to be false")
	}
}

func TestProtoEqualScalarsAndInstances(t *testing.T) {
	_, entryDesc, _ := buildSchema(t)

	nameField := entryDesc.Fields().ByName("service_name")
	countField := entryDesc.Fields().ByName("instance_count")

	msg1 := dynamicpb.NewMessage(entryDesc)
	msg1.Set(nameField, protoreflect.ValueOfString("payment-gateway"))
	msg1.Set(countField, protoreflect.ValueOfInt32(5))

	msg2 := dynamicpb.NewMessage(entryDesc)
	msg2.Set(nameField, protoreflect.ValueOfString("payment-gateway"))
	msg2.Set(countField, protoreflect.ValueOfInt32(5))

	msg3 := dynamicpb.NewMessage(entryDesc)
	msg3.Set(nameField, protoreflect.ValueOfString("payment-gateway"))
	msg3.Set(countField, protoreflect.ValueOfInt32(10))

	if !proto.Equal(msg1, msg2) {
		t.Fatalf("expected proto.Equal(msg1, msg2) to be true for separately allocated identical messages")
	}
	if proto.Equal(msg1, msg3) {
		t.Fatalf("expected proto.Equal(msg1, msg3) to be false when field values differ")
	}
}

func TestProtoEqualPresenceSemantics(t *testing.T) {
	_, entryDesc, _ := buildSchema(t)

	priorityField := entryDesc.Fields().ByName("priority")
	countField := entryDesc.Fields().ByName("instance_count")

	// msg1 has unpopulated priority (optional) and unpopulated instance_count (implicit presence)
	msg1 := dynamicpb.NewMessage(entryDesc)

	// msg2 has priority explicitly set to 0 (proto3_optional presence)
	msg2 := dynamicpb.NewMessage(entryDesc)
	msg2.Set(priorityField, protoreflect.ValueOfInt32(0))

	// Unset optional vs explicitly populated 0 are NOT equal
	if proto.Equal(msg1, msg2) {
		t.Fatalf("expected proto.Equal to be false when comparing unset optional field with explicitly set zero value")
	}

	// msg3 has instance_count explicitly set to 0 (implicit presence in proto3)
	msg3 := dynamicpb.NewMessage(entryDesc)
	msg3.Set(countField, protoreflect.ValueOfInt32(0))

	// For implicit-presence scalars, unpopulated default 0 and explicitly set 0 are semantically equal
	if !proto.Equal(msg1, msg3) {
		t.Fatalf("expected proto.Equal to be true when comparing unpopulated implicit scalar with explicit 0")
	}
}

func TestProtoEqualRepeatedFieldsAndOrder(t *testing.T) {
	_, entryDesc, _ := buildSchema(t)

	tagsField := entryDesc.Fields().ByName("tags")

	msg1 := dynamicpb.NewMessage(entryDesc)
	msg1.Mutable(tagsField).List().Append(protoreflect.ValueOfString("prod"))
	msg1.Mutable(tagsField).List().Append(protoreflect.ValueOfString("us-west"))

	msg2 := dynamicpb.NewMessage(entryDesc)
	msg2.Mutable(tagsField).List().Append(protoreflect.ValueOfString("prod"))
	msg2.Mutable(tagsField).List().Append(protoreflect.ValueOfString("us-west"))

	msg3 := dynamicpb.NewMessage(entryDesc)
	msg3.Mutable(tagsField).List().Append(protoreflect.ValueOfString("us-west"))
	msg3.Mutable(tagsField).List().Append(protoreflect.ValueOfString("prod"))

	// msg4 has empty allocated list, msg5 has unpopulated repeated field
	msg4 := dynamicpb.NewMessage(entryDesc)
	msg4.Mutable(tagsField)
	msg5 := dynamicpb.NewMessage(entryDesc)

	if !proto.Equal(msg1, msg2) {
		t.Fatalf("expected proto.Equal to be true for identical repeated slice elements")
	}
	if proto.Equal(msg1, msg3) {
		t.Fatalf("expected proto.Equal to be false when repeated slice elements have different order")
	}
	if !proto.Equal(msg4, msg5) {
		t.Fatalf("expected proto.Equal to be true for empty repeated slice vs unpopulated repeated field")
	}
}

func TestProtoEqualNestedMessages(t *testing.T) {
	_, entryDesc, endpointDesc := buildSchema(t)

	endpointField := entryDesc.Fields().ByName("endpoint")
	hostField := endpointDesc.Fields().ByName("host")
	portField := endpointDesc.Fields().ByName("port")

	createEntry := func(host string, port int32) *dynamicpb.Message {
		m := dynamicpb.NewMessage(entryDesc)
		ep := dynamicpb.NewMessage(endpointDesc)
		ep.Set(hostField, protoreflect.ValueOfString(host))
		ep.Set(portField, protoreflect.ValueOfInt32(port))
		m.Set(endpointField, protoreflect.ValueOfMessage(ep))
		return m
	}

	m1 := createEntry("node1.internal.net", 8080)
	m2 := createEntry("node1.internal.net", 8080)
	m3 := createEntry("node2.internal.net", 8080)
	m4 := dynamicpb.NewMessage(entryDesc) // unset endpoint

	if !proto.Equal(m1, m2) {
		t.Fatalf("expected proto.Equal to be true for identical nested messages")
	}
	if proto.Equal(m1, m3) {
		t.Fatalf("expected proto.Equal to be false when nested message fields differ")
	}
	if proto.Equal(m1, m4) {
		t.Fatalf("expected proto.Equal to be false when one message has unset nested message")
	}
}

func TestProtoEqualUnknownFields(t *testing.T) {
	_, entryDesc, _ := buildSchema(t)

	m1 := dynamicpb.NewMessage(entryDesc)
	m2 := dynamicpb.NewMessage(entryDesc)
	m3 := dynamicpb.NewMessage(entryDesc)
	m4 := dynamicpb.NewMessage(entryDesc)

	// Unknown field payload: tag 99 (wire type 0 varint) with value 42
	unknownPayload1 := []byte{0x98, 0x06, 0x2a}
	unknownPayload2 := []byte{0x98, 0x06, 0x2b}

	m1.ProtoReflect().SetUnknown(unknownPayload1)
	m2.ProtoReflect().SetUnknown(unknownPayload1)
	m3.ProtoReflect().SetUnknown(unknownPayload2)

	if !proto.Equal(m1, m2) {
		t.Fatalf("expected proto.Equal to be true when messages have identical unknown field bytes")
	}
	if proto.Equal(m1, m3) {
		t.Fatalf("expected proto.Equal to be false when messages have differing unknown field bytes")
	}
	if proto.Equal(m1, m4) {
		t.Fatalf("expected proto.Equal to be false when one message has unknown fields and the other is empty")
	}
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify google.golang.org/protobuf/proto.Equal 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.Equal"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}

오리진 시더

익명