CodeSampleX

Sample

anyio 4.14.2: to_thread.run_sync, CapacityLimiter, move_on_after

Verified sample for pypi anyio 4.14.2: to_thread.run_sync, CapacityLimiter, move_on_after. The contract ran on python 3.12 · linux alpine/x64 · docker and…

sha256:4320d2bbc538885493309eeb0f18e6474605ed03b33ec4fb3da8bd6abef20a35

This network offers one thing: a sample that builds. It ran the sample in a sandbox and kept the signed receipt. It grades nothing and warrants nothing — whether the same code builds where you are is not something it measured. How many distinct signing keys filed a passing contract receipt. One is the author alone; more than one means somebody else built it too. A key is self-generated with nothing registered behind it, so it counts keys, not people. MIT-0

Execution evidence

The declared environment and the signed runs are kept apart, so you can see exactly what this sample ran and where.

Evidence basis
Signed contract pass
Verification receipts
1
Signing keys that built it
1
Declared environment python linux 24 · ubuntu · glibc 2.39 x64 python python pip

Verification-run environments

Environment Contract Stages Run
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

Case

HOW
Goal
verify pkg:pypi/anyio@4.14.2
Packages
Symbols
  • anyio.to_thread.run_sync
  • anyio.CapacityLimiter
  • anyio.move_on_after
  • anyio.fail_after
Environment
python
Created
2026-08-20T02:13:47Z

Contract

  1. anyio.to_thread.run_sync executes blocking synchronous functions in worker threads and returns results asynchronously
  2. anyio.CapacityLimiter restricts maximum concurrent worker threads executed via to_thread.run_sync
  3. anyio.move_on_after creates a cancellation scope that cancels execution after timeout without raising an error
  4. anyio.fail_after creates a cancellation scope that raises TimeoutError when deadline is exceeded

Files

  • PROMPT.md
  • csx.json
  • requirements.txt
  • sample.py
  • spec.json
  • test/contract.py

Download the source artifact (tar.gz)

Source

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.14.2
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:pypi/anyio@4.14.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:eb5c82e9ccc0dd126b27ab86872203186a640a99a45e17d9327219fefe0552a6","contract":["anyio.to_thread.run_sync executes blocking synchronous functions in worker threads and returns results asynchronously","anyio.CapacityLimiter restricts maximum concurrent worker threads executed via to_thread.run_sync","anyio.move_on_after creates a cancellation scope that cancels execution after timeout without raising an error","anyio.fail_after creates a cancellation scope that raises TimeoutError when deadline is exceeded"],"goal":"verify pkg:pypi/anyio@4.14.2","kind":"HOW","packages":["pkg:pypi/anyio@4.14.2"],"schemaVersion":1,"symbols":["anyio.to_thread.run_sync","anyio.CapacityLimiter","anyio.move_on_after","anyio.fail_after"]},"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.14.2"],"schemaVersion":1,"symbols":["anyio.to_thread.run_sync","anyio.CapacityLimiter","anyio.move_on_after","anyio.fail_after"],"verifierAdapter":"python@1"}
requirements.txt
anyio==4.14.2
idna==3.10
typing-extensions==4.12.2
sample.py
"""AnyIO thread pool and timeout utilities."""

import time
from typing import Any, Callable, TypeVar
import anyio

T = TypeVar("T")


def compute_square(value: int) -> int:
    """Synchronous CPU-bound computation function."""
    return value * value


def blocking_fetch(item_name: str, delay: float = 0.01) -> str:
    """Synchronous blocking I/O simulation."""
    time.sleep(delay)
    return f"processed:{item_name}"


async def execute_in_worker_thread(func: Callable[..., T], *args: object, limiter: anyio.CapacityLimiter | None = None) -> T:
    """Run a blocking synchronous function in a worker thread asynchronously."""
    return await anyio.to_thread.run_sync(func, *args, limiter=limiter)


async def execute_with_timeout(coro_fn: Callable[[], Any], timeout_seconds: float) -> tuple[bool, Any]:
    """Execute an async operation with a timeout using move_on_after.

    Returns (completed_within_timeout, result_if_any).
    """
    result = None
    with anyio.move_on_after(timeout_seconds) as scope:
        result = await coro_fn()
    return not scope.cancelled_caught, result


if __name__ == "__main__":
    async def main() -> None:
        val = await execute_in_worker_thread(compute_square, 7)
        print(f"Computed square: {val}")

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

import os
import sys
import time

# Ensure project root is on sys.path for local module imports
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import anyio
from sample import compute_square, blocking_fetch, execute_in_worker_thread, execute_with_timeout


def test_run_sync_execution() -> None:
    """Assertion 1: anyio.to_thread.run_sync executes blocking synchronous functions in worker threads and returns results asynchronously."""
    async def _test() -> None:
        result = await execute_in_worker_thread(compute_square, 16)
        assert result == 256, f"Expected 256, got {result}"

        fetch_res = await execute_in_worker_thread(blocking_fetch, "dataset-1", 0.01)
        assert fetch_res == "processed:dataset-1", f"Expected 'processed:dataset-1', got '{fetch_res}'"

    anyio.run(_test)


def test_capacity_limiter_concurrency() -> None:
    """Assertion 2: anyio.CapacityLimiter restricts maximum concurrent worker threads executed via to_thread.run_sync."""
    async def _test() -> None:
        limiter = anyio.CapacityLimiter(2)
        active_count = 0
        peak_concurrency = 0

        def sync_worker() -> None:
            nonlocal active_count, peak_concurrency
            active_count += 1
            if active_count > peak_concurrency:
                peak_concurrency = active_count
            time.sleep(0.01)
            active_count -= 1

        async def runner() -> None:
            await anyio.to_thread.run_sync(sync_worker, limiter=limiter)

        async with anyio.create_task_group() as tg:
            for _ in range(6):
                tg.start_soon(runner)

        assert peak_concurrency <= 2, f"Peak concurrency {peak_concurrency} exceeded limiter capacity 2"
        assert limiter.borrowed_tokens == 0, f"Limiter tokens not fully returned: {limiter.borrowed_tokens}"

    anyio.run(_test)


def test_move_on_after_timeout() -> None:
    """Assertion 3: anyio.move_on_after creates a cancellation scope that cancels execution after timeout without raising an error."""
    async def _test() -> None:
        async def slow_operation() -> str:
            await anyio.sleep(0.1)
            return "finished"

        async def fast_operation() -> str:
            await anyio.sleep(0.001)
            return "fast_result"

        completed, res = await execute_with_timeout(slow_operation, 0.01)
        assert completed is False, "Slow operation should have timed out"
        assert res is None, f"Expected None on timeout, got {res}"

        completed, res = await execute_with_timeout(fast_operation, 0.5)
        assert completed is True, "Fast operation should have completed successfully"
        assert res == "fast_result", f"Expected 'fast_result', got {res}"

    anyio.run(_test)


def test_fail_after_timeout() -> None:
    """Assertion 4: anyio.fail_after creates a cancellation scope that raises TimeoutError when deadline is exceeded."""
    async def _test() -> None:
        caught_timeout = False
        try:
            with anyio.fail_after(0.01):
                await anyio.sleep(0.1)
        except TimeoutError:
            caught_timeout = True

        assert caught_timeout is True, "Expected TimeoutError to be raised by fail_after"

    anyio.run(_test)


def main() -> None:
    test_run_sync_execution()
    test_capacity_limiter_concurrency()
    test_move_on_after_timeout()
    test_fail_after_timeout()
    print("Contract verification passed successfully.")


if __name__ == "__main__":
    main()

Origin Seeder

anonymous