CodeSampleX

Exemplo

golang.org/x/time v0.11.0: rate.Limiter

Amostra verificada para golang golang.org/x/time v0.11.0: rate.Limiter. O contrato rodou em go 1.26 · linux alpine/x64 · docker e passou.

sha256:764537fbc86db72ad329aaccb9c4f8039458cb662d20c734a5c25a40dca669fc

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
2
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 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-26
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-07

Caso

HOW
Objetivo
verify golang.org/x/time/rate.Limiter in pkg:golang/golang.org/x/time@v0.11.0
Pacotes
Símbolos
  • golang.org/x/time/rate.Limiter
Ambiente
go
Criado
2026-08-26T12:19:45Z

Contrato

  1. rate.NewLimiter initializes a token bucket limiter with the specified Limit and burst size, accessible via Limit() and Burst().
  2. rate.Limiter.Allow and AllowN consume available burst tokens immediately, returning true when tokens are available and false when burst capacity is exceeded or exhausted.
  3. rate.Limiter.ReserveN returns a Reservation with OK() true and a positive wait delay when tokens are temporarily unavailable within burst limits, or OK() false with InfDuration delay when requested tokens exceed burst.
  4. rate.Limiter.Wait and WaitN block until tokens are available, returning nil on success, an immediate error if requested tokens exceed burst capacity, or a context cancellation error when the context is cancelled.
  5. Dynamic updates to rate limit and burst size via SetLimit and SetBurst take effect immediately on subsequent token availability queries and acquisitions.

Arquivos

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • limiter_test.go
  • spec.json

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

Código-fonte

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 golang.org/x/time/rate.Limiter in pkg:golang/golang.org/x/time@v0.11.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/golang.org/x/time@v0.11.0
Demonstrate these symbols/APIs:
  - golang.org/x/time/rate.Limiter

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:0679903d15004a495d054f9163a762e54a9edafe63123239e3f33af86135abd5","contract":["rate.NewLimiter initializes a token bucket limiter with the specified Limit and burst size, accessible via Limit() and Burst().","rate.Limiter.Allow and AllowN consume available burst tokens immediately, returning true when tokens are available and false when burst capacity is exceeded or exhausted.","rate.Limiter.ReserveN returns a Reservation with OK() true and a positive wait delay when tokens are temporarily unavailable within burst limits, or OK() false with InfDuration delay when requested tokens exceed burst.","rate.Limiter.Wait and WaitN block until tokens are available, returning nil on success, an immediate error if requested tokens exceed burst capacity, or a context cancellation error when the context is cancelled.","Dynamic updates to rate limit and burst size via SetLimit and SetBurst take effect immediately on subsequent token availability queries and acquisitions."],"goal":"verify golang.org/x/time/rate.Limiter in pkg:golang/golang.org/x/time@v0.11.0","kind":"HOW","packages":["pkg:golang/golang.org/x/time@v0.11.0"],"schemaVersion":1,"symbols":["golang.org/x/time/rate.Limiter"]},"contractCommand":["go","test","./..."],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","executionContext":"go","language":"go","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"go","runtime":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/golang.org/x/time@v0.11.0"],"schemaVersion":1,"subject":"pkg:golang/golang.org/x/time@v0.11.0","symbols":["golang.org/x/time/rate.Limiter"],"verifierAdapter":"golang@1"}
go.mod
module example.com/ratelimiter

go 1.25.0

require golang.org/x/time v0.11.0
go.sum
golang.org/x/time v0.11.0 h1:/bpjEDfN9tkoN/ryeYHnv5hcMlc8ncjMcM4XBk5NWV0=
golang.org/x/time v0.11.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg=
limiter_test.go
package ratelimiter

import (
	"context"
	"testing"
	"time"

	"golang.org/x/time/rate"
)

func TestLimiterInitializationAndProperties(t *testing.T) {
	// 1. Limiter initialization with rate.Limit and burst size
	limit := rate.Limit(10)
	burst := 5
	lim := rate.NewLimiter(limit, burst)

	if got := lim.Limit(); got != limit {
		t.Fatalf("expected Limit() to be %v, got %v", limit, got)
	}
	if got := lim.Burst(); got != burst {
		t.Fatalf("expected Burst() to be %d, got %d", burst, got)
	}

	// rate.Every converts duration interval to rate.Limit (e.g. 100ms interval -> 10 ops/sec)
	intervalLimit := rate.Every(100 * time.Millisecond)
	if intervalLimit != rate.Limit(10) {
		t.Fatalf("expected rate.Every(100ms) to equal rate.Limit(10), got %v", intervalLimit)
	}

	// rate.Inf represents infinite rate limiting
	infLim := rate.NewLimiter(rate.Inf, 1)
	if infLim.Limit() != rate.Inf {
		t.Fatalf("expected Limit() to be rate.Inf, got %v", infLim.Limit())
	}
}

func TestLimiterAllowAndAllowN(t *testing.T) {
	// 2. Token consumption via Allow and AllowN
	burst := 3
	lim := rate.NewLimiter(rate.Limit(1), burst)

	// Newly created limiter starts with full burst capacity
	for i := 0; i < burst; i++ {
		if !lim.Allow() {
			t.Fatalf("expected Allow() #%d to succeed with initial burst tokens", i+1)
		}
	}

	// Immediate next Allow() must fail as burst is exhausted
	if lim.Allow() {
		t.Fatalf("expected Allow() to return false when bucket is empty")
	}

	// AllowN with n > burst must return false without affecting state
	if lim.AllowN(time.Now(), burst+1) {
		t.Fatalf("expected AllowN with n > burst to return false")
	}
}

func TestLimiterReserveAndCancel(t *testing.T) {
	// 3. Reservation behavior, delays, and cancellation
	now := time.Now()
	lim := rate.NewLimiter(rate.Limit(10), 2) // 10 tokens/sec -> 100ms per token

	// Exhaust burst
	if !lim.AllowN(now, 2) {
		t.Fatalf("expected AllowN(now, 2) to succeed")
	}

	// Reserve 1 token when bucket is empty
	res := lim.ReserveN(now, 1)
	if !res.OK() {
		t.Fatalf("expected ReserveN to be OK within burst capacity")
	}

	delay := res.DelayFrom(now)
	if delay <= 0 {
		t.Fatalf("expected positive delay for empty bucket, got %v", delay)
	}

	// Canceling the reservation restores the reserved token at the reservation time
	res.CancelAt(now)

	// Attempting to reserve more than burst size fails (OK() == false, Delay == InfDuration)
	oversized := lim.ReserveN(now, 5)
	if oversized.OK() {
		t.Fatalf("expected ReserveN with n > burst to return OK() == false")
	}
	if oversized.Delay() != rate.InfDuration {
		t.Fatalf("expected InfDuration delay for oversized reservation, got %v", oversized.Delay())
	}
}

func TestLimiterWaitAndContextCancellation(t *testing.T) {
	// 4. Context-aware blocking with Wait and WaitN
	lim := rate.NewLimiter(rate.Limit(10), 2)

	ctx := context.Background()
	// Consuming within available burst succeeds immediately
	if err := lim.Wait(ctx); err != nil {
		t.Fatalf("expected Wait() to succeed immediately, got %v", err)
	}

	// WaitN with n > burst returns an immediate error without waiting
	if err := lim.WaitN(ctx, 5); err == nil {
		t.Fatalf("expected WaitN with n > burst to fail immediately")
	}

	// Wait with an already-canceled context fails with context error
	cancelCtx, cancel := context.WithCancel(ctx)
	cancel()
	if err := lim.Wait(cancelCtx); err == nil {
		t.Fatalf("expected Wait with canceled context to return error")
	}
}

func TestLimiterDynamicReconfiguration(t *testing.T) {
	// 5. Dynamic mutations of Limit and Burst
	lim := rate.NewLimiter(rate.Limit(5), 2)

	lim.SetLimit(rate.Limit(20))
	if got := lim.Limit(); got != rate.Limit(20) {
		t.Fatalf("expected updated Limit() to be 20, got %v", got)
	}

	lim.SetBurst(10)
	if got := lim.Burst(); got != 10 {
		t.Fatalf("expected updated Burst() to be 10, got %d", got)
	}

	// Available tokens can be inspected via Tokens()
	tokens := lim.Tokens()
	if tokens < 0 || tokens > 10 {
		t.Fatalf("expected tokens between 0 and 10, got %v", tokens)
	}
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify golang.org/x/time/rate.Limiter in pkg:golang/golang.org/x/time@v0.11.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/golang.org/x/time@v0.11.0"
  ],
  "symbols": [
    "golang.org/x/time/rate.Limiter"
  ]
}

Seeder de origem

anônimo