CodeSampleX

示例

anyio 4.13.0: verify CapacityLimiter

已验证示例 — pypi anyio 4.13.0: verify CapacityLimiter. contract 在 python 3.12 · linux alpine/x64 · docker 上运行并通过: async context manager acquires and releases…

sha256:fd0d9fb4d59def2700c31c64aea7e94af6c77c39b0c72e05fbea4f353eeb3e1b

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

执行证据

声明的环境与签名的运行分开呈现,你可以看到这个样本究竟运行了什么、在哪里运行。

证据依据
签名契约通过
验证回执
2
构建过它的签名密钥
2
声明的环境 python 3.12 linux 24 · ubuntu · glibc 2.39 x64 python 3.12 python pip 24

验证运行环境

环境 契约 阶段 运行日期
python 3.12 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1
2026-08-20
python 3.12 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1python:3.12-slim@sha256:09f7da3bc104…
2026-09-07

案例

HOW
目标
verify pkg:pypi/anyio@4.13.0 CapacityLimiter
包
符号
  • anyio.CapacityLimiter
环境
python 3.12
创建时间
2026-08-20T10:15:23Z

契约

  1. async context manager acquires and releases limiter tokens automatically
  2. CapacityLimiter manages token allocation and bounds concurrent access
  3. total_tokens property allows dynamic adjustment of capacity limit
  4. acquire and release methods control manual token acquisition and release
  5. acquire_nowait provides non-blocking token acquisition

文件

  • PROMPT.md
  • csx.json
  • pyproject.toml
  • requirements.txt
  • spec.json
  • src/__init__.py
  • src/sample.py
  • test/contract.py

下载源代码构件 (tar.gz)

源代码

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:pypi/anyio@4.13.0 CapacityLimiter
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:pypi/anyio@4.13.0
Demonstrate these symbols/APIs:
  - anyio.CapacityLimiter
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":{"caseId":"case:sha256:6c2c4410988732ba336c00045cfbc31b8ba7d0e51af524695939f3e2b52d75cf","contract":["async context manager acquires and releases limiter tokens automatically","CapacityLimiter manages token allocation and bounds concurrent access","total_tokens property allows dynamic adjustment of capacity limit","acquire and release methods control manual token acquisition and release","acquire_nowait provides non-blocking token acquisition"],"goal":"verify pkg:pypi/anyio@4.13.0 CapacityLimiter","kind":"HOW","packages":["pkg:pypi/anyio@4.13.0"],"schemaVersion":1,"symbols":["anyio.CapacityLimiter"]},"contractCommand":["python3","test/contract.py"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"pypi","language":"python","libc":"glibc","libcVersion":"2.39","moduleSystem":"standard","os":"linux","osVersionBucket":"24","packageManager":"pip","packageManagerVersion":"24.0","runtime":"python","runtimeVersion":"3.12","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/anyio@4.13.0"],"schemaVersion":1,"symbols":["anyio.CapacityLimiter"],"verifierAdapter":"python@1"}
pyproject.toml
[project]
name = "anyio-capacity-limiter-sample"
version = "0.1.0"
description = "Clean-room verification sample for anyio CapacityLimiter"
requires-python = ">=3.9"
dependencies = [
    "anyio==4.13.0",
    "idna==3.19",
    "typing-extensions==4.16.0"
]
requirements.txt
anyio==4.13.0
idna==3.19
typing-extensions==4.16.0
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:pypi/anyio@4.13.0 CapacityLimiter",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/anyio@4.13.0"
  ],
  "symbols": [
    "anyio.CapacityLimiter"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
src/__init__.py
from .sample import (
    acquire_limiter_context,
    run_concurrency_bounded_tasks,
    adjust_limiter_capacity,
    manual_token_lifecycle,
    nonblocking_token_acquire,
)

__all__ = [
    "acquire_limiter_context",
    "run_concurrency_bounded_tasks",
    "adjust_limiter_capacity",
    "manual_token_lifecycle",
    "nonblocking_token_acquire",
]
src/sample.py
"""Clean-room demonstration of anyio 4.13.0 CapacityLimiter."""

from typing import List, Tuple
import anyio


async def _context_acquire_worker(total_tokens: int) -> Tuple[int, int, int]:
    limiter = anyio.CapacityLimiter(total_tokens)
    initial_available = limiter.available_tokens
    async with limiter:
        borrowed_inside = limiter.borrowed_tokens
    borrowed_after = limiter.borrowed_tokens
    return initial_available, borrowed_inside, borrowed_after


def acquire_limiter_context(total_tokens: int) -> Tuple[int, int, int]:
    """Demonstrates acquiring and releasing CapacityLimiter via async context manager."""
    return anyio.run(_context_acquire_worker, total_tokens)


async def _concurrency_bounded_collector(
    total_tokens: int, task_count: int
) -> Tuple[int, List[int]]:
    limiter = anyio.CapacityLimiter(total_tokens)
    active_counts: List[int] = []
    current_active = 0

    async def worker() -> None:
        nonlocal current_active
        async with limiter:
            current_active += 1
            active_counts.append(current_active)
            await anyio.sleep(0.005)
            current_active -= 1

    async with anyio.create_task_group() as tg:
        for _ in range(task_count):
            tg.start_soon(worker)

    max_concurrent = max(active_counts) if active_counts else 0
    return max_concurrent, active_counts


def run_concurrency_bounded_tasks(
    total_tokens: int, task_count: int
) -> Tuple[int, List[int]]:
    """Runs multiple concurrent tasks bounded by a CapacityLimiter."""
    return anyio.run(_concurrency_bounded_collector, total_tokens, task_count)


async def _capacity_adjustment_worker(
    initial_tokens: int, new_tokens: int
) -> Tuple[int, int]:
    limiter = anyio.CapacityLimiter(initial_tokens)
    initial_val = limiter.total_tokens
    limiter.total_tokens = new_tokens
    updated_val = limiter.total_tokens
    return initial_val, updated_val


def adjust_limiter_capacity(initial_tokens: int, new_tokens: int) -> Tuple[int, int]:
    """Demonstrates dynamic adjustment of CapacityLimiter total_tokens."""
    return anyio.run(_capacity_adjustment_worker, initial_tokens, new_tokens)


async def _manual_lifecycle_worker() -> Tuple[int, int, int]:
    limiter = anyio.CapacityLimiter(2)
    initial_borrowed = limiter.borrowed_tokens
    await limiter.acquire()
    acquired_borrowed = limiter.borrowed_tokens
    limiter.release()
    released_borrowed = limiter.borrowed_tokens
    return initial_borrowed, acquired_borrowed, released_borrowed


def manual_token_lifecycle() -> Tuple[int, int, int]:
    """Demonstrates manual acquire and release calls on CapacityLimiter."""
    return anyio.run(_manual_lifecycle_worker)


async def _nonblocking_acquire_worker() -> Tuple[int, int]:
    limiter = anyio.CapacityLimiter(1)
    limiter.acquire_nowait()
    borrowed_when_held = limiter.borrowed_tokens
    limiter.release()
    borrowed_when_released = limiter.borrowed_tokens
    return borrowed_when_held, borrowed_when_released


def nonblocking_token_acquire() -> Tuple[int, int]:
    """Demonstrates acquire_nowait for non-blocking token acquisition."""
    return anyio.run(_nonblocking_acquire_worker)
test/contract.py
"""Contract verification test for pkg:pypi/anyio@4.13.0 CapacityLimiter."""

import sys
from pathlib import Path

# Ensure src is in python path
src_dir = Path(__file__).resolve().parent.parent / "src"
if str(src_dir) not in sys.path:
    sys.path.insert(0, str(src_dir))

from sample import (
    acquire_limiter_context,
    run_concurrency_bounded_tasks,
    adjust_limiter_capacity,
    manual_token_lifecycle,
    nonblocking_token_acquire,
)


def test_contract_1_context_manager():
    # Assertion: async context manager acquires and releases limiter tokens automatically
    initial_available, borrowed_inside, borrowed_after = acquire_limiter_context(3)
    assert initial_available == 3, f"Expected initial available 3, got {initial_available}"
    assert borrowed_inside == 1, f"Expected borrowed inside context 1, got {borrowed_inside}"
    assert borrowed_after == 0, f"Expected borrowed after context 0, got {borrowed_after}"


def test_contract_2_bounded_concurrency():
    # Assertion: CapacityLimiter manages token allocation and bounds concurrent access
    max_concurrent, active_history = run_concurrency_bounded_tasks(total_tokens=2, task_count=6)
    assert max_concurrent <= 2, f"Expected max concurrent <= 2, got {max_concurrent}"
    assert len(active_history) == 6, f"Expected 6 tasks executed, got {len(active_history)}"


def test_contract_3_dynamic_capacity():
    # Assertion: total_tokens property allows dynamic adjustment of capacity limit
    initial_val, updated_val = adjust_limiter_capacity(2, 5)
    assert initial_val == 2, f"Expected initial tokens 2, got {initial_val}"
    assert updated_val == 5, f"Expected updated tokens 5, got {updated_val}"


def test_contract_4_manual_lifecycle():
    # Assertion: acquire and release methods control manual token acquisition and release
    initial, acquired, released = manual_token_lifecycle()
    assert initial == 0, f"Expected initial borrowed 0, got {initial}"
    assert acquired == 1, f"Expected acquired borrowed 1, got {acquired}"
    assert released == 0, f"Expected released borrowed 0, got {released}"


def test_contract_5_acquire_nowait():
    # Assertion: acquire_nowait provides non-blocking token acquisition
    held, released = nonblocking_token_acquire()
    assert held == 1, f"Expected held borrowed 1, got {held}"
    assert released == 0, f"Expected released borrowed 0, got {released}"


def main():
    print("Running contracts for pkg:pypi/anyio@4.13.0 CapacityLimiter...")
    test_contract_1_context_manager()
    test_contract_2_bounded_concurrency()
    test_contract_3_dynamic_capacity()
    test_contract_4_manual_lifecycle()
    test_contract_5_acquire_nowait()
    print("All contracts passed successfully.")


if __name__ == "__main__":
    main()

原始种子者

匿名