CodeSampleX

Beispiel

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

Verifiziertes Beispiel für pypi greenlet 3.5.4: Observe greenlet switch and throw event dispatching via settrace and trace listener inspection with gettrace.…

sha256:795a164df50449bb69f2824379f55d7e9854b07000a3fb2e948d2f9a301db772

Dieses Netzwerk bietet eine Sache: ein Sample, das baut. Es hat es in einer Sandbox ausgeführt und die signierte Quittung behalten. Es bewertet nichts und garantiert nichts — ob derselbe Code bei Ihnen baut, hat es nicht gemessen. Wie viele verschiedene Signaturschlüssel eine bestandene Vertragsquittung eingereicht haben. Einer ist der Autor allein; mehr als einer heißt, jemand anderes hat es auch gebaut. Ein Schlüssel wird selbst erzeugt und hat keine registrierte Identität dahinter — gezählt werden Schlüssel, nicht Personen. MIT-0

Ausführungsbelege

Die deklarierte Umgebung und die signierten Läufe stehen getrennt, damit Sie genau sehen, was dieses Sample ausgeführt hat und wo.

Beleggrundlage
Signierter Vertrag bestanden
Verifizierungsbelege
1
Signaturschlüssel, die es gebaut haben
1
Deklarierte Umgebung linux 24 · ubuntu · glibc 2.39 x64 pip

Umgebungen der Verifizierungsläufe

Umgebung Contract Stufen Lauf
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

Fall

HOW
Ziel
Observe greenlet switch and throw event dispatching via settrace and trace listener inspection with gettrace
Pakete
Symbole
  • greenlet.getcurrent
  • greenlet.gettrace
  • greenlet.greenlet
  • greenlet.settrace
Erstellt
2026-08-28T03:43:14Z

Contract

  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.

Dateien

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

Quellartefakt herunterladen (tar.gz)

Quelltext

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()

Ursprungs-Seeder

anonym