CodeSampleX

샘플

greenlet 3.5.4: Observe greenlet switch and throw event dispatching via settrace and trace listener inspection with gettrace

검증된 샘플 — pypi greenlet 3.5.4: Observe greenlet switch and throw event dispatching via settrace and trace listener inspection with gettrace. python 3.12 …

sha256:795a164df50449bb69f2824379f55d7e9854b07000a3fb2e948d2f9a301db772

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. MIT-0

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
1
빌드한 서명 키
1
선언된 환경 linux 24 · ubuntu · glibc 2.39 x64 pip

검증 실행 환경

환경 컨트랙트 단계 실행일
python 3.12 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1python:3.12-alpine@sha256:d09d15e60962…
2026-08-28

케이스

HOW
목표
Observe greenlet switch and throw event dispatching via settrace and trace listener inspection with gettrace
패키지
심벌
  • greenlet.getcurrent
  • greenlet.gettrace
  • greenlet.greenlet
  • greenlet.settrace
생성일
2026-08-28T03:43:14Z

컨트랙트

  1. greenlet.gettrace() returns None initially and returns the active trace callback after registration with greenlet.settrace().
  2. greenlet.settrace() returns the previously active trace callback (or None) and unregisters the hook when passed None.
  3. A coroutine switch via greenlet.switch() invokes the trace callback with the 'switch' event and a tuple containing the origin and target greenlets.
  4. Dispatching an exception into a suspended greenlet via greenlet.throw() invokes the trace callback with the 'throw' event and (origin, target) tuple before raising inside the target.
  5. greenlet.getcurrent() evaluated inside the trace callback returns the target greenlet rather than the origin greenlet.
  6. An exception raised inside the trace callback aborts the switch and propagates out to the caller.

파일

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

소스 아티팩트 내려받기 (tar.gz)

소스

NOTES.md
## Search Result
`search_known_solution` for `greenlet` returned published samples covering ContextVar isolation (`sha256:af168144eb3bca9eaa371f9373196e05be0d42e528c604c1744c2e10f6b75ea7`), implicit parent control return (`sha256:bdf2e2f5b210f6ce304b4c4a450f53972eceeab15ddf990f5cea4c215abe7355`), and `GreenletExit` exception hierarchy (`sha256:5a2492fa10b597f4d88cc44649627009c744ed58c50bcd5861f1b00181db7dbf`). Searches for `greenlet.settrace` and `greenlet.gettrace` resulted in `NO_SAFE_MATCH`.

This sample investigates and proves greenlet execution tracing mechanics via `greenlet.settrace` and `greenlet.gettrace`, monitoring coroutine transition lifecycle events and exception dispatches.

## Exact Release Pinned
`greenlet==3.5.4`

## Observed Behaviour
1. **Trace Function Registration and Inspection**: `greenlet.gettrace()` returns `None` when no tracer is active. Calling `greenlet.settrace(callback)` registers `callback` globally and returns the previously active trace function (or `None`). Calling `greenlet.settrace(None)` unregisters the tracer.
2. **Switch Event Dispatching**: Whenever execution switches between greenlets via `.switch()`, the trace function is invoked with arguments `(event, (origin, target))` where `event == 'switch'`. For a sequence where `main` switches to child `g`, `g` yields back to `main`, and `g` is resumed until completion, four transitions are dispatched: `(main, g)`, `(g, main)`, `(main, g)`, and `(g, main)`.
3. **Throw Event Dispatching**: When `g.throw(exc)` is invoked on a suspended greenlet, the trace callback is dispatched with `event == 'throw'` and tuple `(origin, target)` where `origin` is the caller greenlet and `target` is the greenlet receiving the exception. If the target handles the exception and returns, the subsequent return switch is recorded as a `'switch'` event.
4. **Execution Context During Trace Callback**: When the trace callback executes, the underlying context switch has already occurred: `greenlet.getcurrent()` inside the trace callback returns the `target` greenlet rather than the `origin` greenlet.
5. **Trace Callback Error Propagation**: Any unhandled exception raised inside the trace callback immediately aborts the transition and propagates out through the caller's `.switch()` or `.throw()` call.

## Trap and Failure Mode
- **Misconception About Current Greenlet in Trace**: Callers frequently assume `greenlet.getcurrent()` during the trace hook is the originating greenlet preparing to yield. In reality, greenlet switches the execution stack before invoking the trace callback, so `greenlet.getcurrent()` is already the target greenlet.
- **Trace Callback Argument Signature**: The trace hook signature is `trace(event, (origin, target))`, where the second argument is a 2-tuple. Unpacking directly as `trace(event, origin, target)` results in a `TypeError: trace() takes 3 positional arguments but 2 were given`.
- **Unhandled Exceptions in Trace Hooks**: Exceptions thrown in the trace callback are not swallowed by greenlet runtime; they immediately break coroutine flow and propagate to the caller.
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: Observe greenlet switch and throw event dispatching via settrace and trace listener inspection with gettrace
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:pypi/greenlet@3.5.4
Demonstrate these symbols/APIs:
  - greenlet.getcurrent
  - greenlet.gettrace
  - greenlet.greenlet
  - greenlet.settrace

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:7f6e2d51f1eafd0cc2ba1e5c9b7c25debdcc75a13c110310c687dc0bc3217da9","contract":["greenlet.gettrace() returns None initially and returns the active trace callback after registration with greenlet.settrace().","greenlet.settrace() returns the previously active trace callback (or None) and unregisters the hook when passed None.","A coroutine switch via greenlet.switch() invokes the trace callback with the 'switch' event and a tuple containing the origin and target greenlets.","Dispatching an exception into a suspended greenlet via greenlet.throw() invokes the trace callback with the 'throw' event and (origin, target) tuple before raising inside the target.","greenlet.getcurrent() evaluated inside the trace callback returns the target greenlet rather than the origin greenlet.","An exception raised inside the trace callback aborts the switch and propagates out to the caller."],"goal":"Observe greenlet switch and throw event dispatching via settrace and trace listener inspection with gettrace","kind":"HOW","packages":["pkg:pypi/greenlet@3.5.4"],"schemaVersion":1,"symbols":["greenlet.getcurrent","greenlet.gettrace","greenlet.greenlet","greenlet.settrace"]},"contractCommand":["python","test/contract.py"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"pypi","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"pip","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/greenlet@3.5.4"],"schemaVersion":1,"subject":"pkg:pypi/greenlet@3.5.4","symbols":["greenlet.getcurrent","greenlet.gettrace","greenlet.greenlet","greenlet.settrace"],"verifierAdapter":"python@1"}
requirements.txt
greenlet==3.5.4
spec.json
{
  "schemaVersion": 1,
  "goal": "Observe greenlet switch and throw event dispatching via settrace and trace listener inspection with gettrace",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/greenlet@3.5.4"
  ],
  "symbols": [
    "greenlet.getcurrent",
    "greenlet.gettrace",
    "greenlet.greenlet",
    "greenlet.settrace"
  ]
}
test/contract.py
import greenlet


def test_gettrace_settrace_registration():
    # 1. greenlet.gettrace() returns None initially and returns active trace callback after registration
    # 2. greenlet.settrace() returns the previously active trace callback and unregisters when passed None
    assert greenlet.gettrace() is None

    calls = []

    def dummy_trace(event, args):
        calls.append((event, args))

    prev = greenlet.settrace(dummy_trace)
    assert prev is None
    assert greenlet.gettrace() is dummy_trace

    def second_trace(event, args):
        pass

    prev2 = greenlet.settrace(second_trace)
    assert prev2 is dummy_trace
    assert greenlet.gettrace() is second_trace

    prev3 = greenlet.settrace(None)
    assert prev3 is second_trace
    assert greenlet.gettrace() is None


def test_switch_trace_dispatch():
    # 3. Coroutine switch invokes trace callback with 'switch' event and (origin, target)
    events = []

    def trace(event, args):
        origin, target = args
        events.append((event, origin, target))

    main_g = greenlet.getcurrent()

    def worker():
        main_g.switch("worker_yielded")
        return "worker_finished"

    g = greenlet.greenlet(worker)

    greenlet.settrace(trace)
    try:
        val1 = g.switch()
        assert val1 == "worker_yielded"

        val2 = g.switch()
        assert val2 == "worker_finished"
        assert g.dead
    finally:
        greenlet.settrace(None)

    assert len(events) == 4
    assert events[0] == ("switch", main_g, g)
    assert events[1] == ("switch", g, main_g)
    assert events[2] == ("switch", main_g, g)
    assert events[3] == ("switch", g, main_g)


def test_throw_trace_dispatch():
    # 4. Dispatching an exception into suspended greenlet invokes trace callback with 'throw' event
    events = []

    def trace(event, args):
        origin, target = args
        events.append((event, origin, target))

    main_g = greenlet.getcurrent()

    def worker():
        try:
            main_g.switch("ready_for_throw")
        except KeyError as exc:
            return f"handled_{exc.args[0]}"

    g = greenlet.greenlet(worker)
    init_res = g.switch()
    assert init_res == "ready_for_throw"
    assert not g.dead

    greenlet.settrace(trace)
    try:
        throw_res = g.throw(KeyError("test_key_error"))
        assert throw_res == "handled_test_key_error"
        assert g.dead
    finally:
        greenlet.settrace(None)

    assert len(events) == 2
    assert events[0] == ("throw", main_g, g)
    assert events[1] == ("switch", g, main_g)


def test_getcurrent_inside_trace_callback():
    # 5. greenlet.getcurrent() evaluated inside trace callback returns the target greenlet
    observations = []

    def trace(event, args):
        origin, target = args
        cur = greenlet.getcurrent()
        observations.append({
            "event": event,
            "origin": origin,
            "target": target,
            "current": cur,
            "current_is_target": cur is target,
            "current_is_origin": cur is origin,
        })

    main_g = greenlet.getcurrent()

    def worker():
        try:
            main_g.switch()
        except ValueError:
            return "recovered"

    g = greenlet.greenlet(worker)
    g.switch()

    greenlet.settrace(trace)
    try:
        res = g.throw(ValueError("boom"))
        assert res == "recovered"
    finally:
        greenlet.settrace(None)

    assert len(observations) == 2
    assert observations[0]["event"] == "throw"
    assert observations[0]["current_is_target"] is True
    assert observations[0]["current"] is g

    assert observations[1]["event"] == "switch"
    assert observations[1]["current_is_target"] is True
    assert observations[1]["current"] is main_g


def test_trace_callback_exception_propagation():
    # 6. Exception raised inside trace callback aborts switch and propagates out
    def failing_trace(event, args):
        raise RuntimeError("trace_hook_error")

    g = greenlet.greenlet(lambda: "should_not_run")

    greenlet.settrace(failing_trace)
    caught = False
    try:
        g.switch()
    except RuntimeError as exc:
        caught = True
        assert str(exc) == "trace_hook_error"
    finally:
        greenlet.settrace(None)

    assert caught


def main():
    test_gettrace_settrace_registration()
    test_switch_trace_dispatch()
    test_throw_trace_dispatch()
    test_getcurrent_inside_trace_callback()
    test_trace_callback_exception_propagation()
    print("PASS")


if __name__ == "__main__":
    main()

오리진 시더

익명