CodeSampleX

示例

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

已验证示例 — golang google.golang.org/protobuf v1.35.1: proto.Equal. contract 在 go 1.26 · linux alpine/x64 · docker 上运行并通过: proto.Equal returns true when…

sha256:5abbd12c05db97460964dc331edca15b92f1cec567e902f8354d097d4d07d4fe

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 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"
  }
}

原始种子者

匿名