CodeSampleX

サンプル

anyio 4.11.0: create_task_group, create_memory_object_stream, Event

検証済みサンプル — pypi anyio 4.11.0: create_task_group, create_memory_object_stream, Event. python 3.12 · linux alpine/x64 · docker で contract を実行し、成功しました.

sha256:172efb4c749b212a130681b0e5004a6ca7c6c6ff2dda733acbbbd664c123af4b

このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。 合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。 MIT-0

実行証拠

宣言された環境と署名済みの実行を分けてあります。このサンプルが何をどこで実行したかをそのまま確認できます。

証拠の基準
署名済みコントラクト合格
検証レシート
1
ビルドした署名鍵
1
宣言された環境 python linux 24 · ubuntu · glibc 2.39 x64 python python pip

検証実行環境

環境 コントラクト ステージ 実行日
python 3.12 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1
2026-08-20

ケース

HOW
ゴール
verify pkg:pypi/anyio@4.11.0
パッケージ
シンボル
  • anyio.create_task_group
  • anyio.create_memory_object_stream
  • anyio.Event
環境
python
作成日
2026-08-20T02:35:46Z

コントラクト

  1. anyio.create_task_group spawns concurrent asynchronous tasks and waits for their completion
  2. anyio.create_memory_object_stream creates bounded memory streams that deliver items between tasks
  3. anyio.Event synchronizes task execution across concurrent asynchronous tasks

ファイル

  • PROMPT.md
  • csx.json
  • requirements.txt
  • sample.py
  • spec.json
  • 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.11.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:pypi/anyio@4.11.0

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:ad56a33317f01282b54079611be34486ed137130654e66ac0cf4a5e25a973aac","contract":["anyio.create_task_group spawns concurrent asynchronous tasks and waits for their completion","anyio.create_memory_object_stream creates bounded memory streams that deliver items between tasks","anyio.Event synchronizes task execution across concurrent asynchronous tasks"],"goal":"verify pkg:pypi/anyio@4.11.0","kind":"HOW","packages":["pkg:pypi/anyio@4.11.0"],"schemaVersion":1,"symbols":["anyio.create_task_group","anyio.create_memory_object_stream","anyio.Event"]},"contractCommand":["python","test/contract.py"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"pypi","language":"python","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"pip","runtime":"python","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/anyio@4.11.0"],"schemaVersion":1,"symbols":["anyio.create_task_group","anyio.create_memory_object_stream","anyio.Event"],"verifierAdapter":"python@1"}
requirements.txt
anyio==4.11.0
idna==3.10
sniffio==1.3.1
typing-extensions==4.12.2
sample.py
"""AnyIO task coordination, object streams, and synchronization primitives."""

import anyio
from anyio.streams.memory import MemoryObjectReceiveStream, MemoryObjectSendStream


async def produce_items(
    send_stream: MemoryObjectSendStream[str],
    start_signal: anyio.Event,
    item_count: int = 5,
) -> None:
    """Wait for start signal and send sequential items into the stream."""
    await start_signal.wait()
    async with send_stream:
        for idx in range(item_count):
            await send_stream.send(f"item-{idx}")


async def consume_items(
    receive_stream: MemoryObjectReceiveStream[str],
    collected: list[str],
) -> None:
    """Consume all items from the stream until closed."""
    async with receive_stream:
        async for item in receive_stream:
            collected.append(item)


async def run_pipeline(item_count: int = 5, buffer_size: int = 10) -> list[str]:
    """Coordinate producer and consumer tasks using TaskGroup and Event."""
    send_stream, receive_stream = anyio.create_memory_object_stream[str](max_buffer_size=buffer_size)
    start_signal = anyio.Event()
    results: list[str] = []

    async with anyio.create_task_group() as tg:
        tg.start_soon(consume_items, receive_stream, results)
        tg.start_soon(produce_items, send_stream, start_signal, item_count)
        start_signal.set()

    return results


if __name__ == "__main__":
    async def main() -> None:
        out = await run_pipeline(3)
        print(f"Pipeline finished: {out}")

    anyio.run(main)
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:pypi/anyio@4.11.0",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/anyio@4.11.0"
  ]
}
test/contract.py
"""Contract verification test for anyio."""

import os
import sys

# Ensure sample root directory is on sys.path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import anyio
from sample import produce_items, consume_items, run_pipeline


def test_task_group_concurrency() -> None:
    """Assertion 1: anyio.create_task_group spawns concurrent asynchronous tasks and waits for their completion."""
    async def _test() -> None:
        completed_order: list[int] = []

        async def worker(task_id: int) -> None:
            await anyio.sleep(0.001)
            completed_order.append(task_id)

        async with anyio.create_task_group() as tg:
            for i in range(5):
                tg.start_soon(worker, i)

        assert len(completed_order) == 5, f"Expected 5 tasks to finish, got {len(completed_order)}"
        assert sorted(completed_order) == [0, 1, 2, 3, 4], f"Unexpected completed task IDs: {completed_order}"

    anyio.run(_test)


def test_memory_stream_transfer() -> None:
    """Assertion 2: anyio.create_memory_object_stream creates bounded memory streams that deliver items between tasks."""
    async def _test() -> None:
        send_stream, receive_stream = anyio.create_memory_object_stream[int](max_buffer_size=3)
        received_items: list[int] = []

        async def producer() -> None:
            async with send_stream:
                for val in [10, 20, 30, 40]:
                    await send_stream.send(val)

        async def consumer() -> None:
            async with receive_stream:
                async for item in receive_stream:
                    received_items.append(item)

        async with anyio.create_task_group() as tg:
            tg.start_soon(consumer)
            tg.start_soon(producer)

        assert received_items == [10, 20, 30, 40], f"Expected [10, 20, 30, 40], got {received_items}"

    anyio.run(_test)


def test_event_synchronization() -> None:
    """Assertion 3: anyio.Event synchronizes task execution across concurrent asynchronous tasks."""
    async def _test() -> None:
        event = anyio.Event()
        assert not event.is_set(), "Event should initially be unset"

        flag_checked = False

        async def waiter() -> None:
            nonlocal flag_checked
            await event.wait()
            flag_checked = True

        async with anyio.create_task_group() as tg:
            tg.start_soon(waiter)
            assert not flag_checked, "Waiter should be waiting"
            event.set()

        assert flag_checked is True, "Waiter did not resume after event.set()"
        assert event.is_set(), "Event should remain set"

    anyio.run(_test)


def test_integrated_pipeline() -> None:
    """Integration test verifying end-to-end pipeline."""
    async def _test() -> None:
        output = await run_pipeline(item_count=4, buffer_size=10)
        assert output == ["item-0", "item-1", "item-2", "item-3"], f"Unexpected output: {output}"

    anyio.run(_test)


def main() -> None:
    test_task_group_concurrency()
    test_memory_stream_transfer()
    test_event_synchronization()
    test_integrated_pipeline()
    print("Contract verification passed successfully.")


if __name__ == "__main__":
    main()

オリジンシーダー

匿名