diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7136710..72bb14d 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 326: 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..6a34479 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 326: 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 326: 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 326: 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 326: 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 327: 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..3f2248c 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 **Stable** free-threaded CPython 3.14t family (promoted by Plan 327) (`cp314-cp314t`) on Linux x86_64 glibc, macOS arm64, and Windows x86_64 only (Plan 326; 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 eac0161..ac5d950 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,10 +1,25 @@ # Changelog -## Unreleased — post-audit maintenance (Plans 320–325) +## Unreleased — post-audit maintenance (Plans 320–326) 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 (Plan 326, Stable; promoted by Plan 327).** 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. + - **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..b074735 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 **Stable** 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..bb2102c 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 :: 3 - Stable", "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..3476de5 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 326 +/// 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..3cef095 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 326). 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 326: 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..712f51c --- /dev/null +++ b/crates/eggserve-python/tests/test_free_threaded.py @@ -0,0 +1,353 @@ +"""Plan 326: 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..d7f7924 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 **Stable** + (Plan 326). 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..52a0eb9 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 (Stable; 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..4e4a1a5 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 (Stable; 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..1d42fef 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 **Stable** on Linux x86_64 (glibc), macOS + arm64, and Windows x86_64 only (`cp314-cp314t`; Plan 326) +- 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 (**Stable**; Plan 326, promoted by Plan 327). 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 0e98f17..e4cb4ec 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 **Stable** +(Plan 326); 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..d8d97d4 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 + Stable 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 | @@ -180,7 +186,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 +237,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 +322,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 **Stable** (`cp314-cp314t` on Linux x86_64 glibc, macOS arm64, and + Windows x86_64 only; Plan 326). 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..286cca4 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`) | Stable — Linux x86_64 (glibc), macOS arm64, Windows x86_64 only (Plan 326; tier set by Plan 327) | ### ABI @@ -110,15 +110,32 @@ 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 **Stable**: Plan 327 met and the repository +owner confirmed Plan 326's promotion gate (a required-family release +aggregate with all three wheels is green, the contention soak passes, and +the plan carries no medium-or-higher finding). +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 Stable 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 +157,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 Stable. + +| 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 +228,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 (Stable, `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/326-free-threaded-cpython-314t-staged-support.md b/plans/closure/python-facade/326-free-threaded-cpython-314t-staged-support.md new file mode 100644 index 0000000..7b1a234 --- /dev/null +++ b/plans/closure/python-facade/326-free-threaded-cpython-314t-staged-support.md @@ -0,0 +1,284 @@ +# Python Facade Milestone 326 — Closure Status + +Status: closed + +Source implementation plan: + +- `plans/implementation/python-facade/326-free-threaded-cpython-314t-staged-support.md` + +Source subsystem roadmap: + +- `plans/subsystems/python-facade-roadmap.md` (Milestone 326) + +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 326 change set and the Plan 327 + registration; PR https://github.com/eggstack/eggserve/pull/7. +- Corrective commit `b6b793b` moves the two macOS arm64 release jobs to + `macos-latest` (Plan 327 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 326 (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 326 and 327. +- TSan: no TSan-instrumented CPython is available; Plan 327'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 327 soak records `327-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 326/327; needs the same refresh before its next dispatch | + +## 11. Roadmap disposition + +Milestone 326 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 326 +remains. Plan 327 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/327-free-threaded-314t-qualification-and-tier-decision.md`. + +## 12. Registry updates + +- `plans/registry.md`: Python facade current milestone and row 326 become + `closed`, linking this record. +- `plans/subsystems/python-facade-roadmap.md`: status line, dependency graph, + and milestone table record the closure. +- Plan 327 remains the next milestone (registered at `328` as the next number). diff --git a/plans/closure/python-facade/327-free-threaded-314t-qualification-and-tier-decision.md b/plans/closure/python-facade/327-free-threaded-314t-qualification-and-tier-decision.md new file mode 100644 index 0000000..b15732f --- /dev/null +++ b/plans/closure/python-facade/327-free-threaded-314t-qualification-and-tier-decision.md @@ -0,0 +1,238 @@ +# Python Facade Milestone 327 — Closure Status + +Status: closed + +Source implementation plan: + +- `plans/implementation/python-facade/327-free-threaded-314t-qualification-and-tier-decision.md` + +Source subsystem roadmap: + +- `plans/subsystems/python-facade-roadmap.md` (Milestone 327) + +Repository baseline reviewed: `4949a77acfe4114561bd7cfe59a8458ea1983af7` +plus the Plan 326 change set; executed on branch +`feat/auto-20261116-7cc8b1dc`. + +Implementation commits or pull requests: + +- `ab418f8` — Plan 326 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 326's named conditions are observed, so Plan 326 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 326 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 326 closure becomes `closed` with both run URLs and no medium-or-higher finding | `plans/closure/python-facade/326-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/327-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 326/327; roadmap; next number `328` | 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 326 +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 | +|---|---|---|---|---|---|---|---|---| +| `327-soak-1.json` | 120.852 s | 84,769 | 0 | 582 | 592 | 8 | 1 | 585.6 MB | +| `327-soak-2.json` | 120.820 s | 80,411 | 0 | 576 | 585 | 8 | 1 | 525.7 MB | +| `327-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 326 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 326 closure | met | both mediums resolved; remaining findings are low (Plan 326 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 326 and + 327 become `closed`; next number stays `328`. +- `plans/subsystems/python-facade-roadmap.md`: status line, dependency graph, + milestone sections, and the milestone table record both closures. +- Plan 327's header becomes `implemented` with this closure linked. diff --git a/plans/closure/python-facade/327-soak-1.json b/plans/closure/python-facade/327-soak-1.json new file mode 100644 index 0000000..05ab54a --- /dev/null +++ b/plans/closure/python-facade/327-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": "327", + "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/327-soak-2.json b/plans/closure/python-facade/327-soak-2.json new file mode 100644 index 0000000..afb52f1 --- /dev/null +++ b/plans/closure/python-facade/327-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": "327", + "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/327-soak-3.json b/plans/closure/python-facade/327-soak-3.json new file mode 100644 index 0000000..1845cff --- /dev/null +++ b/plans/closure/python-facade/327-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": "327", + "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/326-free-threaded-cpython-314t-staged-support.md b/plans/implementation/python-facade/326-free-threaded-cpython-314t-staged-support.md new file mode 100644 index 0000000..a2785ce --- /dev/null +++ b/plans/implementation/python-facade/326-free-threaded-cpython-314t-staged-support.md @@ -0,0 +1,659 @@ +# Python Facade Milestone 326 — Free-threaded CPython 3.14t staged support + +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/326-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: 326 + +Repository baseline: `4949a77acfe4114561bd7cfe59a8458ea1983af7` + +Source roadmap: + +- `plans/subsystems/python-facade-roadmap.md` (Milestone 326) + +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 326 +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 326 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/326-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/327-free-threaded-314t-qualification-and-tier-decision.md b/plans/implementation/python-facade/327-free-threaded-314t-qualification-and-tier-decision.md new file mode 100644 index 0000000..ee4c8d3 --- /dev/null +++ b/plans/implementation/python-facade/327-free-threaded-314t-qualification-and-tier-decision.md @@ -0,0 +1,556 @@ +# Python Facade Milestone 327 — Free-threaded 3.14t qualification evidence and Beta tier 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 family is +promoted to Stable; see +`plans/closure/python-facade/327-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: 327 + +Repository baseline: `4949a77acfe4114561bd7cfe59a8458ea1983af7` plus the +uncommitted Plan 326 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 327) + +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 326 into an evidence-backed decision. +Two things must happen in order: + +1. **Close Plan 326.** 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 326'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 326'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 326 permits a documented substitute: a bounded soak + with concurrent callbacks, streams, and tunnels. + +## 2. Why this milestone is ready + +- Plan 326 is implemented and conditionally closed + (`plans/closure/python-facade/326-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 326's own implementation is the input, and + the only sequencing requirement is committing it first. + +## 3. Current implementation evidence + +### 3.1 Plan 326 state + +| Item | State | +|---|---| +| Plan 326 implementation | all work packages A–G landed in the working tree | +| Plan 326 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 326 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 326's promotion gate is unevaluated; the family is documented as Beta. + +### 3.3 Promotion gate as written in Plan 326 + +| 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 326 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 326 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 327 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 326'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 326 and observe CI + +Intent: produce the first named closure condition with the exact change set +that was locally verified. + +Required changes: + +- Commit the Plan 326 change set, together with this plan's registration (one + commit is acceptable; two commits, Plan 326 then Plan 327, are cleaner). Name + Plan 326 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 326 + +Intent: replace the conditional record with the observed evidence. + +Required changes: + +- Edit `plans/closure/python-facade/326-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 326 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 326. + +### 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 326 permits. +- Run three repetitions (for example 400 requests / 8 workers / 60–120 s + each) and retain the JSON records as + `plans/closure/python-facade/327-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 326 criteria against the runs from WP-A/B/D and the + closed Plan 326 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 327 + +Intent: record the decision and leave the control surface truthful. + +Required changes: + +- Write `plans/closure/python-facade/327-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 327, 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 326 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 326: 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 326: 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 326 §16). + +## 12. Documentation updates + +- `plans/closure/python-facade/326-free-threaded-cpython-314t-staged-support.md` + (status and evidence; no historical rewrite). +- `plans/closure/python-facade/327-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 327 closure and the docs update + explaining the unmet criterion; the Beta statements stay. + +## 13. Acceptance criteria + +1. The Plan 326 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 326'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 326.** 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 326 §16 still apply. +- **Registry hygiene.** After registering 327, the next-number line must say + `328`. diff --git a/plans/registry.md b/plans/registry.md index 0d30341..7e2969b 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 `326`. Legacy flat plans (`000`–`292`) and `release/plan-*.md` are archived in place and immutable. +New milestone numbers continue from `328`. 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` | 326 free-threaded CPython 3.14t staged support (closed); 327 qualification evidence and tier decision (closed); 322 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/`. Plan 326 is closed (owner-approved 2026-11-23): it adds a Beta `cp314-cp314t` family for Linux x86_64 glibc, macOS arm64, and Windows x86_64, family-aware wheel-matrix/release gates, a free-threaded CI lane, concurrency tests, and the correction for the PyO3 >= 0.28 default declaration. Evidence: CI run 45277923657 with the `python-free-threaded` lane (861 tests on CPython 3.14.10t, GIL stays disabled) and release run 45283657891 with the exact 13-pair aggregate including the three `-ft` wheels and 5/5 ABI-proof lanes (`plans/closure/python-facade/326-free-threaded-cpython-314t-staged-support.md`). Plan 327 is closed (owner-approved 2026-11-23): it obtained both Plan 326 conditions, added a bounded contention soak as the TSan substitute, and recorded the tier decision (promoted to Stable after the owner confirmed the aggregate-as-release reading; classifier, metadata gate, and docs updated; see `plans/closure/python-facade/327-free-threaded-314t-qualification-and-tier-decision.md`). No product behavior change or publication occurred. | | 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) | 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. | | 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. | @@ -70,6 +70,8 @@ Dependency vocabulary: **hard / interface / soft / operational** (`003-planning- | CLI, ops, and observability | 320 | closed | `plans/implementation/cli-ops-observability/320-h3-quic-advisory-remediation.md` | **High.** The root advisory gate fails at the audit baseline: `quinn-proto 0.11.18`, `quinn-udp 0.5.15`, `rustix 1.1.4`, and `tokio 1.52.3`/`1.53.1` carry RUSTSEC-2026-0523/-0524/-0538 (vulnerabilities; H3-only exposure) and -0486/-0386 (unsound; no in-tree affected API calls). Bump the patched releases, prove resolution/feature neutrality, add an offline resolved-version guard with a self-test, and keep H3 experimental. Closure: `plans/closure/cli-ops-observability/320-h3-quic-advisory-remediation.md`. | | Direct H1 runtime | 321 | closed | `plans/implementation/direct-h1-runtime/321-trusted-proxy-peerless-transport-boundary.md` | **Medium.** `trust_unix` trusts every `remote_addr: None` transport, including arbitrary caller-owned streams served by the public driver. Thread an internal transport kind to the one trust decision; preserve Unix/TCP/PROXY behavior; add a trust matrix. Prefer no public `ConnectionContext` field; a public change is a stop condition. Closure: `plans/closure/direct-h1-runtime/321-trusted-proxy-peerless-transport-boundary.md`. | | Python facade | 322 | closed | `plans/implementation/python-facade/322-streamed-response-producer-lifecycle-bounds.md` | **Medium.** `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. Check closure before each pull, bound producers with an admission permit (503 on exhaustion), and document the non-interruptible `__next__` limitation. Closure: `plans/closure/python-facade/322-streamed-response-producer-lifecycle-bounds.md`. | +| Python facade | 326 | closed | `plans/implementation/python-facade/326-free-threaded-cpython-314t-staged-support.md` | **Capability.** Approved 2026-11-23; implemented and closed (closure: `plans/closure/python-facade/326-free-threaded-cpython-314t-staged-support.md`). Adds a Beta `cp314-cp314t` wheel family (Linux x86_64 glibc, macOS arm64, Windows x86_64), family-aware wheel matrix/validators/release lanes, a free-threaded CI job, and the concurrency contract/tests; `cp311-abi3` is unchanged. Evidence: PR #7 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 on 3.11-3.15). Plan 327 owns the tier decision. | +| Python facade | 327 | closed | `plans/implementation/python-facade/327-free-threaded-314t-qualification-and-tier-decision.md` | **Infrastructure.** Approved for handoff 2026-11-23; closed (closure: `plans/closure/python-facade/327-free-threaded-314t-qualification-and-tier-decision.md`). Obtained both Plan 326 conditions (CI run 45277923657; release run 45283657891, exact 13-pair aggregate), closed Plan 326, added `scripts/soak-python-free-threaded.py` with three zero-error records as the TSan substitute, and evaluated the promotion gate: all four criteria met; the owner confirmed the aggregate-as-release reading, so the family is promoted to Stable with the classifier, metadata gate, and documentation updated. No product behavior, dependency, platform, or publication change. | | CLI, ops, and observability | 323 | closed | `plans/implementation/cli-ops-observability/323-post-audit-operator-and-repository-hygiene-sweep.md` | **Low/Informational sweep.** `--public` docs vs actual CLI, inert `audit.toml`, unused core `tokio/signal`, missing credential ignore patterns, mutable release image tags, stale action-pinning inventory, corrupted threat-model opening, macOS static-test canonicalization, and manifest-provenance wording. No `--public` behavior change; image digests may be recorded blocked without registry access. Closure: `plans/closure/cli-ops-observability/323-post-audit-operator-and-repository-hygiene-sweep.md`. | | Direct H1 runtime | 324 | closed | `plans/implementation/direct-h1-runtime/324-runtime-tls-hardening-followups.md` | **Low.** Three fail-closed gaps: systemd descriptor double adoption, keep-alive on ambiguous framing rejection (defense-in-depth; unreachable under Hyper 1.11), and an unbounded identity PEM read in `eggnet-tls`. No TLS identity/trust/auth semantics change; no new `TlsError` variant. Closure: `plans/closure/direct-h1-runtime/324-runtime-tls-hardening-followups.md`. | | CLI, ops, and observability | 325 | closed | `plans/implementation/cli-ops-observability/325-compatible-dependency-refresh-and-tool-pins.md` | **Closed.** All three latest-compatible lockfiles are refreshed, the post-update dry runs are empty, and shared package identities align. The pinned tools (`cargo-audit 0.23.0`, `cargo-deny 0.21.0`) pass the end-to-end supply-chain script. Audits, denies, floors, MSRV, and required suites pass with the documented macOS test skip. Upstream transitive tree differences and the `verify.sh fast` wrapper's macOS skip limitation are recorded in the closure. Breaking upgrades remain separate; no source/API/behavior or release change. Closure: `plans/closure/cli-ops-observability/325-compatible-dependency-refresh-and-tool-pins.md`. | diff --git a/plans/subsystems/python-facade-roadmap.md b/plans/subsystems/python-facade-roadmap.md index 4584de8..a0cf741 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, and 326 closed; 327 closed with the family promoted to Stable) Long-term references: @@ -140,6 +140,12 @@ 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 declares 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. **Tracked by Milestone + 326**: the declaration becomes explicit and the 3.14t slice is qualified as + a Beta wheel family. ## 5. Target architecture @@ -155,13 +161,19 @@ 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 326 (free-threaded CPython 3.14t, closed) + `--> Milestone 327 (qualification evidence + tier decision, closed) ``` 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 326 depends on the closed bridge and Plan 322, and supersedes only +the free-threaded slice of the legacy Plan 267 record. Milestone 327 depends on +Plan 326's implementation and takes over its two named closure conditions plus +the Beta/Stable decision; it changes no product behavior. ## 7. Milestones @@ -219,6 +231,62 @@ 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 326 — Free-threaded CPython 3.14t staged support + +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. + +### Milestone 327 — Free-threaded 3.14t qualification evidence and tier decision + +Class: infrastructure + +Objective: produce the two conditions named by Plan 326's conditional closure +(a green PR CI run including the free-threaded lane, and a +`publish_target: none` three-target release aggregate), close Plan 326, then +make one recorded Beta/Stable decision using Plan 326's promotion gate and a +bounded contention soak as the TSan substitute. + +Dependencies: Plan 326 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 Plan 326 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; Plan 326 closed with both run URLs; soak +self-test plus three zero-error records; the promotion gate evaluated and a +decision recorded. + ## 8. Cross-cutting requirements ### Storage and migration @@ -240,7 +308,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 +337,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 +350,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 +371,5 @@ 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. | +| 326 | closed | `plans/implementation/python-facade/326-free-threaded-cpython-314t-staged-support.md` | `plans/closure/python-facade/326-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). | +| 327 | closed | `plans/implementation/python-facade/327-free-threaded-314t-qualification-and-tier-decision.md` | `plans/closure/python-facade/327-free-threaded-314t-qualification-and-tier-decision.md` | Produced both Plan 326 conditions (CI run 45277923657; release run 45283657891, exact 13-pair aggregate), closed Plan 326, added `scripts/soak-python-free-threaded.py` with three zero-error records as the TSan substitute, and evaluated the promotion gate: all four criteria met; the owner confirmed the aggregate-as-release reading, so the family is promoted to Stable (classifier, metadata gate, and docs). No product behavior or publication change. | diff --git a/release/plan-267-wheel-feasibility.md b/release/plan-267-wheel-feasibility.md index 73b391f..9e7415c 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 326 (2026-11-23).** Track A's **DEFERRED** +> verdict is superseded for the CPython 3.14t slice by +> `plans/implementation/python-facade/326-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..669684f 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 327: 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 326; 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 327: 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..73eefb9 --- /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 326, 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..1c44abd 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 327: 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 = 3 + + +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 326: 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 326) --- + # 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..8aaf6ae 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 326 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 326). + + 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..b7a57e5 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 326: 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..c2f560c --- /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 327). + +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": "327", + "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 327)." + ) + 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..2cdeafd 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 326: 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 326: 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..073c8cc 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 326: 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 326: 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 326: 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 326).""" + 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)))