diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7136710..a910600 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -210,3 +210,29 @@ jobs: run: python -m pip install maturin==1.14.1 - name: Build, install, smoke, and test wheel run: bash scripts/test-python-wheel.sh + + python-free-threaded: + # Plan 333: a separate job so a free-threaded failure is unambiguous and + # never masks (or is masked by) the GIL wheel lane. + name: python-free-threaded + runs-on: ubuntu-latest + timeout-minutes: 30 + env: + PYTHONNOUSERSITE: "1" + steps: + - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1 + - uses: dtolnay/rust-toolchain@fa04a1451ff1842e2626ccb99004d0195b455a88 # master + with: + toolchain: stable + - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 + with: + python-version: "3.14t" + - uses: Swatinem/rust-cache@23869a5bd66c73db3c0ac40331f3206eb23791dc # v2.9.1 + - name: Release metadata sync (fail cheaply before wheel build) + run: python3 scripts/check-python-release-metadata.py + - name: Install Maturin + run: python -m pip install maturin==1.14.1 + - name: Free-threaded compile check + run: PYTHON=python3.14t bash scripts/check-python-free-threaded-compile.sh + - name: Build, install, smoke, and test free-threaded wheel + run: PYTHON=python3.14t bash scripts/test-python-wheel.sh diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 23618a2..25b481f 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -103,7 +103,9 @@ jobs: platforms: ${{ matrix.qemu_platform }} - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 with: - python-version: "3.11" + # Plan 333: the matrix owns the interpreter for each ABI family + # (3.11 for cp311, 3.14t for the free-threaded targets). + python-version: ${{ matrix.setup_python }} - name: Build wheel uses: PyO3/maturin-action@e83996d129638aa358a18fbd1dfb82f0b0fb5d3b # v1 with: @@ -114,7 +116,10 @@ jobs: manylinux: ${{ matrix.manylinux }} # `compatibility` carries the maturin `--compatibility` PyPI policy # separately (pypi for all release targets). - args: "--profile dist --locked --interpreter python3.11 --compatibility ${{ matrix.compatibility }} --out dist" + # Plan 333: the interpreter comes from the matrix authority, never + # a hard-coded python3.11. Linux free-threaded targets use the pypa + # image path; native runners use python3.14t. + args: "--profile dist --locked --interpreter ${{ matrix.interpreter }} --compatibility ${{ matrix.compatibility }} --out dist" working-directory: crates/eggserve-python - name: Verify wheel composition shell: bash @@ -133,6 +138,15 @@ jobs: ${{ matrix.venv_python }} -m eggserve --help >/dev/null ${{ matrix.venv_python }} "$GITHUB_WORKSPACE/scripts/release_smoke.py" ${{ matrix.venv_python }} "$GITHUB_WORKSPACE/scripts/abi_smoke.py" + - name: Free-threaded import stays GIL-free + # Plan 333: the installed 3.14t wheel must leave the GIL disabled. + # -W error::RuntimeWarning turns PyO3's re-enable warning into a + # failure instead of a silent GIL fallback. + if: matrix.abi_family == 'cp314t' + shell: bash + run: | + ${{ matrix.venv_python }} -X gil=0 -W error::RuntimeWarning -c \ + "import sys, eggserve._native; assert sys._is_gil_enabled() is False" - name: Smoke test wheel (QEMU) # Plan 268 Track D: matching ARM userspace via QEMU. Alpine/musl # images are minimal and may not contain bash, so invoke `sh -c`. @@ -161,6 +175,8 @@ jobs: # Plan 264 Track B: build-once, test-many. The exact Linux x86_64 # cp311-abi3 artifact from the build matrix is installed with # binary-only resolution on every supported CPython minor. + # Plan 333: this lane stays GIL-only; the free-threaded family has its own + # install/import assertion in the build job and never enters this proof. # Plan 268 Track F: until final CPython 3.15 is available through the # pinned setup-python action, 3.15 lanes resolve 3.15 RC builds via # allow-prereleases. Remove once final 3.15 resolves without it, and @@ -473,8 +489,9 @@ jobs: os: ubuntu-latest mode: qemu-musl-armv7 python-version: "3.11" + # Plan 334: macos-14 no longer provisions; match the wheel matrix. - name: "macOS arm64" - os: macos-14 + os: macos-latest mode: native python-version: "3.11" - name: "Windows x86_64" diff --git a/.opencode/skills/eggserve-dev/SKILL.md b/.opencode/skills/eggserve-dev/SKILL.md index 083ed91..f6e1c36 100644 --- a/.opencode/skills/eggserve-dev/SKILL.md +++ b/.opencode/skills/eggserve-dev/SKILL.md @@ -436,7 +436,7 @@ requirements and bans - **Python server façade** — `eggserve.server` is the supported six-class API, including rustls-backed `HTTPSServer` and `ThreadingHTTPSServer` with HTTP/1.1 ALPN only. The exact fast-path eligibility and intentional incompatibility contract is maintained in `docs/python-http-server-compatibility.md`. Stock static handlers also support `default_content_type` and ordered safe `extra_response_headers`; those headers are limited to final 200 responses. Handler `protocol_version` must remain HTTP/1.1. Subprocess helpers are canonically owned by `eggserve.subprocess` (`eggserve.server` keeps compatibility re-exports without expanding `__all__`; top-level `serve_directory` re-exports the subprocess implementation). - **Python lowlevel substrate (Plan 166)** — `eggserve.lowlevel` exposes handler-only `Server(config, handler)` (no static root, same native runtime, no second accept loop), frozen `RuntimeConfig` (Plan 164 controls + safe privacy subset: `server_header`/`date_policy` system|suppress/`stripped_response_headers`/`error_policy` minimal|empty; Plan 202 trusted-proxy subset: `trusted_proxies`/`trust_unix_local`/`proxy_protocol`/`forwarded_standard`/`forwarded_legacy`, all default nothing trusted; `None` disables, `0` never unlimited; projected via the single `_native_kwargs()` helper, Plan 182), bounded `Response.stream(status, iterable, headers, content_length)` over a 16-chunk bridge (HEAD/body-forbidden never advance the iterator; sync iterables only — async via `AsyncResponse.stream`; non-bytes/iterator errors truncate with sanitized type-only logs; no `Transfer-Encoding` from services), and caller-owned `StaticResponder` composition (no routing in EggServe). `Request` exposes `remote_addr` unchanged plus `effective_addr`/`effective_scheme`/`effective_authority`/`proxy_provenance`/`forwarded_provenance` (absent without explicit trust). Plan 204 adds experimental `AsyncServer(config, async_handler, max_async_tasks)` (H1-only, same runtime, manual asyncio bridge, no new deps; `AsyncRequest` byte-fidelity + `read_chunk`/`trailers`/`send_interim`/`take_tunnel`, `AsyncResponse.stream` over async iterables via bounded 16-queue + `stream_with_trailers`, one-shot `Tunnel` duplex; ASGI fixture in `crates/eggserve-python/tests/asgi_fixture.py` only, not a product). - **CLI compatibility polish** — Manual parsing accepts hostname `--bind` values, repeatable `-H/--header` and `--content-type` static metadata, and a combined certificate/key PEM when `--tls-key` is omitted. Header metadata is validated against runtime-owned and hop-by-hop fields. Production admission/lifecycle CLI flags: `--max-in-flight-requests`, `--keep-alive-idle-timeout`, `--max-requests-per-connection` (`0` = unlimited), `--response-write-timeout`, `--max-buf-size`, `--max-headers`, `--max-header-bytes`, `--max-request-target-bytes`. -- **Python wheel support** — GIL-enabled CPython 3.11–3.15 via one `cp311-abi3` wheel per platform (build-once/test-many ABI proof on 3.11–3.15; no per-minor wheels; free-threaded owned by Plan 267). Routine CI builds and tests the Linux wheel; release targets 10 required platforms from `release/wheel-matrix.toml` (manylinux x86_64/aarch64/armv7, musllinux x86_64/aarch64/armv7, macOS x86_64/arm64, Windows x86_64/arm64) plus declared i686/win32 candidates. Plan 268: `manylinux` baseline vs `--compatibility pypi` are separate controls; cross-built AArch64 glibc/musl + Windows ARM64 are deferred to native qualifiers gating aggregation (AArch64 musl via Alpine container); ARMv7 via matching QEMU userspace with `sh`; 3.15 lanes use prerelease until final. `scripts/test-python-wheel.sh` has `MODE=full` (primary interpreter suite) and `MODE=abi-smoke` (cross-interpreter lane) with `WHEEL_PATH` reuse; `scripts/qualify-python-wheel-target.sh` is the rootless real-device path. +- **Python wheel support** — GIL-enabled CPython 3.11–3.15 via one `cp311-abi3` wheel per platform (build-once/test-many ABI proof on 3.11–3.15; no per-minor wheels) plus a **Beta** free-threaded CPython 3.14t family (Plans 333–334; promotion owned by Plan 332) (`cp314-cp314t`) on Linux x86_64 glibc, macOS arm64, and Windows x86_64 only (Plan 333; explicit `gil_used = false`; 3.13t/3.15t/`abi3t`/PyPy/ARMv7/Windows arm64/musl are not supported; `max_python_callbacks=1` is the serialized mode and handlers own their thread safety). Routine CI builds and tests the GIL Linux wheel plus a separate `python-free-threaded` lane; release targets 13 required entries on 10 platform tags from `release/wheel-matrix.toml` (manylinux x86_64/aarch64/armv7, musllinux x86_64/aarch64/armv7, macOS x86_64/arm64, Windows x86_64/arm64, plus the three cp314t entries) with matrix-owned interpreters, plus declared i686/win32 candidates. Plan 268: `manylinux` baseline vs `--compatibility pypi` are separate controls; cross-built AArch64 glibc/musl + Windows ARM64 are deferred to native qualifiers gating aggregation (AArch64 musl via Alpine container); ARMv7 via matching QEMU userspace with `sh`; 3.15 lanes use prerelease until final. `scripts/test-python-wheel.sh` has `MODE=full` (primary interpreter suite) and `MODE=abi-smoke` (cross-interpreter lane) with `WHEEL_PATH` reuse; `scripts/qualify-python-wheel-target.sh` is the rootless real-device path. - **Semaphore bounds** — `max_connections`, `max_file_streams`, and `max_in_flight_requests` are validated once in the Plan 179 kernel (`crate::runtime_limits`) against `tokio::sync::Semaphore::MAX_PERMITS`. Values above this bound are rejected with a controlled error. - **Plan 164 admission/lifecycle fields** — `RuntimeConfig`/`Limits` own `max_buf_size` (65536, Hyper min 8192), `max_headers` (100, pinned explicitly; Hyper answers excess with 431), `max_header_bytes` (32 KiB, 431 pre-service), `max_request_target_bytes` (8192, 414 pre-service), `max_in_flight_requests` (64, 503 on exhaustion, held across `Service::call`), `keep_alive_idle_timeout` (60s, resets on activity), `max_requests_per_connection` (`Option`, `None` = unlimited; CLI `0` = unlimited), `response_write_timeout` (30s, no-progress via `ProgressIo` + `TrackedBody`). Idle/write timeouts are NOT cross-checked against `connection_total_timeout`. `ConnectionOutcome` adds `IdleTimeout` (clean) and `WriteTimeout`. Hyper is 1.11.1: lone TE+CL normalizes to TE-wins (200), only duplicate/conflicting CLs still fail; Hyper also applies `header_read_timeout` while keep-alive idle, so set idle shorter for distinct accounting or raise both for long-lived keep-alive. Per-profile defaults live in `docs/deployment.md`; full semantics in `docs/timeout-reference.md`. - **Plan 179 canonical runtime authority** — shared runtime defaults/validation live once in `eggserve-server::runtime_limits` (`SharedRuntimeValues` + `Violation`, public; `eggserve_core::runtime_limits` re-exports with `From` adapters next to `Limits`/`RuntimeConfig`). `Limits::validate()` delegates shared checks + static listing budgets; `RuntimeConfigBuilder::build()` validates the shared group + `ResponsePolicy`; `try_from_serve_config()` projects via `RuntimeConfig::from_shared_runtime`. Static listing/extra-header budgets stay service-owned; frontend-only controls stay in their surfaces. Services may lower `max_request_body_bytes` but never raise the hard ceiling. diff --git a/CHANGELOG.md b/CHANGELOG.md index 9f2f74c..a73e678 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,10 +1,28 @@ # Changelog -## Unreleased — post-audit maintenance (Plans 320–329) +## Unreleased — post-audit maintenance (Plans 320–334) No version has been published from this work; the Rust line stays on `0.5.x` and the wheel on `0.2.5` until a maintainer chooses a release. +- **Free-threaded CPython 3.14t (Plans 333–334, Beta).** The extension now states + `#[pymodule(gil_used = false)]` explicitly and ships an additive + `cp314-cp314t` wheel family on Linux x86_64 (glibc), macOS arm64, and + Windows x86_64 only. The wheel matrix, release-set validator, release + metadata gate, and release workflow understand the ABI-family dimension + (13 required entries on 10 platform tags) and take interpreters from the + matrix. A separate `python-free-threaded` CI lane builds and tests the + wheel with `python3.14t`, and `test_free_threaded.py` covers parallel + callbacks, serialized mode, concurrent stream producers, one-shot body and + iterator contention, tunnel-receive contention, and restart. The tunnel + receive path now reports `concurrent Tunnel.recv is not supported` instead + of a misleading closed state. The GIL `cp311-abi3` contract is unchanged; + there is no Rust crate API, HTTP, TLS, or security behavior change, and no + release is cut. The family lands as **Beta**: the originating branch + promoted it to Stable, but its soak records name no commit, wheel + filename, or host and cover one platform, so Milestone 330 reverses the + promotion and Milestone 332 owns the evidence and the decision. + - **Compatible dependency refresh (Plan 325).** The root, Python-wheel, and fuzz lockfiles now resolve the newest semver-compatible dependency set available at implementation time, with shared packages aligned. The pinned diff --git a/SECURITY.md b/SECURITY.md index 3c3e5d0..d68a3b8 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -55,7 +55,10 @@ minimal reproduction when safe to share. The release wheel targets the CPython 3.11 stable ABI (abi3) and supports GIL-enabled CPython 3.11–3.15 through one `cp311-abi3` wheel per platform -(build-once/test-many ABI proof; PyPy and free-threaded CPython unsupported). +(build-once/test-many ABI proof). An additive **Beta** family supports +free-threaded CPython 3.14t (`cp314-cp314t`) on Linux x86_64 (glibc), macOS +arm64, and Windows x86_64 only; PyPy, free-threaded CPython 3.13t/3.15t, +`abi3t`, ARMv7, Windows arm64, and musl free-threaded builds are unsupported. Routine CI verifies the Linux wheel on the primary interpreter plus the matrix authority gates; macOS and Windows wheels are built and tested in the release/platform workflows, with the Windows ARM64 artifact executed natively diff --git a/crates/eggserve-python/pyproject.toml b/crates/eggserve-python/pyproject.toml index 0c63895..cbc3bd4 100644 --- a/crates/eggserve-python/pyproject.toml +++ b/crates/eggserve-python/pyproject.toml @@ -1,5 +1,5 @@ [build-system] -requires = ["maturin>=1.0,<2.0"] +requires = ["maturin>=1.14.1,<2.0"] build-backend = "maturin" [project] @@ -22,6 +22,7 @@ classifiers = [ "Programming Language :: Python :: 3.13", "Programming Language :: Python :: 3.14", "Programming Language :: Python :: 3.15", + "Programming Language :: Python :: Free Threading :: 2 - Beta", "Programming Language :: Rust", "Topic :: Internet :: WWW/HTTP :: HTTP Servers", "Topic :: System :: Filesystems", diff --git a/crates/eggserve-python/src/lib.rs b/crates/eggserve-python/src/lib.rs index 08a2125..7eba511 100644 --- a/crates/eggserve-python/src/lib.rs +++ b/crates/eggserve-python/src/lib.rs @@ -1667,7 +1667,14 @@ fn run_cli_fn(py: Python<'_>, argv: Vec) -> i32 { py.detach(|| eggserve_bin::run_cli(argv)) } -#[pymodule] +/// Native extension module (`eggserve._native`). +/// +/// The free-threading declaration is explicit. PyO3 >= 0.28 emits +/// `Py_MOD_GIL_NOT_USED` for a `#[pymodule]` without `gil_used`, and Plan 333 +/// qualifies that promise for CPython 3.14t on Linux x86_64 (glibc), macOS +/// arm64, and Windows x86_64 only. On a GIL-enabled interpreter the attribute +/// is a no-op; it never re-enables a disabled GIL. +#[pymodule(gil_used = false)] fn _native(m: &Bound<'_, PyModule>) -> PyResult<()> { registration::register(m) } diff --git a/crates/eggserve-python/src/server/body_bridge.rs b/crates/eggserve-python/src/server/body_bridge.rs index fe1e707..23433c0 100644 --- a/crates/eggserve-python/src/server/body_bridge.rs +++ b/crates/eggserve-python/src/server/body_bridge.rs @@ -264,6 +264,13 @@ pub(super) fn spawn_python_stream_producer( // Python RequestBody — wraps Rust RequestBody // --------------------------------------------------------------------------- +/// Python-facing one-shot request body. +/// +/// `read()`, `read_chunk()`, and `iter_chunks()` are mutually exclusive +/// consumption modes; concurrent callers race the same one-shot state and the +/// losers receive the existing typed consumption errors. This holds on +/// free-threaded builds too: the mutex is structural, not a sharing API, and +/// thread safety is never inferred from the GIL. #[pyclass(frozen, from_py_object, name = "RequestBody")] #[derive(Debug, Clone)] #[allow(dead_code)] @@ -581,7 +588,12 @@ impl PyRequestBody { // Python BodyChunkIterator — synchronous iterator over body chunks // --------------------------------------------------------------------------- -/// PyBodyChunkIterator is not thread-safe; concurrent __next__ calls are not supported. +/// Synchronous iterator over request-body chunks. +/// +/// Not thread-safe: `__next__` takes `&mut self`, so a concurrent call from +/// another Python thread raises `Already borrowed` rather than corrupting the +/// channel. One consumer per iterator; on a free-threaded interpreter the +/// guard stays structural (the GIL is not involved). #[pyclass(name = "BodyChunkIterator")] #[allow(dead_code)] pub struct PyBodyChunkIterator { diff --git a/crates/eggserve-python/src/server/response_bridge.rs b/crates/eggserve-python/src/server/response_bridge.rs index edaf584..bfbd578 100644 --- a/crates/eggserve-python/src/server/response_bridge.rs +++ b/crates/eggserve-python/src/server/response_bridge.rs @@ -19,6 +19,11 @@ use eggserve_primitives::body::BodySource; use super::*; use super::static_responder::validate_response_status; +/// Python-facing response with one-shot body ownership. +/// +/// Reusing or concurrently taking the body raises the existing one-shot +/// errors on GIL-enabled and free-threaded interpreters alike; the interior +/// mutex is structural and is not a cross-thread sharing contract. #[pyclass(frozen, name = "Response")] pub struct PyResponse { #[pyo3(get)] diff --git a/crates/eggserve-python/src/server/tunnel_bridge.rs b/crates/eggserve-python/src/server/tunnel_bridge.rs index 9f188f2..786ab0e 100644 --- a/crates/eggserve-python/src/server/tunnel_bridge.rs +++ b/crates/eggserve-python/src/server/tunnel_bridge.rs @@ -145,6 +145,7 @@ impl PyTunnelCapability { lifecycle: Some(lifecycle.clone()), handle: self.handle.clone(), closed: Arc::new(AtomicBool::new(false)), + recv_in_flight: AtomicBool::new(false), }; // Downstream handler owns `TunnelIo`, no raw transport. The request @@ -249,6 +250,10 @@ pub struct PyTunnel { pub(super) lifecycle: Option, pub(super) handle: Option, pub(super) closed: Arc, + /// Serializes the one blocking `recv` wait (Plan 333). A second + /// concurrent `recv` fails explicitly instead of observing an + /// already-taken receiver and reporting a misleading closed tunnel. + recv_in_flight: AtomicBool, } impl std::fmt::Debug for PyTunnel { @@ -273,43 +278,59 @@ impl PyTunnel { /// failures raise `ConnectionError` with sanitized text (no payload). /// Intended for use via `asyncio.to_thread` in async handlers so the /// event loop stays responsive; direct calls block the caller. + /// + /// Single-consumer: a concurrent second `recv` on the same tunnel raises + /// `RuntimeError("concurrent Tunnel.recv is not supported")` instead of + /// reporting a misleading closed tunnel. The in-flight guard is reset on + /// every exit path (data, EOF, error, and poisoned lock). fn recv<'py>(&self, py: Python<'py>) -> PyResult>> { let handle = self.handle.clone().ok_or_else(|| { pyo3::exceptions::PyRuntimeError::new_err("no runtime handle for tunnel recv") })?; - // Take the receiver out for one blocking wait, then put back unless - // terminal. `std` Mutex guard cannot be held across `block_on`. - // NOTE (B83): `recv` is single-consumer only (`Send`, not `Sync` - // sharing) — concurrent `recv` during the blocking wait sees `None` - // and reports `tunnel already closed` spuriously. Callers must not - // share concurrent `recv` across threads. - let mut rx = { - let mut guard = self - .to_python_rx - .lock() - .map_err(|_| pyo3::exceptions::PyRuntimeError::new_err("tunnel lock poisoned"))?; - guard.take().ok_or_else(|| { - pyo3::exceptions::PyRuntimeError::new_err("tunnel already closed") - })? - }; - let result = py.detach(|| handle.block_on(rx.recv())); - match result { - Some(Ok(chunk)) => { - // Not terminal: return receiver for future recvs. - if let Ok(mut guard) = self.to_python_rx.lock() { - *guard = Some(rx); + // Plan 333: claim the single blocking wait before touching the + // receiver, so a racing caller gets an explicit contention error + // instead of the terminal-looking "tunnel already closed". + if self + .recv_in_flight + .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire) + .is_err() + { + return Err(pyo3::exceptions::PyRuntimeError::new_err( + "concurrent Tunnel.recv is not supported", + )); + } + let result = (|| -> PyResult>> { + // Take the receiver out for one blocking wait, then put back unless + // terminal. `std` Mutex guard cannot be held across `block_on`. + let mut rx = { + let mut guard = self.to_python_rx.lock().map_err(|_| { + pyo3::exceptions::PyRuntimeError::new_err("tunnel lock poisoned") + })?; + guard.take().ok_or_else(|| { + pyo3::exceptions::PyRuntimeError::new_err("tunnel already closed") + })? + }; + let outcome = py.detach(|| handle.block_on(rx.recv())); + match outcome { + Some(Ok(chunk)) => { + // Not terminal: return receiver for future recvs. + if let Ok(mut guard) = self.to_python_rx.lock() { + *guard = Some(rx); + } + Ok(Some(PyBytes::new(py, &chunk))) + } + Some(Err(msg)) => { + self.closed.store(true, Ordering::Release); + Err(pyo3::exceptions::PyConnectionError::new_err(msg)) + } + None => { + self.closed.store(true, Ordering::Release); + Ok(None) } - Ok(Some(PyBytes::new(py, &chunk))) - } - Some(Err(msg)) => { - self.closed.store(true, Ordering::Release); - Err(pyo3::exceptions::PyConnectionError::new_err(msg)) - } - None => { - self.closed.store(true, Ordering::Release); - Ok(None) } - } + })(); + self.recv_in_flight.store(false, Ordering::Release); + result } /// Blocking send (GIL released during backpressure wait). diff --git a/crates/eggserve-python/tests/test_free_threaded.py b/crates/eggserve-python/tests/test_free_threaded.py new file mode 100644 index 0000000..33596bf --- /dev/null +++ b/crates/eggserve-python/tests/test_free_threaded.py @@ -0,0 +1,353 @@ +"""Plan 333: free-threaded CPython 3.14t behavior. + +Skipped unless the interpreter is a free-threaded build +(sysconfig.get_config_var("Py_GIL_DISABLED") truthy). The suite proves the +extension's explicit free-threading declaration, parallel callback and +producer execution, the serialized mode, one-shot contention errors, and the +tunnel receive guard. It is a correctness suite, not a performance test: no +test asserts wall-clock speed or thread counts. +""" + +import http.client +import socket +import subprocess +import sys +import sysconfig +import threading +import time +import unittest + +from eggserve import lowlevel +from eggserve._native import RequestBodyConsumedError, Response + +FREE_THREADED = bool(sysconfig.get_config_var("Py_GIL_DISABLED")) + + +def _start(handler, **config_kwargs): + config = lowlevel.RuntimeConfig(port=0, **config_kwargs) + server = lowlevel.Server(config=config, handler=handler) + server.start() + server.wait_ready() + return server + + +def _stop(server): + try: + server.shutdown() + except Exception: + pass + try: + server.wait() + except Exception: + pass + + +def _request(addr, method="GET", path="/", body=None, headers=None): + host, port = addr.split(":") + connection = http.client.HTTPConnection(host, int(port), timeout=10) + try: + send_headers = {"Connection": "close"} + if headers: + send_headers.update(headers) + connection.request(method, path, body=body, headers=send_headers) + response = connection.getresponse() + return response.status, response.read() + finally: + connection.close() + + +def _parallel(call, count, timeout=30.0): + barrier = threading.Barrier(count) + results = [None] * count + errors = [] + + def run(index): + try: + barrier.wait(timeout=10) + results[index] = call(index) + except BaseException as exc: # noqa: BLE001 - surfaced below + errors.append(exc) + + threads = [ + threading.Thread(target=run, args=(index,), daemon=True) + for index in range(count) + ] + for thread in threads: + thread.start() + deadline = time.monotonic() + timeout + for thread in threads: + thread.join(max(0.0, deadline - time.monotonic())) + stuck = [thread for thread in threads if thread.is_alive()] + if stuck: + raise AssertionError(f"{len(stuck)} worker thread(s) did not finish") + if errors: + raise errors[0] + return results + + +@unittest.skipUnless( + FREE_THREADED, "requires free-threaded CPython (Py_GIL_DISABLED)" +) +class FreeThreadedTests(unittest.TestCase): + def test_fresh_interpreter_import_keeps_gil_disabled(self): + """The installed module must not ask the interpreter to re-enable the GIL.""" + code = ( + "import sys, eggserve._native; " + "assert sys._is_gil_enabled() is False, 'module re-enabled the GIL'" + ) + completed = subprocess.run( + [ + sys.executable, + "-X", + "gil=0", + "-W", + "error::RuntimeWarning", + "-c", + code, + ], + capture_output=True, + text=True, + timeout=120, + ) + self.assertEqual(completed.returncode, 0, completed.stderr) + + def test_parallel_callbacks_keep_exact_state(self): + """Concurrent handlers see a consistent, exactly-counted shared counter.""" + lock = threading.Lock() + state = {"count": 0} + + def handler(request): + with lock: + state["count"] += 1 + time.sleep(0.01) + return Response.text(200, "ok") + + server = _start(handler, max_python_callbacks=8) + try: + results = _parallel(lambda index: _request(server.addr), 16) + finally: + _stop(server) + + self.assertEqual(state["count"], 16) + self.assertEqual(results, [(200, b"ok")] * 16) + + def test_serialized_mode_never_overlaps(self): + """max_python_callbacks=1 is the documented serialized mode.""" + lock = threading.Lock() + state = {"active": 0, "max": 0} + + def handler(request): + with lock: + state["active"] += 1 + state["max"] = max(state["max"], state["active"]) + time.sleep(0.05) + with lock: + state["active"] -= 1 + return Response.text(200, "ok") + + server = _start(handler, max_python_callbacks=1) + try: + results = _parallel(lambda index: _request(server.addr), 8) + finally: + _stop(server) + + self.assertEqual(state["max"], 1) + self.assertEqual(results, [(200, b"ok")] * 8) + + def test_concurrent_stream_producers(self): + """Parallel Response.stream producers deliver exact bytes.""" + chunks = [b"alpha-", b"beta-", b"gamma"] + expected = b"".join(chunks) + + def handler(request): + return lowlevel.Response.stream(200, list(chunks)) + + server = _start(handler, max_python_callbacks=16) + try: + results = _parallel( + lambda index: _request(server.addr, path="/stream"), 6 + ) + finally: + _stop(server) + + self.assertEqual(results, [(200, expected)] * 6) + + def test_two_threads_race_body_read(self): + """Exactly one concurrent RequestBody.read() wins; the loser is typed.""" + state = {} + done = threading.Event() + + def handler(request): + results = [] + barrier = threading.Barrier(2) + + def reader(): + barrier.wait(timeout=5) + try: + results.append(("ok", request.body.read())) + except BaseException as exc: # noqa: BLE001 - asserted below + results.append(("err", exc)) + + threads = [threading.Thread(target=reader, daemon=True) for _ in range(2)] + for thread in threads: + thread.start() + for thread in threads: + thread.join(10) + state["results"] = results + done.set() + return Response.text(200, "ok") + + server = _start( + handler, request_body_mode="buffer", max_request_body_bytes=1024 + ) + try: + status, body = _request(server.addr, "POST", "/", body=b"payload") + finally: + _stop(server) + + self.assertEqual((status, body), (200, b"ok")) + self.assertTrue(done.wait(5), "handler did not finish") + results = state["results"] + wins = [value for kind, value in results if kind == "ok"] + errors = [value for kind, value in results if kind == "err"] + self.assertEqual(wins, [b"payload"], results) + self.assertEqual(len(errors), 1, results) + self.assertIsInstance(errors[0], RequestBodyConsumedError) + + def test_concurrent_iterator_pull_is_typed(self): + """Concurrent BodyChunkIterator.__next__ raises a typed error, never crashes.""" + state = {} + done = threading.Event() + + def handler(request): + if request.method != "POST": + return Response.text(200, "ok") + iterator = request.body.iter_chunks() + results = [] + barrier = threading.Barrier(2) + + def pull(): + barrier.wait(timeout=5) + try: + results.append(("ok", next(iterator))) + except BaseException as exc: # noqa: BLE001 - asserted below + results.append(("err", exc)) + + threads = [threading.Thread(target=pull, daemon=True) for _ in range(2)] + for thread in threads: + thread.start() + for thread in threads: + thread.join(10) + state["results"] = results + done.set() + return Response.text(200, "ok") + + server = _start( + handler, request_body_mode="buffer", max_request_body_bytes=1024 + ) + try: + status, body = _request(server.addr, "POST", "/", body=b"payload") + self.assertEqual((status, body), (200, b"ok")) + self.assertTrue(done.wait(5), "handler did not finish") + follow_up = _request(server.addr, "GET", "/") + finally: + _stop(server) + + results = state["results"] + self.assertTrue(results) + self.assertTrue(any(kind == "ok" for kind, _ in results), results) + for kind, value in results: + if kind == "err": + # A racing pull either observes PyO3's structural borrow error + # or, after the other thread consumed the last chunk, + # StopIteration. Anything else (panic, decode error) fails. + if isinstance(value, StopIteration): + continue + self.assertIsInstance(value, RuntimeError, results) + self.assertIn("borrow", str(value).lower(), results) + self.assertEqual(follow_up, (200, b"ok")) + + def test_tunnel_recv_contention_is_explicit(self): + """A racing Tunnel.recv is rejected and the guard resets for later calls.""" + state = {} + ready = threading.Event() + + def handler(request): + capability = request.take_tunnel() + if capability is None: + state["error"] = "no tunnel capability" + ready.set() + return Response.text(400, "no tunnel") + handshake, tunnel = capability.accept() + state["tunnel"] = tunnel + ready.set() + return handshake + + server = _start(handler, max_python_callbacks=4) + host, port = server.addr.split(":") + sock = socket.create_connection((host, int(port)), timeout=10) + sock.settimeout(10) + try: + sock.sendall( + b"GET /tunnel HTTP/1.1\r\nHost: x\r\n" + b"Upgrade: echo-test\r\nConnection: upgrade\r\n\r\n" + ) + head = b"" + while b"\r\n\r\n" not in head: + chunk = sock.recv(1) + if not chunk: + break + head += chunk + self.assertIn(b" 101 ", head.split(b"\r\n", 1)[0], head) + self.assertTrue(ready.wait(5), "handler did not accept the tunnel") + self.assertIsNone(state.get("error")) + tunnel = state["tunnel"] + + started = threading.Event() + first = {} + + def blocking_recv(): + started.set() + try: + first["value"] = tunnel.recv() + except BaseException as exc: # noqa: BLE001 - EOF/close both valid + first["error"] = exc + + worker = threading.Thread(target=blocking_recv, daemon=True) + worker.start() + self.assertTrue(started.wait(5)) + time.sleep(0.2) + with self.assertRaises(RuntimeError) as contention: + tunnel.recv() + self.assertIn("concurrent Tunnel.recv", str(contention.exception)) + + sock.shutdown(socket.SHUT_RDWR) + worker.join(10) + self.assertFalse(worker.is_alive(), "blocking recv did not finish") + self.assertTrue(first, "first recv produced no result") + + with self.assertRaises(RuntimeError) as terminal: + tunnel.recv() + self.assertIn("already closed", str(terminal.exception)) + finally: + try: + sock.close() + finally: + _stop(server) + + def test_restart_with_concurrent_callbacks(self): + """Start/stop is stable under a concurrent callback burst.""" + for _ in range(2): + server = _start( + lambda request: Response.text(200, "ok"), + max_python_callbacks=4, + ) + try: + results = _parallel(lambda index: _request(server.addr), 8) + finally: + _stop(server) + self.assertEqual(results, [(200, b"ok")] * 8) + + +if __name__ == "__main__": + unittest.main() diff --git a/crates/eggserve-python/tests/test_server_integration.py b/crates/eggserve-python/tests/test_server_integration.py index 32e4fb1..74bac98 100644 --- a/crates/eggserve-python/tests/test_server_integration.py +++ b/crates/eggserve-python/tests/test_server_integration.py @@ -638,7 +638,7 @@ def do_stop(): t.join(timeout=5) def test_no_rust_mutex_held_during_python(self): - """The GIL is the only synchronization during Python callback execution.""" + """No Rust mutex is held while Python callback code executes.""" call_active = _AtomicCounter() def handler(req): diff --git a/docs/api-stability.md b/docs/api-stability.md index 869a08a..253a655 100644 --- a/docs/api-stability.md +++ b/docs/api-stability.md @@ -27,7 +27,7 @@ Error types (`MethodError`, `HttpVersionError`, `AuthorityError`, `HeaderError`, `ResponseBody` and `Response` implement `Send`; file-backed bodies carry an already-opened file capability rather than a path to reopen. -Python wrapper types (`#[pyclass(frozen)]`) are frozen/immutable but are not `Send`/`Sync` in the Rust sense — Python GIL constraints apply. +Python wrapper types (`#[pyclass(frozen)]`) are frozen/immutable but are not `Send`/`Sync` in the Rust sense. On GIL-enabled builds Python's GIL serializes access; on free-threaded 3.14t builds the same types stay one-shot/single-consumer and raise typed contention errors rather than becoming thread-safe. ### Exception classes, fields, and messages diff --git a/docs/extension-contract.md b/docs/extension-contract.md index 815450a..6c988aa 100644 --- a/docs/extension-contract.md +++ b/docs/extension-contract.md @@ -237,7 +237,10 @@ When Python code is used to build a server (via the `Server` primitive or the su - Socket I/O, connection acceptance, and timeout enforcement are handled by the Rust runtime. - File streaming is handled by the Rust runtime; file bodies never pass through Python memory. - Python code returns explicit `Response` values; it does not drive socket I/O directly. -- The GIL is released during I/O operations, allowing other Python threads to run. +- Python work detaches from the interpreter during Rust-owned I/O waits: the + GIL is released on GIL-enabled builds, and a free-threaded build has no GIL + to release. Handlers may run in parallel up to `max_python_callbacks`; + caller-owned shared state needs its own synchronization. - Callback-induced latency or errors must not prevent Rust from enforcing connection-level policy. This separation ensures that Python application code cannot bypass timeout limits, connection caps, or file-stream quotas. diff --git a/docs/library-capability-matrix.md b/docs/library-capability-matrix.md index b0a703e..8785dcb 100644 --- a/docs/library-capability-matrix.md +++ b/docs/library-capability-matrix.md @@ -127,11 +127,15 @@ behavior. skipped due to NTFS path-rename semantics. Windows remains functional-only; do not use it with untrusted public content. -- **Python wheels** are GIL-enabled CPython 3.11–3.15 with abi3 stable ABI - (`>=3.11`, one `cp311-abi3` wheel per platform) on the Linux, - macOS, and Windows wheel matrix. The wheel contains the native extension and +- **Python wheels (GIL)** are GIL-enabled CPython 3.11–3.15 with abi3 stable + ABI (`>=3.11`, one `cp311-abi3` wheel per platform) on the Linux, macOS, and + Windows wheel matrix. The wheel contains the native extension and extension-backed CLI entry point; it does not bundle a second standalone CLI binary. +- **Python wheels (free-threaded)** are CPython 3.14t (`cp314-cp314t`) on + Linux x86_64 (glibc), macOS arm64, and Windows x86_64 only, at **Beta** + (Plan 333). 3.13t/3.15t, PyPy, ARMv7, Windows arm64, and musl free-threaded + builds are not supported. - **Runtime service boundary is experimental.** `eggserve-server` provides the direct generic HTTP/1 runtime for embedding. `eggserve-core::server` remains diff --git a/docs/python-api.md b/docs/python-api.md index 35ba16f..81af77d 100644 --- a/docs/python-api.md +++ b/docs/python-api.md @@ -167,9 +167,21 @@ server.wait() `__next__` that blocks indefinitely cannot be interrupted: the thread may outlive the request and server shutdown, holding its permit until it returns. -- GIL/networking split: Rust owns I/O; at most `max_python_callbacks` - handlers run concurrently; in-flight admission is held before the callback - permit. Timeouts close the HTTP request but cannot kill Python code. +- Interpreter/networking split: Rust owns I/O; at most + `max_python_callbacks` handlers run concurrently; in-flight admission is + held before the callback permit. Timeouts close the HTTP request but cannot + kill Python code. +- Free-threaded CPython 3.14t (Beta; Linux x86_64 glibc, macOS arm64, Windows + x86_64 only): up to `max_python_callbacks` handlers and the independent + stream-producer permits execute Python code in parallel. The bridge's Rust + state stays behind mutexes and atomics, but handler and iterable thread + safety is the caller's responsibility; `max_python_callbacks=1` is the + serialized mode. `RequestBody`, `BodyChunkIterator`, response bodies, and + `Tunnel` stay one-shot/single-consumer: concurrent reuse raises the existing + typed errors (`RequestBodyConsumedError`, `Already borrowed`, `already + consumed`), and a concurrent `Tunnel.recv` raises + `RuntimeError("concurrent Tunnel.recv is not supported")`. None of this + depends on the GIL. The six-class `eggserve.server` façade is the primary stdlib-shaped surface; `eggserve.lowlevel` is the public runtime/service substrate for downstream @@ -191,8 +203,10 @@ static server/library, not a maintained ASGI server). Handlers are - Same native runtime as the sync facade (no second accept loop, H1-only; H2/H3 remain Rust-only experimental). `eggserve.server` stays synchronous. - Manual asyncio bridge (no new PyO3 async dependency, abi3 compatible): - Rust releases the GIL during all network/body waits; Python never blocks - the loop on Rust (blocking native calls go via `asyncio.to_thread`). + Rust detaches from the interpreter during all network/body waits on both + families (the GIL is released on GIL builds; a free-threaded build has no + GIL to release); Python never blocks the loop on Rust (blocking native + calls go via `asyncio.to_thread`). - Byte-fidelity metadata: `header_items_bytes`, `raw_target_bytes`, `path_bytes`/`query_bytes`, the first-wins `headers` dictionary view plus the ordered duplicate-preserving `header_items` sequence, text `*_addr` diff --git a/docs/python-http-server-compatibility.md b/docs/python-http-server-compatibility.md index 3071d88..28e6f42 100644 --- a/docs/python-http-server-compatibility.md +++ b/docs/python-http-server-compatibility.md @@ -62,6 +62,15 @@ When the native fast path is active, `HTTPServer`/`HTTPSServer` are effectively limited to one connection and `ThreadingHTTPServer(N)`/ `ThreadingHTTPSServer(N)` to `N` through native admission control. +On free-threaded CPython 3.14t (Beta; Linux x86_64 glibc, macOS arm64, and +Windows x86_64 only), that bound is true parallelism rather than +execution serialized by the GIL: up to `max_workers` handlers and the +bounded `Response.stream` producers may run Python at once. Handlers that +share mutable state must synchronize it themselves; `max_workers=1` restores +serialization. One-shot bodies, iterators, responses, and tunnels remain +single-consumer and raise the typed contention errors (see +`docs/python-api.md`). GIL-enabled behavior is unchanged. + ## Source-familiar behavior The facade supports the compatibility behaviors that are useful for porting a diff --git a/docs/python-packaging.md b/docs/python-packaging.md index a09ed8d..ff9dae4 100644 --- a/docs/python-packaging.md +++ b/docs/python-packaging.md @@ -65,8 +65,11 @@ See [docs/python-api.md](python-api.md) for the full API reference. ### Prerequisites - Rust toolchain (stable) -- CPython 3.11–3.15 with abi3 stable ABI (GIL-enabled; `>=3.11`); PyPy and free-threaded builds are not supported -- maturin: `pip install maturin` +- CPython 3.11–3.15 with abi3 stable ABI (GIL-enabled; `>=3.11`); PyPy and + free-threaded CPython 3.13t/3.15t are not supported +- Free-threaded CPython 3.14t is **Beta** on Linux x86_64 (glibc), macOS + arm64, and Windows x86_64 only (`cp314-cp314t`; Plan 333) +- maturin: `pip install "maturin>=1.14.1,<2.0"` ### Build a wheel @@ -79,6 +82,13 @@ maturin build --profile dist --interpreter python3.11 -o dist This produces a platform-specific wheel in `target/wheels/`. +Free-threaded 3.14t wheels use the same command with a free-threaded +interpreter; never pass a GIL interpreter: + +```sh +maturin build --profile dist --interpreter python3.14t -o dist +``` + ### Build for development ```sh @@ -106,11 +116,15 @@ cover all 10 required targets: | Windows x86_64 | `win_amd64` | | Windows arm64 | `win_arm64` | -Each wheel is an abi3 wheel (`cp311-abi3`), compatible with GIL-enabled +Each GIL wheel is an abi3 wheel (`cp311-abi3`), compatible with GIL-enabled CPython 3.11–3.15. One wheel per platform serves all supported CPython minor versions; the release proves the same wheel bytes on every minor -(build-once/test-many ABI proof) and executes ARM/Windows-ARM64 artifacts -natively or under matching QEMU userspaces (see `docs/release-process.md`). +(build-once/test-many ABI proof). The free-threaded family adds one +`cp314-cp314t` wheel for CPython 3.14t on Linux x86_64 (glibc), macOS arm64, +and Windows x86_64 (**Beta**; Plans 333–334; promotion owned by Plan 332). It is a separate ABI and is not +covered by the abi3 proof: each target is built and smoked with its own +3.14t interpreter. ARM/Windows-ARM64 artifacts execute natively or under +matching QEMU userspaces (see `docs/release-process.md`). manylinux i686, musllinux i686, and Windows x86 (`win32`) are declared candidates only — not supported until build, binary-install, and smoke evidence exist with no dependency-policy exception. diff --git a/docs/release-contract.md b/docs/release-contract.md index 6f31b76..0f06a8a 100644 --- a/docs/release-contract.md +++ b/docs/release-contract.md @@ -25,9 +25,14 @@ pool and closes incomplete streamed requests. The Python wheel compatibility declaration is GIL-enabled CPython 3.11–3.15 with abi3 stable ABI (`>=3.11`, one `cp311-abi3` wheel per platform, proven -by a build-once/test-many ABI proof) on Linux, macOS, and Windows. The wheel -contains the matching platform-native extension and its extension-backed CLI -entry point; PyPy and free-threaded CPython are not supported. +by a build-once/test-many ABI proof) on Linux, macOS, and Windows. A second, +additive family ships `cp314-cp314t` wheels for free-threaded CPython 3.14t +on Linux x86_64 (glibc), macOS arm64, and Windows x86_64 as **Beta** +(Plan 333); it is built and smoked with a free-threaded interpreter and keeps +the extension's GIL-free declaration explicit. The wheels contain the +matching platform-native extension and its extension-backed CLI entry point. +PyPy, free-threaded CPython 3.13t/3.15t, `abi3t`, ARMv7, Windows arm64, and +musl free-threaded builds are not supported. ## Release Artifacts @@ -152,7 +157,10 @@ Key properties: - Default body policy is `reject` (backward-compatible with Milestone 3). - `read()` and `iter_chunks()` are mutually exclusive; mixing raises `RequestBodyConsumedError`. - All byte limits and timeouts are enforced by the Rust runtime, not Python. -- Python methods release the GIL during Rust-owned I/O waits. +- Python methods detach from the interpreter during Rust-owned I/O waits. + On a GIL-enabled build that releases the GIL so other Python threads can + run; on a free-threaded build there is no GIL, and the detachment is a + thread-state operation instead. - Static service remains bodyless (`RequestBodyPolicy::Reject`). - Callback timeout does not cancel arbitrary Python code; timed-out callbacks still count against concurrency until they return. diff --git a/docs/release-process.md b/docs/release-process.md index 2608676..bfc6582 100644 --- a/docs/release-process.md +++ b/docs/release-process.md @@ -26,9 +26,13 @@ workflow_dispatch (publish_target: none|testpypi|pypi) │ preflight (version-sync check, wheel-matrix authority, source commit) │ ▼ -wide wheel build matrix (10 required targets, from wheel-matrix.toml) +wide wheel build matrix (13 required entries on 10 platform tags across +two ABI families, from wheel-matrix.toml) │ - ├──▶ ABI proof: same x86_64 wheel on CPython 3.11–3.15 (binary-only) + ├──▶ ABI proof: same x86_64 cp311-abi3 wheel on CPython 3.11–3.15 + │ (binary-only; GIL family only) + ├──▶ free-threaded build+smoke: cp314-cp314t on the three declared + │ targets with python3.14t and an explicit GIL-free assertion ├──▶ qualify-aarch64-glibc: manylinux wheel, native ARM64 Ubuntu ├──▶ qualify-aarch64-musl: musllinux wheel, native ARM64 Alpine container ├──▶ qualify-windows-arm64: win_arm64 wheel, native Windows ARM64 @@ -134,7 +138,8 @@ The workflow runs a preflight job before any platform builds: `importlib.metadata.version("eggserve")`), plus exact `[profile.dist]` equivalence between the workspace and the excluded Maturin crate. - Validates `abi3-py311`, `requires-python >=3.11` with advertised 3.11–3.15 - classifiers, and the `python3.11` wheel ABI baseline. + classifiers, the declared `cp311` + `cp314t` families, the free-threading + Beta classifier, and matrix-owned interpreters for both families. - Validates the wheel-target authority (`scripts/wheel-matrix.py validate`, `self-test`, and `scripts/check-release-wheel-set.py --self-test`) and emits the build matrix from `release/wheel-matrix.toml`, so the workflow @@ -146,8 +151,9 @@ A metadata mismatch prevents all platform builds. ## Wide platform wheel matrix -Release wheels are built for all 10 required targets declared in -`release/wheel-matrix.toml` (the single authority; the workflow matrix is +Release wheels are built for all 13 required entries declared in +`release/wheel-matrix.toml` — 10 GIL targets plus the three free-threaded +cp314t targets (the single authority; the workflow matrix is generated from it in preflight): | Platform family | Wheel target | Build method | @@ -172,6 +178,13 @@ rejects `pypi` as a baseline, musl targets carrying a manylinux baseline, and cross-built targets claiming build-host native smoke; see `scripts/check-release-workflow.py` for the workflow-structure guard. +Matrix `tier = "required"` is a release-aggregation property — the entry must +appear in every release aggregate and its absence fails the release — not a +user-facing support level. The user support tier lives in the wheel +classifier and `docs/toolchain-support.md`; for the free-threaded family that +tier is **Beta** (Plan 334; promotion owned by Plan 332), even though its +three `cp314t` entries are `required` in the matrix. + Each wheel is built with exact Rust **1.98.1** and `--profile dist --locked --interpreter python3.11 --compatibility pypi --out dist` and validated for platform/ABI/version correctness, wheel composition (no second @@ -180,7 +193,10 @@ standalone binary), and runtime smoke (import, CLI help, real fixture serving). ### Stable-ABI proof (build-once, test-many) One `cp311-abi3` artifact per platform serves GIL-enabled CPython 3.11–3.15; -no per-minor wheels are produced. The release proves reuse with the exact +no per-minor wheels are produced. The free-threaded `cp314-cp314t` family is +deliberately outside this proof: each of its three targets is built and +smoked with its own 3.14t interpreter, and import asserts the GIL stays +disabled. The release proves reuse with the exact built bytes: the `abi-proof` job downloads the Linux x86_64 wheel artifact and installs it with `--only-binary=:all:` on CPython 3.11, 3.12, 3.13, 3.14, and 3.15, running import, CLI/module help, `scripts/release_smoke.py`, @@ -228,7 +244,8 @@ After all matrix jobs succeed: 2. Place all wheels in one clean directory. 3. Run the release wheel-set validator (`scripts/check-release-wheel-set.py`, which loads its required set from the same `release/wheel-matrix.toml`). -4. Verify all wheels share the expected version and `cp311-abi3` tag. +4. Verify all wheels share the expected version and one of the two declared + tag triples (`cp311-abi3` or `cp314-cp314t`). 5. Produce a human-readable manifest with SHA-256 hashes plus the matrix authority revision, so a published artifact set can be reconstructed. 6. Upload the aggregate set as workflow evidence. @@ -312,8 +329,10 @@ an in-progress publication. - **HTTP/2, redirects, retries, cookies, proxy, and multi-range responses**: outside scope. HTTP/1.1 with single byte ranges only. - **Python wheels**: GIL-enabled CPython 3.11–3.15 with abi3 stable ABI - (`>=3.11`, one `cp311-abi3` wheel per platform; free-threaded CPython - unsupported, see `release/plan-267-wheel-feasibility.md`). + (`>=3.11`, one `cp311-abi3` wheel per platform) plus free-threaded CPython + 3.14t at **Beta** (`cp314-cp314t` on Linux x86_64 glibc, macOS arm64, and + Windows x86_64 only; Plan 333). 3.13t/3.15t, `abi3t`, PyPy, ARMv7, Windows + arm64, and musl free-threaded builds are unsupported. ## crates.io publication diff --git a/docs/threat-model.md b/docs/threat-model.md index 39038a3..9b9d672 100644 --- a/docs/threat-model.md +++ b/docs/threat-model.md @@ -255,7 +255,10 @@ Parser-level protections reject Windows reserved names, ADS syntax, drive prefix - The `Server` primitive runs a tokio runtime in a background thread. Python receives parsed `Request` objects and returns `Response` values. - Socket I/O, HTTP parsing, connection acceptance, and timeout enforcement are handled by Rust. - File streaming is handled by Rust; file bodies never pass through Python memory in the server path. -- The GIL is released during I/O operations, allowing other Python threads to run. +- Python work detaches from the interpreter during Rust-owned I/O waits: the + GIL is released on GIL-enabled builds, and a free-threaded build has no GIL + to release. Handlers may run in parallel up to `max_python_callbacks`; + caller-owned shared state needs its own synchronization. - Python callbacks may be untrusted from a latency/resource perspective but are not sandboxed. Rust enforces connection and I/O policy around them — timeout limits, connection caps, and file-stream quotas are not affected by Python callback behavior. - Callback timeout does not cancel Python execution. The request task stops waiting at the configured deadline and returns 504, but the Python callback continues executing in the background. The callback semaphore permit is held until the Python function returns, meaning timed-out callbacks still count against the concurrency limit until they complete. - Forced shutdown closes the Rust runtime and listener but cannot safely terminate Python code. Blocked Python work does not retain the listener or runtime task registry. diff --git a/docs/toolchain-support.md b/docs/toolchain-support.md index 5ff7319..6e8df68 100644 --- a/docs/toolchain-support.md +++ b/docs/toolchain-support.md @@ -97,7 +97,7 @@ target-native C toolchain for `ring` and `aws-lc-sys`. | GIL-enabled CPython 3.11–3.15 (`>=3.11`) | Supported (one `cp311-abi3` wheel per platform; Plan 264) | | CPython < 3.11 | Unsupported | | PyPy | Unsupported | -| Free-threaded CPython (3.13t, 3.14t, 3.15t) | Unsupported (Plan 267 owns the feasibility decision) | +| Free-threaded CPython 3.14t (`cp314-cp314t`) | Beta — Linux x86_64 (glibc), macOS arm64, Windows x86_64 only (Plan 333; tier set by Plan 334; promotion owned by Plan 332) | ### ABI @@ -110,15 +110,38 @@ same Linux x86_64 wheel bytes on every supported minor (build-once, test-many; see `docs/release-process.md`). No per-minor `cp312-cp312` artifacts are produced. +Free-threaded CPython 3.14t adds an explicit second family: +`cp314-cp314t` wheels on Linux x86_64 (glibc), macOS arm64, and Windows +x86_64 only, at support tier **Beta**. The required-family release aggregate +with all three wheels is green and the bounded contention soak passes, but +the soak records name no commit, wheel filename, or host and were taken on a +single macOS arm64 host, so the claim is not reproducible from the record. +Plan 332 owns the per-target evidence and the only Beta-to-Stable decision. +The `gil_used = false` declaration is explicit and guarded: +`scripts/check-python-free-threaded-compile.sh` asserts `Py_GIL_DISABLED`, +the free-threaded test module asserts the GIL stays disabled after import, +and the release metadata gate requires the classifier to match +`EXPECTED_FREE_THREADING_TIER`. +The GIL `cp311-abi3` family is unchanged. CPython 3.13t/3.15t, `abi3t` +(PEP 803), PyPy, ARMv7, Windows arm64, and musl free-threaded builds are +not supported; this line does not use `abi3t`. + ### Build System -Wheels are built with **maturin** (latest stable, `>=1.0, <2.0`). The build backend is declared in `pyproject.toml`. +Wheels are built with **maturin** (`>=1.14.1, <2.0`, matching the pinned +1.14.1 release pipeline and the `abi3t`-capable backend). The build backend +is declared in `pyproject.toml`. ### PyO3 Version -The Python bindings use PyO3 **0.29.2** with the `extension-module` and -`abi3-py311` features. The excluded Python crate has its own lockfile, which -is audited and checked against the shared dependency policy in CI. +The Python bindings use PyO3 **0.29.3** (resolved; the manifest keeps a +`0.29.2` caret requirement) with the `extension-module` and `abi3-py311` +features. Since PyO3 0.28, `#[pymodule]` without `gil_used` declares +`Py_MOD_GIL_NOT_USED`; the crate now states `gil_used = false` explicitly +for the CPython 3.14t Beta family. `abi3-py311` is ignored on a free-threaded +interpreter, where PyO3 builds version-specifically. The excluded Python +crate has its own lockfile, which is audited and checked against the shared +dependency policy in CI. ### Wheel Matrix @@ -140,10 +163,22 @@ platform list may drift. | Windows x86_64 | `win_amd64` | | Windows arm64 | `win_arm64` | -All wheels are `cp311-abi3`, compatible with GIL-enabled CPython 3.11–3.15. -One wheel per platform serves all supported CPython minor versions. Release -wheels are built against the minimum supported ABI baseline (CPython 3.11) -rather than a newer interpreter. +All GIL wheels are `cp311-abi3`, compatible with GIL-enabled CPython +3.11–3.15. One wheel per platform serves all supported CPython minor +versions, built against the minimum ABI baseline (CPython 3.11) rather than a +newer interpreter. The free-threaded family adds `cp314-cp314t` wheels on +the three targets below; the matrix has 13 required entries on 10 platform +tags, and the public free-threaded tier is Beta. + +| Free-threaded target | Wheel Target | Binary interpreter | +|---|---|---| +| Linux x86_64 (glibc) | `manylinux_2_17_x86_64` | `/opt/python/cp314-cp314t/bin/python` | +| macOS arm64 | `macosx_11_0_arm64` | `python3.14t` | +| Windows x86_64 | `win_amd64` | `python3.14t` | + +The GIL family keeps the unchanged build-once/test-many ABI proof; the +free-threaded family is built and smoked against its own 3.14t interpreter +and must leave the GIL disabled on import. Extended candidates (not supported; promotion needs build, binary-install, and smoke evidence with no dependency-policy exception): manylinux i686, @@ -199,6 +234,6 @@ See [security-policy.md](security-policy.md) and [non-goals.md](non-goals.md) fo | Tool | Required Version | Purpose | |------|-----------------|---------| | Rust stable | Current stable | Building all crates, running tests | -| Python | 3.11–3.15 (GIL-enabled, `cp311-abi3` wheel) | Wheel builds, Python tests | -| maturin | `>=1.0, <2.0` | Python wheel builds | +| Python | 3.11–3.15 (GIL-enabled, `cp311-abi3` wheel); 3.14t (Beta, `cp314-cp314t` on three targets) | Wheel builds, Python tests | +| maturin | `>=1.14.1, <2.0` | Python wheel builds | | bash | Any POSIX-compatible | CI and local scripts (`scripts/`) | diff --git a/plans/closure/python-facade/330-free-threaded-314t-branch-adoption.md b/plans/closure/python-facade/330-free-threaded-314t-branch-adoption.md new file mode 100644 index 0000000..a4df771 --- /dev/null +++ b/plans/closure/python-facade/330-free-threaded-314t-branch-adoption.md @@ -0,0 +1,186 @@ +# Python Facade Milestone 330 — Closure Status + +Status: closed + +Source implementation plan: + +- `plans/implementation/python-facade/330-free-threaded-314t-branch-adoption.md` + +Source roadmap: + +- `plans/subsystems/python-facade-roadmap.md` (Milestone 330) + +Executed 2026-11-28 in worktree `feat/auto-20261128-fb4f0bec`. Baseline +`origin/main` `5fdd7da`; merge commit `87bbb522de6477462279febf94181dd0506cf883`. + +## 1. Outcome + +The adjacent free-threaded branch `feat/auto-20261116-7cc8b1dc` (tip +`6e3003f`, merge base `4949a77`) is merged onto `main` as an additive +`cp314-cp314t` wheel family for CPython 3.14t on Linux x86_64 (glibc), macOS +arm64, and Windows x86_64, with an explicit `#[pymodule(gil_used = false)]` +declaration, a free-threaded CI lane, the concurrency tests, family-aware +wheel-matrix and release validators, the tunnel `recv` contention guard, and +corrected documentation. The user-facing tier is **Beta**. + +Merge size: 42 files, 4564 insertions, 238 deletions. + +## 2. Commits + +| Commit | Content | +|---|---| +| `e30427d` | Plans 330-332, registry and roadmap records (the merge precondition) | +| `87bbb52` | Merge of `6e3003f`: three conflicts resolved, records renumbered to 333/334, tier set to Beta | + +The six branch commits (`ab418f8`..`6e3003f`) keep their identity in the merge +history. + +## 3. Conflicts and resolution + +`git merge-tree --write-tree origin/main 6e3003f`, run before the plan-set +commit, reported conflicts only in `CHANGELOG.md` and `plans/registry.md`. +At merge time `plans/subsystems/python-facade-roadmap.md` also conflicted, +because the plan-set commit edited the same roadmap the branch edits. That is +local, not branch drift: the branch base did not move. + +- `CHANGELOG.md`: kept main's section header ("Plans 320-329", widened to + 320-334) and the branch's free-threaded entry; the entry's tier text became + Beta. +- `plans/registry.md`: kept main's 320-329 rows; the branch's Python facade + row and its 326/327 implementation rows were renumbered and the duplicate + facade row dropped in favour of one merged row. +- `plans/subsystems/python-facade-roadmap.md`: kept the 330-332 milestones the + plan-set commit added and re-added the branch's milestone sections as + 333/334 with amendment blocks. + +No conflict reached product source; every source, workflow, script, test, and +other doc file auto-merged. + +## 4. Renumbering + +`main` already assigns 326 to the public-bind acknowledgment milestone and 327 +to the TLS substrate corrective, so the branch records were renumbered +326 -> 333 and 327 -> 334: + +- implementation records, closure records, and the three soak records + (`334-soak-{1,2,3}.json`, including the JSON `plan` field); +- every cross-reference in `docs/`, `scripts/`, `.github/workflows/`, + `crates/eggserve-python/`, `release/wheel-matrix.toml`, + `release/plan-267-wheel-feasibility.md`, and + `.opencode/skills/eggserve-dev/SKILL.md`; +- the 333/334 records carry an amendment block naming the original number. + +Proof: `git grep -nE '32(6|7)-free-threaded' -- .` returns nothing. The +existing 326 (public bind) and 327 (TLS) records are untouched. + +## 5. Tier + +Beta, and the branch's Stable promotion is reversed. + +- `crates/eggserve-python/pyproject.toml`: + `Programming Language :: Python :: Free Threading :: 2 - Beta`. +- `scripts/check-python-release-metadata.py`: + `EXPECTED_FREE_THREADING_TIER = 2`. +- `docs/toolchain-support.md` (tier authority), `docs/python-packaging.md`, + `docs/release-contract.md`, `docs/release-process.md`, + `docs/library-capability-matrix.md`, `docs/python-api.md`, + `docs/python-http-server-compatibility.md`, `SECURITY.md`, `CHANGELOG.md`, + and `.opencode/skills/eggserve-dev/SKILL.md` all state Beta. + +Reason: the branch's three soak records name no commit, wheel filename, or +host, and all three were taken on one macOS arm64 host, so the Stable claim +is not reproducible from the record and does not meet the branch's own "wheel +filenames are the authority" standard. `docs/release-process.md` now states +that matrix `tier = "required"` is a release-aggregation property, not the +user support tier. + +## 6. Declaration guard + +- Runtime half (already on the branch, kept): + `crates/eggserve-python/tests/test_free_threaded.py` runs a subprocess with + `-X gil=0 -W error::RuntimeWarning`, imports `eggserve._native`, and asserts + `sys._is_gil_enabled() is False`. If `gil_used = false` is removed, PyO3 + declares GIL-required and that assertion fails. +- Compile half: `scripts/check-python-free-threaded-compile.sh` asserts + `Py_GIL_DISABLED` and runs `cargo check --locked`. +- Tier half: the release metadata gate requires exactly + `Free Threading :: 2 - Beta` while the `cp314t` family is required. +- Mutation proof: flipping the classifier to `3 - Stable` made + `check-python-release-metadata.py` exit 1 with "the free-threading + classifier must be exactly ... 2 - Beta"; restoring it passed. + +## 7. Gate log + +Run on 2026-11-28 unless noted. "Export" means the committed tree was +extracted with `git archive` to `/tmp/eggserve-330-src` and an empty +`[workspace]` table was appended to the excluded crate's manifest (see +Section 8); the table is not committed. + +| Command | Result | +|---|---| +| `git diff --check` | clean | +| `python3 scripts/check-crate-topology.py` | pass | +| `python3 scripts/wheel-matrix.py validate` | pass | +| `python3 scripts/wheel-matrix.py self-test` | pass | +| `python3 scripts/check-release-wheel-set.py --self-test` | pass | +| `python3 scripts/check-release-workflow.py` | pass | +| `python3 scripts/check-release-workflow.py --self-test` | pass | +| `python3 scripts/check-python-release-metadata.py` | pass (tier 2) | +| metadata gate with classifier mutated to Stable | fails as designed; restored | +| `cargo fmt --all -- --check` | pass | +| `PYTHON=<3.14t> bash scripts/check-python-free-threaded-compile.sh` (export) | pass; `Py_GIL_DISABLED` asserted | +| `cargo clippy --lib -- -D warnings` in `crates/eggserve-python` (export) | pass | +| `PYTHON=<3.14t> bash scripts/test-python-wheel.sh` (export) | **864 tests, OK**, 123.9 s | +| `PYTHON=<3.14> bash scripts/test-python-wheel.sh` (export) | **864 tests, OK (skipped=8)**, 122.3 s | + +The GIL lane skips exactly the eight free-threaded tests; the two lanes are +otherwise identical, which is the intended contract. + +## 8. Deviations + +1. **Nested worktree.** `cargo check/clippy --manifest-path + crates/eggserve-python/Cargo.toml` cannot run from this worktree: Cargo + resolves the outer checkout and reports "current package believes it's in a + workspace when it's not". The Python-crate gates and both wheel suites ran + from a `git archive` export of `87bbb52` with an empty `[workspace]` table + appended to a temporary copy. The repository manifest is unchanged. +2. **`./scripts/verify.sh fast` was not run end-to-end.** It invokes the same + `--manifest-path crates/eggserve-python/Cargo.toml` checks and fails for the + nested-worktree reason above. Its constituent gates were run individually + (rows above). Workspace-member clippy and tests were not run, because no + workspace crate is touched by this merge: + `git diff --name-only origin/main..HEAD -- crates | grep -v + crates/eggserve-python` is empty. +3. **maturin provisioning.** `scripts/test-python-wheel.sh` requires + `maturin` importable by the target interpreter. The shipped 3.14t + interpreter has none, and the standalone binary is 1.9.5, so + `maturin==1.14.1` was installed into a throwaway venv used as `PYTHON`. The + GIL lane used the already-installed 1.9.5 module, which the script accepts. +4. **Wheel-tag half of the guard.** The plan asked the metadata gate to check + the WHEEL tag family "when a built artifact is available". + `scripts/check-release-wheel-set.py` already enforces family-to-tag-triple + agreement for release sets, so the check was not duplicated in the metadata + gate; the gate owns the tier constant and classifier only. +5. **Third conflict.** See Section 3. +6. **`--ours` resolution gap, caught and repaired.** Taking the pre-merge + version of `plans/subsystems/python-facade-roadmap.md` also discarded the + branch's edits that sat outside the conflict hunks: the §8 free-threading + concurrency semantics, the §9 free-threaded CI-lane paragraph, and the + three free-threading bullets in §10. A branch-added-line comparison + (`git diff --unified=0 origin/main 6e3003f`, then each added line against + the merged file, with the renumbering applied) found them, and a follow-up + commit restores them verbatim. The registry had no such loss: its only + absent branch lines are the superseded next-number line, the superseded + duplicate facade row, the branch's CLI row that omits main's 326, and the + 326/327 rows that now exist as 333/334. + +## 9. Deferred evidence + +The per-target contention evidence and every Beta-to-Stable decision belong to +**Milestone 332**. Milestone 331 owns the concurrency-contract fixes the audit +found. This milestone asserts Beta only. + +## 10. Not done + +No publication, no version bump, no tag, no push. The branch's Stable commit +text survives in history; only the tier was reversed on the merged tree. diff --git a/plans/closure/python-facade/333-free-threaded-cpython-314t-staged-support.md b/plans/closure/python-facade/333-free-threaded-cpython-314t-staged-support.md new file mode 100644 index 0000000..2947003 --- /dev/null +++ b/plans/closure/python-facade/333-free-threaded-cpython-314t-staged-support.md @@ -0,0 +1,288 @@ +# Python Facade Milestone 333 — Closure Status + +> **Amendment — Milestone 330 (2026-11-28).** Renumbered from 326 at merge; +> `main` already assigns 326 to the public-bind acknowledgment milestone. +> Body references were renumbered with it; the Beta tier is unchanged. + +Status: closed + +Source implementation plan: + +- `plans/implementation/python-facade/333-free-threaded-cpython-314t-staged-support.md` + +Source subsystem roadmap: + +- `plans/subsystems/python-facade-roadmap.md` (Milestone 333) + +Repository baseline reviewed: `4949a77acfe4114561bd7cfe59a8458ea1983af7` (Plans 320–325 push); implemented and closed on branch `feat/auto-20261116-7cc8b1dc`. + +Implementation commits or pull requests: + +- Commit `ab418f8` carries the Plan 333 change set and the Plan 334 + registration; PR https://github.com/eggstack/eggserve/pull/7. +- Corrective commit `b6b793b` moves the two macOS arm64 release jobs to + `macos-latest` (Plan 334 finding; see section 10). + +## 1. Executive finding + +The free-threaded slice is implemented and locally qualified on macOS arm64. +The extension now states `#[pymodule(gil_used = false)]` explicitly; a +`cp314-cp314t` wheel builds from the unchanged PyO3 feature set and imports +with the GIL still disabled; the full installed-wheel suite (861 tests, +including the new `test_free_threaded.py`) passes on CPython 3.14.5t; and the +wheel matrix, release-set validator, metadata gate, release workflow, and CI +understand exactly two ABI families with matrix-owned interpreters. + +Both named conditions are now observed. CI run +https://github.com/eggstack/eggserve/actions/runs/45277923657 is green with the +`python-free-threaded` job, and release run +https://github.com/eggstack/eggserve/actions/runs/45283657891 +(`publish_target: none`) reached a green aggregate with the exact 13 +platform/family pairs, including the three `cp314t` wheels. The pinned +manylinux container exposes the declared interpreter at +`/opt/python/cp314-cp314t/bin/python`. No Rust crate API, HTTP, TLS, +confinement, or security behavior changed, and the GIL `cp311-abi3` family is +unchanged across the same run. + +## 2. Requirement-to-evidence matrix + +| Plan requirement | Evidence | Result | Notes | +|---|---|---|---| +| WP-A explicit `gil_used = false` declaration | `crates/eggserve-python/src/lib.rs` (`#[pymodule(gil_used = false)]` + comment naming the three targets); free-threaded `cargo check` passed | pass | GIL builds compile unchanged | +| WP-B tunnel contention guard | `server/tunnel_bridge.rs` `recv_in_flight` compare-exchange; explicit `concurrent Tunnel.recv is not supported`; reset on every exit path | pass | race covered by `test_tunnel_recv_contention_is_explicit` | +| WP-B one-shot/iterator contract documented | doc comments on `PyRequestBody`, `PyBodyChunkIterator`, `PyResponse`; `docs/python-api.md` | pass | no signature change | +| WP-C free-threaded test module | `crates/eggserve-python/tests/test_free_threaded.py` (8 tests: fresh-interpreter import, parallel callbacks, serialized mode, concurrent producers, body-read race, iterator race, tunnel race, restart) | pass | skipped on GIL builds | +| WP-D reproducible build + compile gate | `pyproject.toml` `maturin>=1.14.1,<2.0`; `scripts/check-python-free-threaded-compile.sh` | pass | no PyO3 feature change needed | +| WP-E family-aware matrix and gates | `release/wheel-matrix.toml` (13 required entries / 10 platform tags); `scripts/wheel-matrix.py`; `scripts/check-release-wheel-set.py`; `scripts/check-python-release-metadata.py`; `release.yml` | pass | self-tests cover missing family, wrong triple, duplicate pair | +| WP-F free-threaded CI lane | `.github/workflows/ci.yml` `python-free-threaded` job (`3.14t`, maturin 1.14.1, compile gate, harness) | configured, not observed | requires a push | +| WP-G support tier, docs, classifier | `docs/` (toolchain, packaging, contract, process, capability matrix, Python API/compat, threat model, extension contract, API stability), `SECURITY.md`, `CHANGELOG.md`, skill bullet, Beta classifier | pass | 3.14t Beta on three targets only | +| WP-H closure + promotion gate | this record; promotion gate recorded in the plan | partial | promotion decision deferred to post-CI evidence | + +## 3. Production implementation evidence + +### 3.1 Declaration + +`#[pymodule(gil_used = false)]` replaces the implicit PyO3 >= 0.28 default. +The attribute is a no-op on GIL-enabled interpreters and documents the audited +promise for CPython 3.14t on Linux x86_64 (glibc), macOS arm64, and Windows +x86_64. `grep -n "pymodule" crates/eggserve-python/src/lib.rs` shows exactly +one declaration. + +### 3.2 Tunnel contention + +`PyTunnel` gains a private `recv_in_flight: AtomicBool`. `recv` claims it with +`compare_exchange(false, true, AcqRel, Acquire)` before touching the receiver, +returns `RuntimeError("concurrent Tunnel.recv is not supported")` to a racing +caller, and stores `false` after the inner result (data, EOF, error, or +poisoned/closed lock). No mutex is held across `block_on`. + +### 3.3 Packaging authority + +Every matrix target now declares `abi_family`, `python_tag`, `abi_tag`, +`interpreter`, and `setup_python`. The three free-threaded entries are +`linux-x86_64-glibc-ft`, `macos-arm64-ft`, and `windows-x86_64-ft`, with +artifacts suffixed `-ft`. Uniqueness and completeness are keyed on +`(platform_tag, abi_family)`. The release workflow takes `--interpreter` from +`matrix.interpreter` and setup-python from `matrix.setup_python`; the `abi-proof` +lane remains GIL-only; a `cp314t`-gated step asserts `sys._is_gil_enabled()` +stays false. `scripts/check-release-workflow.py` enforces all four properties. + +### 3.4 CI and harness + +A separate `python-free-threaded` job uses `actions/setup-python` `3.14t`, +`maturin==1.14.1`, the compile-check script, and the shared wheel harness. The +harness derives site-packages from `sysconfig.get_paths()["purelib"]` (a +free-threaded interpreter uses `lib/python3.14t/site-packages`) and, when +`Py_GIL_DISABLED` is set, runs the installed wheel under `-X gil=0` with +`-W error::RuntimeWarning` before the suite. + +### 3.5 Documentation + +All support statements now name the three targets and the Beta tier; no doc +claims 3.13t, 3.15t, `abi3t`, PyPy, ARMv7, Windows arm64, or musl +free-threaded support. The Plan 267 report keeps its historical text and the +additive correction banner added at approval time. + +## 4. Verification executed + +### Commands run + +```bash +# Compile configurations (temp copy; the repository worktree is nested under the +# primary checkout, so Cargo workspace discovery fails for the excluded crate) +PYO3_PYTHON=/Library/Frameworks/Python.framework/Versions/3.14/bin/python3.14 \ + cargo check --manifest-path crates/eggserve-python/Cargo.toml --locked +PYTHON= bash scripts/check-python-free-threaded-compile.sh +cargo clippy --manifest-path crates/eggserve-python/Cargo.toml --lib -- -D warnings +cargo fmt --all -- --check + +# Installed-wheel build, smoke, and full suite on CPython 3.14.5t +PYTHON= bash scripts/test-python-wheel.sh + +# Static gates +python3 scripts/verify-conformance-matrix.py +python3 scripts/check-crate-topology.py +python3 scripts/wheel-matrix.py validate +python3 scripts/wheel-matrix.py self-test +python3 scripts/check-release-wheel-set.py --self-test +python3 scripts/check-python-release-metadata.py +python3 scripts/check-release-workflow.py +python3 scripts/check-release-workflow.py --self-test +``` + +### Results + +- GIL `cargo check`: pass (8.17 s, cached). +- Free-threaded compile check: pass (3.06 s, cached); `Py_GIL_DISABLED` confirmed. +- `cargo clippy ... -D warnings`: pass. +- Workspace `cargo fmt --all -- --check`: pass. +- Wheel: `eggserve-0.2.5-cp314-cp314t-macosx_11_0_arm64.whl`; maturin 1.14.1 + warned that `abi3` does not support 3.14t and built version-specifically, as + expected; wheel composition check passed (no bundled executable). +- Installed-wheel assertions: mypy typing smoke pass; import boundary pass; + free-threaded GIL assertion pass; canonical Python/CLI/subprocess examples pass. +- Free-threaded full suite: `Ran 861 tests in 124.442s` — `OK` on CPython + 3.14.5t (`3.14.5+freethreaded-macos-aarch64-none`), macOS arm64. +- GIL family (invariant proof): wheel + `eggserve-0.2.5-cp311-abi3-macosx_11_0_arm64.whl` builds; the same harness + reports `Ran 861 tests in 122.544s` — `OK (skipped=8)` on CPython 3.14. The + eight skips are the new free-threaded-only tests, by design; the tag and + behavior are unchanged. +- Packaging gates: matrix validate + self-test, wheel-set self-test, metadata + gate, and workflow gate + self-test all pass; both workflow YAML files parse + (5 CI jobs, 10 release jobs). +- `git diff --check`: clean. +- Repository fast gate (`./scripts/verify.sh fast`): all preceding steps passed, + then the wrapper failed at the documented pre-existing macOS test + `application_server_qualification_297::app_bounded_body_accepts_and_over_limit_rejects` + (`ConnectionReset`, exit 101), exactly as recorded in Plan 325's closure. The + wrapper aborts there, so the later TLS/examples lanes did not run. This is + unrelated to Plan 333 (no workspace crate changed). + +### Observed external evidence + +CI run https://github.com/eggstack/eggserve/actions/runs/45277923657 +(head `ab418f8`) — five job groups, all green: + +- `python-free-threaded` (3m45s): `setup-python` `3.14t` resolved + CPython 3.14.10 (x64-freethreaded); the compile check reported + `version: 3.14 (Py_GIL_DISABLED)`; maturin built + `eggserve-0.2.5-cp314-cp314t-manylinux_2_34_x86_64.whl`; the harness + reported `GIL stays disabled on the installed free-threaded wheel` and + `Ran 861 tests in 115.579s` — `OK`. +- `python` (3m20s): `eggserve-0.2.5-cp311-abi3-manylinux_2_34_x86_64.whl`; + `Ran 861 tests in 114.955s` — `OK (skipped=8)` (the free-threaded-only + tests skip on a GIL build). +- `rust` (19m56s), `platform-compile` macOS (45s) and Windows (3m50s), and + `supply-chain` (5m13s) all green. + +Release run https://github.com/eggstack/eggserve/actions/runs/45283657891 +(head `b6b793b`, `publish_target: none`) — preflight, all 13 builds, the +four qualifiers, `abi-proof`, and `aggregate` green; +`publish-testpypi`, `publish-pypi`, and `post-publish` skipped by their +existing conditions: + +- Linux ft: `Found CPython 3.14t at /opt/python/cp314-cp314t/bin/python` + in the pinned manylinux_2_17 container → + `eggserve-0.2.5-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl`. +- macOS ft: `Found CPython 3.14t at + /Library/Frameworks/PythonT.framework/Versions/3.14/bin/python3.14t` → + `eggserve-0.2.5-cp314-cp314t-macosx_11_0_arm64.whl`. +- Windows ft: `eggserve-0.2.5-cp314-cp314t-win_amd64.whl`. +- `abi-proof` (CPython 3.11–3.15, 5/5 green) installs only + `eggserve-0.2.5-cp311-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl` + and runs `release_smoke.py` + `abi_smoke.py`; the GIL family's tags and + count are unchanged. +- `aggregate`: `Wheels found: 13`, `OK: required target set is exact (13 + platform/family pairs)`, `Platform targets found: 10`; the + `release-wheel-set` artifact (ID 14871003335) contains the 13 wheels plus + `MANIFEST`. + +### Not run + +- Publication (TestPyPI/PyPI), tags, and GitHub Releases: out of scope for + Plans 333 and 334. +- TSan: no TSan-instrumented CPython is available; Plan 334's three + contention-soak records are the documented substitute. + +## 5. Invariant review + +| Invariant | Evidence | +|---|---| +| GIL `cp311-abi3` tags/count/behavior unchanged | Matrix keeps 10 GIL targets with `python3.11`/`cp311`/`abi3`; metadata gate asserts the declared set; GIL wheel built as `cp311-abi3` and its suite is green (`OK (skipped=8)`) | +| No new `unsafe`; `unsafe_code = "deny"` | Only safe Rust changed; crate lint unchanged | +| Confinement, TLS, framing, crate ownership untouched | No changes outside `crates/eggserve-python` source and packaging/docs; topology gate green | +| One-shot bodies/responses; HEAD suppression | Existing tests green; docs state the contract; no body path logic changed | +| No lock held across a blocking wait | Tunnel claim is atomic; receiver mutex is released before `block_on` (unchanged pattern) | +| No new public Python API or config knob | No `#[pyfunction]`/signature/config field added | +| Claims bounded by evidence | Docs and classifier limited to 3.14t Beta on three targets; closure marks local-only evidence | + +## 6. Failure and recovery review + +- One-shot contention: exactly one `RequestBody.read()` wins; the loser gets + `RequestBodyConsumedError` (tested). Concurrent iterator pulls raise a + structural borrow error or `StopIteration`, never a crash (tested). +- Tunnel contention: the racing `recv` fails explicitly; the guard resets, and + a later call reports the true terminal state (tested after EOF). +- Restart/shutdown: start/stop under a concurrent callback burst is stable + (tested); existing shutdown/drain suites remain green. +- Producer budget and teardown observation (Plan 322) are unchanged and green + under 3.14t, including the `b""`-forever and 503-exhaustion tests. + +## 7. Migration and compatibility review + +Additive family; no source or API change. Existing handlers may now run in +parallel on 3.14t; this is documented, and `max_python_callbacks=1` restores +serialization. Wheel version stays `0.2.5`; publication is a separate manual +action and was not performed. Rollback within a release window is removing the +three `-ft` matrix entries. + +## 8. Security review + +No new dependency, `unsafe`, policy field, or confinement path. The import +assertion proves the module never asks a free-threaded interpreter to +re-enable the GIL. Handler parallelism is bounded by the existing callback +permit and producer budget; timeouts still close the HTTP request rather than +Python code. No request/response content is logged by the new paths. + +## 9. Documentation and operations + +Updated: `docs/toolchain-support.md`, `docs/python-packaging.md`, +`docs/release-contract.md`, `docs/release-process.md`, +`docs/library-capability-matrix.md`, `docs/python-api.md`, +`docs/python-http-server-compatibility.md`, `docs/threat-model.md`, +`docs/extension-contract.md`, `docs/api-stability.md`, `SECURITY.md`, +`CHANGELOG.md`, `.opencode/skills/eggserve-dev/SKILL.md`, and the pyproject +classifier. Static guards: family-aware matrix/wheel-set/metadata/workflow +validators and `scripts/check-python-free-threaded-compile.sh`. + +## 10. Unresolved findings + +| Severity | Finding | Status | Evidence | +|---|---|---|---| +| medium | `python-free-threaded` CI job and the three-target release aggregate had not run | resolved | CI run 45277923657 (job green, 861 tests on 3.14.10t); release run 45283657891 (13-pair aggregate, three `-ft` wheels) | +| medium | The manylinux image interpreter path was unverified | resolved | `Found CPython 3.14t at /opt/python/cp314-cp314t/bin/python`; wheel tagged `manylinux_2_17_x86_64` | +| low | `verify.sh fast` aborts on the documented pre-existing macOS `ConnectionReset` test (Plan 325 closure) | open | Unchanged; CI runs the same lanes directly | +| low | The excluded Python crate has pre-existing rustfmt drift (not introduced here, not a CI gate) | open | Not a CI gate; optional cleanup in a separate change | +| low | TSan/soak remain optional promotion evidence | resolved (substitute) | Plan 334 soak records `334-soak-{1,2,3}.json`: zero failures across three 120 s runs | +| low | The `macos-14` arm64 runner label stopped provisioning during the first release dispatch | resolved | Attempts 1–2 cancelled one second after assignment with `runner_id 0`; commit `b6b793b` moved the matrix to `macos-latest`, and both arm64 wheels built | +| low | Manual `platform-qualification.yml` still targets `macos-14` | open | Outside Plans 333/334; needs the same refresh before its next dispatch | + +## 11. Roadmap disposition + +Milestone 333 is closed. The implementation, local suite, static gates, docs, +and both named evidence conditions are complete: the `python-free-threaded` CI +job is green and a `publish_target: none` release aggregate contains the exact +13 platform/family pairs, including the three `cp314t` wheels, with the GIL +family unchanged. No medium-or-higher finding attributable to Plan 333 +remains. Plan 334 met the promotion gate and the owner confirmed the +aggregate-as-release reading, so the family is now Stable; the decision is +recorded in `plans/closure/python-facade/334-free-threaded-314t-qualification-and-tier-decision.md`. + +## 12. Registry updates + +- `plans/registry.md`: Python facade current milestone and row 333 become + `closed`, linking this record. +- `plans/subsystems/python-facade-roadmap.md`: status line, dependency graph, + and milestone table record the closure. +- Plan 334 remains the next milestone (registered at `328` as the next number). diff --git a/plans/closure/python-facade/334-free-threaded-314t-qualification-and-tier-decision.md b/plans/closure/python-facade/334-free-threaded-314t-qualification-and-tier-decision.md new file mode 100644 index 0000000..bd3031c --- /dev/null +++ b/plans/closure/python-facade/334-free-threaded-314t-qualification-and-tier-decision.md @@ -0,0 +1,244 @@ +# Python Facade Milestone 334 — Closure Status + +> **Amendment — Milestone 330 (2026-11-28).** Renumbered from 327 at merge; +> `main` already assigns 327 to the TLS substrate corrective. The Stable +> promotion concluded below is **reversed**: the soak records name no commit, +> wheel filename, or host and cover one macOS arm64 host. The family is +> **Beta**; Milestone 332 owns the evidence and the decision. + +Status: closed + +Source implementation plan: + +- `plans/implementation/python-facade/334-free-threaded-314t-qualification-and-tier-decision.md` + +Source subsystem roadmap: + +- `plans/subsystems/python-facade-roadmap.md` (Milestone 334) + +Repository baseline reviewed: `4949a77acfe4114561bd7cfe59a8458ea1983af7` +plus the Plan 333 change set; executed on branch +`feat/auto-20261116-7cc8b1dc`. + +Implementation commits or pull requests: + +- `ab418f8` — Plan 333 change set plus this plan's registration. +- `5327704` — contention soak script and three records. +- `fa6980d` — tier-explicit classifier gate with `--self-test`. +- `b6b793b` — macOS arm64 release runners moved to `macos-latest`. +- Pull request https://github.com/eggstack/eggserve/pull/7 (open; this plan + did not merge it). + +## 1. Executive finding + +Both of Plan 333's named conditions are observed, so Plan 333 is closed. The +free-threaded family is qualified on all three targets by a green +`python-free-threaded` CI job and a green 13-pair release aggregate produced +with `publish_target: none`, and the contention substitute for TSan passes +three 120-second runs with zero failures. + +The promotion gate is met and confirmed: the owner confirmed during execution +that a no-publish aggregate satisfies the gate's release leg. The tier +decision is therefore **promote to Stable** +(`Programming Language :: Python :: Free Threading :: 3 - Stable`), applied as +a metadata-and-documentation change only (section 7). No product behavior, +public API, dependency, platform, or publication change was made. + +## 2. Requirement-to-evidence matrix + +| Work package | Requirement | Evidence | Result | +|---|---|---|---| +| A | Commit and push the Plan 333 change set; open a PR; observe all CI jobs | commit `ab418f8`; PR #7; CI run 45277923657 (five job groups green) | pass | +| A | The free-threaded job shows the 3.14t interpreter, compile check, installed wheel, GIL-free assertion, and suite count | `version: 3.14 (Py_GIL_DISABLED)`; CPython 3.14.10 x64-freethreaded; `GIL stays disabled on the installed free-threaded wheel`; `Ran 861 tests in 115.579s` — `OK` | pass | +| B | Dispatch `release.yml` on the branch with `publish_target: none`; reach a green aggregate | release run 45283657891; preflight, 13 builds, four qualifiers, `abi-proof`, aggregate all green; publish jobs and `post-publish` skipped | pass | +| B | The aggregate contains exactly the declared set, including the three `-ft` wheels | `Wheels found: 13`; `OK: required target set is exact (13 platform/family pairs)`; `Platform targets found: 10` | pass | +| B | Record the Linux container interpreter actually used | `Found CPython 3.14t at /opt/python/cp314-cp314t/bin/python` in the pinned manylinux_2_17 container | pass | +| B | `abi-proof` still proves the unchanged GIL family | 5/5 lanes (CPython 3.11-3.15), each installing only `eggserve-0.2.5-cp311-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl` | pass | +| C | Plan 333 closure becomes `closed` with both run URLs and no medium-or-higher finding | `plans/closure/python-facade/333-free-threaded-cpython-314t-staged-support.md` | pass | +| D | Stdlib-only soak script with `--self-test` and three records | `scripts/soak-python-free-threaded.py`; 16/16 self-test checks; `plans/closure/python-facade/334-soak-{1,2,3}.json` | pass | +| D | Document the TSan decision | section 5 | pass | +| E | Evaluate all four promotion criteria | section 6 | pass | +| E | Decide the tier and update metadata/docs/gate only for a promotion | section 7 (promoted to Stable after owner confirmation) | pass | +| F | Closure record, registry, roadmap, next number | this record; registry rows 333/334; roadmap; next number `335` | pass | + +## 3. Named condition 1 — CI + +CI run https://github.com/eggstack/eggserve/actions/runs/45277923657 +(head `ab418f8`) — five job groups, all green. + +`python-free-threaded` (3m45s): + +- `actions/setup-python` `3.14t` resolved CPython 3.14.10 at + `/opt/hostedtoolcache/Python/3.14.10/x64-freethreaded`. +- The compile check reported `version: 3.14 (Py_GIL_DISABLED)`. +- Maturin built `eggserve-0.2.5-cp314-cp314t-manylinux_2_34_x86_64.whl` + (the 2_34 tag is the ubuntu-latest host floor; the release container emits + the declared 2_17 tag). +- The harness reported `GIL stays disabled on the installed free-threaded + wheel` and `Ran 861 tests in 115.579s` — `OK`. + +`python` (3m20s): `eggserve-0.2.5-cp311-abi3-manylinux_2_34_x86_64.whl`; +`Ran 861 tests in 114.955s` — `OK (skipped=8)` (the eight free-threaded-only +tests skip on a GIL build). + +`rust` (19m56s), `platform-compile` macOS (45s) and Windows (3m50s), and +`supply-chain` (5m13s) are green. + +## 4. Named condition 2 — release aggregate + +Release run https://github.com/eggstack/eggserve/actions/runs/45283657891 +(head `b6b793b`, `publish_target: none`): + +- Preflight green (supply-chain audits, metadata, matrix/wheel-set/workflow + self-tests). +- All 13 build entries green. The three free-threaded artifacts: + - `eggserve-0.2.5-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl` + (`Found CPython 3.14t at /opt/python/cp314-cp314t/bin/python`); + - `eggserve-0.2.5-cp314-cp314t-macosx_11_0_arm64.whl` + (`Found CPython 3.14t at /Library/Frameworks/PythonT.framework/Versions/3.14/bin/python3.14t`); + - `eggserve-0.2.5-cp314-cp314t-win_amd64.whl`. +- The four qualifiers (native AArch64 glibc, AArch64 musl in Alpine, Native + Windows ARM64) are green. +- `abi-proof`: five lanes (CPython 3.11, 3.12, 3.13, 3.14, 3.15) green; every + lane installs the same + `eggserve-0.2.5-cp311-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl` + and runs `release_smoke.py` plus `abi_smoke.py`. +- `aggregate`: `Wheels found: 13`, `OK: required target set is exact (13 + platform/family pairs)`, `Platform targets found: 10`. The + `release-wheel-set` artifact (ID 14871003335) holds the 13 wheels plus + `MANIFEST`. +- `publish-testpypi`, `publish-pypi`, and `post-publish` are skipped by their + existing conditions; nothing was published. + +### 4.1 First dispatch and the macOS runner corrective + +The first dispatch (run 45281528704, head `ab418f8`) failed before aggregate: +both `macos-14` arm64 jobs were cancelled one second after assignment with +`runner_id 0` and no steps, on attempt 1 and again on attempt 2. The other 11 +builds succeeded, including the Linux and Windows free-threaded wheels, but +`abi-proof` and `aggregate` were skipped. + +This was diagnosed as runner provisioning, not a build defect: the CI +`platform-compile (macos-latest)` job provisioned an arm64 runner in 45 s on +the same day, and the 2026-10-22 release had built macOS arm64 on `macos-14` +successfully. Commit `b6b793b` moved the two arm64 entries (and the +post-publish macOS smoke) to `macos-latest`; both arm64 wheels then built in +the rerun. The platform tag stays pinned by `MACOSX_DEPLOYMENT_TARGET 11.0` +and `platform_tag`, so no support claim changed. + +## 5. Contention evidence and the TSan substitute + +A TSan-instrumented CPython is not available in this environment, and +Rust-only TSan would not observe Python callback state (the handlers, bodies, +streams, and tunnels that the free-threaded contract is about). Plan 333 +permits a documented substitute; this plan's substitute is +`scripts/soak-python-free-threaded.py` plus the existing contention tests. + +The script is stdlib-only, uses loopback only, logs no request or response +content, and runs two server phases (a stop/start cycle) of concurrent +buffered POSTs with payload digests, streamed responses with exact byte +verification, one-shot `RequestBody.read()` races, concurrent +`BodyChunkIterator.__next__` races, tunnel upgrades with concurrent +`Tunnel.recv` contention, and client disconnects during a slow stream. It +exits non-zero on any unexpected error, content mismatch, invariant +violation, GIL re-enable, or request-budget shortfall. + +| Record | Duration | HTTP requests | Failures | Tunnel cycles | Disconnects | Handler peak | Threads at exit | Peak RSS | +|---|---|---|---|---|---|---|---|---| +| `334-soak-1.json` | 120.852 s | 84,769 | 0 | 582 | 592 | 8 | 1 | 585.6 MB | +| `334-soak-2.json` | 120.820 s | 80,411 | 0 | 576 | 585 | 8 | 1 | 525.7 MB | +| `334-soak-3.json` | 120.771 s | 82,748 | 0 | 579 | 590 | 8 | 1 | 629.9 MB | + +All three ran on CPython 3.14.5 freethreading (macOS arm64) with +`--requests 400 --workers 8 --duration 120`, `max_python_callbacks=8`, +`request_body_mode=buffer`, `max_request_body_bytes=1048576`. The handler +peak equals the permit bound in both phases of every run, the GIL is +disabled before and after, and no worker thread survives a phase. +`--self-test` passes 16/16 checks. No timing threshold is asserted. + +## 6. Promotion gate evaluation + +| Plan 333 criterion | Status | Evidence | +|---|---|---| +| One release with the family `required` and the aggregate green on all three targets | met | release run 45283657891; matrix tier `required`; three `-ft` wheels in the 13-pair aggregate | +| GIL family unchanged across that release | met | `abi-proof` 5/5 on CPython 3.11-3.15 installing one `cp311-abi3` wheel; 10 GIL wheels unchanged | +| Adversarial/contention pass (TSan or documented substitute) | met | three soak runs, zero failures; section 5 | +| No unresolved medium-or-higher finding in the Plan 333 closure | met | both mediums resolved; remaining findings are low (Plan 333 closure section 10) | + +The plan additionally requires the owner to confirm that a +`publish_target: none` aggregate satisfies the gate's release leg. The owner +confirmed during execution (questionnaire response, 2026-11-23) that the +no-publish aggregate counts, so all four criteria are met and confirmed. + +## 7. Tier decision + +**Promote to Stable** (`Programming Language :: Python :: Free Threading :: +3 - Stable`) on Linux x86_64 (glibc), macOS arm64, and Windows x86_64 only. +The owner confirmed that the no-publish aggregate satisfies the gate's release +leg; all four criteria in section 6 are met. + +Applied in this change set: + +1. `crates/eggserve-python/pyproject.toml`: the tier-3 classifier replaces + the tier-2 one. +2. `scripts/check-python-release-metadata.py`: + `EXPECTED_FREE_THREADING_TIER = 3`; the gate requires exactly one + free-threading classifier at the declared tier, and its `--self-test` + covers both configurations (10/10 checks). +3. Tier statements updated: `docs/toolchain-support.md` (support table, + promotion paragraph, PyO3 note, wheel-matrix note, verification table), + `docs/python-api.md`, `docs/python-http-server-compatibility.md`, + `docs/python-packaging.md`, `docs/release-contract.md`, + `docs/release-process.md`, `docs/library-capability-matrix.md`, + `SECURITY.md`, `CHANGELOG.md`, and the `eggserve-dev` skill bullet. + +No runtime, API, dependency, wheel-tag, or platform change; the wheel set and +its tags are identical to the qualified aggregate. + +## 8. Invariant review + +| Invariant | Evidence | +|---|---| +| No product behavior, API, runtime config, wire format, or dependency change | Only packaging scripts, soak tooling, matrix runner labels, plans, and one test-free gate script changed | +| GIL `cp311-abi3` family unchanged | 10 GIL wheels in the aggregate; `abi-proof` 5/5; CI GIL suite `OK (skipped=8)` | +| No publication, version bump, tag, or environment approval | `publish_target: none`; publish and post-publish jobs skipped | +| Every support statement backed by an observed run | sections 3, 4, 6; local soak labelled local | +| No claim outside 3.14t on the three targets | matrix still declares exactly three `cp314t` entries; metadata gate green | +| `unsafe_code = "deny"`, confinement, TLS, framing, topology untouched | no Rust source changed; topology gate green in CI | +| A lane failure was fixed only with matrix/workflow wiring | `b6b793b` changes runner labels only | + +## 9. Failure and recovery review + +- **CI lane failures:** none. All five job groups were green on the first + run. +- **Release lane failure:** the macOS arm64 jobs were cancelled by runner + provisioning on two attempts. Diagnosis used the runner id, the step list, + the successful `macos-latest` CI lane, and the 2026-10-22 release history; + the corrective changed only runner labels, and the whole workflow was + redispatched (never a hand-assembled aggregate). +- **Soak failures:** none. The three runs are from clean processes; no run + was shortened or reduced after a failure. +- **Cancellation and restart:** each soak phase stops its server in a + `finally` block; the second phase is the stop/start cycle, and no worker + thread survives. +- **Stale evidence:** the first dispatch (45281528704) is recorded as an + infrastructure failure, not as aggregate evidence; only 45283657891 is + cited for the aggregate. + +## 10. Residual findings + +| Severity | Finding | Status | Note | +|---|---|---|---| +| low | `.github/workflows/platform-qualification.yml` still targets `macos-14` | open | Manual workflow, outside this plan; refresh before its next dispatch | +| low | `./scripts/verify.sh fast` aborts on the pre-existing macOS `ConnectionReset` test (Plan 325 closure) | open | Unchanged; CI runs the same lanes directly | +| low | The excluded Python crate has pre-existing rustfmt drift | open | Not a CI gate | + +No medium-or-higher finding remains. + +## 11. Registry updates + +- `plans/registry.md`: Python facade current-milestone note and rows 333 and + 334 become `closed`; next number `335`. +- `plans/subsystems/python-facade-roadmap.md`: status line, dependency graph, + milestone sections, and the milestone table record both closures. +- Plan 334's header becomes `implemented` with this closure linked. diff --git a/plans/closure/python-facade/334-soak-1.json b/plans/closure/python-facade/334-soak-1.json new file mode 100644 index 0000000..b7a5a3b --- /dev/null +++ b/plans/closure/python-facade/334-soak-1.json @@ -0,0 +1,86 @@ +{ + "config": { + "duration_requested_seconds": 120.0, + "max_python_callbacks": 8, + "max_request_body_bytes": 1048576, + "pace_ms": 10.0, + "request_body_mode": "buffer", + "requests_minimum": 400, + "workers": 8 + }, + "duration_seconds": 120.852, + "gil": { + "disabled_build": true, + "enabled_after": false, + "enabled_before": false + }, + "interpreter": { + "build": "3.14.5 free-threading build (main, May 10 2026, 19:22:49) [Clang 22.1.3 ]", + "debug_build": false, + "gil_disabled_build": true, + "implementation": "cpython", + "machine": "arm64", + "os": "macOS-26.6.2-arm64-arm-64bit-Mach-O", + "platform": "macosx-11.0-arm64", + "version": "3.14.5" + }, + "phases": [ + { + "client_peak_concurrency": 8, + "index": 0, + "seconds": 60.207, + "server_peak_concurrency": 8, + "stuck_threads": [], + "tunnel_queue_remaining": 0 + }, + { + "client_peak_concurrency": 8, + "index": 1, + "seconds": 60.184, + "server_peak_concurrency": 8, + "stuck_threads": [], + "tunnel_queue_remaining": 0 + } + ], + "plan": "334", + "problems": [], + "qualified": true, + "resources": { + "peak_rss_bytes": 614023168, + "threads_at_end": 1 + }, + "started_at": "2026-11-23T22:20:05Z", + "tool": "soak-python-free-threaded", + "totals": { + "by_scenario": { + "disconnect": { + "fail": 0, + "ok": 592 + }, + "iter": { + "fail": 0, + "ok": 21193 + }, + "post": { + "fail": 0, + "ok": 21194 + }, + "race": { + "fail": 0, + "ok": 21192 + }, + "stream": { + "fail": 0, + "ok": 21190 + }, + "tunnel": { + "fail": 0, + "ok": 582 + } + }, + "errors": [], + "fail": 0, + "http_requests": 84769, + "ok": 85943 + } +} diff --git a/plans/closure/python-facade/334-soak-2.json b/plans/closure/python-facade/334-soak-2.json new file mode 100644 index 0000000..b7e2ca4 --- /dev/null +++ b/plans/closure/python-facade/334-soak-2.json @@ -0,0 +1,86 @@ +{ + "config": { + "duration_requested_seconds": 120.0, + "max_python_callbacks": 8, + "max_request_body_bytes": 1048576, + "pace_ms": 10.0, + "request_body_mode": "buffer", + "requests_minimum": 400, + "workers": 8 + }, + "duration_seconds": 120.82, + "gil": { + "disabled_build": true, + "enabled_after": false, + "enabled_before": false + }, + "interpreter": { + "build": "3.14.5 free-threading build (main, May 10 2026, 19:22:49) [Clang 22.1.3 ]", + "debug_build": false, + "gil_disabled_build": true, + "implementation": "cpython", + "machine": "arm64", + "os": "macOS-26.6.2-arm64-arm-64bit-Mach-O", + "platform": "macosx-11.0-arm64", + "version": "3.14.5" + }, + "phases": [ + { + "client_peak_concurrency": 8, + "index": 0, + "seconds": 60.134, + "server_peak_concurrency": 8, + "stuck_threads": [], + "tunnel_queue_remaining": 0 + }, + { + "client_peak_concurrency": 8, + "index": 1, + "seconds": 60.216, + "server_peak_concurrency": 8, + "stuck_threads": [], + "tunnel_queue_remaining": 0 + } + ], + "plan": "334", + "problems": [], + "qualified": true, + "resources": { + "peak_rss_bytes": 551239680, + "threads_at_end": 1 + }, + "started_at": "2026-11-23T22:22:07Z", + "tool": "soak-python-free-threaded", + "totals": { + "by_scenario": { + "disconnect": { + "fail": 0, + "ok": 585 + }, + "iter": { + "fail": 0, + "ok": 20103 + }, + "post": { + "fail": 0, + "ok": 20103 + }, + "race": { + "fail": 0, + "ok": 20102 + }, + "stream": { + "fail": 0, + "ok": 20103 + }, + "tunnel": { + "fail": 0, + "ok": 576 + } + }, + "errors": [], + "fail": 0, + "http_requests": 80411, + "ok": 81572 + } +} diff --git a/plans/closure/python-facade/334-soak-3.json b/plans/closure/python-facade/334-soak-3.json new file mode 100644 index 0000000..cd02aaa --- /dev/null +++ b/plans/closure/python-facade/334-soak-3.json @@ -0,0 +1,86 @@ +{ + "config": { + "duration_requested_seconds": 120.0, + "max_python_callbacks": 8, + "max_request_body_bytes": 1048576, + "pace_ms": 10.0, + "request_body_mode": "buffer", + "requests_minimum": 400, + "workers": 8 + }, + "duration_seconds": 120.771, + "gil": { + "disabled_build": true, + "enabled_after": false, + "enabled_before": false + }, + "interpreter": { + "build": "3.14.5 free-threading build (main, May 10 2026, 19:22:49) [Clang 22.1.3 ]", + "debug_build": false, + "gil_disabled_build": true, + "implementation": "cpython", + "machine": "arm64", + "os": "macOS-26.6.2-arm64-arm-64bit-Mach-O", + "platform": "macosx-11.0-arm64", + "version": "3.14.5" + }, + "phases": [ + { + "client_peak_concurrency": 8, + "index": 0, + "seconds": 60.096, + "server_peak_concurrency": 8, + "stuck_threads": [], + "tunnel_queue_remaining": 0 + }, + { + "client_peak_concurrency": 8, + "index": 1, + "seconds": 60.206, + "server_peak_concurrency": 8, + "stuck_threads": [], + "tunnel_queue_remaining": 0 + } + ], + "plan": "334", + "problems": [], + "qualified": true, + "resources": { + "peak_rss_bytes": 660537344, + "threads_at_end": 1 + }, + "started_at": "2026-11-23T22:24:08Z", + "tool": "soak-python-free-threaded", + "totals": { + "by_scenario": { + "disconnect": { + "fail": 0, + "ok": 590 + }, + "iter": { + "fail": 0, + "ok": 20686 + }, + "post": { + "fail": 0, + "ok": 20687 + }, + "race": { + "fail": 0, + "ok": 20686 + }, + "stream": { + "fail": 0, + "ok": 20689 + }, + "tunnel": { + "fail": 0, + "ok": 579 + } + }, + "errors": [], + "fail": 0, + "http_requests": 82748, + "ok": 83917 + } +} diff --git a/plans/implementation/python-facade/330-free-threaded-314t-branch-adoption.md b/plans/implementation/python-facade/330-free-threaded-314t-branch-adoption.md new file mode 100644 index 0000000..74cef7c --- /dev/null +++ b/plans/implementation/python-facade/330-free-threaded-314t-branch-adoption.md @@ -0,0 +1,507 @@ +# Python Facade Milestone 330 — Adopt the free-threaded CPython 3.14t family (Beta) + +Status: ready for handoff + +Repository baseline: `origin/main` `5fdd7da801056e00a8b20bb885aaf9641f3a3c3c` +(worktree `feat/auto-20261128-fb4f0bec`). Adjacent unmerged branch +`feat/auto-20261116-7cc8b1dc`, tip `6e3003f` ("Plan 327: promote the +free-threaded family to Stable"), merge base `4949a77`. + +Source roadmap: + +- `plans/subsystems/python-facade-roadmap.md#7` (milestones) + +Long-term requirements: + +- `plans/000-long-term-specification.md#2` (Python `http.server`-shaped + facade and handler-only `lowlevel` substrate) +- `plans/001-terminology-and-domain-model.md` (`Request`, `Response`, + `RequestBody`, `Service`) +- `plans/002-long-term-roadmap.md` (phase 4) + +Applicable ADRs: none (no accepted ADR governs the Python bridge or the wheel +support tiers). + +Primary class: capability (a new wheel family) with invariant obligations. + +## 1. Objective + +Land the six-commit adjacent free-threaded branch on `main` as a **Beta** +wheel family: one additive `cp314-cp314t` family for CPython 3.14t on Linux +x86_64 (glibc), macOS arm64, and Windows x86_64; an explicit +`#[pymodule(gil_used = false)]` declaration; a free-threaded CI lane; the +free-threaded concurrency tests; family-aware wheel-matrix and release +validators; and documentation that states Beta, not Stable. + +The user-facing tier is deliberately **Beta** at the end of this milestone. +The branch tip flips the family to Stable; this milestone keeps everything +else from that commit and reverses only the promotion, because the +qualification evidence required for Stable is not complete (Section 3.4) and +is owned by Milestone 332. + +## 2. Why this milestone is ready + +- The adjacent branch is code-complete and self-tested: 8 free-threaded tests, + a `python-free-threaded` CI job, a compile check, family-aware validators + with self-tests, and three `-ft` matrix entries. +- The pre-merge `git merge-tree --write-tree origin/main 6e3003f` produced a + tree with conflicts only in `CHANGELOG.md` and `plans/registry.md`. At merge + time `plans/subsystems/python-facade-roadmap.md` conflicted as well, because + the plan-set commit edited the same roadmap the branch edits; every source, + workflow, script, test, and other doc file auto-merged. +- The current `main` state is strictly worse than the branch: the extension + already advertises `Py_MOD_GIL_NOT_USED` and runs GIL-free from a source + build, while the docs claim free-threaded is unsupported and Plan 267's + rationale for that claim is inverted (Section 3.1). +- Plan 267 Track A is a closed DEFERRED gate; it does not block this slice, + and the branch supersedes its free-threaded conclusion. + +## 3. Current implementation evidence + +### 3.1 Baseline audit (2026-11-28, this worktree) + +- `crates/eggserve-python/Cargo.toml:45` declares `pyo3 = "0.29.2"`; the + committed lock resolves **0.29.3**. PyO3 0.28.0 made free-threading + **opt-out** (`pyo3-0.29.2/CHANGELOG.md`: "Support for free-threaded Python + is now opt-out rather than opt-in"), so the bare `#[pymodule]` at + `crates/eggserve-python/src/lib.rs:1670` emits `Py_MOD_GIL_NOT_USED` + (`pyo3-macros-backend-0.29.3/src/module.rs:394`). +- A clean `git archive` of this commit built with CPython 3.14.5 + free-threading produced `eggserve-0.2.5-cp314-cp314t-macosx_11_0_arm64.whl`; + `sys._is_gil_enabled()` stayed `False` before import, after + `import eggserve._native`, and after `import eggserve`. +- Concurrent smoke (`lowlevel.Server`, `max_python_callbacks=8`, 8 client + threads x 5 requests, buffered and streamed): 40/40 correct, maximum + concurrent callbacks 8, 0.134 s. +- The full Python suite on 3.14t: 856 tests, `OK`, 123.4 s (stderr carried + ResourceWarnings, one timeout traceback, and a `RuntimeError: server is + closed` from a `serve_forever` thread; unittest counted none as failures). +- The `cp311-abi3` wheel built from the same tree is rejected by 3.14t pip + ("not a supported wheel on this platform"), so released wheels are not + installable on free-threaded interpreters; only source builds are exposed. +- `release/plan-267-wheel-feasibility.md:30` claims the module "loads + GIL-required by default"; that is false for the locked PyO3 line. + +### 3.2 What the branch adds + +Six commits (`ab418f8`..`6e3003f`), `40 files changed, 4530 insertions`: + +- `crates/eggserve-python/src/lib.rs`: explicit + `#[pymodule(gil_used = false)]` with a doc comment. +- `crates/eggserve-python/src/server/tunnel_bridge.rs`: `recv_in_flight` + CAS so concurrent `Tunnel.recv` raises a typed contention error instead of + a spurious "already closed". +- `crates/eggserve-python/tests/test_free_threaded.py` (353 lines, 8 tests), + skipped on GIL builds. +- `scripts/check-python-free-threaded-compile.sh`: asserts + `Py_GIL_DISABLED` and runs `cargo check --locked` against the `-t` + interpreter. +- `scripts/soak-python-free-threaded.py`: bounded contention soak + (`--requests 400 --workers 8 --duration 120`, JSON record, `qualified`). +- `release/wheel-matrix.toml`: three `required` `-ft` entries + (`cp314-cp314t`) for linux-x86_64-glibc, macos-arm64, windows-x86_64. +- Family-aware `scripts/wheel-matrix.py`, `check-release-wheel-set.py`, + `check-release-workflow.py`, `check-python-release-metadata.py` + (including `EXPECTED_FREE_THREADING_TIER`). +- `.github/workflows/ci.yml`: `python-free-threaded` job on + `setup-python 3.14t`; `.github/workflows/release.yml`: interpreter-driven + build and a GIL-off assertion in the `-ft` smoke. +- Docs and `plans/` records: toolchain-support, python-packaging, + release-contract/process, library-capability-matrix, python-api, + python-http-server-compatibility, SECURITY, CHANGELOG, skill, roadmap, + Plans 326/327 and their closure records. + +### 3.3 Conflict and renumbering map + +- Textual conflicts: `CHANGELOG.md`, `plans/registry.md`. Both sides + append; keep main's entries and add the free-threaded entry in the + unreleased section. +- Plan-number collision: the branch uses **326** and **327**, which `main` + already assigns to the public-bind acknowledgment milestone and the TLS + substrate corrective. The registry's next free number is **330**. + Renumber the branch's implementation and closure records to **333** and + **334** during merge resolution, and leave main's 326/327 untouched. + +### 3.4 Evidence not yet sufficient for Stable + +- `plans/closure/python-facade/334-soak-1.json` (and 2/3, renumbered at merge) record the + interpreter build, platform, arm64, and `qualified: true`, but **no commit + SHA, no wheel filename/tag, and no host identifier**; all three runs are on + one local macOS arm64 interpreter, two minutes apart. +- The release aggregate proves build + smoke on three targets; the full suite + runs on Linux only. No contention soak exists for Linux or Windows. +- The branch's own Plan 327 says "wheel filenames are the authority" and "no + partial promotion", so its own standard is not met by the records as + written. + +Milestone 332 owns that evidence and the Beta→Stable decision. This milestone +must not anticipate it. + +## 4. Invariants that must not regress + +- The GIL `cp311-abi3` family is unchanged: same 10 required targets, same + wheel tags, same `requires-python >= 3.11`, same test results. +- The free-threaded family is additive: no `abi3t`, no CPython 3.13t/3.15t, + no ARMv7, no Windows arm64, no musl free-threaded build. +- `#[pyclass(frozen)]` and the one-shot/single-consumer contracts stay as + documented; no public Rust crate API changes. +- No HTTP, TLS, confinement, or runtime default changes. +- The user-facing tier statement never exceeds the recorded evidence; Beta + is the ceiling for this milestone. +- Plan numbers stay unique; main's 326/327 remain the public-bind and TLS + milestones. +- No publication: the release workflow is exercised with + `publish_target: none` only. + +## 5. Scope + +### In scope + +- Rebase/merge the adjacent branch onto current `main`. +- Renumber the branch's plan and closure records (326/327 -> 333/334) and + update every cross-reference. +- Keep the explicit GIL declaration, CI lane, tests, validators, matrix + entries, tunnel `recv` guard, and docs. +- Set the tier to **Beta** in the classifier, metadata gate, and every doc + the branch touched. +- Add one executable guard that fails if the declaration and the recorded + tier drift (Section 7, work package D). +- Re-run the gates and merge. + +### Explicitly out of scope + +- Beta->Stable promotion (Milestone 332). +- Concurrency-contract fixes beyond what the branch carries (Milestone 331). +- Publication to PyPI/crates.io or a release tag. +- New platforms, `abi3t`, 3.13t/3.15t, or any GIL-family change. +- Rewriting Plan 267; only a short superseded pointer is added (work package + E). The archived record keeps its original text. + +## 6. Required production changes + +### Crates and ownership + +No crate graph changes. `crates/eggserve-python` stays excluded from the +workspace with its own lockfile. `scripts/check-crate-topology.py` must stay +green. + +### Config and policy + +None. No default, limit, or policy value changes. + +### Protocol and compatibility + +The wheel family is additive. Python compatibility remains HTTP/1.1-only. +The `cp311-abi3` compatibility declaration is unchanged. + +### Runtime and concurrency + +Take the branch's tunnel `recv` CAS guard. No other runtime change. + +### Frontend or operator surface (CLI / Python) + +The `-ft` family is installable for 3.14t users and documented as Beta. +The GIL surfaces are unchanged. + +### Security and confinement + +No change. The three-target scope is a support boundary, not a security +relaxation. + +### Documentation and static guards + +Every doc the branch touched must say Beta; `docs/toolchain-support.md` is +the tier authority. Add the declaration/tier guard. + +## 7. Ordered work packages + +### Work package A — Prepare the merge branch + +Intent: land the branch on current `main` with a reviewable history. + +Required changes: + +- Create an integration branch from `origin/main`. +- Merge (not rebase) `6e3003f` so the branch's six commits and closure + records keep their identity, or rebase with `--rebase-merges` if the merge + proves unreadable; record the choice. +- Resolve `CHANGELOG.md` by keeping both sides and adding one free-threaded + entry under the unreleased section. +- Resolve `plans/registry.md` by keeping main's 320-329 rows and adding the + renumbered rows (work package B). + +Acceptance evidence: `git log --oneline origin/main..HEAD` shows the merge; +`git diff --check` is clean; `git merge-tree` has no remaining conflict. + +### Work package B — Renumber the branch records + +Intent: remove the 326/327 collision without losing traceability. + +Required changes: + +- `git mv` the branch's implementation records to + `plans/implementation/python-facade/333-free-threaded-cpython-314t-staged-support.md` + and `.../334-free-threaded-314t-qualification-and-tier-decision.md`. +- `git mv` the closure records to + `plans/closure/python-facade/333-...` and `.../334-...`. +- Update every heading, status line, cross-reference, registry row, roadmap + entry, doc reference, and skill reference from 326/327 to 333/334. +- Rename the soak records' `plan` field if it names 327 (the JSON + `plan` field is trace metadata, not a filename authority). +- Confirm no file or registry row remains at 326/327 for free-threading; the + existing 326 (public bind) and 327 (TLS) records must be byte-identical to + `origin/main`. + +Acceptance evidence: `git grep -nE '32(6|7)-free-threaded'` returns nothing; `python3 scripts/check-crate-topology.py` passes; the +registry has exactly one row per number. + +### Work package C — Beta tier + +Intent: make the user-facing claim match the evidence. + +Required changes: + +- `crates/eggserve-python/pyproject.toml`: classifier + `Programming Language :: Python :: Free Threading :: 2 - Beta`. +- `scripts/check-python-release-metadata.py`: + `EXPECTED_FREE_THREADING_TIER = 2`. +- `docs/toolchain-support.md`: the 3.14t row and prose say **Beta**, three + targets only, and name Milestone 332 as the promotion owner. +- `docs/python-packaging.md`, `docs/release-contract.md`, + `docs/release-process.md`, `docs/library-capability-matrix.md`, + `docs/python-api.md`, `docs/python-http-server-compatibility.md`, + `SECURITY.md`, `CHANGELOG.md`, and + `.opencode/skills/eggserve-dev/SKILL.md`: same Beta statement. +- Keep `release/wheel-matrix.toml` `tier = "required"` for the three `-ft` + entries. Matrix `tier` means "must appear in every release aggregate"; it + is not the user support tier. State that distinction in + `docs/release-process.md` so the two vocabularies cannot be confused. + +Acceptance evidence: `git grep -n "Free Threading :: 3\|Stable"` over the +touched docs returns only unrelated matches; the metadata gate passes with the +Beta constant; the classifier in the built wheel is Beta. + +### Work package D — Declaration guard + +Intent: make the GIL declaration and the documented tier impossible to drift +silently. + +Required changes: + +- Keep `#[pymodule(gil_used = false)]` explicit (do not rely on the PyO3 + default). +- `crates/eggserve-python/tests/test_free_threaded.py` (or a dedicated + test): on a free-threaded interpreter, assert + `sys._is_gil_enabled() is False` after `import eggserve._native`, and + fail if the interpreter is `-t` and the GIL was re-enabled. +- `scripts/check-python-free-threaded-compile.sh` stays the compile-time + half (`Py_GIL_DISABLED` asserted). +- Extend `scripts/check-python-release-metadata.py` so the declared tier + constant must match the classifier and, when a built artifact is available, + the WHEEL tag family (`cp314-cp314t` only for the Beta family). +- Add a short note to `docs/toolchain-support.md` that the declaration is + explicit and guarded. + +Acceptance evidence: the guard fails when the attribute is removed or the +classifier is moved to Stable, proven by a local mutation; CI runs the test in +the `python-free-threaded` lane. + +### Work package E — Record the supersession + +Intent: leave the planning surface truthful without rewriting history. + +Required changes: + +- Add a one-line "Superseded for the free-threaded slice by Milestone 333" + pointer to `release/plan-267-wheel-feasibility.md` **only if** the file's + archival status permits a pointer; otherwise record the supersession in + `plans/subsystems/python-facade-roadmap.md` and the new closure records and + leave the archived record untouched. +- Do not edit `plans/000`-`003`. + +Acceptance evidence: the roadmap or closure record states which Plan 267 +conclusion is superseded; the archived record is either untouched or carries +only the pointer. + +### Work package F — Gates, merge, and control surface + +Intent: prove the integration and close it honestly. + +Required changes: + +- Run every command in Section 11 and record the exact outcomes. +- Merge to `main` (or open the PR for the owner to merge, per repository + practice). +- Update `plans/registry.md` (rows 330/331/332, current milestone, next + number) and `plans/subsystems/python-facade-roadmap.md` (status, graph, + milestone table) in the same change. + +Acceptance evidence: gate log with exact commands and results; merge SHA; +registry next number advanced to 335 after 330 consumes 333/334. + +## 8. Failure, cancellation, restart, and contention semantics + +- A conflict outside `CHANGELOG.md` and `plans/registry.md` means the + branch base has drifted further than observed; stop and rebase-resolve file + by file rather than guessing. +- If the `python-free-threaded` CI job cannot be provisioned (`3.14t` + unavailable), the milestone is **blocked**; a GIL-interpreter substitute is + not acceptable evidence. +- If a gate fails, fix the integration or stop; never merge with a known red + gate and never mark the closure closed. +- No publication is attempted; `publish_target: none` only. + +## 9. Compatibility and migration + +- Additive wheel family; GIL users see no change. +- 3.14t users move from an unqualified source build to a documented Beta + wheel. +- `requires-python` stays `>=3.11`; the family is selected by interpreter + tag, not by metadata. +- Removal criterion: if Milestone 332 cannot produce the evidence, demote the + family to `candidate` in the matrix and record the decision; do not leave a + Beta claim without an owner. + +## 10. Required tests + +### Focused unit tests + +- The branch's 8 free-threaded tests, unchanged except numbering/comments. +- The declaration guard (work package D). + +### Integration tests + +- Full Python suite on 3.14t (`PYTHON=<3.14t> bash scripts/test-python-wheel.sh`). +- Full Python suite on the GIL lane, unchanged, with the free-threaded tests + skipped. + +### Restart and recovery tests + +- The branch's stop/start phase in the contention tests; no new restart + surface. + +### Contention and cancellation tests + +- The branch's concurrent callbacks, stream producers, body-read race, + iterator race, and tunnel contention tests. +- The bounded soak is **not** required here; it belongs to Milestone 332. + +### Security and negative tests + +- Validator rejection of a GIL wheel in the `-ft` slot and vice versa, via + the existing self-tests. +- No new negative security surface. + +### Migration and compatibility tests + +- GIL wheel bytes/tags unchanged across the 10 required targets. +- Metadata gate passes for both families. + +## 11. Required verification commands + +```bash +# 1. Integration hygiene +git diff --check +git log --oneline origin/main..HEAD + +# 2. Static gates +python3 scripts/check-crate-topology.py +python3 scripts/wheel-matrix.py validate +python3 scripts/wheel-matrix.py self-test +python3 scripts/check-release-wheel-set.py --self-test +python3 scripts/check-release-workflow.py +python3 scripts/check-release-workflow.py --self-test +python3 scripts/check-python-release-metadata.py + +# 3. Rust + excluded Python crate +cargo fmt --all -- --check +cargo clippy --manifest-path crates/eggserve-python/Cargo.toml --lib -- -D warnings +cargo check --manifest-path crates/eggserve-python/Cargo.toml --locked + +# 4. GIL lane (unchanged contract) +PYTHON=python3.14 bash scripts/test-python-wheel.sh + +# 5. Free-threaded lane (Beta family) +PYTHON=python3.14t bash scripts/check-python-free-threaded-compile.sh +PYTHON=python3.14t bash scripts/test-python-wheel.sh + +# 6. Repository fast gate +./scripts/verify.sh fast +``` + +Do not claim a command that was not actually run in the closure record. + +## 12. Documentation updates + +- `docs/toolchain-support.md` (tier authority; Beta, three targets only, + ownership by Milestone 332). +- `docs/python-packaging.md`, `docs/release-contract.md`, + `docs/release-process.md` (matrix `tier` vs support tier), + `docs/library-capability-matrix.md`, `docs/python-api.md`, + `docs/python-http-server-compatibility.md`. +- `SECURITY.md`, `CHANGELOG.md`, `README.md` (only if the branch already + touched them; do not broaden). +- `.opencode/skills/eggserve-dev/SKILL.md` and `AGENTS.md` only where the + branch already states a tier. +- `plans/registry.md` and `plans/subsystems/python-facade-roadmap.md`. + +## 13. Acceptance criteria + +1. `main` contains the branch's free-threaded code, tests, CI lane, matrix + entries, validators, and docs, with no plan-number collision. +2. The wheel classifier and every touched doc say **Beta**; no touched + surface says Stable. +3. The GIL `cp311-abi3` family is byte-for-byte unchanged in tags, targets, + metadata, and tests. +4. The declaration guard fails if `gil_used = false` is removed or the tier + is moved to Stable without the evidence plan. +5. The 3.14t suite and the GIL suite pass; the static gates and self-tests + pass. +6. The closure records the deferred contention evidence and names Milestone + 332 as the owner. + +## 14. Stop conditions + +Stop and report rather than improvise when: + +- a merge conflict reaches a file outside `CHANGELOG.md` and + `plans/registry.md` and cannot be resolved without choosing between + unrelated main work and branch work; +- a plan number other than 333/334 would be consumed; +- the `3.14t` interpreter or CI job is unavailable; +- the GIL family would change in any observable way; +- a repository gate fails for reasons outside this scope; +- the owner asks for Stable in this milestone (that is Milestone 332's + decision, and it requires the evidence). + +## 15. Closure evidence required + +- Merge commit SHA and the exact commands run, with outcomes. +- The renumbering diff (`git grep` proving no 326/327 free-threaded + references remain). +- The classifier/doc diff showing Beta. +- 3.14t suite result and GIL suite result. +- Validator and metadata self-test results. +- A statement that contention evidence is deferred to Milestone 332 and that + the family is Beta, with the condition named. + +## 16. Handoff notes + +- **Nested worktree hazard:** building `crates/eggserve-python` from a + worktree nested under the main checkout fails with "current package believes + it's in a workspace when it's not" because Cargo walks past the worktree's + excluded workspace to the outer checkout. Build from the primary checkout, + or export with `git archive` and append an empty `[workspace]` table to a + temporary copy. Do not add `[workspace]` to the repository manifest. +- **Local free-threaded interpreter:** `python3.14t` is available on this + machine; maturin 1.9.5 builds a `cp314-cp314t` wheel with the dev profile. + A dev-profile wheel is sufficient for GIL/tag/behavior evidence; release + claims still require the dist profile. +- **Do not merge the branch's Stable commit as-is.** `6e3003f` is a + documentation/classifier flip layered on the Beta decision in `a42edc0`; + keep its text improvements and reverse only the tier. +- **Do not copy the branch's plan files into this tree before the merge**; + that duplicates 326/327 and guarantees conflicts. Renumber during merge + resolution. +- **Do not reopen Plan 331/332 scope here.** The BodySource lost-update and + the per-target soak are separate milestones with separate evidence. diff --git a/plans/implementation/python-facade/331-free-threading-concurrency-contract-hardening.md b/plans/implementation/python-facade/331-free-threading-concurrency-contract-hardening.md new file mode 100644 index 0000000..f8d9711 --- /dev/null +++ b/plans/implementation/python-facade/331-free-threading-concurrency-contract-hardening.md @@ -0,0 +1,416 @@ +# Python Facade Milestone 331 — Free-threading concurrency contract hardening + +Status: ready for handoff (hard dependency: Milestone 330) + +Repository baseline: the Milestone 330 merge commit (free-threaded family +landed as Beta). The evidence below was taken at `origin/main` `5fdd7da` +before that merge; re-confirm the line numbers after 330 lands. + +Source roadmap: + +- `plans/subsystems/python-facade-roadmap.md#7` (milestones) + +Long-term requirements: + +- `plans/000-long-term-specification.md#2` +- `plans/001-terminology-and-domain-model.md` (`RequestBody`, `Response`) +- `plans/002-long-term-roadmap.md` (phase 4) + +Applicable ADRs: none. + +Primary class: invariant (concurrent use must never return silent wrong data; +it either works or raises a typed error). + +## 1. Objective + +Make every Python-visible concurrency contract in the affected surface either +safe or explicitly failing when the GIL is absent. The target is the class of +defect where two OS threads race a take/restore slot and one caller receives a +plausible but wrong result instead of an error. + +This milestone does not add parallelism, change admission limits, or promote +the free-threaded tier. It closes the audit findings that Milestone 330's +branch does not address. + +## 2. Why this milestone is ready + +- Milestone 330 lands the explicit `gil_used = false` declaration and the + free-threaded test module, so the runtime this milestone hardens is a + supported (Beta) configuration with an owning test file. +- The audit reproduced GIL-free execution on CPython 3.14.5t (GIL disabled + after import; 8 concurrent callbacks; 856-test suite passes), so the races + below are reachable today, not hypothetical. +- The branch already fixes concurrent `Tunnel.recv`; this milestone must not + duplicate that guard. + +## 3. Current implementation evidence + +All paths are in `crates/eggserve-python/`. + +### 3.1 `BodySource` silent lost read (highest severity) + +`src/lib.rs:283` `read_all` and `src/lib.rs:302` `read_range` use a +take-restore idiom: + +- lock `Mutex`, `std::mem::replace(&mut *guard, Empty)`, unlock; +- `py.detach(|| body.read_all())` (or `read_range`); +- restore with `if let Ok(mut guard) = self.inner.lock() { *guard = body; }`. + +Two threads calling concurrently can interleave as: T1 takes the real body, +T2 takes `Empty`, T2 reads zero bytes and restores `Empty`, T1 restores the +real body last. T2 returns `Ok(vec![])` with no error. The other ordering +loses T1's restore. The result is silent short/empty data, not a crash. +Sequential repeated reads are intended to work today because the body seeks +explicitly. + +### 3.2 Request-body bridge (typed, but inconsistent) + +`src/server/body_bridge.rs` uses the same take/restore shape in +`read_chunk` (~line 470) and `trailers` (~line 535), but the slot is +`Mutex>`, so a losing concurrent caller gets +`RequestBodyConsumedError` instead of silent data. That is acceptable +behavior, but the restore is still `if let Ok(...)`, and `read_chunk` sets +`incremental=true` before the take, so a losing call mutates mode before it +errors. Align both sites on one helper and one tested contract. + +### 3.3 Single-consumer iterator + +`src/server/body_bridge.rs:585` `BodyChunkIterator` is the only non-frozen +`#[pyclass]` and is documented "not thread-safe; concurrent __next__ calls +are not supported". PyO3's runtime borrow check turns a concurrent +`__next__` into a typed `Already borrowed` error, not UB. The contract is +fine; it lacks a regression test and is now load-bearing. + +### 3.4 Compatibility facade lifecycle state + +`python/eggserve/server.py`: `_closed` is set at `:486` and read at `:648`, +and `server_close` clears `_native` at `:685` before setting `_closed` at +`:687`, with no lock. A concurrent `serve_forever` and `server_close` can +start a native server after the close decided to stop (the audit saw +`RuntimeError: server is closed` raised from a `serve_forever` thread during +teardown). No memory-safety issue; a lifecycle race that should be +deterministic. + +### 3.5 Async bridge loop affinity + +`python/eggserve/lowlevel.py:1051` `track()` mutates the `_tasks` set +directly. Every other mutation path runs on the loop thread +(`:999`, `:1002`, `:820`, `:829`). Calling `track()` from a foreign +thread is unprotected. + +### 3.6 GIL-shaped tests + +`tests/test_server_integration.py:574` and +`tests/test_boundary_hardening.py:386` increment handler counters without a +lock. `tests/test_server_integration.py:640` states "The GIL is the only +synchronization during Python callback execution". The suite passes on 3.14t +today, but those tests would not detect a real callback-parallelism defect. + +### 3.7 Runtime worker shape + +`src/server/runtime.rs:701-707` builds a single 2-worker Tokio runtime for +listeners, body producers, and `block_on` waits; the B86 note records the +contention. No public knob exists and this milestone must not add one. + +## 4. Invariants that must not regress + +- Sequential repeated `BodySource.read_all`/`read_range` behavior stays as + it is today (reads seek explicitly and restore the body). +- `RequestBody.read()` / `iter_chunks()` / `read_chunk()` / `trailers()` + one-shot and mode-exclusivity semantics are unchanged. +- `max_python_callbacks`, stream-producer admission, and the 16-chunk bridge + are unchanged. +- No Rust lock is held across `Python::attach`, `Py::call`, or + `block_on`; no `unsafe`. +- The GIL `cp311-abi3` family and the free-threaded Beta family behave + identically for these contracts. +- No public worker-count API and no new dependency. + +## 5. Scope + +### In scope + +- `PyBodySource` concurrent-entry contract and its tests. +- One shared take/restore helper for the request-body bridge, with typed + failure on concurrent entry. +- Regression tests for `BodyChunkIterator`, tunnel `recv` (landed by 330), + facade close/serve, and async `track()`. +- Test-suite atomicity and the GIL-free assertion. +- Measurement and documentation of the 2-worker runtime envelope. + +### Explicitly out of scope + +- A public worker-count knob or runtime API change. +- The Plan 238 async producer redesign. +- Tier promotion (Milestone 332) or new platforms. +- Any change to static serving, HTTP framing, TLS, or confinement. +- Rewriting the tunnel guard from Milestone 330. + +## 6. Required production changes + +### Crates and ownership + +`crates/eggserve-python` only. No workspace crate changes. The excluded +crate's lint lane must stay green. + +### Config and policy + +None. + +### Protocol and compatibility + +No wire change. Error codes/messages for concurrent misuse are additive; do +not reuse an unrelated code. + +### Runtime and concurrency + +- Replace `Mutex` + replace/restore with an explicit state: + `Ready(BodySource)`, `Busy`, `Consumed` (or equivalent). `Ready` enters + `Busy`; a second entrant gets a typed + `BodySourceError` (new stable code, e.g. `body_in_use`); the owner + restores `Ready` on success and on every error path. Use a drop guard so an + unwind cannot strand `Busy`. +- Apply the same helper shape to `read_chunk`/`trailers`; preserve the + existing `RequestBodyConsumedError` for a genuinely completed/consumed + body. +- Guard the compatibility facade's close/serve transition with a lock or a + single atomic state machine so exactly one start wins and a close after + start is deterministic. +- Route `AsyncServer.track()` through the loop thread or document and enforce + loop-thread affinity with a clear error. + +### Frontend or operator surface (CLI / Python) + +No CLI change. `BodySource` gains one documented error condition; the stubs +and `docs/python-api.md` describe it. + +### Security and confinement + +No change. Fail-closed on concurrent misuse; never fall back to empty data. + +### Documentation and static guards + +`docs/python-api.md`, `docs/api-stability.md`, `lowlevel.py` docstrings, +and the affected test docstrings state the concurrent rules. No new script is +required. + +## 7. Ordered work packages + +### Work package A — BodySource state machine + +Intent: remove the silent lost read. + +Required changes: + +- Introduce the three-state interior and the drop-safe restore. +- Keep sequential re-read behavior; concurrent entry is an error. +- Map the error through the existing `BodySourceError` type with a stable + code. + +Acceptance evidence: a two-thread test where exactly one call returns the +bytes and the loser raises the typed error; a sequential re-read test still +passes; a mutation test that removes the guard fails. + +### Work package B — Request-body bridge consistency + +Intent: one take/restore helper and no pre-take mode mutation on a losing +call. + +Required changes: + +- Move `read_chunk`/`trailers` onto the shared helper. +- Set `incremental` only after the take succeeds. +- Keep `RequestBodyConsumedError` for consumed bodies. + +Acceptance evidence: concurrent `read_chunk` tests (one winner, typed loser); +`trailers()` after terminal state still works. + +### Work package C — Single-consumer regression tests + +Intent: make the existing documented contracts executable. + +Required changes: + +- Concurrent `BodyChunkIterator.__next__` yields a typed + `Already borrowed`/`RuntimeError`, never UB or a hang. +- Concurrent `Tunnel.recv` yields the Milestone 330 error (do not + re-implement it; assert it). + +Acceptance evidence: tests on both the GIL and free-threaded lanes. + +### Work package D — Facade lifecycle determinism + +Intent: remove the close/serve race seen in the audit. + +Required changes: + +- Lock or atomically transition `_closed`/`_native`. +- Define the outcome for close-during-start: one deterministic winner, the + other raises the existing "server is closed" error; no native server is + leaked. + +Acceptance evidence: a repeated race test (close while `serve_forever` +starts) never leaves a running native server and never raises an unhandled +thread exception. + +### Work package E — Async bridge affinity + +Intent: make `track()` safe or explicitly loop-only. + +Required changes: + +- If the intended contract is loop-thread-only, detect the wrong thread and + raise a clear error; otherwise schedule via `call_soon_threadsafe`. +- Document the choice in `lowlevel.py` and `docs/python-api.md`. + +Acceptance evidence: a foreign-thread `track()` test matches the documented +contract. + +### Work package F — GIL-free test honesty + +Intent: stop the suite from depending on GIL serialization. + +Required changes: + +- Replace unlocked handler counters in + `tests/test_server_integration.py:574` and + `tests/test_boundary_hardening.py:386` with locked counters. +- Rewrite the `test_server_integration.py:640` docstring to describe the + actual contract. +- Add one assertion that the free-threaded lane really has the GIL disabled + (already partly covered by Milestone 330's guard; do not duplicate it). + +Acceptance evidence: the suite passes on both lanes; the free-threaded lane +asserts `sys._is_gil_enabled() is False`. + +### Work package G — Runtime envelope evidence + +Intent: know the contention limit before documenting it. + +Required changes: + +- Measure the 2-worker runtime under `max_python_callbacks=8` with body + uploads and streamed responses; record the observed behavior. +- Document the envelope in `docs/python-api.md` (no public knob). +- If a deadlock or starvation is proven, stop and report; a worker-shape + change needs its own decision. + +Acceptance evidence: a short measurement record in the closure (not a CI +timing gate). + +## 8. Failure, cancellation, restart, and contention semantics + +- Concurrent entry to a one-shot slot fails fast with a typed error; it never + waits on another thread's work. +- A panic during a detached read must restore the slot to `Ready` (drop + guard) or leave it `Consumed`; never `Busy` forever. +- Close-during-start is deterministic; the loser observes a closed server. +- Shutdown still cannot kill Python code; the existing limitation is + unchanged. + +## 9. Compatibility and migration + +- No public API removal. The new concurrent-misuse error is additive. +- Sequential code sees no change. +- Both wheel families keep identical semantics. +- If a fix requires a public API change, stop (Section 14). + +## 10. Required tests + +### Focused unit tests + +- `BodySource` concurrent entry (one winner, typed loser), sequential + re-read, panic/disconnect restore. +- `read_chunk`/`trailers` concurrent entry and mode exclusivity. +- `BodyChunkIterator` concurrent `__next__`. +- `Tunnel.recv` contention (asserts Milestone 330's guard). +- `track()` foreign-thread behavior. + +### Integration tests + +- Full Python suite on the GIL lane and the free-threaded lane. +- Close/serve race under repeated starts. + +### Restart and recovery tests + +- Restart after a failed start still works; no leaked native server. + +### Contention and cancellation tests + +- The two-thread races above; the disconnect-during-read path restores the + slot. + +### Security and negative tests + +- No silent empty body on any concurrent path; error codes are stable and do + not leak request data. + +### Migration and compatibility tests + +- Both wheel families pass the same tests (the `-ft` tests skip only where + they assert GIL-disabled execution). + +## 11. Required verification commands + +```bash +cargo fmt --all -- --check +cargo clippy --manifest-path crates/eggserve-python/Cargo.toml --lib -- -D warnings +cargo check --manifest-path crates/eggserve-python/Cargo.toml --locked +PYTHON=python3.14 bash scripts/test-python-wheel.sh +PYTHON=python3.14t bash scripts/test-python-wheel.sh +./scripts/verify.sh fast +``` + +Run the focused test files first with the interpreter that owns the failure. + +## 12. Documentation updates + +- `docs/python-api.md`: `BodySource` concurrent rule; facade lifecycle; + async `track()` affinity; runtime envelope. +- `docs/api-stability.md`: clarify the one-shot/single-consumer statement so + it describes the actual error, not just "GIL constraints". +- `lowlevel.py`/`server.py` docstrings for the changed contracts. +- No change to tier statements (Milestone 332 owns them). + +## 13. Acceptance criteria + +1. A concurrent `BodySource.read_all`/`read_range` either returns the + correct bytes once or raises a typed error; no silent empty/short result. +2. Sequential re-reads behave as before. +3. `read_chunk`/`trailers` share one restore helper and never mutate mode on + a losing take. +4. Concurrent iterator/tunnel misuse is tested and typed. +5. Close-during-start is deterministic and leaks no native server. +6. The suite passes on both wheel families; the free-threaded lane asserts + the GIL is disabled. +7. No public API, default, or dependency change; no `unsafe`. + +## 14. Stop conditions + +Stop and report when: + +- the only correct fix would change a public API shape or add a public + worker-count knob; +- the runtime measurement proves a deadlock requiring a runtime redesign; +- a fix would change `max_python_callbacks` semantics or the 16-chunk bridge; +- the GIL family would behave differently from the free-threaded family; +- Milestone 330 has not landed (hard dependency absent). + +## 15. Closure evidence required + +- The failing-before/passing-after tests for each work package. +- Exact command outcomes on both interpreters. +- The runtime envelope measurement. +- A list of any contract left documented-but-unchanged, with rationale. +- Residual findings classified by severity. + +## 16. Handoff notes + +- Re-verify line numbers after the Milestone 330 merge; the branch touches + `body_bridge.rs`, `response_bridge.rs`, and `tunnel_bridge.rs`. +- Keep the take/restore helper in one place; do not add a second copy in + `body_bridge.rs`. +- PyO3's non-frozen runtime borrow check is a feature here: do not "fix" it + by making `BodyChunkIterator` `frozen` with a hand-rolled lock. +- The 2-worker runtime note (B86) is intentional; a change needs its own + plan, not a drive-by edit. diff --git a/plans/implementation/python-facade/332-free-threaded-contention-evidence-and-promotion.md b/plans/implementation/python-facade/332-free-threaded-contention-evidence-and-promotion.md new file mode 100644 index 0000000..d25b8b9 --- /dev/null +++ b/plans/implementation/python-facade/332-free-threaded-contention-evidence-and-promotion.md @@ -0,0 +1,389 @@ +# Python Facade Milestone 332 — Free-threaded contention evidence and Beta→Stable promotion + +Status: ready for handoff (hard dependency: Milestone 330; soft dependency: +Milestone 331) + +Repository baseline: the Milestone 330 merge commit. Plan 330 lands the +free-threaded family as **Beta**; this milestone is the only owner of the +Beta→Stable decision. + +Source roadmap: + +- `plans/subsystems/python-facade-roadmap.md#7` (milestones) + +Long-term requirements: + +- `plans/000-long-term-specification.md#2` +- `plans/002-long-term-roadmap.md` (phase 4) + +Applicable ADRs: none. + +Primary class: infrastructure (qualification evidence) with a documentation +capability outcome (the tier statement). + +## 1. Objective + +Make the free-threaded support claim repeatable and target-specific, then +decide the tier from that evidence: + +1. Extend the contention soak to record provenance (commit, wheel filename + and tag, host, interpreter, configuration, result). +2. Run it on all three declared targets against the actual `-ft` wheels. +3. Add a bounded contention subset to CI so the claim does not rest on a + local run. +4. Promote Beta→Stable only if every criterion in Section 13 holds; + otherwise retain Beta and record the blocker. + +No product behavior changes. The only user-facing change is the tier +statement when the evidence supports it. + +## 2. Why this milestone is ready + +- Milestone 330 lands the wheel family, the `python-free-threaded` CI lane, + the compile check, and the soak script; this milestone consumes them. +- Milestone 331 closes the concurrency-contract findings; a promotion + decision must not precede those fixes. +- The branch's own tier record says "wheel filenames are the authority" and + "no partial promotion"; this milestone supplies exactly that authority. + +## 3. Current implementation evidence + +### 3.1 What exists after Milestone 330 + +- `scripts/soak-python-free-threaded.py`: bounded loopback soak; exercises + buffered POSTs with digests, `Response.stream` byte verification, one-shot + `RequestBody.read()` races, `BodyChunkIterator.__next__` races, tunnel + upgrades and `recv` contention, disconnects during slow streams, and a + stop/start phase. +- CLI: `--requests` (default 400), `--workers` (8), `--duration` (120 s), + `--callbacks` (8), `--pace-ms` (10), `--max-body-bytes` (1 MiB), + `--json`. +- Existing records (`plans/closure/python-facade/334-soak-{1,2,3}.json` on + the adjacent branch, renumbered with its plan): 120 s each, ~80-85k HTTP + requests, 0 failures, GIL disabled before/after, peak concurrency 8. +- Provenance present: interpreter build string, platform, machine=arm64, + timestamps, configuration. +- Provenance missing: commit SHA, wheel filename/tag, host identifier, + runner identity. All three runs are the same local macOS arm64 interpreter + two minutes apart. +- CI: `python-free-threaded` builds, installs, smokes, and runs the full + suite on Linux; it does not run the soak. +- Release: the aggregate builds and smokes the three `-ft` wheels; the full + suite does not run on macOS/Windows. + +### 3.2 Why the current evidence is not enough for Stable + +The Stable claim covers three operating systems, but contention was measured +on one. The records cannot be tied to a commit or a wheel, so they cannot be +reproduced. The branch's own plan required wheel filenames and no partial +promotion; the records do not meet that bar. + +## 4. Invariants that must not regress + +- The promotion is all-or-nothing: three targets, one commit, the actual + released wheel bytes. +- No timing threshold becomes a CI gate; contention failures are invariant, + content, exception, or GIL-state failures, never raw throughput. +- No publication, tag, or PyPI/crates.io action. +- The GIL family is unchanged and is not re-qualified by this milestone. +- Beta remains the documented tier until the promotion commit lands. +- No new platform, `abi3t`, 3.13t/3.15t, ARMv7, Windows arm64, or musl + free-threaded target. + +## 5. Scope + +### In scope + +- Soak provenance fields and their validation. +- Three-target soak execution against the `-ft` wheels. +- A bounded contention subset in the `python-free-threaded` CI job. +- A `publish_target: none` release aggregate, with run URL and wheel hashes + recorded. +- The Beta→Stable decision and its documentation. +- Closing the renumbered branch tier record (334) and updating the registry + and roadmap. + +### Explicitly out of scope + +- Concurrency-contract fixes (Milestone 331). +- Any change to the wheel matrix targets, tags, or build model. +- Publication or version bumps. +- Benchmarks, throughput claims, or absolute latency comparisons. +- Windows/macOS full-suite parity (a separate capability decision). + +## 6. Required production changes + +### Crates and ownership + +None. This milestone changes qualification scripts, CI, and documentation. + +### Config and policy + +None. + +### Protocol and compatibility + +None; the tier statement is packaging metadata and documentation. + +### Runtime and concurrency + +No runtime change. The soak asserts existing behavior. + +### Frontend or operator surface (CLI / Python) + +The classifier in `crates/eggserve-python/pyproject.toml` and the tier text +in `docs/toolchain-support.md` move only if the gate passes. + +### Security and confinement + +No change. The soak stays loopback-only, logs no payloads, and uses bounded +bodies. + +### Documentation and static guards + +- `scripts/soak-python-free-threaded.py`: provenance schema and a + `--require-provenance` validation mode. +- `scripts/check-python-release-metadata.py`: the tier constant remains the + single declaration; promotion changes it in one place. +- `.github/workflows/ci.yml`: bounded contention step. +- `docs/toolchain-support.md` and every tier-bearing doc. + +## 7. Ordered work packages + +### Work package A — Provenance-complete records + +Intent: make one soak record sufficient to reproduce it. + +Required changes: + +- Add fields: `commit` (exact SHA), `wheel` (filename and WHEEL tag + family), `host` (runner name or machine id), `interpreter` (build + string, `sys.executable`, `Py_GIL_DISABLED`), `started_at`/`ended_at`, + `config`, and the existing counters. +- Add `--require-provenance` (or equivalent) so a record missing any field + fails validation. +- Keep `qualified = not problems`. + +Acceptance evidence: a record from the local interpreter contains every +field; a record with a missing field fails validation by mutation. + +### Work package B — Three-target soak against the wheels + +Intent: measure contention on the platforms the tier claims. + +Required changes: + +- Obtain the three `-ft` wheels from the same commit and record their + filenames and hashes. +- Run the soak on Linux x86_64 (glibc container), macOS arm64, and Windows + x86_64 (native runners) against the installed wheel, not a source build. +- Retain at least two records per target (three preferred), 120 s, 8 workers, + 8 callbacks. +- Assert `sys._is_gil_enabled() is False` before and after each run. + +Acceptance evidence: six to nine provenance-complete records, all +`qualified: true`, tied to the same commit and wheel bytes. + +### Work package C — Bounded CI contention gate + +Intent: stop the claim from resting only on manual runs. + +Required changes: + +- Add a short soak to the `python-free-threaded` job: for example + `--requests 200 --workers 4 --duration 20 --callbacks 4`, with + `--require-provenance` supplied from the workflow environment. +- Fail the job on any problem, unexpected exception, content mismatch, or + GIL re-enable. Do not assert a throughput or latency threshold. +- Keep the full soak manual and documented. + +Acceptance evidence: the job fails when the soak is deliberately pointed at a +GIL-enabled interpreter (mutation), and passes on the Beta family. + +### Work package D — Release aggregate evidence + +Intent: tie the tier to real release artifacts. + +Required changes: + +- Dispatch the release workflow with `publish_target: none` from the + promotion commit. +- Record the run URL, the aggregate result, the three `-ft` wheel filenames, + and their hashes. +- Do not publish. + +Acceptance evidence: green aggregate; artifacts match the soak inputs. + +### Work package E — Tier decision + +Intent: one explicit decision, no partial promotion. + +Required changes: + +- Evaluate every criterion in Section 13 and tabulate met/not met with + evidence pointers. +- If all hold: set the classifier to + `Programming Language :: Python :: Free Threading :: 3 - Stable`, update + `EXPECTED_FREE_THREADING_TIER`, and update every tier-bearing doc in one + commit. +- Otherwise: retain Beta, record the unmet criterion, and stop. No partial + promotion. + +Acceptance evidence: the gate table; the classifier diff or the explicit +retain decision; the metadata gate passes in both configurations. + +### Work package F — Close and update the control surface + +Intent: leave the planning surface truthful. + +Required changes: + +- Close the renumbered branch qualification record (334) with the new + evidence; if any criterion is unmet, mark it conditionally closed with the + blocker. +- Update `plans/registry.md` and `plans/subsystems/python-facade-roadmap.md` + (status, graph, milestone table, next number). + +Acceptance evidence: closure record; registry/roadmap diff; next number +advanced. + +## 8. Failure, cancellation, restart, and contention semantics + +- Any failed target retains Beta; there is no "two of three" promotion. +- A soak problem is fail-closed: record it, do not rerun until it passes and + then report only the pass. +- Runner unavailability is a blocker, not a reason to substitute a different + target or a GIL interpreter. +- The soak's restart phase filters expected "server closed" races; only + unexpected exceptions count. + +## 9. Compatibility and migration + +- Beta→Stable is a metadata/documentation change; no install or wire + behavior changes. +- If Stable is not reached, the Beta statement remains and the blocker is + recorded; no user action is required. +- Removing the family later requires a new plan; this milestone does not + create a removal path. + +## 10. Required tests + +### Focused unit tests + +- Soak provenance validation and self-test. +- Metadata gate self-test for both tier constants. + +### Integration tests + +- Three-target soak against installed wheels. +- Bounded CI contention gate. + +### Restart and recovery tests + +- The soak's stop/start phase on each target. + +### Contention and cancellation tests + +- Concurrent callbacks, streams, body reads, iterator pulls, tunnels, and + disconnect-during-stream on each target. + +### Security and negative tests + +- A GIL-enabled interpreter must fail the free-threaded lane's assertion. +- A provenance-incomplete record must fail validation. + +### Migration and compatibility tests + +- The GIL family's wheel set and suite are unchanged. + +## 11. Required verification commands + +```bash +# Provenance and self-tests +python3 scripts/soak-python-free-threaded.py --self-test +python3 scripts/check-python-release-metadata.py + +# Per-target manual soak (run on each target, from the installed wheel) +python3 scripts/soak-python-free-threaded.py \ + --requests 400 --workers 8 --duration 120 --callbacks 8 \ + --require-provenance --json plans/closure/python-facade/332-soak--.json + +# CI-shaped bounded subset (same flags, reduced) +python3 scripts/soak-python-free-threaded.py \ + --requests 200 --workers 4 --duration 20 --callbacks 4 --require-provenance + +# Release aggregate (no publication) +gh workflow run release.yml --ref -f publish_target=none + +# Standard gates after any doc/classifier change +python3 scripts/check-crate-topology.py +python3 scripts/check-release-workflow.py --self-test +PYTHON=python3.14t bash scripts/test-python-wheel.sh +``` + +Do not claim a command that was not actually run. + +## 12. Documentation updates + +- `docs/toolchain-support.md` (tier authority; Stable or Beta with the + blocker). +- `docs/python-packaging.md`, `docs/release-contract.md`, + `docs/release-process.md`, `docs/library-capability-matrix.md`, + `docs/python-api.md`. +- `SECURITY.md`, `CHANGELOG.md`, `README.md` where they state the tier. +- `.opencode/skills/eggserve-dev/SKILL.md` and `AGENTS.md` tier lines. +- `plans/registry.md`, `plans/subsystems/python-facade-roadmap.md`, + closure record 334. + +## 13. Promotion criteria (all required) + +1. Provenance-complete soak records exist for Linux x86_64 glibc, macOS + arm64, and Windows x86_64. +2. Every record is `qualified: true` with the GIL disabled before and after. +3. The records use the exact wheels from the `publish_target: none` release + aggregate of the promotion commit (filenames and hashes match). +4. The bounded contention gate is green in CI on the free-threaded lane. +5. No Medium-or-higher finding is open from Milestone 331 or this milestone. +6. The GIL `cp311-abi3` family is unchanged. +7. No publication is claimed. +8. The tier change and its evidence land in one commit set, with the closure + record naming the run URL and wheel hashes. + +If any criterion is unmet, the tier stays Beta and the closure names the +blocker. + +## 14. Stop conditions + +Stop and report when: + +- a required runner or target is unavailable; +- a target fails the soak and the failure is not understood; +- the wheel bytes tested differ from the aggregate artifacts; +- the promotion would require a code change (that belongs to 331); +- the owner has not confirmed the aggregate-as-release reading for the Stable + tier; +- the tier change would touch a doc outside the listed set in a way that + changes unrelated claims. + +## 15. Closure evidence required + +- The gate table with met/not met and evidence links. +- Provenance-complete records (paths + hashes) for every target. +- The CI run URL for the bounded contention gate. +- The release aggregate run URL and the three wheel filenames/hashes. +- The classifier/doc diff or the explicit retain-Beta decision. +- Registry/roadmap diff and the next-number advance. +- Any residual finding classified by severity. + +## 16. Handoff notes + +- Run the soak against the installed wheel, not the source tree; a source + build is not the released artifact. +- Keep the soak loopback-only and payload-free; do not add request logging to + make failures easier to debug. +- The three targets are the entire claim; do not add a fourth "while we are + here". +- The branch's original soak records remain trace in the renumbered closure; + do not delete them. Add the new provenance-complete records alongside. +- If only one target can run, the correct outcome is Beta plus a blocker, not + a narrowed Stable claim. diff --git a/plans/implementation/python-facade/333-free-threaded-cpython-314t-staged-support.md b/plans/implementation/python-facade/333-free-threaded-cpython-314t-staged-support.md new file mode 100644 index 0000000..45786da --- /dev/null +++ b/plans/implementation/python-facade/333-free-threaded-cpython-314t-staged-support.md @@ -0,0 +1,664 @@ +# Python Facade Milestone 333 — Free-threaded CPython 3.14t staged support + +> **Amendment — Milestone 330 (2026-11-28).** This record was Milestone 326 on +> its originating branch. It is Milestone 333 here because `main` already +> assigns 326 to the public-bind acknowledgment milestone; every reference in +> the body was renumbered with it. The Beta tier it establishes is unchanged. + +Status: implemented (closure closed 2026-11-23: the `python-free-threaded` CI +lane is green and a `publish_target: none` release aggregate contains the +three `cp314t` wheels; see +`plans/closure/python-facade/333-free-threaded-cpython-314t-staged-support.md`) + +Approval: repository owner, 2026-11-23. Approved as drafted; no scope +change from the reviewed plan. + +Plan number: 333 + +Repository baseline: `4949a77acfe4114561bd7cfe59a8458ea1983af7` + +Source roadmap: + +- `plans/subsystems/python-facade-roadmap.md` (Milestone 333) + +Long-term requirements: + +- `plans/000-long-term-specification.md#2` (Python `http.server`-shaped + facade; bounded resources) +- `plans/001-terminology-and-domain-model.md` (`Request`, `Response`, + `ResponseBody`, `Service`) +- `plans/002-long-term-roadmap.md` (phase 4, Python distribution) +- `docs/python-api.md`, `docs/python-http-server-compatibility.md`, + `docs/toolchain-support.md` + +Applicable ADRs: + +- none (no accepted ADR governs the wheel ABI family; this plan records the + decision it executes and does not change architecture ownership) + +Primary class: capability (a new runtime family) with invariant obligations +(the GIL family, security policy, confinement, and crate ownership must not +change) + +## 1. Objective + +Publish `cp314-cp314t` wheels for free-threaded CPython 3.14 on three +release targets (Linux x86_64 glibc, macOS arm64, Windows x86_64), prove the +existing bridge is safe when the GIL is disabled, and record the support +level as **Beta** until the promotion gate in work package H. The GIL-enabled +`cp311-abi3` contract stays exactly as it is. + +### Decision being executed (Option B, refined) + +- Free-threaded CPython **3.14t only**. 3.13t (experimental, and no longer + part of the manylinux interpreter inventory) and 3.15t are out of scope. +- `abi3t` (PEP 803) is out of scope. PyO3 0.29.3 already supports the + feature: its build-config logic selects `abi3t` only for Python >= 3.15 + and otherwise falls back to a version-specific free-threaded build, which + a probe with `abi3t-py315` on 3.14t confirmed. Adopting it requires a 3.15 + build lane and a second stable tag; that is a separate decision. +- Three targets, not ten: Linux x86_64 glibc, macOS arm64, Windows x86_64. + ARMv7 QEMU, Windows arm64, and the musl family are excluded because a + free-threaded interpreter is not currently guaranteed in those lanes. +- **Matrix tier is `required`; support maturity is Beta.** The matrix + `candidate` tier means "may be built experimentally; never satisfies the + release aggregate", so a candidate family would not ship at all. Release + presence and support maturity are therefore recorded separately: the family + must be in every aggregate, while the public claim is + `Programming Language :: Python :: Free Threading :: 2 - Beta` until the + promotion gate is met. This is a refinement of Option B's wording, not a + widening of scope. + +## 2. Why this milestone is ready + +- PyO3 0.29.3 is the resolved Python-crate dependency (Plan 325) and supports + free-threaded builds. Since PyO3 0.28 the `#[pymodule]` default declares + free-threading support (`Py_MOD_GIL_NOT_USED`); `gil_used = true` is now + the opt-out. +- maturin 1.14.1 is pinned in `ci.yml` and `release.yml` and is the + `abi3t`-capable backend (1.14.0+). Free-threaded wheel tags predate that + pin: the research build used the locally installed 1.9.5 and still emitted + `cp314-cp314t`, so the tag is not contingent on 1.14. +- `actions/setup-python` supports `python-version: 3.14t`, and + `uv python install 3.14t` provides a local interpreter. The Plan 267 + blocker "no free-threaded interpreter available" no longer holds. +- The current pypa manylinux/musllinux images list CPython 3.14t/3.15t in + their Python inventory; the exact interpreter path inside the pinned + `manylinux_2_17` image must still be verified (work package E). +- Plan 322 (producer admission bounds) is closed, so streamed producers are + already bounded before this plan adds free-threaded execution. +- No hard dependency is open. `docs/non-goals.md` contains no + free-threaded or PyPy implementation entry, so this is a support-tier + change, not a non-goal crossing. + +## 3. Current implementation evidence + +### 3.1 Correction of the Plan 267 Track A record + +`plans/267-free-threaded-long-tail-wheel-feasibility.md` and +`release/plan-267-wheel-feasibility.md` are legacy trace and immutable under +`plans/README.md`. The DEFERRED verdict is not rewritten. Plan 333 +supersedes the Track A free-threaded slice only, and the report carries an +additive status-correction banner (requested by the owner) that leaves all +historical text in place. + +The stale premises, for the record: + +| Plan 267 statement | Current fact | +|---|---| +| "no free-threaded (`-t`) interpreter available in this environment or in routine CI" | `actions/setup-python` serves `3.14t`; `uv python install 3.14t` installed CPython 3.14.5t locally during the research pass | +| "Module declares `#[pymodule]` without `gil_used = false`, so it loads GIL-required by default" | False for PyO3 >= 0.28. The macro emits `Py_MOD_GIL_NOT_USED` when the attribute is absent; the resolved 0.29.3 keeps `sys._is_gil_enabled()` false after import | +| "PyO3 0.29.2 supports ... the `abi3t` tag family" | `abi3t` is PEP 803, Python 3.15+, `abi3t-py315` in PyO3, maturin 1.14.0+. It is not available on 3.13t/3.14t and is not part of this plan | + +The retained contract statement ("free-threaded CPython unsupported") also +disagrees with the shipped declaration. Plan 333 removes that mismatch by +qualifying the declaration and documenting the Beta tier. If the plan is not +executed, the fallback is the one-line opt-out described in section 14. + +### 3.2 Baseline code and tests + +- Module declaration: `crates/eggserve-python/src/lib.rs:1670-1673` + (`#[pymodule] fn _native`), no `gil_used` attribute. +- Callback path: `PythonCallbackService` invokes the Python handler from + `spawn_blocking` through `Python::attach`, bounded by + `max_python_callbacks` (`crates/eggserve-python/src/server/sync_handler.rs:700-725`). +- Streamed producers: one `std::thread` per response, admitted by the Plan + 322 producer semaphore, attaching to Python per item + (`crates/eggserve-python/src/server/body_bridge.rs:86-215`). +- One-shot state: `RequestBody` (`body_bridge.rs:267-271`), `Response` + (`response_bridge.rs:22-31`), and the tunnel receiver + (`tunnel_bridge.rs:243-249`) are `frozen` pyclasses with mutex/take-put + interiors. +- Iterator: `BodyChunkIterator.__next__` takes `&mut self` and detaches + around `blocking_recv` (`body_bridge.rs:585-600`). +- Tunnel receive takes the receiver out for one blocking wait; a concurrent + call reports "tunnel already closed" (`tunnel_bridge.rs:273-300`, NOTE + B83). +- Server lifecycle: concurrent `start()` is serialized with an atomic swap + (`server/runtime.rs:482-510`). +- No `unsafe` in the crate (manifest `unsafe_code = "deny"`), no custom + `Drop`, no mutable module statics; one per-instance `OnceLock` caches the + request header view (`request_bridge.rs:32`). +- Python-side async bridge uses `run_coroutine_threadsafe`, + `asyncio.to_thread`, and per-dispatch local state + (`python/eggserve/lowlevel.py:600-700, 840-900`). + +### 3.3 Pre-plan evidence (research only, not qualification evidence) + +All runs used an unmodified tree at the baseline commit and a 3.14t +interpreter; only macOS arm64 was exercised. + +| Check | Result | +|---|---| +| `cargo check` with a free-threaded `PYO3_CONFIG_FILE` | pass (7.2 s); the bridge compiles under the free-threaded configuration, which is where PyO3 shared-access bounds apply | +| `maturin build -i python3.14t` (unchanged manifest) | `eggserve-0.2.5-cp314-cp314t-macosx_11_0_arm64.whl` | +| install + import under `-X gil=0` | pass; `sys._is_gil_enabled() == False`; no `RuntimeWarning` | +| full Python suite on CPython 3.14.5t | `Ran 853 tests ... OK` (123.2 s) | +| 80 POSTs / 8 workers, buffered bodies + `Response.stream` | 80 callbacks, 0 errors, correct streamed bytes | +| `abi3t-py315` enabled with 3.14t | resolves to `target_abi=CPython-free_threaded-3.14`; compiles | + +### 3.4 Known gaps at the baseline + +- The module already advertises free-threading support by default, but no + document says so and no CI lane verifies it; a source build on 3.14t runs + GIL-free without qualification. This is the primary gap. +- No free-threaded CI lane and no `test_free_threaded.py`; no assertion that + the GIL stays disabled. +- `release/wheel-matrix.toml` has no ABI-family dimension; + `scripts/wheel-matrix.py` keys uniqueness on the platform tag alone; + `scripts/check-release-wheel-set.py` hard-asserts `abi3`/`cp311`; + `scripts/check-python-release-metadata.py` requires `abi3-py311` and + rejects per-minor tags; `release.yml` hard-codes + `--interpreter python3.11`. +- Handler and iterable thread-safety is not part of the documented contract. +- Concurrent `Tunnel.recv` returns a misleading terminal-looking error. + +## 4. Invariants that must not regress + +1. The GIL-enabled `cp311-abi3` family keeps its tags, wheel count, version, + and behavior; the existing suite stays green. +2. No new `unsafe`; `unsafe_code = "deny"` stays. +3. Static/path/filesystem confinement, TLS identity, HTTP framing, and crate + ownership are untouched. +4. `RequestBody` stays one-shot; `Response` stays one-shot; HEAD and + body-forbidden responses never advance a producer. +5. Bridge Rust state stays behind `Mutex`, atomics, or one-shot take/put; no + lock is held across a blocking wait except an explicitly reviewed + serialization gate. +6. No new public Python API or runtime config knob. +7. Support claims never exceed evidence: no 3.13t/3.15t, `abi3t`, PyPy, + ARMv7, Windows arm64, or musl free-threaded claim. + +## 5. Scope + +### In scope + +- An explicit `#[pymodule(gil_used = false)]` declaration with a comment + naming the qualified platforms. +- One tunnel-receive contention fix and documentation of the one-shot / + iterator semantics under free-threading. +- A free-threaded test module and a CI lane. +- A family-aware wheel matrix, validator, and release workflow with three + `cp314-cp314t` targets. +- Documentation, classifier, and support-tier updates. +- The Plan 267 correction banner and the registry/roadmap updates. + +### Explicitly out of scope + +- 3.13t and 3.15t support; `abi3t`; PyPy. +- Any platform outside the three named targets. +- Any Rust crate API, HTTP, TLS, or security change. +- TSan/soak as a mandatory CI gate (optional evidence for promotion). +- Performance claims or benchmarks. +- Publication itself: this plan produces the artifacts and evidence; cutting + a release remains a separate manual action. + +## 6. Required production changes + +### Crates and ownership + +Only `crates/eggserve-python` changes, plus the new test file and the +compile-check script. No other crate is touched; the topology gate must stay +green. + +### Config and policy + +No `RuntimeConfig` field changes. The release matrix gains an ABI-family +dimension; the support tier changes in metadata and docs only. + +### Protocol and compatibility + +No wire behavior change. The compatibility statement changes: handlers and +stream iterables may execute Python code in parallel on a free-threaded +interpreter. + +### Runtime and concurrency + +The declaration becomes explicit; the tunnel receive path gains a contention +guard; one-shot and iterator semantics are documented. No new admission +semantics: `max_python_callbacks` remains the callback and producer bound. + +### Frontend or operator surface + +Wheel tags, artifacts, and the PyPI classifier. No CLI change. + +### Security and confinement + +No policy change. Threat-model and extension-contract wording is corrected +where it says "the GIL is released during I/O", which is wrong on a +free-threaded build (the thread detaches from the interpreter; there is no +GIL). + +### Documentation and static guards + +Family-aware validators and the metadata gate become static guards for the +advertised support set. + +## 7. Ordered work packages + +### Work package A — Make the declaration explicit and correct the record + +Intent: the code's attestation and the support contract must agree. + +Required changes: + +- `crates/eggserve-python/src/lib.rs`: add + `#[pymodule(gil_used = false)]` above `fn _native`, with a comment naming + CPython 3.14t on the three qualified targets. The attribute is a no-op on + GIL-enabled builds and documents the audited promise. +- `release/plan-267-wheel-feasibility.md`: add the additive + status-correction banner at the top (no historical line changes). +- Registry and roadmap updates described in work package H. + +Acceptance evidence: + +- `cargo check` passes for the GIL-enabled and free-threaded configurations. +- Importing the 3.14t wheel keeps `sys._is_gil_enabled()` false. +- `grep -n "pymodule" crates/eggserve-python/src/lib.rs` shows exactly one + declaration. + +### Work package B — Free-threaded concurrency hardening + +Intent: remove the one misleading contention path and state the contract +before users meet it. + +Required changes: + +- `server/tunnel_bridge.rs`: guard `recv` with an in-flight flag + (compare-exchange; reset on every exit path, including errors). A + concurrent second `recv` raises a clear `RuntimeError` ("concurrent + Tunnel.recv is not supported") instead of "tunnel already closed". Do not + hold a `std::sync::Mutex` across `block_on`. +- `server/body_bridge.rs`: extend the `BodyChunkIterator` doc comment to + state that concurrent `__next__` raises `Already borrowed` and is not + supported. +- `Response` and `RequestBody` doc comments: state that concurrent reuse + raises the existing one-shot errors; no behavior change. +- No new public type or signature. + +Acceptance evidence: the tests in work package C pass on 3.14t and the GIL +suite stays green. + +### Work package C — Free-threaded test module + +Intent: make the free-threading promise testable and regressive. + +Required changes: add `crates/eggserve-python/tests/test_free_threaded.py`, +skipped unless `sysconfig.get_config_var("Py_GIL_DISABLED")` is truthy: + +1. **Import stays GIL-free**: in a fresh interpreter, import + `eggserve._native` and assert `sys._is_gil_enabled() is False` and no + `RuntimeWarning` was raised. +2. **Parallel callbacks with shared state**: N concurrent requests through a + handler that increments a locked counter; assert the count is exact and + every response is correct. +3. **Serialized mode**: with `max_python_callbacks=1`, a handler records + the maximum concurrent entry count and asserts it is 1. +4. **Concurrent stream producers**: concurrent `Response.stream` requests + deliver the exact expected bytes and respect the producer budget. +5. **One-shot contention**: two threads racing `RequestBody.read()` produce + exactly one success and one `RequestBodyConsumedError`; two threads + racing `BodyChunkIterator.__next__` produce a typed error, never a crash. +6. **Tunnel contention**: concurrent `Tunnel.recv` returns the new explicit + error, not "tunnel already closed". + +Use bounded waits and `max_in_flight_requests`/timeouts that keep the suite +fast; no thread-count assertions from Python. + +Acceptance evidence: the module skips on the GIL build and passes on 3.14t. + +### Work package D — Build configuration and compile check + +Intent: make the free-threaded build reproducible and regression-gated. + +Required changes: + +- Confirm no PyO3 feature change is needed for `cp314-cp314t`: `abi3-py311` + is ignored on a free-threaded interpreter and PyO3 falls back to a + version-specific build. Record the observed behavior in the closure. +- `crates/eggserve-python/pyproject.toml`: raise the build-system floor to + `maturin>=1.14.1,<2.0` to match the pipeline pin and the `abi3t`-ready + backend. `requires-python` stays `>=3.11`. +- Add `scripts/check-python-free-threaded-compile.sh`: + - require a `-t` interpreter (default `python3.14t`, `PYTHON=` override); + - run `PYO3_PYTHON="$PYTHON" cargo check --manifest-path + crates/eggserve-python/Cargo.toml --locked`; + - fail with a clear message when the interpreter is absent. +- Record the `PYO3_PRINT_CONFIG=1` output + (`target_abi=CPython-free_threaded-3.14`, `build_flags=Py_GIL_DISABLED`). + +Acceptance evidence: the script passes locally and in CI; the config print is +in the closure. + +### Work package E — Family-aware wheel matrix and release gates + +Intent: one declarative authority that can express two ABI families without +a second platform list. + +Required changes: + +- `release/wheel-matrix.toml`: add explicit `abi_family`, `python_tag`, + `abi_tag`, and `interpreter` keys to every target (migrating the existing + entries explicitly). Add three `cp314t` entries with + `abi_family = "cp314t"`, `python_tag = "cp314"`, + `abi_tag = "cp314t"`, `interpreter = "python3.14t"`, and artifact IDs + suffixed `-ft`: Linux x86_64 glibc, macOS arm64, Windows x86_64. Keep the + GIL entries on `python3.11` / `cp311` / `abi3`. +- `scripts/wheel-matrix.py`: validate the new keys; make uniqueness + `(platform_tag, abi_family)`; emit `abi_family`, `python_tag`, + `abi_tag`, and `interpreter`; extend `expected-tags`/self-tests. +- `scripts/check-release-wheel-set.py`: require one wheel per + `(platform, family)`; validate the tag triple per family (allow the + dotted `abi3.abi3t` form only when a future family declares it); update + the self-tests to cover a missing family, a wrong family tag, and a + duplicate family. +- `scripts/check-python-release-metadata.py`: keep `abi3-py311`; accept the + declared free-threaded family; allow only `cp314t` tags, only for the + declared targets; keep rejecting `abi3t` claims. +- `release.yml`: use the matrix-emitted `interpreter` field instead of the + hard-coded `python3.11`; add the family to the artifact names; keep the + `abi-proof` lane GIL-only; add a free-threaded smoke path (install and + run `release_smoke.py` plus the GIL assertion). Determine and record the + interpreter path for each lane: native runners use + `actions/setup-python` 3.14t; manylinux/musllinux use the image's + `/opt/python/cp314-cp314t/bin/python` or a python-build-standalone + install; do not publish a wheel whose interpreter differs from the + declared ABI. +- Exclude ARMv7, Windows arm64, and the musl family from the free-threaded + family in this plan. + +Acceptance evidence: `wheel-matrix.py validate`, both self-test suites, and +synthetic aggregate checks (complete set passes; missing family fails; wrong +tag fails). + +### Work package F — Free-threaded CI lane + +Intent: continuous proof instead of a one-off run. + +Required changes: + +- `ci.yml`: add a `python-free-threaded` job (separate from the existing + `python` job so failures are unambiguous) with + `actions/setup-python` `python-version: "3.14t"`, + `pip install maturin==1.14.1`, the compile-check script, and + `PYTHON=python3.14t bash scripts/test-python-wheel.sh`. +- Add an explicit assertion after install: + `python -X gil=0 -W error::RuntimeWarning -c "import sys, eggserve._native; assert sys._is_gil_enabled() is False"`. +- The job runs the full suite, including `test_free_threaded.py`. +- Keep the existing GIL `python` job and its wheel path unchanged. + +Acceptance evidence: a green CI run linked in the closure; the job fails if +the module re-enables the GIL or if the new tests fail. + +### Work package G — Support tier, documentation, and classifier + +Intent: the public claim matches the evidence. + +Required changes: + +- `docs/toolchain-support.md`: add free-threaded CPython 3.14t (Beta; three + targets) and state that 3.13t/3.15t/PyPy remain unsupported; update the + PyO3 version line and the wheel matrix table. +- `docs/python-packaging.md`: list both families, their tags, and the + platform subsets. +- `docs/release-contract.md` and `docs/release-process.md`: replace the + single-family statements with the family set; keep free-threaded claims + Beta; note that the `abi-proof` lane stays GIL-only. +- `docs/library-capability-matrix.md`: split the Python wheel row by + family. +- `docs/python-api.md` and `docs/python-http-server-compatibility.md`: + document parallel handler/iterable execution, the caller's thread-safety + responsibility, `max_python_callbacks=1` as serialized mode, and the + one-shot contention errors. +- `docs/threat-model.md` and `docs/extension-contract.md`: correct "the GIL + is released during I/O" to describe interpreter detach on free-threaded + builds. +- `SECURITY.md`: update the unsupported-implementations sentence. +- `CHANGELOG.md`: additive wheel family and Beta tier. +- `.opencode/skills/eggserve-dev/SKILL.md`: update the wheel-support bullet + and the Plan 267 pointer. +- `crates/eggserve-python/pyproject.toml`: add + `Programming Language :: Python :: Free Threading :: 2 - Beta`; + `scripts/check-python-release-metadata.py` enforces that the classifier + exists exactly when the family is declared. +- No doc may claim support outside the three targets. + +Acceptance evidence: the metadata gate passes; a doc search for +"free-threaded" returns only the Beta statements above. + +### Work package H — Closure and promotion gate + +Intent: make the tier decision evidence-based and reversible. + +Required changes: + +- Write `plans/closure/python-facade/333-free-threaded-cpython-314t-staged-support.md` + using the closure template. +- Promotion gate (Beta to Stable) requires all of: + - one release in which the family is `required` and the aggregate is + green on all three targets; + - the GIL family unchanged across that release; + - an adversarial/contention evidence pass (TSan on the Rust build, or a + documented substitute such as a soak with concurrent callbacks, + streams, and tunnels); + - no unresolved medium-or-higher finding in the closure. +- Expanding to more platforms, adding `abi3t`, or adding 3.13t/3.15t needs a + new plan; it is not an extension of this one. + +Acceptance evidence: the closure record with the evidence matrix and an +explicit promotion decision (promote or retain Beta with the reason). + +## 8. Failure, cancellation, restart, and contention semantics + +- **Handler parallelism**: on 3.14t, up to `max_python_callbacks` handlers + execute Python in parallel. The callback semaphore and pre-response + admission are unchanged. A handler that shares mutable Python state without + its own lock may race; that is the caller's responsibility and is + documented. +- **Stream producers**: bounded by the Plan 322 producer budget; concurrent + iterables may run in parallel; teardown observation before each pull is + unchanged. +- **Timeouts**: still close the HTTP request, not Python code; the callback + permit stays held until the handler returns. +- **One-shot contention**: exactly one caller wins; the others receive the + existing typed errors; no partial state. +- **Tunnel contention**: the new in-flight guard makes the second concurrent + `recv` fail with an explicit error; no receiver is lost. +- **Shutdown**: unchanged; no join of arbitrary Python threads; no new + detached work. +- **GIL re-enabled at runtime**: if the interpreter is started with + `PYTHON_GIL=1`/ `-X gil=1`, execution serializes and all behavior remains + correct; the test asserts the module does not re-enable it on its own. + +## 9. Compatibility and migration + +- Additive: GIL users on 3.11-3.15 keep receiving `cp311-abi3`; 3.14t users + gain `cp314-cp314t`. No source or API change. +- Existing handlers that are not thread-safe may now be called in parallel on + 3.14t. This is a documented semantic change, not a silent one; + `max_python_callbacks=1` restores serialization. +- No Rust crate version or semver change. The wheel version stays unchanged + until a release is cut. +- PyPI publication is effectively irreversible; publish only after the + closure gates pass. Rollback inside a release window is removing the family + from the matrix; published wheels cannot be withdrawn reliably. + +## 10. Required tests + +### Focused unit tests + +- Tunnel recv in-flight guard: second concurrent call, guard reset after + success, error, and EOF. +- Matrix validator self-tests for the family dimension. + +### Integration tests + +- `test_free_threaded.py` cases 1-6 (work package C). +- Existing suite under 3.14t (the research run is the starting evidence; CI + becomes the authority). + +### Restart and recovery tests + +- Server start/stop under 3.14t with concurrent callbacks; shutdown with an + idle producer. + +### Contention and cancellation tests + +- Two threads racing `RequestBody.read()`; two threads racing + `BodyChunkIterator.__next__`; concurrent `Tunnel.recv`; concurrent + stream producers at budget. + +### Security and negative tests + +- Import under `-W error::RuntimeWarning` proves no GIL re-enable. +- Concurrent handlers never exceed `max_python_callbacks`. +- No error path logs request/response content. + +### Migration and compatibility tests + +- The existing GIL suite and wheel-set validator remain green with the family + added. + +## 11. Required verification commands + +```bash +# Free-threaded interpreter (local; CI uses actions/setup-python 3.14t) +uv python install 3.14t +PY="$(uv python find 3.14t)" + +# Compile under Py_GIL_DISABLED +PYO3_PYTHON="$PY" cargo check --manifest-path crates/eggserve-python/Cargo.toml --locked +PYO3_PRINT_CONFIG=1 PYO3_PYTHON="$PY" cargo check \ + --manifest-path crates/eggserve-python/Cargo.toml --locked +# (intentionally halts after printing) +# expect: target_abi=CPython-free_threaded-3.14 and build_flags=Py_GIL_DISABLED + +# Wheel, install, and suite +"$PY" -m pip install maturin==1.14.1 +PYTHON="$PY" bash scripts/test-python-wheel.sh +"$PY" -X gil=0 -W error::RuntimeWarning -c \ + "import sys, eggserve._native; assert sys._is_gil_enabled() is False" + +# Static guards +python3 scripts/wheel-matrix.py validate +python3 scripts/wheel-matrix.py self-test +python3 scripts/check-release-wheel-set.py --self-test +python3 scripts/check-python-release-metadata.py +python3 scripts/check-release-workflow.py +python3 scripts/check-release-workflow.py --self-test +python3 scripts/check-crate-topology.py + +# Repository gate +./scripts/verify.sh fast +``` + +Known baseline hazard: on macOS, `verify.sh fast` currently fails +`application_server_qualification_297::app_bounded_body_accepts_and_over_limit_rejects` +with a `ConnectionReset` (recorded in Plan 325's closure). Record the skip or +failure honestly; do not hide it or change the wrapper. + +## 12. Documentation updates + +- `docs/toolchain-support.md` (support table, ABI section, PyO3/maturin + versions, wheel matrix) +- `docs/python-packaging.md` (prerequisites, both families, tags) +- `docs/release-contract.md`, `docs/release-process.md` (family set, + Beta tier, `abi-proof` scope) +- `docs/library-capability-matrix.md` (Python wheel row) +- `docs/python-api.md`, `docs/python-http-server-compatibility.md` + (parallel execution and contention contract) +- `docs/threat-model.md`, `docs/extension-contract.md` (GIL wording) +- `SECURITY.md`, `CHANGELOG.md` +- `.opencode/skills/eggserve-dev/SKILL.md` +- `plans/subsystems/python-facade-roadmap.md`, `plans/registry.md`, + `release/plan-267-wheel-feasibility.md` (correction banner) + +## 13. Acceptance criteria + +1. `cp314-cp314t` wheels build for Linux x86_64 glibc, macOS arm64, and + Windows x86_64, with correct tags, and install on CPython 3.14t. +2. Importing the extension on 3.14t leaves the GIL disabled and raises no + `RuntimeWarning`. +3. The full Python suite plus `test_free_threaded.py` passes on 3.14t. +4. The GIL `cp311-abi3` family keeps its tags, wheel count, and suite + behavior. +5. The wheel matrix, release-set validator, metadata gate, and release + workflow understand exactly two families on the declared platform subsets. +6. The tunnel contention fix returns the explicit error; no one-shot state is + lost. +7. Documentation and the PyPI classifier state Beta for 3.14t on the three + targets only. +8. No security, confinement, TLS, HTTP-tier, or Rust public-API change. + +## 14. Stop conditions + +Stop and report rather than improvise when: + +- any free-threaded test shows a crash, data corruption, or a bridge state + race; the fallback is `#[pymodule(gil_used = true)]` plus the documented + unsupported contract, not a partial GO; +- the family-aware matrix would require changing the meaning of the existing + `tier` values or keeping a second platform list; +- a required target has no free-threaded interpreter and no reproducible + install path; narrow the family rather than publish an ABI-mismatched + wheel; +- `abi3t`, 3.15, or 3.13t becomes necessary to satisfy the tag set (out of + scope; new plan); +- the GIL family's tags or suite regress; +- the fix requires a new public Python API or runtime config knob. + +## 15. Closure evidence required + +- Exact wheel filenames and tags for all three targets, with the platform + matrix revision. +- CI run URLs for the free-threaded job and the existing lanes. +- `sys._is_gil_enabled()` output from the installed wheel, with the + `RuntimeWarning` assertion enabled. +- Test counts and output for the full suite and `test_free_threaded.py`. +- The 80-request/8-worker stress output (or the CI equivalent). +- Matrix/validator self-test output, including the negative cases. +- `PYO3_PRINT_CONFIG` output showing the free-threaded target ABI. +- Proof that the GIL `cp311-abi3` family is unchanged. +- Documentation and classifier diffs. +- Residual risks and the promotion decision (promote or retain Beta). + +## 16. Handoff notes + +- **Excluded-crate Cargo gotcha**: `crates/eggserve-python` is excluded from + the workspace and has its own lockfile. Running Cargo from a checkout nested + inside another workspace root can fail with "current package believes it's + in a workspace when it's not". Run Python-crate Cargo commands from the + primary checkout or a standalone worktree. +- The free-threaded interpreter is not installed by default. Install it with + `uv python install 3.14t` or `actions/setup-python` `3.14t`; record the + exact build and version in the closure. +- The pre-plan evidence is macOS arm64 only and is not qualification evidence. + Linux and Windows proof must come from CI or a qualifier. +- Do not add `abi3t-py315` opportunistically. The probe shows it is safe, but + it changes the 3.15 tag story and needs its own plan. +- Keep the family out of ARMv7/Windows arm64/musl until a free-threaded + interpreter is proven there. +- The macOS baseline test failure in section 11 is pre-existing; do not + "fix" it by weakening the wrapper or the suite. +- `verify.sh full` needs Python 3.14 plus maturin; the free-threaded lane is + separate and must not depend on the local 3.14 GIL interpreter. diff --git a/plans/implementation/python-facade/334-free-threaded-314t-qualification-and-tier-decision.md b/plans/implementation/python-facade/334-free-threaded-314t-qualification-and-tier-decision.md new file mode 100644 index 0000000..48972a1 --- /dev/null +++ b/plans/implementation/python-facade/334-free-threaded-314t-qualification-and-tier-decision.md @@ -0,0 +1,565 @@ +# Python Facade Milestone 334 — Free-threaded 3.14t qualification evidence and Beta tier decision + +> **Amendment — Milestone 330 (2026-11-28).** This record was Milestone 327 on +> its originating branch and is Milestone 334 here because `main` already +> assigns 327 to the TLS substrate corrective. The **Stable promotion recorded +> below was reversed**: the three soak records name no commit, wheel filename, +> or host and were taken on a single macOS arm64 host, so the claim is not +> reproducible from the record and does not meet this milestone's own +> "wheel filenames are the authority" standard. The family is **Beta**; +> Milestone 332 owns the per-target evidence and the promotion decision. + +Status: implemented (closure closed 2026-11-23: both named conditions are +observed, the contention soak passes three runs, the promotion gate is met, +and the owner confirmed the aggregate-as-release reading, so the branch promoted the family to +Stable; Milestone 330 reversed the tier to Beta — see +`plans/closure/python-facade/334-free-threaded-314t-qualification-and-tier-decision.md`) + +Approval: repository owner, 2026-11-23. Approved as drafted; no scope +change from the reviewed plan. + +Plan number: 334 + +Repository baseline: `4949a77acfe4114561bd7cfe59a8458ea1983af7` plus the +uncommitted Plan 333 change set (and this plan's registration). Execution +starts only after that change set is committed and the branch is pushed; +record the resulting SHA at handoff. + +Source roadmap: + +- `plans/subsystems/python-facade-roadmap.md` (Milestone 334) + +Long-term requirements: + +- `plans/000-long-term-specification.md#2` (Python `http.server`-shaped + facade; bounded resources; support claims must match evidence) +- `plans/001-terminology-and-domain-model.md` (verification vocabulary) +- `plans/002-long-term-roadmap.md` (phase 4, Python distribution) +- `plans/003-planning-process.md` §6 and §10 (handoff and planning review) +- `docs/toolchain-support.md`, `docs/release-process.md`, + `docs/python-packaging.md` + +Applicable ADRs: + +- none (no architecture or ownership decision; this plan gathers evidence and + may change a support-tier claim only) + +Primary class: infrastructure (qualification evidence and support-tier +decision) with invariant obligations (no product behavior change, the GIL +family unchanged, and no publication) + +## 1. Objective + +Turn the conditional closure of Plan 333 into an evidence-backed decision. +Two things must happen in order: + +1. **Close Plan 333.** Obtain the two conditions its closure record names — a + green `python-free-threaded` CI job and a three-target release aggregate + containing the `cp314t` wheels — then update the closure record, registry, + and roadmap from `conditionally closed` to `closed`. +2. **Decide the Beta tier.** Evaluate Plan 333's promotion gate. Add only the + missing evidence (a documented substitute for TSan: a bounded contention + soak), then either promote the family to Stable with the classifier and doc + changes, or retain Beta and record exactly why. + +The plan changes no product behavior in its evidence stage. A support-tier +change is conditional on all four promotion criteria and is the only +packaging change authorized here. + +### Decision being executed + +- **Evidence before claims.** No document, registry row, or classifier moves + ahead of an observed run. Run URLs and wheel filenames are the authority. +- **No publication.** The release workflow is dispatched with + `publish_target: none`; `publish-testpypi`, `publish-pypi`, and + `post-publish` are skipped by their existing conditions. Cutting a release + remains a separate owner action. +- **Aggregate counts as the release leg.** Plan 333's gate says one release in + which the family is required and the aggregate is green on all three + targets. A `publish_target: none` run produces exactly that aggregate. The + owner confirms this reading at the promotion decision; if a published + release is additionally required, this plan stops before the tier change. +- **TSan substitute is explicit.** A TSan-instrumented CPython is not + available in this environment, and Rust-only TSan would not cover Python + callback state. Plan 333 permits a documented substitute: a bounded soak + with concurrent callbacks, streams, and tunnels. + +## 2. Why this milestone is ready + +- Plan 333 is implemented and conditionally closed + (`plans/closure/python-facade/333-free-threaded-cpython-314t-staged-support.md`). + The declaration, family-aware matrix/validators/workflows, CI lane, tests, + and documentation are in the working tree. +- Local evidence already exists: the free-threaded wheel builds and 861 tests + pass on CPython 3.14.5t, the GIL wheel stays `cp311-abi3` with 861 tests + passing (`skipped=8`), the compile gates and clippy pass, and every + packaging/workflow gate and self-test passes. +- The repository is public, `main` is unprotected, `gh` is authenticated with + `repo`/`workflow` scopes, and the branch already tracks its remote. The + branch has no open PR; the last CI runs belong to merged PR #5. +- The CI trigger is known: `push: [main]` and `pull_request: [main]`, so a PR + is required to exercise the new job. The release trigger is + `workflow_dispatch` with a `none` mode that skips publication. +- The pypa manylinux image documentation confirms CPython 3.14t lives at + `/opt/python/cp314-cp314t`, matching the matrix entry. `setup-python` + documents the `-t` free-threaded version form. Both remain first-run + confirmations, not blockers. +- No hard dependency is open: Plan 333's own implementation is the input, and + the only sequencing requirement is committing it first. + +## 3. Current implementation evidence + +### 3.1 Plan 333 state + +| Item | State | +|---|---| +| Plan 333 implementation | all work packages A–G landed in the working tree | +| Plan 333 closure | `conditionally closed`, two medium findings (CI lane not observed; manylinux interpreter path unverified) | +| Local free-threaded suite | `Ran 861 tests ... OK` on CPython 3.14.5t, macOS arm64 | +| Local GIL suite | `Ran 861 tests ... OK (skipped=8)`, wheel `cp311-abi3` | +| Packaging gates | matrix validate/self-test, wheel-set self-test, metadata, workflow gate/self-test: pass | +| Commit | none; the Plan 333 change set (30 modified, 4 new files) is uncommitted, plus this plan and its registration | + +### 3.2 Missing evidence + +- No CI run for the change set (no commit, no PR). The new + `python-free-threaded` job has never executed. +- No release aggregate containing the three `cp314t` wheels. The Linux, + macOS arm64, and Windows x86_64 free-threaded builds have never run on + their real release targets. +- No soak or TSan evidence. The free-threaded test module proves specific + contention behaviors, not sustained concurrent load. +- Plan 333's promotion gate is unevaluated; the family is documented as Beta. + +### 3.3 Promotion gate as written in Plan 333 + +| Criterion | Current status | +|---|---| +| One release with the family `required` and the aggregate green on all three targets | not met (no run) | +| GIL family unchanged across that release | locally proven; needs the same run | +| Adversarial/contention pass (TSan or documented substitute) | not met (no soak) | +| No unresolved medium-or-higher finding in the closure | not met (two mediums) | + +## 4. Invariants that must not regress + +1. No product behavior, public API, runtime configuration, wire format, or + dependency change in the evidence stage. +2. The GIL `cp311-abi3` family keeps its tags, wheel count, version, and + suite behavior. +3. No publication, no version bump, no tag, and no PyPI environment approval + is part of this plan. +4. Every support or tier statement is backed by an observed run URL; local + evidence is labelled local. +5. No free-threaded claim outside CPython 3.14t on Linux x86_64 (glibc), + macOS arm64, and Windows x86_64. +6. `unsafe_code = "deny"`, confinement, TLS identity, framing ownership, and + crate topology stay untouched. +7. A lane failure may be fixed only with packaging, metadata, or matrix + corrections. Any required product-behavior change stops the plan. + +## 5. Scope + +### In scope + +- Committing and pushing the Plan 333 change set; opening a PR to `main` and + observing CI. +- Dispatching the release workflow with `publish_target: none` on the feature + branch and observing preflight, the 13 builds, `abi-proof`, the four + qualifiers, and the aggregate. +- Bounded fixes when a lane fails: matrix interpreter/ABI metadata, workflow + wiring, validator expectations, or harness assumptions. No behavior change. +- Updating the Plan 333 closure record to `closed` with run evidence. +- A stdlib-only soak script for free-threaded contention evidence, three + recorded runs, and a TSan-feasibility note. +- The promotion decision: either the classifier/doc tier change to Stable, or + a recorded decision to retain Beta. +- The Plan 334 closure record and registry/roadmap updates. + +### Explicitly out of scope + +- Publishing to TestPyPI or PyPI; creating tags or GitHub Releases. +- 3.13t, 3.15t, `abi3t`, PyPy, ARMv7, Windows arm64, or musl free-threaded + support. +- New platforms, new runtime knobs, new Python API, or dependency changes. +- TSan as a mandatory gate; performance measurement or claims. +- Any change to Plan 333's historical plan body beyond its status line and + closure record. + +## 6. Required production changes + +### Crates and ownership + +None in the evidence stage. The soak is a standalone script under `scripts/`; +it consumes only public Python surface and adds no crate dependency. Topology +must stay green. + +### Config and policy + +None. The release matrix already declares the two families; this plan only +confirms the declared interpreters on real runners. + +### Protocol and compatibility + +None. No wire or API behavior changes. + +### Runtime and concurrency + +None. The soak exercises existing bounds (`max_python_callbacks`, the Plan 322 +producer budget, one-shot errors, and the tunnel guard) without adding +semantics. + +### Frontend or operator surface (CLI / Python) + +None in the evidence stage. If the tier is promoted, only the PyPI classifier +and documentation change; no runtime surface changes. + +### Security and confinement + +None. The soak must not log payload content and must use loopback only. + +### Documentation and static guards + +- `scripts/check-python-release-metadata.py` must accept exactly one + free-threading classifier whose tier matches the documented support level; + today it hard-codes the Beta classifier. This is required so a promotion + cannot leave metadata and docs out of sync. +- Documentation updates are listed in section 12; only the tier statements + change, and only after the decision. + +## 7. Ordered work packages + +### Work package A — Land Plan 333 and observe CI + +Intent: produce the first named closure condition with the exact change set +that was locally verified. + +Required changes: + +- Commit the Plan 333 change set, together with this plan's registration (one + commit is acceptable; two commits, Plan 333 then Plan 334, are cleaner). Name + Plan 333 and its evidence in the message. Do not amend or rebase the Plan 325 + history. +- Push the branch and open a PR to `main` (the only trigger that exercises CI + for a non-`main` branch). The PR body lists the local evidence and the two + named conditions. +- Observe all five jobs: `rust`, `platform-compile`, `supply-chain`, `python`, + and `python-free-threaded`. +- If a lane fails, classify the failure before editing: packaging/metadata + defect (allowed, minimal fix in a follow-up commit) or product behavior + defect (stop; see section 14). + +Acceptance evidence: + +- PR URL and exact head SHA. +- Green run URL for the PR, with the `python-free-threaded` job visible. +- The free-threaded job log shows the `3.14t` interpreter, the compile check, + the installed wheel, the GIL-free assertion, and the full suite count. + +### Work package B — Produce the three-target release aggregate + +Intent: produce the second closure condition without publishing. + +Required changes: + +- Dispatch `release.yml` on the feature branch with + `publish_target: none`. The branch, not `main`, carries the updated + workflow and matrix. +- Confirm preflight passes (supply-chain, metadata, matrix and workflow + self-tests), then the 13 build entries, `abi-proof`, the four qualifiers, + and `aggregate`. +- Confirm the aggregate contains exactly the declared set: 10 GIL wheels plus + `wheel-manylinux-x86_64-ft`, `wheel-macos-arm64-ft`, and + `wheel-windows-x86_64-ft`. +- Record the Linux container interpreter actually used; if the pinned image + exposes a different path, correct only the matrix `interpreter` field and + rerun. + +Acceptance evidence: + +- Release run URL and source SHA. +- `aggregate` green; validator output proving the exact 13-pair set. +- Artifact listing with the three `-ft` wheels and their platform tags. +- `abi-proof` still installs only the GIL wheel across CPython 3.11–3.15. + +### Work package C — Close Plan 333 + +Intent: replace the conditional record with the observed evidence. + +Required changes: + +- Edit `plans/closure/python-facade/333-free-threaded-cpython-314t-staged-support.md`: + status `conditionally closed` → `closed`; add both run URLs, the wheel list, + and the resolution of the two medium findings (or a corrected finding if a + lane needed a fix). +- Update `plans/registry.md` and + `plans/subsystems/python-facade-roadmap.md`: row 333 and the milestone + table become `closed`; the current-milestone note cites the closure. + +Acceptance evidence: closure record diff, registry/roadmap rows, no remaining +medium-or-higher finding attributable to Plan 333. + +### Work package D — Adversarial and contention evidence + +Intent: satisfy the promotion gate's evidence leg with a bounded, repeatable +substitute for TSan. + +Required changes: + +- Add `scripts/soak-python-free-threaded.py` (stdlib only, 3.14t only). It + starts a `lowlevel.Server` on loopback with `request_body_mode="buffer"`, + `max_python_callbacks` configurable, and runs a bounded mixed workload: + concurrent buffered POSTs with a locked counter, concurrent + `Response.stream` responses with byte verification, repeated tunnel + upgrades with concurrent `recv` contention, one-shot body/iterator races, + and at least one server stop/start cycle. +- The script writes one JSON record per run: interpreter build, GIL state, + configuration, request/worker counts, per-scenario success/failure counts, + observed max concurrency, peak RSS, final thread count, and duration. It + exits non-zero on any unexpected error, crash, or content mismatch. +- Provide `--self-test` for its bookkeeping and fixture builders so the script + is testable without a server. +- Document the TSan decision: no TSan-instrumented CPython is available, and + Rust-only TSan would not observe Python callback state; the soak plus the + existing contention tests are the substitute Plan 333 permits. +- Run three repetitions (for example 400 requests / 8 workers / 60–120 s + each) and retain the JSON records as + `plans/closure/python-facade/334-soak-{1,2,3}.json` (or as fenced blocks in + the closure record). + +Acceptance evidence: script self-test output, three JSON records with zero +errors, and the TSan assessment paragraph. No timing threshold is asserted. + +### Work package E — Evaluate the gate and decide the tier + +Intent: make one explicit, evidence-based Beta/Stable decision. + +Required changes: + +- Evaluate all four Plan 333 criteria against the runs from WP-A/B/D and the + closed Plan 333 record. +- If all four hold **and** the owner confirms the aggregate-as-release + reading: change the classifier to + `Programming Language :: Python :: Free Threading :: 3 - Stable`, update the + tier statements, and update the metadata gate/self-tests to require the + Stable classifier for the declared family. +- Otherwise retain the Beta classifier and record the unmet criterion and the + owner decision. No partial promotion. +- Either outcome updates only packaging metadata and documentation. + +Acceptance evidence: a gate matrix with each criterion marked met/not met and +its URL or record; classifier diff (or explicit retain decision); metadata +gate passes in both configurations via its self-tests. + +### Work package F — Close Plan 334 + +Intent: record the decision and leave the control surface truthful. + +Required changes: + +- Write `plans/closure/python-facade/334-free-threaded-314t-qualification-and-tier-decision.md` + with the requirement-to-evidence matrix, run URLs, soak records, the + decision, and any residual findings. +- Update `plans/registry.md` (row 334, current milestone, next number) and the + roadmap status, graph, and milestone table. + +Acceptance evidence: closure record, registry/roadmap diffs, next number +advanced, and no claim stronger than the recorded evidence. + +## 8. Failure, cancellation, restart, and contention semantics + +- **CI lane failure.** Stop and classify. Packaging/metadata/wiring fixes may + be made in a follow-up commit and rerun. A discrepancy that requires + changing bridge behavior or a public contract ends the plan and becomes a + corrective implementation plan. +- **Release lane failure.** Fix only the matrix `interpreter`/ABI metadata or + workflow wiring, then rerun the whole workflow. Never hand-assemble an + aggregate or publish to bypass a failed qualifier. +- **Soak failure.** Any crash, corruption, content mismatch, or unexpected + exception is a stop condition. Do not reduce the workload until it passes; + record the failure. If the family cannot be qualified, retaining Beta (or + opting out with `gil_used = true` in a separate plan) is the fallback. +- **Cancellation and restart.** The soak uses bounded waits and terminates + its server in `finally`; a cancelled run produces no evidence and is rerun + from a clean process. +- **Partial or stale evidence.** A run that did not execute the declared + workload is recorded as not run, never as pass. Evidence from a different + SHA is labelled and not reused. +- **Concurrent writers.** Only one agent edits the closure/registry surfaces; + the work packages are ordered to avoid overlapping edits. + +## 9. Compatibility and migration + +- No product change is planned. The free-threaded consumer contract and wheel + tags stay exactly as Plan 333 shipped them. +- A promotion changes only the advertised support tier; installing, running, + and failing over are unchanged. A retain decision changes nothing. +- No semver decision is made here. A published release that carries the + family remains a separate manual action and is not part of this plan. +- Rollback: a classifier/doc change is a two-line revert; no artifact or + runtime behavior is affected. + +## 10. Required tests + +### Focused unit tests + +- `scripts/soak-python-free-threaded.py --self-test` (bookkeeping, scenario + construction, JSON shape). +- `scripts/check-python-release-metadata.py` in both tier configurations + (Beta and Stable) via fixtures or a self-test. + +### Integration tests + +- The full free-threaded installed-wheel suite through CI (authority) and + locally where needed. +- The full GIL suite through CI, proving the unchanged family. + +### Restart and recovery tests + +- The soak's stop/start cycle, including a shutdown with an idle stream. + +### Contention and cancellation tests + +- Soak scenarios: concurrent callbacks at the permit bound, concurrent + producers at the budget, tunnel `recv` contention, one-shot body and + iterator races, and client disconnects during streams. + +### Security and negative tests + +- GIL-free import assertion with `-W error::RuntimeWarning` (CI). +- Soak uses loopback only and logs no request or response content. + +### Migration and compatibility tests + +- Wheel-set validator self-tests and the GIL `abi-proof` lane. + +## 11. Required verification commands + +```bash +# Work package A +git add -A +git commit -m "Plan 333: free-threaded CPython 3.14t staged support" +git push -u origin feat/auto-20261116-7cc8b1dc +gh pr create --base main --head feat/auto-20261116-7cc8b1dc \ + --title "Plan 333: free-threaded CPython 3.14t staged support" +gh pr checks --watch + +# Work package B (must run on the branch that carries the updated workflow) +gh workflow run release.yml --ref feat/auto-20261116-7cc8b1dc \ + -f publish_target=none +gh run list --workflow release.yml --limit 3 +gh run watch --exit-status + +# Work package D +/path/to/python3.14t scripts/soak-python-free-threaded.py --self-test +/path/to/python3.14t scripts/soak-python-free-threaded.py \ + --requests 400 --workers 8 --duration 120 --json /tmp/soak-1.json +# repeat twice; retain all three JSON records + +# Static guards (unchanged expectations) +python3 scripts/check-python-release-metadata.py +python3 scripts/wheel-matrix.py validate +python3 scripts/wheel-matrix.py self-test +python3 scripts/check-release-wheel-set.py --self-test +python3 scripts/check-release-workflow.py +python3 scripts/check-release-workflow.py --self-test +python3 scripts/check-crate-topology.py +``` + +Known baseline hazard: on macOS, `./scripts/verify.sh fast` currently aborts +at `application_server_qualification_297::app_bounded_body_accepts_and_over_limit_rejects` +(`ConnectionReset`), as recorded in Plan 325's closure. Record it honestly; do +not change the wrapper. CI runs the same lanes directly. + +Excluded-crate Cargo commands from this nested worktree fail workspace +discovery; run them from a standalone copy or worktree (Plan 333 §16). + +## 12. Documentation updates + +- `plans/closure/python-facade/333-free-threaded-cpython-314t-staged-support.md` + (status and evidence; no historical rewrite). +- `plans/closure/python-facade/334-free-threaded-314t-qualification-and-tier-decision.md`. +- `plans/registry.md`, `plans/subsystems/python-facade-roadmap.md`. +- If promoted: `docs/toolchain-support.md`, `docs/python-packaging.md`, + `docs/release-contract.md`, `docs/release-process.md`, + `docs/library-capability-matrix.md`, `SECURITY.md`, `CHANGELOG.md`, + `.opencode/skills/eggserve-dev/SKILL.md`, and the pyproject classifier. +- If retained: one sentence in the Plan 334 closure and the docs update + explaining the unmet criterion; the Beta statements stay. + +## 13. Acceptance criteria + +1. The Plan 333 change set is committed and pushed; a PR to `main` exists with + a green CI run, including `python-free-threaded`. +2. A `publish_target: none` release run reaches a green `aggregate` with the + exact 13 required platform/family pairs, including the three `-ft` wheels. +3. The GIL `abi-proof` lane in that run still proves the unchanged + `cp311-abi3` family. +4. Plan 333's closure record is `closed` with both run URLs and no unresolved + medium-or-higher finding attributable to it. +5. The soak script exists, self-tests, and produces three JSON records with + zero unexpected errors; the TSan-substitute rationale is recorded. +6. The promotion gate is evaluated criterion by criterion; the family is + either Stable with metadata/docs/gate updated, or Beta with the unmet + criterion and owner decision recorded. +7. No product behavior, API, dependency, platform, or publication change + occurred; the GIL family is unchanged. + +## 14. Stop conditions + +Stop and report rather than improvise when: + +- CI or the release aggregate shows a crash, data corruption, or a bridge + state race under the free-threaded build; the fallback is not a partial + promotion; +- a lane failure requires changing product behavior, a public contract, or a + dependency rather than packaging metadata; +- the Linux container interpreter or a target runner cannot provide a 3.14t + interpreter and no declared alternative exists; +- the aggregate cannot be produced without publishing, or the owner requires a + published release before promotion (publication is out of scope); +- the GIL family's tags, wheel count, or suite regress; +- the soak cannot be run against a real 3.14t build, or its results + contradict the existing contention tests; +- an unresolved medium-or-higher finding would remain at the promotion + decision. + +## 15. Closure evidence required + +- PR URL, head SHA, and the green CI run URL with all five jobs. +- Release run URL, source SHA, aggregate output, and the artifact list with + the three `-ft` wheel names and tags. +- The `abi-proof` readout for the unchanged GIL family. +- Three soak JSON records, the self-test output, and the TSan assessment. +- The promotion gate matrix with URLs/records and the owner-confirmed + decision. +- The device/OS evidence for each target (hosted runner identity is enough). +- Documentation and classifier diffs, or the retain-Beta decision. +- Registry/roadmap rows and the advanced next milestone number. + +## 16. Handoff notes + +- **CI trigger.** Only `pull_request: [main]` or `push: [main]` runs CI. A + branch push alone produces nothing; the PR is the mechanism. +- **Release trigger.** Dispatch on the feature branch so the updated + `release.yml` and matrix are used. `publish_target: none` skips both publish + jobs and, by their conditions, `post-publish`; no environment approval or + secret is needed. +- **External visibility.** Commit, push, PR, and workflow dispatch are all + externally visible; execute them only under the owner's approval of this + plan. +- **Cost.** CI is roughly 10–15 minutes. The release dry run builds 13 entries + and runs four native qualifiers; expect 30–60 minutes of runner time. +- **First-run unknowns.** `actions/setup-python` 3.14t resolution on macOS and + Windows, and the pinned manylinux image interpreter path, are unverified + until WP-A/B. Both are matrix or workflow metadata, not design changes. +- **Do not publish.** TestPyPI/PyPI, tags, and GitHub Releases are outside + this plan. If promotion requires a published release, stop and let the owner + schedule it. +- **No cherry-picked evidence.** A rerun replaces a failed run; never cite an + earlier SHA's lane as current. +- **Preserve Plan 333.** Only its status line and closure record change; the + historical plan body and the Plan 267 banner stay intact. +- **macOS fast-gate hazard** and the **nested-worktree Cargo gotcha** from + Plan 333 §16 still apply. +- **Registry hygiene.** After registering 334, the next-number line must say + `328`. diff --git a/plans/registry.md b/plans/registry.md index 682d049..a4c09f8 100644 --- a/plans/registry.md +++ b/plans/registry.md @@ -9,7 +9,7 @@ Canonical direction remains in: - `plans/002-long-term-roadmap.md` - `plans/003-planning-process.md` -New milestone numbers continue from `330`. Legacy flat plans (`000`–`292`) and `release/plan-*.md` are archived in place and immutable. +New milestone numbers continue from `335`. Milestones 333 and 334 are the renumbered free-threaded records that Milestone 330 landed as Beta. Legacy flat plans (`000`–`292`) and `release/plan-*.md` are archived in place and immutable. ## Status vocabulary @@ -32,7 +32,7 @@ Dependency vocabulary: **hard / interface / soft / operational** (`003-planning- | Static confinement + static service | active | `plans/subsystems/static-confinement-roadmap.md` | 316 Windows directory-buffer offset realignment (closed) | 310 closed the fuzz harness and made the NT directory-buffer parser public and platform neutral; that surfaced two parser defects (F1 zero budget, F2 offsets). 316 closed them: the parser was correct and the FFI struct was wrong, so the struct was deleted rather than realigned, the corpus was regenerated from the authoritative layout, and the topology gate now enforces the agreement. The Windows runtime qualification suite remains a manual lane. Sole static/path/filesystem authority itself is unchanged. | | Direct H1 runtime + service contract | active | `plans/subsystems/direct-h1-runtime-roadmap.md` | 321 peerless-transport trust boundary (closed); 324 runtime/TLS hardening follow-ups (closed) | 294–297 polish campaign closed; 299 F3 repair closed. Plan 300's publication completed on 2026-09-25 and was closed by Milestone 304, whose disclosed condition — that the published artifact predated the post-tag corrective batch — Milestone 305 discharged by republishing the corrected 0.5.0 line on 2026-10-22. Milestones 306–309 are all closed: one runtime-error authority, an accurate drift-bounded Plan 253 ledger, a parity-preserving compatibility projection, and one accept-error classification authority. A post-audit security pass added 321 (peerless `trust_unix` trust boundary) and 324 (systemd double adoption, framing rejection close, identity PEM bound); both are closed, with records under `plans/closure/direct-h1-runtime/`. | | Planning governance | active | `plans/subsystems/planning-governance-roadmap.md` | 314 publication-state staleness sweep | Milestones 1 and 302 closed. Reopened: six surfaces still describe the published 0.4.0 line as pending, including the agent-facing skill. Interface dependency: 304's closure record supplies the facts. | -| Python facade | active | `plans/subsystems/python-facade-roadmap.md` | 322 streamed-response producer bounds (closed) | Milestone 311 is closed: the bridge's second listing renderer is gone and the 1 MiB response-byte ceiling now applies to the Python path. A post-audit security pass added 322: streamed-response producers are detached per response and not bounded by the callback permit, and the empty-yield branch does not observe receiver closure. Plan 322 is closed, with the record under `plans/closure/python-facade/`. | +| Python facade | active | `plans/subsystems/python-facade-roadmap.md` | 330 free-threaded 3.14t adoption (closed); 333–334 renumbered free-threaded records (closed, Beta); 331 concurrency hardening (ready); 332 contention evidence + tier promotion (ready) | Milestone 311 is closed: the bridge's second listing renderer is gone and the 1 MiB response-byte ceiling now applies to the Python path. A post-audit security pass added 322: streamed-response producers are detached per response and not bounded by the callback permit, and the empty-yield branch does not observe receiver closure. Plan 322 is closed, with the record under `plans/closure/python-facade/`. The 2026-11-28 free-threading audit found the extension already advertises `Py_MOD_GIL_NOT_USED` (PyO3 0.29 opt-out default) while the docs say free-threaded is unsupported, and Plan 267's rationale for that claim is inverted. Milestone 330 integrates the adjacent free-threaded branch as **Beta** and renumbers its records to 333/334; 331 hardens the concurrency contracts the audit found; 332 owns the per-target contention evidence and the only Beta→Stable decision. Plan 330 completed the integration on 2026-11-28: the branch's records are 333/334, the classifier and every touched doc state Beta, and the branch's Stable promotion is reversed. The recorded CI evidence is carried forward unchanged — CI run 45277923657 (861 tests on CPython 3.14.10t, GIL stays disabled) and release run 45283657891 (13-pair aggregate, 5/5 ABI-proof lanes). | | CLI, ops, and observability | active | `plans/subsystems/cli-ops-observability-roadmap.md` | 320 QUIC advisory remediation (closed); 323 post-audit hygiene sweep (closed); 325 compatible dependency refresh (closed); 326 public-bind acknowledgment tightening (closed) | 312 closed the routine Windows/macOS compile coverage. 313 closed the lint policy: `missing_docs` and `clippy::undocumented_unsafe_blocks` are enforced in the root lint table, with lanes for the Python-internal feature, the excluded Python crate, and the Windows confinement boundary. 315 closed the dependency specification consolidation: a root `[workspace.dependencies]` table owns the shared versions and the `rustls` floor, with all three lockfiles byte-identical. 318 closed the `rustls` floor guard. A post-audit security pass added 320 (Quinn/`rustix`/`tokio` advisories and an offline floor guard) and 323 (operator documentation and repository hygiene); both are closed, with records under `plans/closure/cli-ops-observability/`. Plan 325 is closed: all three latest-compatible lockfiles are refreshed and aligned, the audit tools are current, and audits, denies, floors, MSRV, and required test suites pass with the documented macOS skip. Upstream transitive feature-tree differences and the `verify.sh fast` wrapper's macOS skip limitation are recorded in the closure. No product-source or release change. Plan 326 (allocated on the feature branch, originally 320) widens the acknowledgment requirement to any non-loopback bind without changing the flag's acknowledgment-only semantics. | | TLS identity | active | `plans/subsystems/tls-identity-roadmap.md` | 328 reload ALPN coherence (closed); 329 H3 send-window bound (closed) | 327 corrected five seam defects at `26649bd` (provider panic, ALPN/runtime disagreement, CLI timeout mismatch, identity-cap order dependence, H3 transport-bound diagnostics) without a tier or default change. Its follow-up security review found that a running server's reload swap still accepted an h2 advertisement on an HTTP/2-disabled runtime; 328 enforces the check at the swap with the previous identity live. Originally allocated 321/322 on the feature branch and renumbered when the post-audit batch landed 320–325. Closures: `plans/closure/tls-identity/327-tls-substrate-corrective.md`, `plans/closure/tls-identity/328-reload-alpn-coherence.md`. Milestone 329 (closed) bounds the H3 send-window retained-write cap and `max_send_buf_size` at `u32::MAX`, closing 327's remaining low finding; closure: `plans/closure/tls-identity/329-h3-send-window-bound.md`. | | Docs architecture (overview index + deep dives) | closed | `plans/subsystems/docs-architecture-roadmap.md` | 301 closed (overview + deep dives refreshed to 0.4.0 baseline) | Trace: `plans/closure/docs-architecture/293-architecture-overview-deep-dive-refresh.md`. Interface: closed 294–299 code state + Plan 300 publication as review input. | @@ -78,6 +78,11 @@ Dependency vocabulary: **hard / interface / soft / operational** (`003-planning- | TLS identity | 327 | closed | `plans/implementation/tls-identity/327-tls-substrate-corrective.md` | The five reviewed defects are corrected with regression tests; Python/MSRV/clippy lanes pass. Closure: `plans/closure/tls-identity/327-tls-substrate-corrective.md`. The static canonicalization failure recorded there was fixed upstream by Plan 323; only the platform-specific `eggserve-server` test remains local-only. | | TLS identity | 328 | closed | `plans/implementation/tls-identity/328-reload-alpn-coherence.md` | `ServerHandle::replace_tls_config` rejects an h2-advertising snapshot when the runtime cannot serve HTTP/2, before the swap, leaving the previous identity live; `tls_identity::reload_rejects_h2_alpn_when_http2_disabled` fails on the earlier behavior. The raw `TlsReloadHandle` accessor remains a documented bypass. Closure: `plans/closure/tls-identity/328-reload-alpn-coherence.md`. | | TLS identity | 329 | closed | `plans/implementation/tls-identity/329-h3-send-window-bound.md` | **Low.** `Http3Config.send_window` (quinn's per-connection retained-write memory cap) and `max_send_buf_size` are bounded to `1..=u32::MAX`, matching `http2.max_send_buf_size`, with field-named diagnostics and unit tests at and above the ceiling; the QUIC VarInt ceiling stays on the wire-encoded fields. Closes the remaining 327 low finding recorded in its closure section 13. No CLI/Python surface, default, tier, or wire change. Closure: `plans/closure/tls-identity/329-h3-send-window-bound.md`. | +| Python facade | 330 | closed | `plans/implementation/python-facade/330-free-threaded-314t-branch-adoption.md` | **Capability.** Integrate the adjacent free-threaded branch (`feat/auto-20261116-7cc8b1dc` tip `6e3003f`) onto `main` as a **Beta** `cp314-cp314t` family: explicit `#[pymodule(gil_used = false)]`, `-t` CI lane, 8 concurrency tests, three `-ft` matrix entries, family-aware validators, tunnel `recv` CAS guard, and corrected docs. Merge-tree conflicts at merge time: `CHANGELOG.md`, `plans/registry.md`, and `plans/subsystems/python-facade-roadmap.md` (the last because the plan-set commit edited the same roadmap). Renumbers the branch's 326/327 records to **333/334** (no collision with main's public-bind 326 and TLS 327) and reverses only the branch's Stable flip. Hard dependency: no milestone; the branch tip is a hard input. Closure: `plans/closure/python-facade/330-free-threaded-314t-branch-adoption.md`. | +| Python facade | 331 | ready | `plans/implementation/python-facade/331-free-threading-concurrency-contract-hardening.md` | **Invariant.** Concurrent `BodySource.read_all`/`read_range` can silently return empty/short data (take-`detach`-restore with a best-effort restore), the request-body bridge has the same restore shape with typed but inconsistent behavior, `BodyChunkIterator` and tunnel `recv` lack contention regressions, `HTTPServer` close/serve is unsynchronized, `AsyncServer.track()` is loop-thread-only without enforcement, and two suite counters are GIL-shaped. Hard dependency: 330 (do not re-implement its tunnel guard). | +| Python facade | 332 | ready | `plans/implementation/python-facade/332-free-threaded-contention-evidence-and-promotion.md` | **Infrastructure.** Make the tier claim repeatable: provenance-complete soak records (commit, wheel filename/tag, host, interpreter), three-target runs against the actual `-ft` wheels, a bounded contention subset in the `python-free-threaded` CI job, and a `publish_target: none` aggregate with run URL and hashes. The only milestone authorized to promote Beta→Stable; any unmet criterion retains Beta. Hard dependency: 330; soft: 331. | +| Python facade | 333 | closed | `plans/implementation/python-facade/333-free-threaded-cpython-314t-staged-support.md` | **Capability.** Renumbered from 326 on merge because main's 326 is the public-bind milestone. Adds the `cp314-cp314t` wheel family for Linux x86_64 glibc, macOS arm64, and Windows x86_64, family-aware wheel matrix/validators/release lanes, the `python-free-threaded` CI job, and the free-threaded concurrency contract and tests; `cp311-abi3` is unchanged. Evidence: CI run 45277923657 (861 tests on CPython 3.14.10t, GIL stays disabled) and release run 45283657891 (13-pair aggregate with the three `-ft` wheels; 5/5 ABI-proof lanes). Closure: `plans/closure/python-facade/333-free-threaded-cpython-314t-staged-support.md`. | +| Python facade | 334 | closed | `plans/implementation/python-facade/334-free-threaded-314t-qualification-and-tier-decision.md` | **Infrastructure.** Renumbered from 327 on merge. Obtained both 333 conditions, added `scripts/soak-python-free-threaded.py` with three zero-error records as the TSan substitute, and evaluated the promotion gate. The branch recorded a Stable promotion; Milestone 330 reversed it to **Beta** because the records name no commit, wheel filename, or host and cover one macOS arm64 host, so the claim is not reproducible from the record. Milestone 332 owns promotion. Closure: `plans/closure/python-facade/334-free-threaded-314t-qualification-and-tier-decision.md`. | ## Blocked work diff --git a/plans/subsystems/python-facade-roadmap.md b/plans/subsystems/python-facade-roadmap.md index 4584de8..b2aff10 100644 --- a/plans/subsystems/python-facade-roadmap.md +++ b/plans/subsystems/python-facade-roadmap.md @@ -1,6 +1,6 @@ # Python Facade Roadmap -Status: active (311 and 322 closed) +Status: active (311, 322, 333, and 334 closed; 330 closed as the adoption record; 331–332 planned) Long-term references: @@ -140,6 +140,18 @@ Known gaps at the baseline: - Plan 238 (async producer redesign) is deferred; the current async bridge is a bounded `asyncio.to_thread` + 16-chunk queue bridge and stays experimental. +- The extension declared free-threading support implicitly: PyO3 >= 0.28 + emits `Py_MOD_GIL_NOT_USED` for a `#[pymodule]` without `gil_used`, so a + source build on free-threaded CPython 3.14 already runs GIL-free while the + support contract says free-threaded is unsupported. The 2026-11-28 audit + confirmed this on 3.14.5t (GIL disabled after import; 856 tests pass) and + found Plan 267's "loads GIL-required" rationale inverted. **Tracked by + Milestone 330**: the declaration becomes explicit, the branch records are + renumbered, and the family lands as **Beta**. Milestone 331 hardens the + concurrency contracts the audit found; Milestone 332 owns the per-target + contention evidence and the only Beta→Stable decision. That adoption + landed on 2026-11-28: the branch records are 333/334 and the family is + **Beta**. ## 5. Target architecture @@ -155,13 +167,24 @@ canonical values into Python objects and nothing more. core compatibility runtime + static authority (closed) | +--> Milestone 311 (listing renderer consolidation) - `--> Milestone 322 (streamed-response producer bounds) + +--> Milestone 322 (streamed-response producer bounds) + +--> Milestone 333 (free-threaded 3.14t staged support, closed; renumbered 326) + +--> Milestone 334 (3.14t qualification and tier decision, closed at Beta; renumbered 327) + `--> Milestone 330 (free-threaded 3.14t adoption, Beta) + | + +--> Milestone 331 (concurrency contract hardening, hard) + `--> Milestone 332 (contention evidence + tier promotion, hard; 331 soft) ``` Milestone 311 has no hard dependency on other open milestones; it depends on the closed `eggserve-static` authority and on the closed core runtime projection. Milestone 322 is an independent post-audit corrective over the same closed bridge; it does not reopen the static-listing authority. +Milestone 330 integrated the adjacent free-threaded branch and renumbered its +records to 333/334, which stay closed as the originating capability and +qualification records. Milestone 331 depends on 330 for the landed declaration +and test module; Milestone 332 depends on 330 for the wheel family and treats +331's fixes as a soft prerequisite for any promotion decision. ## 7. Milestones @@ -219,6 +242,154 @@ exhaustion is a 503, not a hang; normal streaming, trailers, HEAD/body suppression, and truncation behavior are unchanged; the residual blocking limitation is documented. +### Milestone 330 — Free-threaded CPython 3.14t branch adoption (Beta) + +Class: capability + +Objective: integrate the adjacent free-threaded branch onto `main` as an +additive `cp314-cp314t` family for CPython 3.14t on Linux x86_64 (glibc), +macOS arm64, and Windows x86_64, with an explicit `gil_used = false` +declaration, a free-threaded CI lane, the concurrency tests, and corrected +documentation — at **Beta**, not Stable. + +Dependencies: the adjacent branch `feat/auto-20261116-7cc8b1dc` tip +`6e3003f` (hard, code-complete); PyO3 0.29 opt-out declaration semantics +(hard, resolved); Plan 267 Track A (interface, closed as DEFERRED and +superseded for this slice). + +Deliverable boundary: one additive wheel family; the branch's records +renumbered to 333/334; Beta tier in the classifier and every touched doc; +one declaration/tier guard. No publication, no new platform, no GIL-family +change, no concurrency-contract fix beyond what the branch carries. + +User or operator value: 3.14t users get an installable, documented Beta wheel +instead of an unqualified source build, and the documentation no longer +claims something the binary contradicts. + +Exit conditions: the merge lands with no plan-number collision; every tier +surface says Beta; the GIL family is unchanged; the 3.14t and GIL suites pass; +the declaration guard fails when the attribute or tier drifts. + +### Milestone 331 — Free-threading concurrency contract hardening + +Class: invariant + +Objective: remove silent wrong-data races from the Python-visible concurrency +contracts now that the GIL can be absent: the `BodySource` take/restore lost +read, the request-body bridge's restore consistency, untested single-consumer +contracts, the facade's close/serve race, and the async bridge's loop +affinity. + +Dependencies: Milestone 330 (hard; supplies the explicit declaration, the +free-threaded test module, and the tunnel `recv` guard this milestone must +not duplicate). + +Deliverable boundary: one shared take/restore helper with a typed +concurrent-entry error; regression tests for each contract; no public API +removal, no worker-count knob, no admission/default change. + +User or operator value: concurrent misuse fails loudly with a stable error +instead of returning plausible but wrong data. + +Exit conditions: a concurrent `BodySource` read returns the bytes once or +raises; sequential re-reads are unchanged; the facade close/serve race is +deterministic; the suite passes on both wheel families. + +### Milestone 332 — Free-threaded contention evidence and Beta→Stable promotion + +Class: infrastructure + +Objective: make the free-threaded claim repeatable — provenance-complete +soak records on all three targets against the actual `-ft` wheels, a bounded +contention subset in the free-threaded CI job, and a `publish_target: none` +aggregate — then decide Beta→Stable from that evidence. + +Dependencies: Milestone 330 (hard; wheel family, CI lane, soak script); +Milestone 331 (soft; a promotion decision should not precede the +concurrency-contract fixes). + +Deliverable boundary: qualification scripts, CI, records, and the tier +statement. No product behavior, no publication, no new target, no timing +gate. + +User or operator value: the documented support tier is backed by a run that +can be reproduced from a commit and a wheel filename, on every claimed +platform. + +Exit conditions: every promotion criterion is met and the classifier/doc +change lands with the evidence, or Beta is retained with the blocker named. + +### Milestone 333 — Free-threaded CPython 3.14t staged support (closed; renumbered from 326) + +Class: capability + +Objective: publish `cp314-cp314t` wheels for free-threaded CPython 3.14 on +Linux x86_64 glibc, macOS arm64, and Windows x86_64, and record the support +level as Beta until the promotion gate, without changing the GIL +`cp311-abi3` contract. + +Dependencies: PyO3 free-threading declaration semantics and the resolved +0.29.3 (hard, closed); maturin 1.14.1 pipeline pin (hard, closed); Plan 267 +Track A (interface, closed as DEFERRED; superseded for this slice by this +milestone); Plan 322 producer bounds (hard, closed). + +Deliverable boundary: one additive wheel family; an explicit +`#[pymodule(gil_used = false)]` declaration; a free-threaded CI lane; +family-aware wheel-matrix/release validators; free-threaded concurrency +tests; documentation and classifier. No Rust-crate API change, no HTTP, +TLS, or security change, no `abi3t`, no 3.13t/3.15t, and no platform outside +the three targets. + +User or operator value: 3.14t users get an installable binary wheel instead +of an unqualified source build, and the documented support level matches the +evidence. + +Exit conditions: the family builds and installs on all three targets; the +suite and the new concurrency tests pass with the GIL disabled; the GIL +family is unchanged; the validators enforce exactly the declared family; the +docs state Beta for the three targets only. + +Outcome: closed on the originating branch at `6e3003f` and merged by +Milestone 330 on 2026-11-28 with the Beta statement intact. Evidence: CI run +45277923657 (`python-free-threaded` green, 861 tests on CPython 3.14.10t, +GIL stays disabled) and release run 45283657891 (exact 13-pair aggregate with +the three `-ft` wheels; 5/5 ABI-proof lanes). + +### Milestone 334 — Free-threaded 3.14t qualification evidence and tier decision (closed; renumbered from 327) + +Class: infrastructure + +Objective: produce the two conditions named by Milestone 333's conditional +closure (a green PR CI run including the free-threaded lane, and a +`publish_target: none` three-target release aggregate), close 333, then make +one recorded Beta/Stable decision using 333's promotion gate and a bounded +contention soak as the TSan substitute. + +Dependencies: Milestone 333 implementation (hard, closed); repository write +access and the existing CI/release workflows (operational); owner +confirmation of the aggregate-as-release reading for promotion (interface). +No publication is in scope. + +Deliverable boundary: commit/PR/CI evidence, one release-workflow aggregate +with the three `-ft` wheels, the 333 closure update, a stdlib-only soak +script and three records, the TSan assessment, and either the Stable +classifier/doc change or a recorded retain-Beta decision. No behavior, API, +dependency, platform, or publication change. + +Exit conditions: CI green with `python-free-threaded`; aggregate green with +the exact 13 platform/family pairs; 333 closed with both run URLs; soak +self-test plus three zero-error records; the promotion gate evaluated and a +decision recorded. + +Outcome: closed on the originating branch at `6e3003f` with a Stable +promotion. The 2026-11-28 audit found the three soak records name no commit, +wheel filename, or host and were all taken on one macOS arm64 host, so the +claim is not reproducible from the record and does not meet the milestone's +own "wheel filenames are the authority" standard. Milestone 330 therefore +reversed the promotion to **Beta**; Milestone 332 owns the per-target +evidence and the decision. + + ## 8. Cross-cutting requirements ### Storage and migration @@ -240,7 +411,14 @@ enforced on every path that can produce a listing. ### Concurrency, cancellation, and recovery -Unchanged; the bridge keeps the existing bounded queue semantics. +GIL-enabled behavior is unchanged: callbacks and stream producers are bounded +by `max_python_callbacks` and the Plan 322 producer budget. On a +free-threaded build, up to that many callbacks and producers can execute +Python code in parallel; the bridge's Rust state stays behind `Mutex` and +atomics, and handler/iterable thread-safety is the caller's responsibility +(documented, with `max_python_callbacks=1` as the serialized mode). Timeouts +still cannot interrupt Python code. No new cancellation or shutdown +semantics. ### Observability and audit @@ -262,7 +440,10 @@ change; `architecture/eggserve-python.md` records the ownership boundary. Python test suite (`crates/eggserve-python/tests/`), packaging smoke tests, the Rust workspace suite through the excluded-crate check, stub/runtime fidelity comparison, and `./scripts/verify.sh fast` plus the Python lane of -`./scripts/verify.sh full`. +`./scripts/verify.sh full`. The free-threaded 3.14t lane is separate: it +compiles the excluded crate against a `-t` interpreter (`Py_GIL_DISABLED`), +builds and installs a `cp314-cp314t` wheel, asserts the GIL stays disabled, +and runs the suite plus `test_free_threaded.py`. ## 10. Risks and decision points @@ -272,6 +453,13 @@ fidelity comparison, and `./scripts/verify.sh fast` plus the Python lane of in the bridge) reintroduces the second authority this milestone removes. - Listing HTML is user-visible output. Changing it to satisfy a bound check is a compatibility change and must not happen silently. +- Free-threaded handlers execute in parallel, which is a user-visible + semantic change for handlers that share mutable Python state; the Beta + tier, the documentation, and `max_python_callbacks=1` are the mitigation. +- Routine CI has no TSan or adversarial soak; the promotion gate names that + evidence explicitly. +- Free-threaded interpreters are not guaranteed in every release lane + (ARMv7, Windows arm64, musl), so the family starts on three targets only. ## 11. Completion definition @@ -286,3 +474,8 @@ behavior. |---|---|---|---|---| | 311 | closed | `plans/implementation/python-facade/311-directory-listing-renderer-consolidation.md` | `plans/closure/python-facade/311-directory-listing-renderer-consolidation.md` | One listing renderer: the bridge delegates to `eggserve-static`, so both surfaces emit byte-identical HTML and enforce the same 1 MiB response-byte ceiling. Gate rule `check_plan311_listing_renderer_authority`. Reported follow-up: six pre-existing clippy lints in the excluded Python crate, which belong to Milestone 313's scope. | | 322 | closed | `plans/implementation/python-facade/322-streamed-response-producer-lifecycle-bounds.md` | `plans/closure/python-facade/322-streamed-response-producer-lifecycle-bounds.md` | `Response.stream` spawns a detached producer thread per response. The empty-yield branch never checks the closed receiver, and the callback permit ends before the producer runs, so a blocking/endless iterator can accumulate threads after disconnect/timeout. The plan checks closure before each pull, bounds producers with an admission permit, and documents the non-interruptible `__next__` limitation. | +| 330 | closed | `plans/implementation/python-facade/330-free-threaded-314t-branch-adoption.md` | `plans/closure/python-facade/330-free-threaded-314t-branch-adoption.md` | Integrates the adjacent free-threaded branch as Beta; renumbers its records; resolves the three merge conflicts; adds the declaration/tier guard. Hard dependency: none. | +| 331 | ready | `plans/implementation/python-facade/331-free-threading-concurrency-contract-hardening.md` | (to be written) | `BodySource` lost read, body-bridge restore consistency, single-consumer regressions, facade close/serve, async affinity, test atomicity, runtime envelope. Hard dependency: 330. | +| 332 | ready | `plans/implementation/python-facade/332-free-threaded-contention-evidence-and-promotion.md` | (to be written) | Provenance-complete three-target soak, bounded CI gate, aggregate evidence, Beta→Stable decision. Hard: 330; soft: 331. | +| 333 | closed | `plans/implementation/python-facade/333-free-threaded-cpython-314t-staged-support.md` | `plans/closure/python-facade/333-free-threaded-cpython-314t-staged-support.md` | Beta `cp314-cp314t` family on Linux x86_64 glibc, macOS arm64, and Windows x86_64; family-aware matrix/validators/release lanes; free-threaded CI lane and concurrency tests. Closed with both named conditions observed: CI run 45277923657 (`python-free-threaded` green, 861 tests on CPython 3.14.10t, GIL stays disabled) and release run 45283657891 (exact 13-pair aggregate with the three `-ft` wheels; 5/5 ABI-proof lanes). Renumbered from 326 on merge. | +| 334 | closed | `plans/implementation/python-facade/334-free-threaded-314t-qualification-and-tier-decision.md` | `plans/closure/python-facade/334-free-threaded-314t-qualification-and-tier-decision.md` | Produced both 333 conditions, added `scripts/soak-python-free-threaded.py` with three zero-error records as the TSan substitute, and evaluated the promotion gate. The branch promoted to Stable; Milestone 330 reversed it to **Beta** because the records name no commit, wheel filename, or host and cover one macOS arm64 host. Milestone 332 owns promotion. Renumbered from 327 on merge. | diff --git a/release/plan-267-wheel-feasibility.md b/release/plan-267-wheel-feasibility.md index 73b391f..e202a36 100644 --- a/release/plan-267-wheel-feasibility.md +++ b/release/plan-267-wheel-feasibility.md @@ -1,5 +1,17 @@ # Plan 267 — Free-threaded Python and long-tail wheel feasibility +> **Status correction — Plan 333 (2026-11-23).** Track A's **DEFERRED** +> verdict is superseded for the CPython 3.14t slice by +> `plans/implementation/python-facade/333-free-threaded-cpython-314t-staged-support.md`. +> Two premises in this record are stale for the currently resolved PyO3 +> 0.29.3: a free-threaded interpreter is available in CI +> (`actions/setup-python` `3.14t`) and locally (`uv python install 3.14t`), +> and `#[pymodule]` without `gil_used` declares free-threaded support since +> PyO3 0.28, so the extension does not load GIL-required by default. The +> GIL-enabled `cp311-abi3` contract, the `abi3t`/3.15t slice, and every other +> Track B-D decision below remains as recorded. Historical text is retained +> verbatim. + This is a qualification gate, not a publication order. Each item closes independently as GO, NO-GO, or DEFERRED. No item below changes the normal GIL-enabled CPython 3.11–3.15 `cp311-abi3` contract, the TLS/security diff --git a/release/wheel-matrix.toml b/release/wheel-matrix.toml index fe91826..44affd8 100644 --- a/release/wheel-matrix.toml +++ b/release/wheel-matrix.toml @@ -48,6 +48,11 @@ tier = "required" arch_family = "x86_64" libc = "glibc" artifact = "wheel-manylinux-x86_64" +abi_family = "cp311" +python_tag = "cp311" +abi_tag = "abi3" +interpreter = "python3.11" +setup_python = "3.11" notes = "Representative stable-ABI host; build-once test-many artifact (Plan 264). Same-arch container build, so build-host native smoke is valid." [[target]] @@ -64,6 +69,11 @@ tier = "required" arch_family = "aarch64" libc = "glibc" artifact = "wheel-manylinux-aarch64" +abi_family = "cp311" +python_tag = "cp311" +abi_tag = "abi3" +interpreter = "python3.11" +setup_python = "3.11" qualify_runner = "ubuntu-24.04-arm" notes = "Cross-built for deterministic packaging; never executed on the x86_64 build host. Execution belongs to qualify-aarch64-glibc on the ARM64 hosted runner (Plan 268). Covers 64-bit Raspberry Pi / Le Potato-class userspaces." @@ -81,6 +91,11 @@ tier = "required" arch_family = "armv7" libc = "glibc" artifact = "wheel-manylinux-armv7" +abi_family = "cp311" +python_tag = "cp311" +abi_tag = "abi3" +interpreter = "python3.11" +setup_python = "3.11" qemu_platform = "linux/arm/v7" qemu_image = "arm32v7/python:3.11-bookworm" notes = "Executed under a matching ARMv7 glibc userspace via QEMU; never proven by AArch64 compat mode alone." @@ -99,6 +114,11 @@ tier = "required" arch_family = "x86_64" libc = "musl" artifact = "wheel-musllinux-x86_64" +abi_family = "cp311" +python_tag = "cp311" +abi_tag = "abi3" +interpreter = "python3.11" +setup_python = "3.11" notes = "Pre-publish composition gate only; runtime proof is the Alpine post-publication smoke." [[target]] @@ -115,6 +135,11 @@ tier = "required" arch_family = "aarch64" libc = "musl" artifact = "wheel-musllinux-aarch64" +abi_family = "cp311" +python_tag = "cp311" +abi_tag = "abi3" +interpreter = "python3.11" +setup_python = "3.11" qualify_runner = "ubuntu-24.04-arm" notes = "Cross-built; never installed on the glibc build host. Pre-publish execution belongs to qualify-aarch64-musl in a native ARM64 Alpine container (Plan 268); post-publication Alpine smoke retained." @@ -132,6 +157,11 @@ tier = "required" arch_family = "armv7" libc = "musl" artifact = "wheel-musllinux-armv7" +abi_family = "cp311" +python_tag = "cp311" +abi_tag = "abi3" +interpreter = "python3.11" +setup_python = "3.11" qemu_platform = "linux/arm/v7" qemu_image = "arm32v7/python:3.11-alpine" notes = "Added by Plan 265. Rust/maturin target spelling confirmed against the pinned toolchain: armv7-unknown-linux-musleabihf. Executed under a matching ARMv7 musl userspace via QEMU with sh (no bash in minimal Alpine)." @@ -150,6 +180,11 @@ tier = "required" arch_family = "x86_64" libc = "darwin" artifact = "wheel-macos-x86_64" +abi_family = "cp311" +python_tag = "cp311" +abi_tag = "abi3" +interpreter = "python3.11" +setup_python = "3.11" notes = "Deployment tag is matrix policy (11_0); docs and validator derive from this file. Native baseline (auto, ignored on non-Linux); PyPI policy enforced separately." [[target]] @@ -157,7 +192,11 @@ id = "macos-arm64" name = "macOS arm64" rust_target = "aarch64-apple-darwin" platform_tag = "macosx_11_0_arm64" -runner = "macos-14" +# Plan 334: macos-14 stopped provisioning for this repository (its jobs were +# cancelled one second after assignment with runner_id 0, twice). The CI +# platform-compile lane proves macos-latest resolves an arm64 runner; the +# platform tag stays pinned by MACOSX_DEPLOYMENT_TARGET and this platform_tag. +runner = "macos-latest" manylinux = "auto" compatibility = "pypi" build = "native" @@ -166,6 +205,11 @@ tier = "required" arch_family = "arm64" libc = "darwin" artifact = "wheel-macos-arm64" +abi_family = "cp311" +python_tag = "cp311" +abi_tag = "abi3" +interpreter = "python3.11" +setup_python = "3.11" notes = "Native hosted runner build and smoke. Native baseline (auto); PyPI policy enforced separately." [[target]] @@ -182,6 +226,11 @@ tier = "required" arch_family = "x86_64" libc = "msvc" artifact = "wheel-windows-x86_64" +abi_family = "cp311" +python_tag = "cp311" +abi_tag = "abi3" +interpreter = "python3.11" +setup_python = "3.11" notes = "Native hosted runner build and smoke. Native baseline (auto); PyPI policy enforced separately." [[target]] @@ -198,9 +247,86 @@ tier = "required" arch_family = "arm64" libc = "msvc" artifact = "wheel-windows-arm64" +abi_family = "cp311" +python_tag = "cp311" +abi_tag = "abi3" +interpreter = "python3.11" +setup_python = "3.11" qualify_runner = "windows-11-arm" notes = "Cross-built artifact; never executed on the x86_64 Windows build host. Execution belongs to qualify-windows-arm64 on the native Windows ARM64 runner (Plan 268, required gate). Support remains functional (trusted/local-content only)." + +# --- Free-threaded CPython 3.14t family (Plan 333; Beta) --- +# +# Three targets only. ARMv7, Windows arm64, and musl are excluded until a +# free-threaded interpreter is proven there. Tier is required because a +# candidate entry never satisfies the release aggregate; public support +# maturity is Beta (classifier + docs), not the matrix tier. + +[[target]] +id = "linux-x86_64-glibc-ft" +name = "Linux x86_64 (glibc, free-threaded 3.14t)" +rust_target = "x86_64-unknown-linux-gnu" +platform_tag = "manylinux_2_17_x86_64" +runner = "ubuntu-latest" +manylinux = "2_17" +compatibility = "pypi" +build = "cross-container" +smoke = "native" +tier = "required" +arch_family = "x86_64" +libc = "glibc" +artifact = "wheel-manylinux-x86_64-ft" +abi_family = "cp314t" +python_tag = "cp314" +abi_tag = "cp314t" +interpreter = "/opt/python/cp314-cp314t/bin/python" +setup_python = "3.14t" +notes = "Free-threaded 3.14t build inside the pinned manylinux_2_17 container; the same-arch host installs and smokes the wheel. The container interpreter path follows the pypa manylinux /opt/python naming; verify it in CI and never substitute a GIL interpreter." + +[[target]] +id = "macos-arm64-ft" +name = "macOS arm64 (free-threaded 3.14t)" +rust_target = "aarch64-apple-darwin" +platform_tag = "macosx_11_0_arm64" +# Plan 334: same runner corrective as macos-arm64 (macos-14 did not provision). +runner = "macos-latest" +manylinux = "auto" +compatibility = "pypi" +build = "native" +smoke = "native" +tier = "required" +arch_family = "arm64" +libc = "darwin" +artifact = "wheel-macos-arm64-ft" +abi_family = "cp314t" +python_tag = "cp314" +abi_tag = "cp314t" +interpreter = "python3.14t" +setup_python = "3.14t" +notes = "Native free-threaded build and smoke via actions/setup-python 3.14t. The installed wheel must keep the GIL disabled (asserted in the smoke path)." + +[[target]] +id = "windows-x86_64-ft" +name = "Windows x86_64 (free-threaded 3.14t)" +rust_target = "x86_64-pc-windows-msvc" +platform_tag = "win_amd64" +runner = "windows-latest" +manylinux = "auto" +compatibility = "pypi" +build = "native" +smoke = "native" +tier = "required" +arch_family = "x86_64" +libc = "msvc" +artifact = "wheel-windows-x86_64-ft" +abi_family = "cp314t" +python_tag = "cp314" +abi_tag = "cp314t" +interpreter = "python3.14t" +setup_python = "3.14t" +notes = "Native free-threaded build and smoke via actions/setup-python 3.14t. Windows arm64 stays excluded from this family." + # --- Candidates (Plan 265 Track D; Plan 267 owns the final verdict) --- [[target]] @@ -217,6 +343,11 @@ tier = "candidate" arch_family = "i686" libc = "glibc" artifact = "wheel-manylinux-i686" +abi_family = "cp311" +python_tag = "cp311" +abi_tag = "abi3" +interpreter = "python3.11" +setup_python = "3.11" qemu_platform = "linux/386" qemu_image = "i386/python:3.11-bookworm" notes = "Candidate: promotion needs a clean dependency-closure build, binary-only install, release smoke, and acceptable CI cost. Not attempted in this plan; no dependency change authorized." @@ -235,6 +366,11 @@ tier = "candidate" arch_family = "i686" libc = "musl" artifact = "wheel-musllinux-i686" +abi_family = "cp311" +python_tag = "cp311" +abi_tag = "abi3" +interpreter = "python3.11" +setup_python = "3.11" qemu_platform = "linux/386" qemu_image = "i386/python:3.11-alpine" notes = "Candidate: same promotion bar as i686 glibc. Not attempted in this plan." @@ -253,4 +389,9 @@ tier = "candidate" arch_family = "i686" libc = "msvc" artifact = "wheel-windows-x86" +abi_family = "cp311" +python_tag = "cp311" +abi_tag = "abi3" +interpreter = "python3.11" +setup_python = "3.11" notes = "Candidate: promotion needs tag acceptance by current packaging tooling plus install/smoke evidence on a 32-bit Python lane (a win32 wheel cannot install on the 64-bit build-host Python, so no build-host native smoke). Not attempted in this plan." diff --git a/scripts/check-python-free-threaded-compile.sh b/scripts/check-python-free-threaded-compile.sh new file mode 100755 index 0000000..1da2781 --- /dev/null +++ b/scripts/check-python-free-threaded-compile.sh @@ -0,0 +1,41 @@ +#!/usr/bin/env bash +# check-python-free-threaded-compile.sh — compile the Python extension against +# a free-threaded CPython (Plan 333, work package D). +# +# Requires a `-t` interpreter. Set PYTHON=/path/to/python3.14t to override; +# the default matches `uv python install 3.14t` and actions/setup-python +# `3.14t` on PATH. +# +# PYO3_PYTHON is derived from the resolved interpreter so the PyO3 build-script +# probe and the cargo build target the same free-threaded ABI. + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)" + +PYTHON="${PYTHON:-python3.14t}" + +die() { printf 'FATAL: %s\n' "$*" >&2; exit 1; } + +command -v "$PYTHON" >/dev/null 2>&1 || die \ + "free-threaded interpreter not found: $PYTHON (install with 'uv python install 3.14t' or actions/setup-python '3.14t', or set PYTHON=...)" + +"$PYTHON" -c ' +import sys +import sysconfig + +if not sysconfig.get_config_var("Py_GIL_DISABLED"): + raise SystemExit(f"interpreter is not free-threaded (Py_GIL_DISABLED unset): {sys.executable}") +' || die "$PYTHON is not a free-threaded (3.14t) build" + +PYTHON_ABS="$("$PYTHON" -c 'import sys; print(sys.executable)')" +PYTHON_VERSION="$("$PYTHON" -c 'import sys; print(f"{sys.version_info.major}.{sys.version_info.minor}")')" + +echo "Free-threaded compile check" +echo " interpreter: $PYTHON_ABS" +echo " version: $PYTHON_VERSION (Py_GIL_DISABLED)" + +PYO3_PYTHON="$PYTHON_ABS" cargo check \ + --manifest-path "$REPO_ROOT/crates/eggserve-python/Cargo.toml" \ + --locked diff --git a/scripts/check-python-release-metadata.py b/scripts/check-python-release-metadata.py index 31860ba..a63761b 100755 --- a/scripts/check-python-release-metadata.py +++ b/scripts/check-python-release-metadata.py @@ -10,6 +10,56 @@ import zipfile from pathlib import Path +# Plan 334: the free-threading classifier is the advertised support tier. The +# gate accepts exactly one classifier, at the tier this constant declares, and +# requires it exactly when the cp314t family is a required matrix family. A +# tier change flips pyproject, the docs, and this constant in one change. +FREE_THREADING_CLASSIFIER_PREFIX = ( + "Programming Language :: Python :: Free Threading :: " +) +FREE_THREADING_TIERS = { + 1: "Unstable", + 2: "Beta", + 3: "Stable", + 4: "Resilient", +} +EXPECTED_FREE_THREADING_TIER = 2 + + +def free_threading_classifier_errors( + classifiers: list[str], + ft_declared: bool, + expected_tier: int = EXPECTED_FREE_THREADING_TIER, +) -> list[str]: + """Return classifier-contract violations for the declared ABI families.""" + errors: list[str] = [] + found = [ + classifier + for classifier in classifiers + if classifier.startswith(FREE_THREADING_CLASSIFIER_PREFIX) + ] + expected = ( + f"{FREE_THREADING_CLASSIFIER_PREFIX}{expected_tier} - " + f"{FREE_THREADING_TIERS[expected_tier]}" + ) + if len(found) > 1: + errors.append( + "pyproject declares more than one free-threading classifier: " + f"{sorted(found)}; declare exactly one" + ) + if ft_declared and expected not in found: + errors.append( + "the free-threading classifier must be exactly " + f"{expected!r} when the cp314t family is required " + f"(got {sorted(found) if found else 'none'})" + ) + if not ft_declared and found: + errors.append( + "the free-threading classifier must not be declared when the " + f"cp314t family is absent (got {sorted(found)})" + ) + return errors + def main() -> int: repo_root = Path(__file__).resolve().parent.parent @@ -116,9 +166,10 @@ def main() -> int: ) # --- B3: Python compatibility contract --- - # Plan 264: normal GIL-enabled CPython support is 3.11-3.15 through one - # cp311-abi3 artifact per platform. Free-threaded CPython is owned by - # Plan 267 and must not be advertised here. + # Plan 264 + Plan 333: GIL-enabled CPython support is 3.11-3.15 through + # one cp311-abi3 artifact per platform. The free-threaded family is + # cp314-cp314t on three targets only (Beta); no other free-threaded + # implementation or platform may be advertised here. requires_python = pyproject.get("project", {}).get("requires-python", "") if "3.11" not in requires_python: errors.append(f"requires-python does not include 3.11: {requires_python!r}") @@ -158,22 +209,104 @@ def main() -> int: if maturin_bindings != "pyo3": errors.append(f"maturin bindings != pyo3: {maturin_bindings!r}") - # --- B3b: ABI baseline agreement (Plan 264 Track D) --- - # The executable packaging configuration must agree on cp311-abi3: - # pyproject classifiers (checked above), the PyO3 abi3-py311 feature - # (checked below), and the release workflow interpreter baseline. + # --- B3b: Declared ABI families (Plan 264 Track D; Plan 333) --- + # The packaging configuration, the release matrix, and the release + # workflow must agree on exactly two families: the GIL cp311-abi3 family + # on every platform and the Beta cp314-cp314t family on three targets. + # The workflow takes both its build interpreter and its setup-python + # version from the matrix; a hard-coded interpreter is a defect. + build_requires = pyproject.get("build-system", {}).get("requires", []) + if not any( + isinstance(req, str) and req.strip().startswith("maturin>=1.14.1") + for req in build_requires + ): + errors.append( + "build-system maturin floor must be >=1.14.1 " + f"(got {build_requires!r})" + ) + + matrix_path = repo_root / "release" / "wheel-matrix.toml" + families: dict[str, set[str]] = {} + ft_platforms: set[str] = set() + matrix: dict = {} + try: + with open(matrix_path, "rb") as f: + matrix = tomllib.load(f) + except (FileNotFoundError, tomllib.TOMLDecodeError) as exc: + errors.append(f"wheel matrix unreadable for ABI-family checks: {exc}") + expected_tags = { + "cp311": ("cp311", "abi3"), + "cp314t": ("cp314", "cp314t"), + } + for target in matrix.get("target", []): + if target.get("tier") != "required": + continue + family = target.get("abi_family") + if not isinstance(family, str): + errors.append( + f"required target {target.get('id')!r} has no abi_family" + ) + continue + families.setdefault(family, set()).add( + target.get("platform_tag", "") + ) + if family == "cp314t": + ft_platforms.add(target.get("platform_tag", "")) + expected = expected_tags.get(family) + if expected is None: + errors.append(f"required target declares unknown family {family!r}") + continue + if (target.get("python_tag"), target.get("abi_tag")) != expected: + errors.append( + f"{target.get('id')}: tag triple " + f"{target.get('python_tag')}-{target.get('abi_tag')} " + f"!= {expected[0]}-{expected[1]}" + ) + if not target.get("interpreter") or not target.get("setup_python"): + errors.append( + f"{target.get('id')}: missing interpreter/setup_python " + "matrix metadata" + ) + if set(families) != set(expected_tags): + errors.append( + "required ABI families must be exactly cp311 + cp314t " + f"(got {sorted(families)})" + ) + declared_ft_platforms = { + "manylinux_2_17_x86_64", "macosx_11_0_arm64", "win_amd64", + } + if ft_platforms != declared_ft_platforms: + errors.append( + "free-threaded family platforms must be exactly the three " + f"declared targets (got {sorted(ft_platforms)})" + ) + ft_declared = "cp314t" in families + errors.extend( + free_threading_classifier_errors(classifiers, ft_declared) + ) + release_yml = repo_root / ".github" / "workflows" / "release.yml" if release_yml.is_file(): workflow_text = release_yml.read_text() - if "--interpreter python3.11" not in workflow_text: + if "--interpreter ${{ matrix.interpreter }}" not in workflow_text: errors.append( - "release workflow does not build against the python3.11 ABI " - "baseline (--interpreter python3.11 missing)" + "release workflow must take --interpreter from " + "matrix.interpreter" + ) + if re.search(r"--interpreter\s+python3\.\d+", workflow_text): + errors.append( + "release workflow hard-codes a python3.x interpreter; the " + "wheel matrix is its only authority" + ) + if "python-version: ${{ matrix.setup_python }}" not in workflow_text: + errors.append( + "release workflow must take actions/setup-python " + "python-version from matrix.setup_python" ) if "cp312-cp312" in workflow_text or "cp315-cp315" in workflow_text: errors.append( "release workflow appears to build per-minor cpNN wheels; " - "Plan 264 requires one cp311-abi3 artifact per platform" + "the GIL family requires one cp311-abi3 artifact per platform" ) # --- B4: Wheel architecture contract (if wheel exists in dist/) --- @@ -209,8 +342,14 @@ def main() -> int: break if name.endswith(".dist-info/WHEEL"): wheel_text = zf.read(name).decode() - if "abi3" not in wheel_text and "cp311" not in wheel_text: - errors.append(f"{whl.name} WHEEL metadata missing abi3 tag") + if not any( + token in wheel_text + for token in ("abi3", "cp311", "cp314t", "cp314") + ): + errors.append( + f"{whl.name} WHEEL metadata missing a declared " + "ABI tag" + ) if errors: print("Release preflight FAILED:", file=sys.stderr) @@ -222,5 +361,77 @@ def main() -> int: return 0 +def self_test() -> int: + """Exercise the classifier contract in both tier configurations.""" + beta = "Programming Language :: Python :: Free Threading :: 2 - Beta" + stable = "Programming Language :: Python :: Free Threading :: 3 - Stable" + unstable = ( + "Programming Language :: Python :: Free Threading :: 1 - Unstable" + ) + results = [] + + def check(name: str, condition: bool, detail: str = "") -> None: + results.append((name, bool(condition), detail)) + + check( + "beta-expected-beta-present", + free_threading_classifier_errors([beta], True, 2) == [], + ) + check( + "stable-expected-stable-present", + free_threading_classifier_errors([stable], True, 3) == [], + ) + check( + "beta-expected-stable-present", + len(free_threading_classifier_errors([stable], True, 2)) == 1, + ) + check( + "stable-expected-beta-present", + len(free_threading_classifier_errors([beta], True, 3)) == 1, + ) + check( + "declared-family-missing-classifier", + len(free_threading_classifier_errors([], True, 2)) == 1, + ) + check( + "wrong-tier-unstable", + len(free_threading_classifier_errors([unstable], True, 2)) == 1, + ) + check( + "two-tiers-rejected", + len(free_threading_classifier_errors([beta, stable], True, 2)) == 1, + ) + check( + "no-family-no-classifier", + free_threading_classifier_errors([], False, 2) == [], + ) + check( + "no-family-with-classifier", + len(free_threading_classifier_errors([beta], False, 2)) == 1, + ) + unrelated = free_threading_classifier_errors( + ["Programming Language :: Python :: 3.14"], True, 2 + ) + check( + "unrelated-classifiers-ignored", + len(unrelated) == 1 and beta in unrelated[0], + repr(unrelated), + ) + + failures = [name for name, ok, _ in results if not ok] + for name, ok, detail in results: + suffix = "" if ok else ": " + detail + print(f"{'ok ' if ok else 'FAIL'}{name}{suffix}") + print( + f"self-test: {len(results)} checks, {len(failures)} failure(s)" + ) + if failures: + print("failed: " + ", ".join(failures), file=sys.stderr) + return 1 + return 0 + + if __name__ == "__main__": + if "--self-test" in sys.argv[1:]: + raise SystemExit(self_test()) raise SystemExit(main()) diff --git a/scripts/check-release-wheel-set.py b/scripts/check-release-wheel-set.py index 9f23a82..a99fb68 100644 --- a/scripts/check-release-wheel-set.py +++ b/scripts/check-release-wheel-set.py @@ -20,11 +20,17 @@ DEFAULT_MATRIX = REPO_ROOT / "release" / "wheel-matrix.toml" -def load_required_targets(matrix_path: Path) -> tuple[set[str], set[str]]: - """Load required + declared platform tags from the wheel-matrix authority. - - Returns (required, declared). Raises SystemExit with a clear message when - the manifest is missing or invalid so the release fails closed. +def load_required_targets( + matrix_path: Path, +) -> tuple[set[tuple[str, str]], set[tuple[str, str]], dict[str, tuple[str, str]]]: + """Load required + declared (platform_tag, abi_family) pairs. + + Returns (required, declared, families) where families maps an ABI family + to its declared (python_tag, abi_tag) triple. Plan 333 adds the family + dimension: one platform may carry both cp311-abi3 and cp314-cp314t, so + uniqueness and completeness are keyed on the pair. Raises SystemExit with + a clear message when the manifest is missing or invalid so the release + fails closed. """ try: with open(matrix_path, "rb") as f: @@ -39,29 +45,35 @@ def load_required_targets(matrix_path: Path) -> tuple[set[str], set[str]]: print("FAIL: wheel matrix authority_version must be 1", file=sys.stderr) raise SystemExit(1) targets = data.get("target", []) - required: set[str] = set() - declared: set[str] = set() - seen_tags: dict[str, str] = {} + required: set[tuple[str, str]] = set() + declared: set[tuple[str, str]] = set() + families: dict[str, tuple[str, str]] = {} + seen_pairs: dict[tuple[str, str], str] = {} for t in targets: tag = t.get("platform_tag") + family = t.get("abi_family") tid = t.get("id", "?") - if not tag: + if not tag or not family: continue - declared.add(tag) - if tag in seen_tags: + pair = (tag, family) + declared.add(pair) + if pair in seen_pairs: print( - f"FAIL: wheel matrix duplicate platform tag {tag!r} " - f"({seen_tags[tag]!r} and {tid!r})", + f"FAIL: wheel matrix duplicate (platform, family) pair {pair!r} " + f"({seen_pairs[pair]!r} and {tid!r})", file=sys.stderr, ) raise SystemExit(1) - seen_tags[tag] = tid + seen_pairs[pair] = tid + families.setdefault( + family, (t.get("python_tag", ""), t.get("abi_tag", "")) + ) if t.get("tier") == "required": - required.add(tag) + required.add(pair) if not required: print("FAIL: wheel matrix declares no required targets", file=sys.stderr) raise SystemExit(1) - return required, declared + return required, declared, families def verify_record(archive: zipfile.ZipFile) -> list[str]: @@ -155,6 +167,24 @@ def format_targets(targets: set[str]) -> str: return "\n ".join(sorted(targets)) +def format_pairs(pairs: set[tuple[str, str]]) -> str: + return "\n ".join(f"{family}: {tag}" for tag, family in sorted(pairs)) + + +def family_for_wheel( + python_tag: str, abi_tag: str, families: dict[str, tuple[str, str]] +) -> str | None: + """Map a wheel's tag triple to a declared ABI family (Plan 333). + + A dotted future ABI (for example abi3.abi3t) is accepted only when a + declared family names that exact abi tag; nothing is inferred. + """ + for family, (py, abi) in families.items(): + if python_tag == py and abi_tag == abi: + return family + return None + + def _synthetic_wheel(directory: Path, version: str, platform_tag: str, python_tag: str = "cp311", abi_tag: str = "abi3", build_tag: str = "") -> Path: @@ -194,23 +224,30 @@ def _synthetic_wheel(directory: Path, version: str, platform_tag: str, def cmd_self_test(matrix: Path) -> int: - """Fixture-level proofs (Plan 265): baseline passes; missing, extra, - duplicate, wrong-ABI, and generic-linux fixtures fail.""" + """Fixture-level proofs: baseline passes; missing, extra, duplicate, + wrong-family, and generic-linux fixtures fail.""" import subprocess import tempfile - required, declared = load_required_targets(matrix) + required, declared, families = load_required_targets(matrix) version = "0.2.0" failures = 0 - def run_case(name: str, tags: list[str], expect_ok: bool, - expect_snippet: str = "", - python_tag: str = "cp311", abi_tag: str = "abi3") -> None: + def write_pairs(directory: Path, pairs: set[tuple[str, str]]) -> None: + for platform_tag, family in sorted(pairs): + python_tag, abi_tag = families[family] + _synthetic_wheel(directory, version, platform_tag, python_tag, abi_tag) + + def run_case( + name: str, + pairs: set[tuple[str, str]], + expect_ok: bool, + expect_snippet: str = "", + ) -> None: nonlocal failures with tempfile.TemporaryDirectory(prefix="wheelset-selftest-") as tmp: tmpdir = Path(tmp) - for tag in tags: - _synthetic_wheel(tmpdir, version, tag, python_tag, abi_tag) + write_pairs(tmpdir, pairs) proc = subprocess.run( [sys.executable, str(Path(__file__).resolve()), str(tmpdir), "--version", version, "--matrix", str(matrix)], @@ -218,7 +255,9 @@ def run_case(name: str, tags: list[str], expect_ok: bool, ) ok = proc.returncode == 0 combined = proc.stdout + proc.stderr - if ok == expect_ok and (not expect_snippet or expect_snippet in combined): + if ok == expect_ok and ( + not expect_snippet or expect_snippet in combined + ): print(f"OK {name}") else: print(f"FAIL {name}: rc={proc.returncode} expected_ok={expect_ok}") @@ -226,44 +265,87 @@ def run_case(name: str, tags: list[str], expect_ok: bool, failures += 1 baseline = sorted(required) - run_case("baseline required set passes", baseline, True) - run_case("missing required target fails", baseline[1:], False, "missing required") - run_case("undeclared extra target fails", - baseline + ["manylinux_2_17_ppc64le"], False, "undeclared") - with tempfile.TemporaryDirectory(prefix="wheelset-dup-") as tmp: - tmpdir = Path(tmp) - _synthetic_wheel(tmpdir, version, baseline[0]) - # Second wheel file carrying the same platform tag. The numeric - # build segment keeps the filename valid while the platform collides. - _synthetic_wheel(tmpdir, version, baseline[0], build_tag="1") - proc = subprocess.run( - [sys.executable, str(Path(__file__).resolve()), - str(tmpdir), "--version", version, "--matrix", str(matrix)], - capture_output=True, text=True, + run_case("baseline required set passes", set(baseline), True) + run_case( + "missing required target fails", set(baseline[1:]), False, + "missing required", + ) + ft_pairs = [pair for pair in baseline if pair[1] == "cp314t"] + if len(ft_pairs) != 3: + print(f"FAIL expected 3 free-threaded pairs, got {ft_pairs}") + failures += 1 + else: + run_case( + "missing free-threaded target fails", + {pair for pair in baseline if pair != ft_pairs[0]}, + False, + "missing required", ) - if proc.returncode != 0 and "duplicate platform tag" in proc.stdout + proc.stderr: - print("OK duplicate platform tags fail") - else: - print(f"FAIL duplicate platform tags: rc={proc.returncode}") - print((proc.stdout + proc.stderr)[-2000:]) - failures += 1 - run_case("wrong ABI tag fails", baseline, False, "abi", - python_tag="cp312", abi_tag="cp312") - run_case("generic linux tag fails", ["linux_x86_64"], False, "linux") + ft_platform, ft_family = ft_pairs[0] + with tempfile.TemporaryDirectory(prefix="wheelset-dup-") as tmp: + tmpdir = Path(tmp) + write_pairs(tmpdir, set(baseline)) + python_tag, abi_tag = families[ft_family] + _synthetic_wheel( + tmpdir, version, ft_platform, python_tag, abi_tag, + build_tag="1", + ) + proc = subprocess.run( + [sys.executable, str(Path(__file__).resolve()), + str(tmpdir), "--version", version, "--matrix", str(matrix)], + capture_output=True, text=True, + ) + combined = proc.stdout + proc.stderr + if proc.returncode != 0 and "duplicate" in combined: + print("OK duplicate family pair fails") + else: + print(f"FAIL duplicate family pair: rc={proc.returncode}") + print(combined[-2000:]) + failures += 1 + with tempfile.TemporaryDirectory(prefix="wheelset-tag-") as tmp: + tmpdir = Path(tmp) + write_pairs(tmpdir, set(baseline)) + _synthetic_wheel( + tmpdir, version, ft_platform, "cp314", "abi3", build_tag="2" + ) + proc = subprocess.run( + [sys.executable, str(Path(__file__).resolve()), + str(tmpdir), "--version", version, "--matrix", str(matrix)], + capture_output=True, text=True, + ) + combined = proc.stdout + proc.stderr + if proc.returncode != 0 and "no declared ABI family" in combined: + print("OK undeclared tag triple fails") + else: + print(f"FAIL undeclared tag triple: rc={proc.returncode}") + print(combined[-2000:]) + failures += 1 - # ARMv7 musl is accepted only when the wheel exists: baseline (which - # contains it) passes, and removing just that tag fails. - musl_armv7 = "musllinux_1_2_armv7l" + run_case( + "undeclared extra target fails", + set(baseline) | {("manylinux_2_17_ppc64le", "cp311")}, + False, + "undeclared", + ) + run_case( + "generic linux tag fails", {("linux_x86_64", "cp311")}, False, "linux", + ) + + musl_armv7 = ("musllinux_1_2_armv7l", "cp311") if musl_armv7 in required: - run_case("armv7-musl present passes (in baseline)", baseline, True) - run_case("armv7-musl missing fails", - [t for t in baseline if t != musl_armv7], False, "missing required") + run_case("armv7-musl present passes (in baseline)", set(baseline), True) + run_case( + "armv7-musl missing fails", + {pair for pair in baseline if pair != musl_armv7}, + False, + "missing required", + ) else: print("FAIL manifest does not require musllinux_1_2_armv7l") failures += 1 + _ = declared return 1 if failures else 0 - def main() -> int: args = parse_args() if args.self_test: @@ -275,7 +357,9 @@ def main() -> int: directory: Path = args.directory expected_version: str = args.version - required_targets, declared_targets = load_required_targets(args.matrix) + required_targets, declared_targets, families = load_required_targets( + args.matrix + ) allowed_targets = set(required_targets) if args.include_candidates: allowed_targets = set(declared_targets) @@ -287,8 +371,9 @@ def main() -> int: failures = 0 parsed = [] - seen_platforms: dict[str, str] = {} + seen_pairs: dict[tuple[str, str], str] = {} all_platforms: set[str] = set() + all_pairs: set[tuple[str, str]] = set() for wheel in wheels: # --- Check 1: filename shape --- @@ -306,6 +391,7 @@ def main() -> int: platform_tag = match.group("platform") platforms = list(dict.fromkeys(parse_platform_tags(platform_tag))) + family = family_for_wheel(python_tag, abi_tag, families) parsed.append({ "wheel": wheel, @@ -316,6 +402,8 @@ def main() -> int: "abi_tag": abi_tag, "platform_tag": platform_tag, "platforms": platforms, + "family": family, + "pair": (platform_tag, family), }) if failures: @@ -329,8 +417,17 @@ def main() -> int: abi_tag = entry["abi_tag"] platform_tag = entry["platform_tag"] platforms = entry["platforms"] + family = entry["family"] + pair = entry["pair"] print(f"\n--- {wheel.name} ---") + if family is None: + print( + f" FAIL: wheel tags {python_tag}-{abi_tag} match no " + "declared ABI family", + file=sys.stderr, + ) + failures += 1 # --- Check 2: project name --- if distribution != "eggserve": @@ -400,63 +497,58 @@ def _scalar(name: str) -> str | None: if line.lower().startswith("tag:"): tag_lines.append(line.split(":", 1)[1].strip()) - all_abi3 = True - all_cp311 = True - for tag in tag_lines: - parts = tag.split("-") - if len(parts) == 3: - tag_python, tag_abi, tag_platform = parts - if tag_abi != "abi3": - all_abi3 = False - if not tag_python.startswith("cp311"): - all_cp311 = False - - if not all_abi3: - print( - f" FAIL: not all WHEEL Tag abi fields are abi3: {tag_lines}", - file=sys.stderr, - ) - failures += 1 - else: - print(f" OK: WHEEL Tag abi = abi3") - - if not all_cp311: + if family is None: print( - f" FAIL: not all WHEEL Tag python fields start with cp311: {tag_lines}", + f" FAIL: WHEEL tags match no declared ABI family: " + f"{tag_lines}", file=sys.stderr, ) failures += 1 else: - print(f" OK: WHEEL Tag python starts with cp311") - - # Check filename abi/python tags match WHEEL tags - if abi_tag != "abi3": - print( - f" FAIL: filename abi tag '{abi_tag}' != expected 'abi3'", - file=sys.stderr, - ) - failures += 1 - - if not python_tag.startswith("cp311"): - print( - f" FAIL: filename python tag '{python_tag}' does not start with 'cp311'", - file=sys.stderr, - ) - failures += 1 + expected_python, expected_abi = families[family] + bad = [ + tag for tag in tag_lines + if len(tag.split("-")) != 3 + or tag.split("-")[0] != expected_python + or tag.split("-")[1] != expected_abi + ] + if not tag_lines or bad: + print( + f" FAIL: WHEEL Tag triple != declared " + f"{expected_python}-{expected_abi} ({family}): " + f"{tag_lines}", + file=sys.stderr, + ) + failures += 1 + else: + print( + f" OK: WHEEL Tag = {expected_python}-{expected_abi} " + f"({family})" + ) + if (python_tag, abi_tag) != (expected_python, expected_abi): + print( + f" FAIL: filename tags {python_tag}-{abi_tag} " + f"!= declared {expected_python}-{expected_abi} " + f"({family})", + file=sys.stderr, + ) + failures += 1 # --- Check 5: Tier 1 target set --- all_platforms.update(platforms) - # --- Check 6: no duplicate platform target --- + # --- Check 6: no duplicate (platform, family) pair --- for plat in platforms: - if plat in seen_platforms: + key = (plat, family) + if key in seen_pairs: print( - f" FAIL: duplicate platform tag '{plat}' in {wheel.name} " - f"(first seen in {seen_platforms[plat]})", + f" FAIL: duplicate (platform, family) pair {key!r} " + f"in {wheel.name} (first seen in {seen_pairs[key]})", file=sys.stderr, ) failures += 1 - seen_platforms[plat] = wheel.name + seen_pairs[key] = wheel.name + all_pairs.add(key) # --- Check 7: no generic linux_* --- for plat in platforms: @@ -524,20 +616,35 @@ def _scalar(name: str) -> str | None: # Every enabled required target must be present; no required target may # appear twice (enforced above); unexpected targets not declared in the # manifest fail; declared candidates may not silently count as supported. - missing = required_targets - all_platforms - extra = all_platforms - allowed_targets - undeclared = all_platforms - declared_targets + missing = required_targets - all_pairs + extra = all_pairs - allowed_targets + undeclared = all_pairs - declared_targets if missing: - print(f"FAIL: missing required targets:\n {format_targets(missing)}", file=sys.stderr) + print( + f"FAIL: missing required (platform, family) targets:\n " + f"{format_pairs(missing)}", + file=sys.stderr, + ) failures += 1 if undeclared: - print(f"FAIL: undeclared platform targets (not in wheel matrix):\n {format_targets(undeclared)}", file=sys.stderr) + print( + f"FAIL: undeclared (platform, family) targets (not in wheel " + f"matrix):\n {format_pairs(undeclared)}", + file=sys.stderr, + ) failures += 1 elif extra: - print(f"FAIL: unexpected extra platform targets:\n {format_targets(extra)}", file=sys.stderr) + print( + f"FAIL: unexpected extra (platform, family) targets:\n " + f"{format_pairs(extra)}", + file=sys.stderr, + ) failures += 1 if not missing and not extra: - print(f"OK: required target set is exact ({len(required_targets)} targets)") + print( + f"OK: required target set is exact " + f"({len(required_targets)} platform/family pairs)" + ) # --- Summary of platform distribution --- print(f"Platform targets found: {len(all_platforms)}") diff --git a/scripts/check-release-workflow.py b/scripts/check-release-workflow.py index 62c7b42..4a2004b 100755 --- a/scripts/check-release-workflow.py +++ b/scripts/check-release-workflow.py @@ -112,6 +112,35 @@ def check_workflow(text: str) -> list[str]: "in the maturin args" ) + # --- Plan 333: ABI-family build metadata --- + # The wheel matrix is the only interpreter authority. A free-threaded + # wheel gets an explicit import/GIL assertion, and setup-python follows + # the matrix instead of a hard-coded minor. + if "--interpreter ${{ matrix.interpreter }}" not in text: + errors.append( + "workflow must pass `--interpreter ${{ matrix.interpreter }}` " + "(the wheel matrix owns the ABI family)" + ) + if re.search(r"--interpreter\s+python3\.\d+", text): + errors.append( + "workflow must not hard-code a python3.x interpreter; the wheel " + "matrix is its only authority" + ) + if "python-version: ${{ matrix.setup_python }}" not in text: + errors.append( + "build job must take actions/setup-python `python-version` from " + "matrix.setup_python" + ) + if re.search(r"matrix\.abi_family\s*==\s*'cp314t'", text) is None: + errors.append( + "workflow must gate the free-threaded import assertion on " + "matrix.abi_family == 'cp314t'" + ) + elif "sys._is_gil_enabled() is False" not in text: + errors.append( + "free-threaded lane must assert sys._is_gil_enabled() is False" + ) + # --- Track D: explicit QEMU setup + sh (not bash) in minimal images --- # Build job QEMU setup (for matrix.qemu_platform). if "docker/setup-qemu-action" not in text: @@ -250,6 +279,30 @@ def check(name: str, text: str, expect_ok: bool, snippet: str = "") -> None: False, "exclude the evidence manifest", ) + check( + "hard-coded interpreter fails", + real.replace( + "--interpreter ${{ matrix.interpreter }}", + "--interpreter python3.11", + ), + False, + "hard-code", + ) + check( + "static setup-python fails", + real.replace( + "python-version: ${{ matrix.setup_python }}", + 'python-version: "3.11"', + ), + False, + "setup_python", + ) + check( + "missing free-threaded gate fails", + real.replace("matrix.abi_family == 'cp314t'", "true"), + False, + "free-threaded import assertion", + ) return 1 if failures else 0 @@ -279,6 +332,7 @@ def main(argv: list[str] | None = None) -> int: print(" 3.15 prerelease resolution present") print(' MACOSX_DEPLOYMENT_TARGET "11.0" pinned') print(" evidence MANIFEST excluded from twine upload set") + print(" matrix-owned interpreter/setup-python + free-threaded GIL gate") return 0 diff --git a/scripts/soak-python-free-threaded.py b/scripts/soak-python-free-threaded.py new file mode 100644 index 0000000..7e16ebb --- /dev/null +++ b/scripts/soak-python-free-threaded.py @@ -0,0 +1,931 @@ +#!/usr/bin/env python3 +"""Bounded contention soak for the free-threaded CPython wheel (Plan 334). + +This script is the documented substitute for a TSan-instrumented CPython: +no TSan-instrumented interpreter is available in the qualification +environment, and Rust-only TSan would not observe Python callback state. +It drives the public eggserve.lowlevel surface on loopback with a mixed +concurrent workload and writes one JSON record per run. + +Scenarios per run, across two server phases (a stop/start cycle): + +- concurrent buffered POSTs with a locked counter and payload digests +- concurrent Response.stream responses with exact byte verification +- one-shot RequestBody.read() races (exactly one winner) +- concurrent BodyChunkIterator.__next__ races (typed outcomes only) +- repeated tunnel upgrades with concurrent Tunnel.recv contention +- client disconnects during a slow streamed response + +The script never logs request or response content. It exits non-zero on any +unexpected exception, content mismatch, invariant violation, GIL re-enable, +or request-budget shortfall. + +Usage: + + python3.14t scripts/soak-python-free-threaded.py --self-test + python3.14t scripts/soak-python-free-threaded.py \ + --requests 400 --workers 8 --duration 120 --json /tmp/soak-1.json +""" + +import argparse +import hashlib +import http.client +import json +import platform +import queue +import resource +import socket +import sys +import sysconfig +import threading +import time + +HTTP_SCENARIOS = ("post", "stream", "race", "iter") +SCENARIOS = HTTP_SCENARIOS + ("tunnel", "disconnect") +CHUNK_COUNT = 6 +SLOW_CHUNK_COUNT = 64 +SLOW_CHUNK_DELAY = 0.01 +TUNNEL_RECV_SETTLE = 0.2 + +_lowlevel = None +_consumed_error = None + + +def _load_bindings(): + """Import the installed extension and cache the public symbols.""" + global _lowlevel, _consumed_error + if _lowlevel is not None: + return + from eggserve import lowlevel + from eggserve._native import RequestBodyConsumedError + + _lowlevel = lowlevel + _consumed_error = RequestBodyConsumedError + + +class Stats: + """Thread-safe counters for one soak run.""" + + def __init__(self): + self._lock = threading.Lock() + self.http_requests = 0 + self.ok = 0 + self.fail = 0 + self.by_scenario = {name: {"ok": 0, "fail": 0} for name in SCENARIOS} + self.errors = [] + + def request_done(self): + with self._lock: + self.http_requests += 1 + + def record(self, scenario, error=None): + with self._lock: + bucket = self.by_scenario[scenario] + if error is None: + self.ok += 1 + bucket["ok"] += 1 + else: + self.fail += 1 + bucket["fail"] += 1 + if len(self.errors) < 25: + self.errors.append( + {"scenario": scenario, "error": str(error)[:300]} + ) + + def snapshot(self): + with self._lock: + return { + "http_requests": self.http_requests, + "ok": self.ok, + "fail": self.fail, + "by_scenario": { + name: dict(bucket) + for name, bucket in self.by_scenario.items() + }, + "errors": list(self.errors), + } + + +class Concurrency: + """Track observed concurrent entries without blocking.""" + + def __init__(self): + self._lock = threading.Lock() + self.active = 0 + self.peak = 0 + + def enter(self): + with self._lock: + self.active += 1 + if self.active > self.peak: + self.peak = self.active + + def leave(self): + with self._lock: + self.active -= 1 + + def snapshot(self): + with self._lock: + return {"active": self.active, "peak": self.peak} + + +def payload_for(index): + """Deterministic request body for a request index.""" + seed = hashlib.sha256(("payload-%d" % index).encode("ascii")).digest() + size = 32 + (index % 8) * 64 + return (seed * ((size // len(seed)) + 1))[:size] + + +def payload_digest(payload): + return hashlib.sha256(payload).hexdigest() + + +def stream_chunks(index, count=CHUNK_COUNT): + """Deterministic chunk list for a streamed response.""" + seed = hashlib.sha256(("stream-%d" % index).encode("ascii")).digest() + chunks = [] + for offset in range(count): + digest = hashlib.sha256(seed + bytes([offset % 256])).digest() + size = 1 + (index + offset) % 97 + chunks.append((digest * ((size // len(digest)) + 1))[:size]) + return chunks + + +def stream_bytes(chunks): + return b"".join(chunks) + + +def scenario_for(index): + return HTTP_SCENARIOS[index % len(HTTP_SCENARIOS)] + + +def upgrade_request(path="/tunnel"): + return ( + "GET %s HTTP/1.1\r\nHost: soak\r\nUpgrade: soak-echo\r\n" + "Connection: upgrade\r\n\r\n" % path + ).encode("ascii") + + +def disconnect_request(index): + return ( + "GET /stream/slow/%d HTTP/1.1\r\nHost: soak\r\n" + "Connection: close\r\n\r\n" % index + ).encode("ascii") + + +def read_head(sock, limit=65536): + """Read up to and including the response head terminator.""" + data = b"" + while b"\r\n\r\n" not in data: + chunk = sock.recv(256) + if not chunk: + break + data += chunk + if len(data) > limit: + raise RuntimeError("response head exceeded %d bytes" % limit) + return data + + +def _gil_enabled(): + probe = getattr(sys, "_is_gil_enabled", None) + if probe is None: + return None + return bool(probe()) + + +def _peak_rss_bytes(): + usage = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss + if sys.platform == "darwin": + return int(usage) + return int(usage) * 1024 + + +def _interpreter(): + return { + "implementation": sys.implementation.name, + "version": platform.python_version(), + "build": sys.version.replace("\n", " "), + "platform": sysconfig.get_platform(), + "machine": platform.machine(), + "os": platform.platform(), + "gil_disabled_build": bool(sysconfig.get_config_var("Py_GIL_DISABLED")), + "debug_build": bool(sysconfig.get_config_var("Py_DEBUG")), + } + + +class Phase: + """One server lifetime with its own handler, queues, and counters.""" + + def __init__(self, callbacks, max_body_bytes): + _load_bindings() + self.server_concurrency = Concurrency() + self.client_concurrency = Concurrency() + self.tunnels = queue.Queue() + self.stats = Stats() + config = _lowlevel.RuntimeConfig( + port=0, + request_body_mode="buffer", + max_request_body_bytes=max_body_bytes, + max_python_callbacks=callbacks, + ) + self.server = _lowlevel.Server(config=config, handler=self.handle) + self.host = None + self.port = None + + def start(self): + self.server.start() + self.server.wait_ready() + host, port = self.server.addr.split(":") + self.host = host + self.port = int(port) + + def stop(self): + try: + self.server.shutdown() + except Exception: + pass + try: + self.server.wait() + except Exception: + pass + + def handle(self, request): + self.server_concurrency.enter() + try: + return self._dispatch(request) + except BaseException as exc: + return _lowlevel.Response.text( + 500, "handler-error:%s" % type(exc).__name__ + ) + finally: + self.server_concurrency.leave() + + def _dispatch(self, request): + path = request.path + if path.startswith("/stream/slow/"): + return self._slow_stream(path) + if path.startswith("/stream/"): + return self._stream(path) + if path.startswith("/post"): + return self._post(request) + if path.startswith("/race"): + return self._race(request) + if path.startswith("/iter"): + return self._iter(request) + if path.startswith("/tunnel"): + return self._tunnel(request) + return _lowlevel.Response.text(404, "unknown") + + def _post(self, request): + body = request.body.read() + return _lowlevel.Response.text(200, payload_digest(body)) + + def _stream(self, path): + try: + index = int(path.rsplit("/", 1)[1]) + except ValueError: + return _lowlevel.Response.text(400, "bad-index") + chunks = stream_chunks(index) + return _lowlevel.Response.stream( + 200, chunks, content_length=len(stream_bytes(chunks)) + ) + + def _slow_stream(self, path): + try: + index = int(path.rsplit("/", 1)[1]) + except ValueError: + index = 0 + + def generate(): + for offset in range(SLOW_CHUNK_COUNT): + time.sleep(SLOW_CHUNK_DELAY) + yield hashlib.sha256( + b"slow-%d-%d" % (index, offset) + ).digest() + + return _lowlevel.Response.stream(200, generate()) + + def _race(self, request): + body = request.body + barrier = threading.Barrier(2) + results = [] + lock = threading.Lock() + + def read_once(): + barrier.wait(timeout=10) + try: + outcome = ("ok", body.read()) + except BaseException as exc: + outcome = ("err", exc) + with lock: + results.append(outcome) + + threads = [ + threading.Thread(target=read_once, daemon=True) for _ in range(2) + ] + for thread in threads: + thread.start() + for thread in threads: + thread.join(15) + if any(thread.is_alive() for thread in threads): + return _lowlevel.Response.text(500, "race-timeout") + wins = [value for kind, value in results if kind == "ok"] + errors = [value for kind, value in results if kind == "err"] + valid = ( + len(wins) == 1 + and len(errors) == 1 + and isinstance(errors[0], _consumed_error) + ) + if not valid: + return _lowlevel.Response.text(500, "race-invariant") + return _lowlevel.Response.text(200, "ok") + + def _iter(self, request): + iterator = request.body.iter_chunks() + barrier = threading.Barrier(2) + results = [] + lock = threading.Lock() + + def pull(): + barrier.wait(timeout=10) + try: + outcome = ("ok", next(iterator)) + except BaseException as exc: + outcome = ("err", exc) + with lock: + results.append(outcome) + + threads = [ + threading.Thread(target=pull, daemon=True) for _ in range(2) + ] + for thread in threads: + thread.start() + for thread in threads: + thread.join(15) + if any(thread.is_alive() for thread in threads): + return _lowlevel.Response.text(500, "iterator-timeout") + if not any(kind == "ok" for kind, _ in results): + return _lowlevel.Response.text(500, "iterator-no-progress") + for kind, value in results: + if kind != "err" or isinstance(value, StopIteration): + continue + typed = isinstance(value, RuntimeError) and "borrow" in str( + value + ).lower() + if not typed: + return _lowlevel.Response.text(500, "iterator-untyped") + return _lowlevel.Response.text(200, "ok") + + def _tunnel(self, request): + capability = request.take_tunnel() + if capability is None: + return _lowlevel.Response.text(400, "no-tunnel") + handshake, tunnel = capability.accept() + self.tunnels.put(tunnel) + return handshake + + +def _run_scenario(phase, scenario, index, stats): + connection = http.client.HTTPConnection( + phase.host, phase.port, timeout=20 + ) + try: + if scenario == "post": + payload = payload_for(index) + connection.request( + "POST", "/post", body=payload, headers={"Connection": "close"} + ) + response = connection.getresponse() + body = response.read() + stats.request_done() + if response.status != 200: + raise RuntimeError("post status %d" % response.status) + if body.decode("ascii", "replace") != payload_digest(payload): + raise RuntimeError("post payload digest mismatch") + elif scenario == "stream": + chunks = stream_chunks(index) + expected = stream_bytes(chunks) + connection.request( + "GET", + "/stream/%d" % index, + headers={"Connection": "close"}, + ) + response = connection.getresponse() + body = response.read() + stats.request_done() + if response.status != 200: + raise RuntimeError("stream status %d" % response.status) + if body != expected: + raise RuntimeError("stream bytes mismatch") + elif scenario == "race": + payload = payload_for(index) + connection.request( + "POST", "/race", body=payload, headers={"Connection": "close"} + ) + response = connection.getresponse() + body = response.read() + stats.request_done() + if response.status != 200 or body != b"ok": + raise RuntimeError( + "race rejected: %d %s" + % (response.status, body[:40].decode("ascii", "replace")) + ) + else: + payload = payload_for(index) + connection.request( + "POST", "/iter", body=payload, headers={"Connection": "close"} + ) + response = connection.getresponse() + body = response.read() + stats.request_done() + if response.status != 200 or body != b"ok": + raise RuntimeError( + "iterator rejected: %d %s" + % (response.status, body[:40].decode("ascii", "replace")) + ) + stats.record(scenario) + finally: + connection.close() + + +def http_worker(phase, stats, stop, pace, index): + while not stop.is_set(): + scenario = scenario_for(index) + phase.client_concurrency.enter() + started = time.monotonic() + try: + _run_scenario(phase, scenario, index, stats) + except BaseException as exc: + message = str(exc)[:200] + stats.record(scenario, "%s: %s" % (type(exc).__name__, message)) + finally: + phase.client_concurrency.leave() + index += 1 + elapsed = time.monotonic() - started + if elapsed < pace: + time.sleep(pace - elapsed) + + +def _one_tunnel(host, port, phase, stats): + sock = socket.create_connection((host, port), timeout=15) + sock.settimeout(15) + try: + sock.sendall(upgrade_request()) + head = read_head(sock) + status_line = head.split(b"\r\n", 1)[0] + if b" 101 " not in status_line: + raise RuntimeError( + "upgrade rejected: %s" + % status_line[:80].decode("ascii", "replace") + ) + tunnel = phase.tunnels.get(timeout=15) + started = threading.Event() + holder = {} + + def blocking_recv(): + started.set() + try: + holder["value"] = tunnel.recv() + except BaseException as exc: + holder["error"] = exc + + worker = threading.Thread(target=blocking_recv, daemon=True) + worker.start() + if not started.wait(10): + raise RuntimeError("blocking recv did not start") + time.sleep(TUNNEL_RECV_SETTLE) + try: + tunnel.recv() + except RuntimeError as exc: + if "concurrent Tunnel.recv" not in str(exc): + raise RuntimeError( + "unexpected contention error: %s" % str(exc)[:120] + ) + else: + raise RuntimeError("concurrent Tunnel.recv was accepted") + sock.shutdown(socket.SHUT_RDWR) + worker.join(15) + if worker.is_alive(): + raise RuntimeError("blocking recv did not finish") + try: + tunnel.recv() + except RuntimeError as exc: + if "already closed" not in str(exc): + raise RuntimeError( + "unexpected post-close error: %s" % str(exc)[:120] + ) + else: + raise RuntimeError("closed tunnel.recv returned data") + if not holder: + raise RuntimeError("blocking recv produced no result") + stats.record("tunnel") + finally: + try: + sock.close() + except OSError: + pass + + +def tunnel_worker(phase, stats, stop, pace): + while not stop.is_set(): + started = time.monotonic() + try: + _one_tunnel(phase.host, phase.port, phase, stats) + except BaseException as exc: + message = str(exc)[:200] + stats.record("tunnel", "%s: %s" % (type(exc).__name__, message)) + elapsed = time.monotonic() - started + if elapsed < pace: + time.sleep(pace - elapsed) + + +def _one_disconnect(host, port): + sock = socket.create_connection((host, port), timeout=15) + sock.settimeout(15) + try: + sock.sendall(disconnect_request(7)) + head = read_head(sock) + status_line = head.split(b"\r\n", 1)[0] + if b" 200 " not in status_line: + raise RuntimeError( + "slow stream status: %s" + % status_line[:80].decode("ascii", "replace") + ) + finally: + sock.close() + + +def disconnect_worker(phase, stats, stop, pace): + while not stop.is_set(): + started = time.monotonic() + try: + _one_disconnect(phase.host, phase.port) + stats.record("disconnect") + except BaseException as exc: + message = str(exc)[:200] + stats.record( + "disconnect", "%s: %s" % (type(exc).__name__, message) + ) + elapsed = time.monotonic() - started + if elapsed < pace: + time.sleep(pace - elapsed) + + +def run_phase(phase, stats, seconds, workers, pace, base): + stop = threading.Event() + threads = [] + for worker_index in range(workers): + thread = threading.Thread( + target=http_worker, + args=(phase, stats, stop, pace, base + worker_index), + name="soak-http-%d" % worker_index, + daemon=True, + ) + threads.append(thread) + threads.append( + threading.Thread( + target=tunnel_worker, + args=(phase, stats, stop, 0.05), + name="soak-tunnel", + daemon=True, + ) + ) + threads.append( + threading.Thread( + target=disconnect_worker, + args=(phase, stats, stop, 0.2), + name="soak-disconnect", + daemon=True, + ) + ) + started = time.monotonic() + for thread in threads: + thread.start() + stop.wait(seconds) + stop.set() + for thread in threads: + thread.join(20) + return { + "seconds": time.monotonic() - started, + "stuck_threads": [thread.name for thread in threads if thread.is_alive()], + } + + +def _empty_record(args): + return { + "plan": "334", + "tool": "soak-python-free-threaded", + "started_at": None, + "interpreter": _interpreter(), + "gil": { + "disabled_build": bool(sysconfig.get_config_var("Py_GIL_DISABLED")), + "enabled_before": None, + "enabled_after": None, + }, + "config": { + "requests_minimum": args.requests, + "workers": args.workers, + "duration_requested_seconds": args.duration, + "max_python_callbacks": args.callbacks, + "request_body_mode": "buffer", + "max_request_body_bytes": args.max_body_bytes, + "pace_ms": args.pace_ms, + }, + "phases": [], + "totals": None, + "resources": {"peak_rss_bytes": None, "threads_at_end": None}, + "duration_seconds": None, + "problems": [], + "qualified": False, + } + + +def run(args): + record = _empty_record(args) + record["started_at"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) + record["gil"]["enabled_before"] = _gil_enabled() + stats = Stats() + started = time.monotonic() + phase_seconds = max(1.0, args.duration / 2.0) + base = 0 + for phase_index in range(2): + phase = Phase(args.callbacks, args.max_body_bytes) + phase.start() + try: + outcome = run_phase( + phase, stats, phase_seconds, args.workers, args.pace_ms / 1000.0, base + ) + finally: + phase.stop() + server_peak = phase.server_concurrency.snapshot()["peak"] + record["phases"].append( + { + "index": phase_index, + "seconds": round(outcome["seconds"], 3), + "stuck_threads": outcome["stuck_threads"], + "server_peak_concurrency": server_peak, + "client_peak_concurrency": phase.client_concurrency.snapshot()[ + "peak" + ], + "tunnel_queue_remaining": phase.tunnels.qsize(), + } + ) + if outcome["stuck_threads"]: + record["problems"].append( + "phase %d left worker threads running: %s" + % (phase_index, ",".join(outcome["stuck_threads"])) + ) + if server_peak > args.callbacks: + record["problems"].append( + "phase %d exceeded max_python_callbacks: %d > %d" + % (phase_index, server_peak, args.callbacks) + ) + base += 100000 + time.sleep(0.2) + record["duration_seconds"] = round(time.monotonic() - started, 3) + record["totals"] = stats.snapshot() + record["resources"]["peak_rss_bytes"] = _peak_rss_bytes() + record["resources"]["threads_at_end"] = threading.active_count() + record["gil"]["enabled_after"] = _gil_enabled() + if record["totals"]["fail"]: + record["problems"].append( + "%d recorded scenario failure(s)" % record["totals"]["fail"] + ) + if record["totals"]["http_requests"] < args.requests: + record["problems"].append( + "request budget not met: %d < %d" + % (record["totals"]["http_requests"], args.requests) + ) + if record["gil"]["enabled_after"] is not False: + record["problems"].append("GIL state after the run is not False") + record["qualified"] = not record["problems"] + return record + + +def validate_args(args): + problems = [] + if args.requests < 1: + problems.append("--requests must be at least 1") + if not 1 <= args.workers <= 64: + problems.append("--workers must be between 1 and 64") + if args.duration < 2: + problems.append("--duration must be at least 2 seconds") + if not 1 <= args.callbacks <= 64: + problems.append("--callbacks must be between 1 and 64") + if args.pace_ms < 0: + problems.append("--pace-ms must not be negative") + if args.max_body_bytes < 1024: + problems.append("--max-body-bytes must be at least 1024") + return problems + + +def parse_args(argv=None): + parser = argparse.ArgumentParser( + description="Bounded free-threaded contention soak (Plan 334)." + ) + parser.add_argument( + "--self-test", + action="store_true", + help="run the bookkeeping and fixture self-tests, then exit", + ) + parser.add_argument("--requests", type=int, default=400) + parser.add_argument("--workers", type=int, default=8) + parser.add_argument("--duration", type=float, default=120.0) + parser.add_argument("--callbacks", type=int, default=8) + parser.add_argument("--pace-ms", type=float, default=10.0) + parser.add_argument("--max-body-bytes", type=int, default=1048576) + parser.add_argument("--json", default=None) + return parser.parse_args(argv) + + +def _valid_namespace(): + return argparse.Namespace( + requests=400, + workers=8, + duration=120.0, + callbacks=8, + pace_ms=10.0, + max_body_bytes=1048576, + json=None, + self_test=False, + ) + + +def self_test(): + """Exercise bookkeeping and fixtures without starting a server.""" + results = [] + + def check(name, condition, detail=""): + results.append((name, bool(condition), detail)) + + stats = Stats() + stats.request_done() + stats.request_done() + stats.record("post") + stats.record("post", "boom") + snapshot = stats.snapshot() + check( + "stats-counts", + snapshot["http_requests"] == 2 + and snapshot["ok"] == 1 + and snapshot["fail"] == 1 + and snapshot["by_scenario"]["post"] == {"ok": 1, "fail": 1}, + repr(snapshot["by_scenario"]), + ) + for _ in range(40): + stats.record("stream", "x") + check("stats-error-cap", len(stats.snapshot()["errors"]) == 25) + + concurrency = Concurrency() + concurrency.enter() + concurrency.enter() + concurrency.leave() + check( + "concurrency-peak", + concurrency.snapshot() == {"active": 1, "peak": 2}, + repr(concurrency.snapshot()), + ) + + payload = payload_for(7) + check( + "payload-deterministic", + payload == payload_for(7) and len(payload) == 32 + (7 % 8) * 64, + "len=%d" % len(payload), + ) + check( + "payload-digest", + payload_digest(payload) == hashlib.sha256(payload).hexdigest(), + ) + + chunks = stream_chunks(3) + check( + "stream-chunks", + chunks == stream_chunks(3) + and len(chunks) == CHUNK_COUNT + and stream_bytes(chunks) == b"".join(chunks) + and len(stream_chunks(3, 1)) == 1, + ) + + check( + "scenario-cycle", + [scenario_for(index) for index in range(4)] == list(HTTP_SCENARIOS), + ) + + request = upgrade_request() + check( + "upgrade-request", + request.startswith(b"GET /tunnel HTTP/1.1\r\n") + and request.endswith(b"\r\n\r\n") + and b"Upgrade: soak-echo" in request, + ) + disconnect = disconnect_request(7) + check( + "disconnect-request", + disconnect.startswith(b"GET /stream/slow/7 HTTP/1.1\r\n") + and disconnect.endswith(b"\r\n\r\n"), + ) + + left, right = socket.socketpair() + try: + right.sendall( + b"HTTP/1.1 101 Switching Protocols\r\nUpgrade: x\r\n\r\n" + ) + head = read_head(left) + check( + "read-head", + head.split(b"\r\n", 1)[0] == b"HTTP/1.1 101 Switching Protocols", + ) + finally: + left.close() + right.close() + + check("peak-rss-positive", _peak_rss_bytes() > 0) + check("gil-probe", _gil_enabled() in (True, False, None)) + + interpreter = _interpreter() + check( + "interpreter-shape", + isinstance(interpreter["version"], str) + and isinstance(interpreter["gil_disabled_build"], bool), + ) + + record = _empty_record(_valid_namespace()) + encoded = json.dumps(record, sort_keys=True) + decoded = json.loads(encoded) + required = { + "plan", + "tool", + "interpreter", + "gil", + "config", + "phases", + "totals", + "resources", + "problems", + "qualified", + } + check("record-shape", required.issubset(decoded)) + + namespace = _valid_namespace() + check("validate-accepts", validate_args(namespace) == []) + namespace.requests = 0 + namespace.workers = 0 + namespace.callbacks = 0 + namespace.duration = 1 + namespace.pace_ms = -1 + namespace.max_body_bytes = 1 + check("validate-rejects", len(validate_args(namespace)) == 6) + + failures = [name for name, ok, _ in results if not ok] + for name, ok, detail in results: + print("%s %s%s" % ("ok " if ok else "FAIL", name, "" if ok else ": " + detail)) + print("self-test: %d checks, %d failure(s)" % (len(results), len(failures))) + if failures: + print("failed: " + ", ".join(failures), file=sys.stderr) + return 1 + return 0 + + +def main(argv=None): + args = parse_args(argv) + if args.self_test: + return self_test() + problems = validate_args(args) + if problems: + for problem in problems: + print("error: " + problem, file=sys.stderr) + return 2 + if not sysconfig.get_config_var("Py_GIL_DISABLED"): + print( + "error: this soak requires a free-threaded CPython build " + "(Py_GIL_DISABLED is not set)", + file=sys.stderr, + ) + return 2 + record = run(args) + if args.json: + with open(args.json, "w", encoding="utf-8") as handle: + json.dump(record, handle, indent=2, sort_keys=True) + handle.write("\n") + totals = record["totals"] + print( + "soak: %d http requests (%d ok, %d fail), tunnel=%d, disconnect=%d, %.1fs, qualified=%s" + % ( + totals["http_requests"], + totals["ok"], + totals["fail"], + totals["by_scenario"]["tunnel"]["ok"], + totals["by_scenario"]["disconnect"]["ok"], + record["duration_seconds"], + record["qualified"], + ) + ) + if record["problems"]: + for problem in record["problems"]: + print("problem: " + problem, file=sys.stderr) + return 1 + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/test-python-wheel.sh b/scripts/test-python-wheel.sh index 6bf482f..ac34b0d 100755 --- a/scripts/test-python-wheel.sh +++ b/scripts/test-python-wheel.sh @@ -116,15 +116,15 @@ info "Running installed-wheel typing smoke" info "Verifying import boundary" "$VENV_PYTHON" <<'PYEOF' from pathlib import Path -import sys +import sysconfig import eggserve import eggserve._native ef = Path(eggserve.__file__).resolve() nf = Path(eggserve._native.__file__).resolve() -maj = sys.version_info.major -minr = sys.version_info.minor -site_packages = Path(sys.prefix) / 'lib' / f'python{maj}.{minr}' / 'site-packages' +# Plan 333: derive site-packages from sysconfig, not "python.". +# A free-threaded interpreter uses lib/python3.14t/site-packages. +site_packages = Path(sysconfig.get_paths()["purelib"]).resolve() assert site_packages in ef.parents, f'eggserve.__file__ not in site-packages: {ef}' assert site_packages in nf.parents, f'eggserve._native.__file__ not in site-packages: {nf}' @@ -132,6 +132,17 @@ print(f' eggserve: {ef}') print(f' _native: {nf}') PYEOF +# Plan 333: a free-threaded interpreter must stay GIL-free after the +# installed wheel is imported. This lives in the shared harness so CI and +# local runs execute the identical assertion; -W error::RuntimeWarning turns +# PyO3's "GIL re-enabled" warning into a failure instead of a silent fallback. +if [[ "$("$VENV_PYTHON" -c 'import sysconfig; print(1 if sysconfig.get_config_var("Py_GIL_DISABLED") else 0)')" == "1" ]]; then + info "Verifying free-threaded import keeps the GIL disabled" + "$VENV_PYTHON" -X gil=0 -W error::RuntimeWarning -c \ + "import sys, eggserve._native; assert sys._is_gil_enabled() is False" + success "GIL stays disabled on the installed free-threaded wheel" +fi + # Smoke checks info "Running smoke checks" "$VENV_PYTHON" -c "import eggserve, eggserve._native; print(' imports OK')" diff --git a/scripts/wheel-matrix.py b/scripts/wheel-matrix.py index f90ea9d..f94a0d7 100755 --- a/scripts/wheel-matrix.py +++ b/scripts/wheel-matrix.py @@ -44,6 +44,25 @@ VALID_MANYLINUX = {"2_17", "musllinux_1_2", "auto"} VALID_COMPATIBILITY = {"pypi", "auto"} +# Plan 333: the matrix gains an ABI-family dimension. The GIL family stays +# cp311-abi3 on every existing target; the free-threaded family is +# cp314-cp314t on three targets only and is tier `required` so it must appear +# in every release aggregate (the public tier stays Beta). +VALID_ABI_FAMILIES = {"cp311", "cp314t"} +ABI_FAMILY_TAGS = { + "cp311": ("cp311", "abi3"), + "cp314t": ("cp314", "cp314t"), +} +FREE_THREADED_PLATFORM_TAGS = { + "manylinux_2_17_x86_64", + "macosx_11_0_arm64", + "win_amd64", +} +FREE_THREADED_INTERPRETERS = { + "python3.14t", + "/opt/python/cp314-cp314t/bin/python", +} + RUST_TARGET_RE = re.compile(r"^[a-z0-9_]+-[a-z0-9_]+-[a-z0-9_]+(-[a-z0-9_]+)?$") PLATFORM_TAG_RE = re.compile(r"^[A-Za-z0-9_]+$") @@ -77,8 +96,8 @@ def validate_matrix(path: Path) -> list[str]: return errors + ["no [[target]] entries"] seen_ids: dict[str, int] = {} - seen_tags: dict[str, str] = {} - seen_rust: dict[str, str] = {} + seen_tags: dict[tuple[str, str], str] = {} + seen_rust: dict[tuple[str, str], str] = {} for i, t in enumerate(targets): where = f"target[{i}]" if not isinstance(t, dict): @@ -89,6 +108,8 @@ def validate_matrix(path: Path) -> list[str]: "id", "name", "rust_target", "platform_tag", "runner", "manylinux", "compatibility", "build", "smoke", "tier", "arch_family", "libc", "artifact", + "abi_family", "python_tag", "abi_tag", "interpreter", + "setup_python", ): if key not in t: errors.append(f"{where} ({tid}): missing key {key!r}") @@ -119,6 +140,61 @@ def validate_matrix(path: Path) -> list[str]: f"{where} ({tid}): unknown compatibility {compat!r} " "(expected 'pypi' or 'auto')" ) + # Plan 333: the declared ABI family must agree with its tag triple, + # interpreter, and (for free-threaded) the three-target subset. + family = t.get("abi_family") + if family not in VALID_ABI_FAMILIES: + errors.append( + f"{where} ({tid}): unknown abi_family {family!r} " + f"(expected one of {sorted(VALID_ABI_FAMILIES)})" + ) + else: + expected_python, expected_abi = ABI_FAMILY_TAGS[family] + if t.get("python_tag") != expected_python: + errors.append( + f"{where} ({tid}): abi_family {family!r} needs " + f"python_tag {expected_python!r}, got " + f"{t.get('python_tag')!r}" + ) + if t.get("abi_tag") != expected_abi: + errors.append( + f"{where} ({tid}): abi_family {family!r} needs " + f"abi_tag {expected_abi!r}, got {t.get('abi_tag')!r}" + ) + if family == "cp311": + if t.get("interpreter") != "python3.11": + errors.append( + f"{where} ({tid}): cp311 family must build with " + "interpreter 'python3.11' " + f"(got {t.get('interpreter')!r})" + ) + if t.get("setup_python") != "3.11": + errors.append( + f"{where} ({tid}): cp311 family must set " + "setup_python '3.11' " + f"(got {t.get('setup_python')!r})" + ) + else: + if t.get("platform_tag") not in FREE_THREADED_PLATFORM_TAGS: + errors.append( + f"{where} ({tid}): free-threaded target outside the " + "declared subset (Linux x86_64 glibc, macOS arm64, " + "Windows x86_64); got " + f"{t.get('platform_tag')!r}" + ) + if t.get("interpreter") not in FREE_THREADED_INTERPRETERS: + errors.append( + f"{where} ({tid}): free-threaded interpreter must be " + "python3.14t or the manylinux " + "/opt/python/cp314-cp314t/bin/python path " + f"(got {t.get('interpreter')!r})" + ) + if t.get("setup_python") != "3.14t": + errors.append( + f"{where} ({tid}): free-threaded setup_python must be " + "'3.14t' " + f"(got {t.get('setup_python')!r})" + ) # Track A: never reuse the compatibility policy as the container selector. if manylinux == "pypi": errors.append( @@ -217,21 +293,26 @@ def validate_matrix(path: Path) -> list[str]: if tid in seen_ids: errors.append(f"duplicate target id {tid!r}") seen_ids[tid] = i - if tag and tag in seen_tags: + # Plan 333: one entry per (platform_tag, abi_family); the same + # platform may carry both families (cp311 + cp314t). + family_key = t.get("abi_family", "") + if tag and (tag, family_key) in seen_tags: errors.append( - f"duplicate platform tag {tag!r} " - f"({seen_tags[tag]!r} and {tid!r})" + f"duplicate platform tag {tag!r} for family " + f"{family_key!r} ({seen_tags[(tag, family_key)]!r} and " + f"{tid!r})" ) - seen_tags[tag] = tid + seen_tags[(tag, family_key)] = tid else: - seen_tags[tag] = tid - if rust_target and rust_target in seen_rust: + seen_tags[(tag, family_key)] = tid + if rust_target and (rust_target, family_key) in seen_rust: errors.append( - f"duplicate rust target {rust_target!r} " - f"({seen_rust[rust_target]!r} and {tid!r})" + f"duplicate rust target {rust_target!r} for family " + f"{family_key!r} ({seen_rust[(rust_target, family_key)]!r} " + f"and {tid!r})" ) else: - seen_rust[rust_target] = tid + seen_rust[(rust_target, family_key)] = tid required = [t for t in targets if isinstance(t, dict) and t.get("tier") == "required"] if not required: @@ -240,9 +321,17 @@ def validate_matrix(path: Path) -> list[str]: def required_tags(data: dict) -> list[str]: - return sorted( + return sorted({ t["platform_tag"] for t in data.get("target", []) if isinstance(t, dict) and t.get("tier") == "required" + }) + + +def required_pairs(data: dict) -> list[tuple[str, str]]: + """Required (platform_tag, abi_family) pairs (Plan 333).""" + return sorted( + (t["platform_tag"], t["abi_family"]) for t in data.get("target", []) + if isinstance(t, dict) and t.get("tier") == "required" ) @@ -273,6 +362,11 @@ def emit_gha_matrix(data: dict) -> list[dict]: "compatibility": t["compatibility"], "artifact": t["artifact"], "platform_tag": t["platform_tag"], + "abi_family": t.get("abi_family", ""), + "python_tag": t.get("python_tag", ""), + "abi_tag": t.get("abi_tag", ""), + "interpreter": t.get("interpreter", ""), + "setup_python": t.get("setup_python", ""), "build": t["build"], "smoke": t["smoke"], "qemu_platform": t.get("qemu_platform", ""), @@ -329,6 +423,8 @@ def check(name: str, manifest: dict, expect_error_substr: str | None) -> None: "build": "cross-container", "smoke": "native", "tier": "required", "arch_family": "x86_64", "libc": "glibc", "artifact": "wheel-a", + "abi_family": "cp311", "python_tag": "cp311", "abi_tag": "abi3", + "interpreter": "python3.11", "setup_python": "3.11", } def clone(**over: object) -> dict: @@ -341,6 +437,32 @@ def clone(**over: object) -> dict: rust_target="aarch64-unknown-linux-gnu", artifact="wheel-b", smoke="deferred-native", qualify_runner="ubuntu-24.04-arm") check("two-target valid", {"target": [clone(), other]}, None) + free_threaded = clone( + id="t1ft", abi_family="cp314t", python_tag="cp314", + abi_tag="cp314t", interpreter="python3.14t", + setup_python="3.14t", artifact="wheel-a-ft", + ) + check("same platform carries both families", + {"target": [clone(), free_threaded]}, None) + check("unknown abi family", + {"target": [clone(abi_family="cp313t")]}, "unknown abi_family") + check("family tag mismatch", + {"target": [clone(abi_family="cp314t")]}, "python_tag") + check("free-threaded on musl", + {"target": [clone( + id="m", platform_tag="musllinux_1_2_x86_64", + rust_target="x86_64-unknown-linux-musl", + manylinux="musllinux_1_2", libc="musl", + abi_family="cp314t", python_tag="cp314", abi_tag="cp314t", + interpreter="python3.14t", setup_python="3.14t", + artifact="wheel-m")]}, + "outside the declared subset") + check("duplicate family pair", + {"target": [free_threaded, clone( + id="t2", abi_family="cp314t", python_tag="cp314", + abi_tag="cp314t", interpreter="python3.14t", + setup_python="3.14t", artifact="wheel-b-ft")]}, + "duplicate platform tag") check("duplicate ids", {"target": [clone(), clone(id="t1", platform_tag="win_amd64", rust_target="x86_64-pc-windows-msvc", artifact="wheel-c", manylinux="auto", libc="msvc", arch_family="x86_64")]}, "duplicate target id") @@ -419,10 +541,28 @@ def clone(**over: object) -> dict: else: print("OK real manifest contains musllinux_1_2_armv7l") if len(tags) != 10: - print(f"FAIL required tag count != 10: {tags}") + print(f"FAIL required platform tag count != 10: {tags}") + failures += 1 + else: + print("OK required platform tag count is 10") + pairs = required_pairs(data) + if len(pairs) != 13: + print(f"FAIL required target count != 13 (10 GIL + 3 ft): {pairs}") failures += 1 else: - print("OK required tag count is 10") + print("OK required target count is 13 (10 GIL + 3 free-threaded)") + ft_ids = { + t["id"] for t in data.get("target", []) + if t.get("abi_family") == "cp314t" + } + expected_ft = { + "linux-x86_64-glibc-ft", "macos-arm64-ft", "windows-x86_64-ft", + } + if ft_ids != expected_ft: + print(f"FAIL free-threaded target set != expected: {sorted(ft_ids)}") + failures += 1 + else: + print("OK free-threaded family covers exactly the three declared targets") # Plan 268: emitted matrix must carry the split controls and must never # emit `pypi` as the container selector. emitted = emit_gha_matrix(data) @@ -436,6 +576,15 @@ def clone(**over: object) -> dict: failures += 1 else: print("OK emitted matrix carries compatibility") + if any( + not e.get("abi_family") or not e.get("interpreter") + or not e.get("setup_python") + for e in emitted + ): + print("FAIL emitted matrix missing family/interpreter fields") + failures += 1 + else: + print("OK emitted matrix carries abi_family/interpreter/setup_python") # Deferred targets must not request build-host native smoke. by_id = {e["id"]: e for e in emitted} for did in ("linux-aarch64-glibc", "windows-arm64", "linux-aarch64-musl"): @@ -481,10 +630,14 @@ def main(argv: list[str] | None = None) -> int: data = load_matrix(args.matrix) if args.command == "validate": + pairs = required_pairs(data) tags = required_tags(data) - print(f"Wheel matrix valid: {len(tags)} required targets") - for tag in tags: - print(f" {tag}") + print( + f"Wheel matrix valid: {len(pairs)} required targets on " + f"{len(tags)} platform tags" + ) + for tag, family in pairs: + print(f" {family:7s} {tag}") return 0 if args.command == "emit-matrix": print(json.dumps(emit_gha_matrix(data)))