CodeSampleX

샘플

anyio 4.13.0: verify Semaphore

검증된 샘플 — pypi anyio 4.13.0: verify Semaphore. python 3.12 · linux alpine/x64 · docker에서 contract를 실행해 통과했습니다: async context manager acquires and releases…

sha256:1f9a9bce99b3d8496244b3178c01b1079e39788ca9f9581e77c73ad9822e5065

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. 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 Semaphore
패키지
심벌
  • anyio.Semaphore
환경
python 3.12
생성일
2026-08-20T10:22:49Z

컨트랙트

  1. async context manager acquires and releases semaphore permits automatically
  2. Semaphore bounds concurrent task execution to initial permit count
  3. value and max_value properties expose current permits and bound
  4. acquire and release methods manage semaphore permits manually
  5. acquire_nowait provides non-blocking permit 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 Semaphore
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:pypi/anyio@4.13.0
Demonstrate these symbols/APIs:
  - anyio.Semaphore
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:00300f849bf783af17dd56a07beae1d3f5a2031d699f1ac0de7d87010f625059","contract":["async context manager acquires and releases semaphore permits automatically","Semaphore bounds concurrent task execution to initial permit count","value and max_value properties expose current permits and bound","acquire and release methods manage semaphore permits manually","acquire_nowait provides non-blocking permit acquisition"],"goal":"verify pkg:pypi/anyio@4.13.0 Semaphore","kind":"HOW","packages":["pkg:pypi/anyio@4.13.0"],"schemaVersion":1,"symbols":["anyio.Semaphore"]},"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.Semaphore"],"verifierAdapter":"python@1"}
pyproject.toml
[project]
name = "anyio-semaphore-sample"
version = "0.1.0"
description = "Clean-room verification sample for anyio Semaphore"
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 Semaphore",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/anyio@4.13.0"
  ],
  "symbols": [
    "anyio.Semaphore"
  ],
  "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_semaphore_context,
    run_semaphore_bounded_tasks,
    check_semaphore_values,
    manual_semaphore_lifecycle,
    nonblocking_semaphore_acquire,
)

__all__ = [
    "acquire_semaphore_context",
    "run_semaphore_bounded_tasks",
    "check_semaphore_values",
    "manual_semaphore_lifecycle",
    "nonblocking_semaphore_acquire",
]
src/sample.py
"""Clean-room demonstration of anyio 4.13.0 Semaphore."""

from typing import List, Tuple
import anyio


async def _context_acquire_worker(initial_value: int) -> Tuple[int, int, int]:
    sem = anyio.Semaphore(initial_value)
    initial_val = sem.value
    async with sem:
        inside_val = sem.value
    after_val = sem.value
    return initial_val, inside_val, after_val


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


async def _concurrency_bounded_collector(
    permits: int, task_count: int
) -> Tuple[int, List[int]]:
    sem = anyio.Semaphore(permits)
    active_counts: List[int] = []
    current_active = 0

    async def worker() -> None:
        nonlocal current_active
        async with sem:
            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_semaphore_bounded_tasks(
    permits: int, task_count: int
) -> Tuple[int, List[int]]:
    """Runs multiple concurrent tasks bounded by a Semaphore."""
    return anyio.run(_concurrency_bounded_collector, permits, task_count)


async def _value_check_worker(initial_value: int, max_value: int) -> Tuple[int, int]:
    sem = anyio.Semaphore(initial_value, max_value=max_value)
    val = sem.value
    max_val = sem.max_value
    return val, max_val


def check_semaphore_values(initial_value: int, max_value: int) -> Tuple[int, int]:
    """Demonstrates value and max_value properties on Semaphore."""
    return anyio.run(_value_check_worker, initial_value, max_value)


async def _manual_lifecycle_worker() -> Tuple[int, int, int]:
    sem = anyio.Semaphore(2)
    initial_val = sem.value
    await sem.acquire()
    acquired_val = sem.value
    sem.release()
    released_val = sem.value
    return initial_val, acquired_val, released_val


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


async def _nonblocking_acquire_worker() -> Tuple[int, int]:
    sem = anyio.Semaphore(1)
    sem.acquire_nowait()
    held_val = sem.value
    sem.release()
    released_val = sem.value
    return held_val, released_val


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

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_semaphore_context,
    run_semaphore_bounded_tasks,
    check_semaphore_values,
    manual_semaphore_lifecycle,
    nonblocking_semaphore_acquire,
)


def test_contract_1_context_manager():
    # Assertion: async context manager acquires and releases semaphore permits automatically
    initial, inside, after = acquire_semaphore_context(3)
    assert initial == 3, f"Expected initial value 3, got {initial}"
    assert inside == 2, f"Expected inside context value 2, got {inside}"
    assert after == 3, f"Expected after context value 3, got {after}"


def test_contract_2_bounded_concurrency():
    # Assertion: Semaphore bounds concurrent task execution to initial permit count
    max_concurrent, active_history = run_semaphore_bounded_tasks(permits=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_value_properties():
    # Assertion: value and max_value properties expose current permits and bound
    val, max_val = check_semaphore_values(3, 5)
    assert val == 3, f"Expected value 3, got {val}"
    assert max_val == 5, f"Expected max_value 5, got {max_val}"


def test_contract_4_manual_lifecycle():
    # Assertion: acquire and release methods manage semaphore permits manually
    initial, acquired, released = manual_semaphore_lifecycle()
    assert initial == 2, f"Expected initial value 2, got {initial}"
    assert acquired == 1, f"Expected acquired value 1, got {acquired}"
    assert released == 2, f"Expected released value 2, got {released}"


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


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


if __name__ == "__main__":
    main()

오리진 시더

익명