CodeSampleX

Ejemplo

anyio 4.13.0: verify CancelScope

Muestra verificada para pypi anyio 4.13.0: verify CancelScope. El contrato se ejecutó en python 3.12 · linux alpine/x64 · docker y pasó.

sha256:8a3f292b274208fa458a26d54851fb1e7ee10f7a616bf666ec21e3a24287d997

Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido. Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas. MIT-0

Evidencia de ejecución

El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.

Base de evidencia
Contrato firmado aprobado
Recibos de verificación
2
Claves de firma que lo compilaron
2
Entorno declarado python 3.12 linux 24 · ubuntu · glibc 2.39 x64 python 3.12 python pip 24

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
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

Caso

HOW
Objetivo
verify pkg:pypi/anyio@4.13.0 CancelScope
Paquetes
Símbolos
  • anyio.CancelScope
Entorno
python 3.12
Creado
2026-08-20T10:34:05Z

Contrato

  1. CancelScope context manager allows scoping cancellation for async execution
  2. cancel method triggers cancellation causing subsequent async operations to abort
  3. cancelled_caught property indicates whether a cancellation exception was caught
  4. deadline property triggers automatic cancellation when current time reaches deadline
  5. shield property protects code block from cancellation triggered by outer scopes

Archivos

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

Descargar el artefacto de código fuente (tar.gz)

Código fuente

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 CancelScope
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:pypi/anyio@4.13.0
Demonstrate these symbols/APIs:
  - anyio.CancelScope
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:232759a879555e3b96ac3187fbbc9659b8fabac17f3716214828af357be4a94f","contract":["CancelScope context manager allows scoping cancellation for async execution","cancel method triggers cancellation causing subsequent async operations to abort","cancelled_caught property indicates whether a cancellation exception was caught","deadline property triggers automatic cancellation when current time reaches deadline","shield property protects code block from cancellation triggered by outer scopes"],"goal":"verify pkg:pypi/anyio@4.13.0 CancelScope","kind":"HOW","packages":["pkg:pypi/anyio@4.13.0"],"schemaVersion":1,"symbols":["anyio.CancelScope"]},"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.CancelScope"],"verifierAdapter":"python@1"}
pyproject.toml
[project]
name = "anyio-cancelscope-sample"
version = "0.1.0"
description = "Clean-room verification sample for anyio CancelScope"
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 CancelScope",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/anyio@4.13.0"
  ],
  "symbols": [
    "anyio.CancelScope"
  ],
  "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 (
    check_cancel_state,
    run_cancel_execution,
    check_cancelled_caught,
    run_deadline_cancellation,
    run_shielded_scope,
)

__all__ = [
    "check_cancel_state",
    "run_cancel_execution",
    "check_cancelled_caught",
    "run_deadline_cancellation",
    "run_shielded_scope",
]
src/sample.py
"""Clean-room demonstration of anyio 4.13.0 CancelScope."""

from typing import Tuple
import anyio


async def _cancel_state_worker() -> Tuple[bool, bool]:
    with anyio.CancelScope() as scope:
        initial = scope.cancel_called
        scope.cancel()
        after_cancel = scope.cancel_called
    return initial, after_cancel


def check_cancel_state() -> Tuple[bool, bool]:
    """Demonstrates CancelScope context manager and cancel_called state."""
    return anyio.run(_cancel_state_worker)


async def _cancel_execution_worker() -> bool:
    executed_after_cancel = False
    with anyio.CancelScope() as scope:
        scope.cancel()
        await anyio.sleep(0.05)
        executed_after_cancel = True
    return executed_after_cancel


def run_cancel_execution() -> bool:
    """Demonstrates cancel method triggering cancellation of pending async operations."""
    return anyio.run(_cancel_execution_worker)


async def _cancelled_caught_worker() -> Tuple[bool, bool]:
    with anyio.CancelScope() as scope_normal:
        await anyio.sleep(0.001)
    with anyio.CancelScope() as scope_cancelled:
        scope_cancelled.cancel()
        await anyio.sleep(0.05)
    return scope_normal.cancelled_caught, scope_cancelled.cancelled_caught


def check_cancelled_caught() -> Tuple[bool, bool]:
    """Demonstrates cancelled_caught property indicating caught cancellation exception."""
    return anyio.run(_cancelled_caught_worker)


async def _deadline_worker() -> Tuple[bool, bool]:
    with anyio.CancelScope(deadline=anyio.current_time() + 0.02) as scope:
        await anyio.sleep(0.1)
    return scope.cancel_called, scope.cancelled_caught


def run_deadline_cancellation() -> Tuple[bool, bool]:
    """Demonstrates deadline property triggering automatic cancellation upon expiration."""
    return anyio.run(_deadline_worker)


async def _shield_worker() -> Tuple[bool, bool, bool]:
    inner_completed = False
    after_shield_completed = False
    with anyio.CancelScope() as outer:
        outer.cancel()
        with anyio.CancelScope(shield=True):
            await anyio.sleep(0.01)
            inner_completed = True
        await anyio.sleep(0.05)
        after_shield_completed = True
    return outer.cancelled_caught, inner_completed, after_shield_completed


def run_shielded_scope() -> Tuple[bool, bool, bool]:
    """Demonstrates shield property protecting code block from outer cancellation."""
    return anyio.run(_shield_worker)
test/contract.py
"""Contract verification test for pkg:pypi/anyio@4.13.0 CancelScope."""

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 (
    check_cancel_state,
    run_cancel_execution,
    check_cancelled_caught,
    run_deadline_cancellation,
    run_shielded_scope,
)


def test_contract_1_cancel_state():
    # Assertion: CancelScope context manager allows scoping cancellation for async execution
    initial, after_cancel = check_cancel_state()
    assert initial is False, f"Expected initial cancel_called to be False, got {initial}"
    assert after_cancel is True, f"Expected after_cancel cancel_called to be True, got {after_cancel}"


def test_contract_2_cancel_execution():
    # Assertion: cancel method triggers cancellation causing subsequent async operations to abort
    executed = run_cancel_execution()
    assert executed is False, f"Expected executed_after_cancel to be False, got {executed}"


def test_contract_3_cancelled_caught():
    # Assertion: cancelled_caught property indicates whether a cancellation exception was caught
    normal_caught, cancelled_caught = check_cancelled_caught()
    assert normal_caught is False, f"Expected normal scope cancelled_caught to be False, got {normal_caught}"
    assert cancelled_caught is True, f"Expected cancelled scope cancelled_caught to be True, got {cancelled_caught}"


def test_contract_4_deadline():
    # Assertion: deadline property triggers automatic cancellation when current time reaches deadline
    cancel_called, cancelled_caught = run_deadline_cancellation()
    assert cancel_called is True, f"Expected deadline scope cancel_called to be True, got {cancel_called}"
    assert cancelled_caught is True, f"Expected deadline scope cancelled_caught to be True, got {cancelled_caught}"


def test_contract_5_shield():
    # Assertion: shield property protects code block from cancellation triggered by outer scopes
    outer_caught, inner_done, after_done = run_shielded_scope()
    assert outer_caught is True, f"Expected outer scope cancelled_caught to be True, got {outer_caught}"
    assert inner_done is True, f"Expected shielded inner scope to complete (True), got {inner_done}"
    assert after_done is False, f"Expected unshielded outer code to abort (False), got {after_done}"


def main():
    print("Running contracts for pkg:pypi/anyio@4.13.0 CancelScope...")
    test_contract_1_cancel_state()
    test_contract_2_cancel_execution()
    test_contract_3_cancelled_caught()
    test_contract_4_deadline()
    test_contract_5_shield()
    print("All contracts passed successfully.")


if __name__ == "__main__":
    main()

Seeder de origen

anónimo