Пример
google.golang.org/protobuf v1.35.1: durationpb.New
Проверенный пример — golang google.golang.org/protobuf v1.35.1: durationpb.New. Контракт выполнен на go 1.26 · linux alpine/x64 · docker и пройден.
sha256:7f79ef0e71f5811e50d337dc6e0f605ef3b855b43f73481ad07c06938931c8b0
Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла.
Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди.
MIT-0
Свидетельства выполнения
Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.
- Основа свидетельства
- Подписанный контракт пройден
- Квитанции проверки
- 1
- Ключи подписи, собравшие его
- 1
Заявленная среда
linux 24 · ubuntu · glibc 2.39 x64 go
Среды запусков проверки
| Окружение | Контракт | Этапы | Запуск |
|---|---|---|---|
| go 1.26 · linux alpine/x64 · docker ed25519:c1973797be207ac4 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · golang@1golang:1.26-alpine@sha256:28d89ee9cc0f… |
2026-08-27 |
Кейс
HOW- Цель
- verify google.golang.org/protobuf/types/known/durationpb.New in pkg:golang/google.golang.org/protobuf@v1.35.1
- Символы
-
- google.golang.org/protobuf/types/known/durationpb.New
- Создан
- 2026-08-27T10:39:50Z
Контракт
- durationpb.New converts time.Duration into *durationpb.Duration with corresponding Seconds and Nanos fields, where negative durations have both negative Seconds and negative Nanos.
- durationpb.Duration.AsDuration converts the protobuf message back to time.Duration, and calling AsDuration on a nil receiver safely returns 0.
- durationpb.Duration.CheckValid and IsValid validate duration bounds within +/-10,000 years and reject sign discrepancies between Seconds and Nanos or out-of-range nanoseconds.
- durationpb.Duration supports protobuf wire serialization and protojson serialization formatting as a string with a trailing 's' suffix.
Файлы
- NOTES.md
- PROMPT.md
- csx.json
- duration_test.go
- go.mod
- go.sum
- spec.json
Исходный код
# Protocol Buffers Duration Well-Known Type Behavior
A known-solution search for `google.golang.org/protobuf/types/known/durationpb.New` in package `pkg:golang/google.golang.org/protobuf@v1.35.1` returned no safe match. This sample verifies the construction, conversion, validation, and serialization semantics of `google.protobuf.Duration` using `durationpb.New`.
## Observed Behavior
1. **Conversion with `durationpb.New`**:
- `durationpb.New(d)` converts a standard Go `time.Duration` into a protobuf `*durationpb.Duration` message consisting of `Seconds` (`int64`) and `Nanos` (`int32`).
- For positive durations, both `Seconds` and `Nanos` are non-negative.
- For negative durations, protobuf specification dictates that both `Seconds` and `Nanos` carry negative signs (e.g., `-1.75s` maps to `Seconds: -1, Nanos: -750000000`).
- Sub-second negative durations (e.g., `-250ms`) map to `Seconds: 0, Nanos: -250000000`.
2. **Reconstitution and Nil Safety (`AsDuration`)**:
- `pb.AsDuration()` accurately converts the protobuf `*durationpb.Duration` back into a Go `time.Duration`.
- Calling `(*durationpb.Duration)(nil).AsDuration()` is safe and returns `time.Duration(0)` without panicking.
3. **Validation Semantics (`CheckValid` and `IsValid`)**:
- Durations are valid only if `Seconds` is within `[-315576000000, +315576000000]` (representing approx. ±10,000 years), `Nanos` is within `[-999999999, +999999999]`, and `Seconds` and `Nanos` have consistent signs (or zero).
- Sign mismatch (such as `Seconds: 1, Nanos: -1` or `Seconds: -1, Nanos: 1`) is invalid and causes `CheckValid()` to return an error.
- Nil receiver reports `IsValid() == false` and `CheckValid()` returns a non-nil error.
4. **Wire and JSON Serialization**:
- `proto.Marshal` and `proto.Unmarshal` preserve binary representations.
- `protojson.Marshal` serializes the well-known duration type to canonical JSON string format with a trailing `"s"` (e.g., `"1.500s"`, `"-0.25s"`).
- `protojson.Unmarshal` parses canonical duration strings into `*durationpb.Duration`.
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/types/known/durationpb.New 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/types/known/durationpb.New
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.
{"case":{"caseId":"case:sha256:cd81f6ebf160e6440a0b14eb3c02a92678b5a24478d2c40368c11c50aaa246f1","contract":["durationpb.New converts time.Duration into *durationpb.Duration with corresponding Seconds and Nanos fields, where negative durations have both negative Seconds and negative Nanos.","durationpb.Duration.AsDuration converts the protobuf message back to time.Duration, and calling AsDuration on a nil receiver safely returns 0.","durationpb.Duration.CheckValid and IsValid validate duration bounds within +/-10,000 years and reject sign discrepancies between Seconds and Nanos or out-of-range nanoseconds.","durationpb.Duration supports protobuf wire serialization and protojson serialization formatting as a string with a trailing 's' suffix."],"goal":"verify google.golang.org/protobuf/types/known/durationpb.New 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/types/known/durationpb.New"]},"contractCommand":["go","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.35.1"],"schemaVersion":1,"subject":"pkg:golang/google.golang.org/protobuf@v1.35.1","symbols":["google.golang.org/protobuf/types/known/durationpb.New"],"verifierAdapter":"golang@1"}
package durationpbtest
import (
"testing"
"time"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/durationpb"
)
func TestDurationpbNewAndAsDuration(t *testing.T) {
tests := []struct {
name string
input time.Duration
wantSec int64
wantNanos int32
}{
{
name: "zero duration",
input: 0,
wantSec: 0,
wantNanos: 0,
},
{
name: "positive whole seconds",
input: 5 * time.Second,
wantSec: 5,
wantNanos: 0,
},
{
name: "positive compound duration",
input: 2*time.Second + 500*time.Millisecond + 123*time.Nanosecond,
wantSec: 2,
wantNanos: 500000123,
},
{
name: "negative whole seconds",
input: -3 * time.Second,
wantSec: -3,
wantNanos: 0,
},
{
name: "negative sub-second duration",
input: -250 * time.Millisecond,
wantSec: 0,
wantNanos: -250000000,
},
{
name: "negative compound duration",
input: -1*time.Second - 750*time.Millisecond,
wantSec: -1,
wantNanos: -750000000,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
pb := durationpb.New(tc.input)
if pb == nil {
t.Fatalf("durationpb.New(%v) returned nil", tc.input)
}
if got := pb.GetSeconds(); got != tc.wantSec {
t.Errorf("GetSeconds() = %d, want %d", got, tc.wantSec)
}
if got := pb.GetNanos(); got != tc.wantNanos {
t.Errorf("GetNanos() = %d, want %d", got, tc.wantNanos)
}
// AsDuration should round-trip back to original time.Duration
gotDur := pb.AsDuration()
if gotDur != tc.input {
t.Errorf("AsDuration() = %v, want %v", gotDur, tc.input)
}
})
}
// Verify nil receiver returns 0 duration safely
var nilPb *durationpb.Duration
if got := nilPb.AsDuration(); got != 0 {
t.Errorf("(*durationpb.Duration)(nil).AsDuration() = %v, want 0", got)
}
}
func TestDurationpbValidation(t *testing.T) {
// Valid cases
validCases := []*durationpb.Duration{
durationpb.New(0),
durationpb.New(10 * time.Minute),
durationpb.New(-10 * time.Minute),
{Seconds: 315576000000, Nanos: 999999999},
{Seconds: -315576000000, Nanos: -999999999},
}
for _, d := range validCases {
if !d.IsValid() {
t.Errorf("expected %v to be valid", d)
}
if err := d.CheckValid(); err != nil {
t.Errorf("CheckValid() for %v returned unexpected error: %v", d, err)
}
}
// Nil receiver validation
var nilPb *durationpb.Duration
if nilPb.IsValid() {
t.Errorf("nil duration must report IsValid() == false")
}
if err := nilPb.CheckValid(); err == nil {
t.Errorf("nil duration must return non-nil error from CheckValid()")
}
// Invalid cases: sign mismatch, out-of-range nanos, out-of-range seconds
invalidCases := []struct {
name string
dur *durationpb.Duration
}{
{
name: "positive seconds with negative nanos",
dur: &durationpb.Duration{Seconds: 1, Nanos: -1},
},
{
name: "negative seconds with positive nanos",
dur: &durationpb.Duration{Seconds: -1, Nanos: 1},
},
{
name: "nanos overflow positive (>= 1e9)",
dur: &durationpb.Duration{Seconds: 0, Nanos: 1000000000},
},
{
name: "nanos underflow negative (<= -1e9)",
dur: &durationpb.Duration{Seconds: 0, Nanos: -1000000000},
},
{
name: "seconds exceed upper bound (+315576000000)",
dur: &durationpb.Duration{Seconds: 315576000001, Nanos: 0},
},
{
name: "seconds exceed lower bound (-315576000000)",
dur: &durationpb.Duration{Seconds: -315576000001, Nanos: 0},
},
}
for _, tc := range invalidCases {
t.Run(tc.name, func(t *testing.T) {
if tc.dur.IsValid() {
t.Errorf("expected IsValid() == false for %s (%v)", tc.name, tc.dur)
}
if err := tc.dur.CheckValid(); err == nil {
t.Errorf("expected CheckValid() to fail for %s (%v)", tc.name, tc.dur)
}
})
}
}
func TestDurationpbSerialization(t *testing.T) {
orig := durationpb.New(1500 * time.Millisecond)
// Binary proto serialization round-trip
data, err := proto.Marshal(orig)
if err != nil {
t.Fatalf("proto.Marshal failed: %v", err)
}
var unmarshaled durationpb.Duration
if err := proto.Unmarshal(data, &unmarshaled); err != nil {
t.Fatalf("proto.Unmarshal failed: %v", err)
}
if !proto.Equal(orig, &unmarshaled) {
t.Errorf("unmarshaled message %v != original %v", &unmarshaled, orig)
}
// JSON format serialization (well-known duration formats with "s" suffix)
jsonBytes, err := protojson.Marshal(orig)
if err != nil {
t.Fatalf("protojson.Marshal failed: %v", err)
}
wantJSON := `"1.500s"`
if string(jsonBytes) != wantJSON {
t.Errorf("protojson.Marshal() = %s, want %s", string(jsonBytes), wantJSON)
}
// JSON format parsing
var fromJSON durationpb.Duration
if err := protojson.Unmarshal([]byte(`"-2.5s"`), &fromJSON); err != nil {
t.Fatalf("protojson.Unmarshal failed: %v", err)
}
if gotSec, gotNanos := fromJSON.GetSeconds(), fromJSON.GetNanos(); gotSec != -2 || gotNanos != -500000000 {
t.Errorf("fromJSON = seconds:%d nanos:%d, want seconds:-2 nanos:-500000000", gotSec, gotNanos)
}
}
module example.com/durationpb-verify
go 1.22.0
require google.golang.org/protobuf v1.35.1
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.1 h1:m3LfL6/Ca+fqnjnlqQXNpFPABW1UD7mjh8KO2mKFytA=
google.golang.org/protobuf v1.35.1/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE=
{
"schemaVersion": 1,
"goal": "verify google.golang.org/protobuf/types/known/durationpb.New 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/types/known/durationpb.New"
]
}
Исходный сидер
аноним