Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 13 additions & 4 deletions .github/workflows/core.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ on:
branches:
- master
- modernize
- modernize-followup
pull_request:

permissions:
Expand All @@ -21,10 +22,10 @@ jobs:

steps:
- name: Check out source
uses: actions/checkout@v4
uses: actions/checkout@v7

- name: Set up Python
uses: actions/setup-python@v5
uses: actions/setup-python@v7
with:
python-version: ${{ matrix.python-version }}
cache: pip
Expand All @@ -43,11 +44,19 @@ jobs:
- name: Run unittest contracts
run: python -m unittest discover -s tests -p "test_*.py" -v

- name: Run optimized unittest contracts
run: python -O -m unittest discover -s tests -p "test_*.py" -v

- name: Run pytest collection
run: python -m pytest -q

- name: Lint new tests
run: python -m ruff check tests/test_contracts.py tests/test_websocket.py
- name: Lint contract and smoke tests
run: >-
python -m ruff check
tests/test_contracts.py
tests/test_websocket.py
tests/test_malformed_inputs.py
tests/test_leaks.py

- name: Build a wheel
run: python -m build --wheel
35 changes: 28 additions & 7 deletions .github/workflows/optional.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ on:
branches:
- master
- modernize
- modernize-followup
pull_request:

permissions:
Expand All @@ -18,27 +19,47 @@ jobs:
fail-fast: false
matrix:
include:
- name: HTTP/2
- name: HTTP/2 Python 3.12
python-version: "3.12"
extra: h2
module: h2
- name: SSH
- name: HTTP/2 Python 3.13
python-version: "3.13"
extra: h2
module: h2
- name: SSH Python 3.12
python-version: "3.12"
extra: sshtunnel
module: asyncssh
- name: SSH Python 3.13
python-version: "3.13"
extra: sshtunnel
module: asyncssh
- name: QUIC and HTTP/3
- name: QUIC and HTTP/3 Python 3.12
python-version: "3.12"
extra: quic
module: aioquic
- name: Accelerated crypto and event loop
- name: QUIC and HTTP/3 Python 3.13
python-version: "3.13"
extra: quic
module: aioquic
- name: Accelerated crypto and event loop Python 3.12
python-version: "3.12"
extra: accelerated
module: Crypto
- name: Accelerated crypto and event loop Python 3.13
python-version: "3.13"
extra: accelerated
module: Crypto

steps:
- name: Check out source
uses: actions/checkout@v4
uses: actions/checkout@v7

- name: Set up Python
uses: actions/setup-python@v5
uses: actions/setup-python@v7
with:
python-version: "3.12"
python-version: ${{ matrix.python-version }}
cache: pip

- name: Install the selected optional extra
Expand Down
128 changes: 128 additions & 0 deletions docs/FOLLOWUP_PERFORMANCE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
# Follow-up Performance Review

This document records the Phase 3 and Phase 5 measurements from the follow-up
modernization branch. It is a decision record, not an absolute performance claim.
The loopback workload is sensitive to scheduler and host load, so medians and sample
variation are reported together.

## Environment and commands

- Revision under test: `modernize-followup` after the setup-only cleanup and benchmark
harness commits.
- Runtime: CPython `3.12.3` on Linux x86_64/WSL2 with the default asyncio event loop.
- Optional runtime modules: `uvloop` and PyCryptodome were not installed.
- Proxy workload:

```text
python tests/benchmark_proxy.py --protocols http socks5 --requests 1000 --concurrency 8 --payload-size 4096 --warmup 5
```

- Setup latency workload:

```text
python tests/benchmark_setup.py --connections 100
```

- Long-relay workload used to exercise the 256 KiB drain batching threshold:

```text
python tests/benchmark_proxy.py --protocols http socks5 --requests 100 --concurrency 4 --payload-size 1048576 --warmup 2
```

- Microbenchmarks:

```text
python tests/benchmark_followup.py -p 1 -n 5 -w 2 --min-time 0.03
```

All loopback and setup commands were repeated five times. The pyperf run used five
values and two warmups in one process. The direct echo case is not used as a proxy
performance gate.

## Proxy workload

| Case | Throughput median | Sample stdev | Roundtrip average median | Roundtrip p95 median |
| --- | ---: | ---: | ---: | ---: |
| HTTP | 2,333.1 req/s | 187.1 | 3.217 ms | 4.358 ms |
| SOCKS5 | 5,948.3 req/s | 580.3 | 1.186 ms | 1.698 ms |

These values are the reference for this follow-up branch. They are not compared with
the direct echo path, and the variance is large enough that a small microbenchmark
change cannot be promoted without a separate before/after proxy run.

## Connection setup latency

| Case | Setup median | Sample stdev | Setup p95 median | Connections/s median |
| --- | ---: | ---: | ---: | ---: |
| HTTP | 1.802 ms | 0.138 ms | 2.376 ms | 554.9 |
| SOCKS5 | 1.753 ms | 0.052 ms | 2.258 ms | 570.5 |

The setup measurement opens a new proxy connection, completes the protocol handshake,
and closes the returned stream for every sample. It does not measure an already-open
long-lived relay.

The 1 MiB long-relay run produced these medians across five samples:

| Case | Throughput median | Sample stdev | Roundtrip average median | Roundtrip p95 median |
| --- | ---: | ---: | ---: | ---: |
| HTTP | 128.1 req/s | 28.6 | 27.899 ms | 34.209 ms |
| SOCKS5 | 154.9 req/s | 26.2 | 23.266 ms | 31.631 ms |

This exercises repeated writes and `drain` batching, but it does not identify a safe
alternative batching policy. The existing threshold and close behavior are retained.

## Setup microbenchmarks

The following are pyperf mean values with the reported standard deviation. They isolate
costs; they are not proxy throughput results.

| Operation | Mean | Standard deviation | Interpretation |
| --- | ---: | ---: | --- |
| `vars` plus keyword expansion | 1.20 us | 0.12 us | Small setup cost; not a per-payload operation. |
| Cached mapping expansion | 1.49 us | 0.25 us | No stable advantage over the current operation. |
| Protocol guess, one candidate | 7.57 us | 0.08 us | Required by the current auto-detection contract. |
| Protocol guess, two candidates | 18.6 us | 3.2 us | Scales with configured candidates. |
| Protocol guess, four candidates | 32.5 us | 0.6 us | An explicit listener could avoid this, but would be additive API work. |
| Task creation | 11.3 us | 1.0 us | Baseline asyncio task cost. |
| Registry task creation | 15.7 us | 1.1 us | Tracking adds a small lifecycle cost. |
| TaskGroup creation | 26.6 us | 0.2 us | Preserves structured cancellation semantics. |
| TaskGroup cancellation | 68.0 us | 0.4 us | Error/cancellation path, not the normal payload path. |
| Disabled-statistics callback calls | 319 ns | 2 ns | Too small to justify a new runtime branch. |

The `vars`/mapping comparison is not a production optimization result: server startup
creates the handler partial once, and replacing that setup plumbing would enlarge the
compatibility surface without changing the measured relay path.

## Parser, bookkeeping, and cipher microbenchmarks

| Operation | Mean | Standard deviation |
| --- | ---: | ---: |
| HTTP header parsing | 6.93 us | 0.50 us |
| WebSocket frame parsing | 2.19 us | 0.25 us |
| SOCKS address parsing | 1.51 us | 0.19 us |
| UDP bookkeeping | 1.75 us | 0.36 us |
| Pure-Python ChaCha20 packet encryption | 1.19 ms | 0.20 ms |

The accelerated cipher benchmark was skipped because PyCryptodome was not installed in
the measurement environment. Existing cipher tests continue to cover pure-Python
correctness and packet round trips. The pure-Python implementation remains supported;
this follow-up does not change cipher selection, packet boundaries, nonce/IV handling,
or plugin framing.

The pyperf allocation-tracking mode was also run for the parser, bookkeeping, task, and
cipher cases. It reported process-level memory baselines rather than a stable
operation-specific allocation delta, so no allocation-sensitive rewrite was accepted.

## Optimization decision

No Phase 4 runtime optimization was accepted. The measured candidates either:

- were small setup-only costs;
- were required to preserve protocol auto-detection or structured cancellation;
- had no stable advantage in the isolated comparison; or
- would require a compatibility or API decision outside the approved scope.

No parser or cipher rewrite was accepted either. The measurements identify future
profiling targets, but they do not establish a safe 5% proxy-level improvement. The
existing pure-Python cipher fallback and all current protocol facades therefore remain
unchanged.
124 changes: 124 additions & 0 deletions docs/LEGACY_INVENTORY.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
# Follow-up Legacy Inventory

This inventory records the starting point for the follow-up modernization work. It
separates compatibility surfaces from implementation details that may be simplified
after measurement. It is intentionally limited to the current source tree and does
not add a new protocol or distribution target.

## Baseline

- Base revision: `master` at `9f9f8bd` (`Modernize internals while preserving proxy compatibility (#4)`).
- Working branch: `modernize-followup`.
- Runtime: CPython `3.12.3` on Linux x86_64/WSL2, using the default asyncio event loop.
- Package requirement: Python `3.12+`.
- Distribution model: private Git repository installation through a PEP 517-compatible
`pip install git+https://...` workflow; no PyPI release is planned.
- Optional modules available in the baseline environment: none of `uvloop`,
PyCryptodome, `h2`, `aioquic`, or `asyncssh`.
- Development tools are available in the local development environment through the
existing development setup; reproducible checks are listed below.

## Compatibility surfaces to preserve

The following are user-visible or wire-visible and are out of scope for implicit
cleanup:

- The `pproxy` command, its existing options, defaults, exit behavior, and version/help
output shape.
- URI parsing, composed schemes, user information, cipher/plugin parameters, local
binds, query rules, fragments, and jump configuration.
- The public import facades in `pproxy`, `pproxy.proto`, `pproxy.server`,
`pproxy.transport`, and the protocol/runtime packages introduced by the previous
modernization.
- HTTP, SOCKS4, SOCKS5, WebSocket, Shadowsocks, ShadowsocksR, Trojan, direct, tunnel,
redirect, PF, Unix-socket, TCP, and UDP behavior supported by the current tree.
- Authentication, scheduling modes, statistics/verbose meaning, EOF and cancellation
behavior, cipher fallback behavior, packet boundaries, nonce/IV handling, and plugin
framing.
- Optional H2, H3/QUIC, and SSH adapters. Their dependencies remain optional and are
tested separately when installed.

Compatibility facades and optional adapters may be reorganized internally, but their
current import names and callable contracts remain stable unless a separate change is
approved.

## Legacy and simplification candidates

| Area | Current observation | Treatment |
| --- | --- | --- |
| `setup.py` | A one-line setuptools invocation that delegates to `pyproject.toml`. | Approved breaking cleanup for Phase 2, after Phase 0 and Phase 1 validation. |
| Asyncio compatibility | `pproxy.app` still contains a fallback to the removed `asyncio.Task.all_tasks` API. | Safe Phase 1 cleanup. |
| Source versioning | `pproxy.__doc__` uses source Git metadata and a `setuptools-scm` fallback. | Keep; source checkouts and built wheels need consistent versions. |
| Stream compatibility | `pproxy.transport.streams` supports legacy `read_w` and `read_n` reader methods. | Keep until a separately measured compatibility decision is made. |
| Server argument plumbing | Server startup and protocol adapters use `vars(...)` and `**kwargs` in setup paths. | Measure in Phase 3; change only if the proxy workload shows a stable gain. |
| Protocol detection | The registry tries configured protocols in order and preserves auto-detection. | Measure handshake cost; keep the existing path and consider only additive explicit listeners. |
| Relay lifecycle | The bidirectional relay uses `asyncio.TaskGroup` and cancellation propagation. | Measure creation/cancellation and preserve EOF/error semantics. |
| Statistics callbacks | The default callback is a no-op, but callback construction/bookkeeping remains in the connection path. | Measure disabled-statistics cost before considering a fast path. |
| Parser/cipher buffers | Parsers and cipher implementations use existing bytes/bytearray operations and pure-Python fallbacks. | Measure representative workloads; preserve wire behavior and fallback support. |
| Private optional APIs | H2, QUIC, TLS, and SSH adapters access backend-private objects. | Isolate incrementally behind adapters; do not alter optional behavior in this pass. |

## Hot-path map

Connection setup flows through `pproxy.server.stream_handler`, protocol registry
guess/accept calls, optional cipher preparation, remote selection, and relay startup.
The setup path currently includes `vars(self)`/`**kwargs` expansion, protocol guessing,
connection tasks, statistics callback creation, and remote handshake work.

Payload relay flows through `pproxy.relay.relay_with_taskgroup`, protocol channel
methods, transport reads/writes, optional cipher transforms, and `drain` calls. The
relay path must be evaluated separately from setup because its costs scale with byte
volume rather than connection count.

The initial measurement targets are therefore:

1. Argument/context construction and expansion.
2. Protocol guess/accept attempts for HTTP and SOCKS5.
3. Per-connection task creation and `TaskGroup` cancellation.
4. Disabled statistics and verbose callback overhead.
5. HTTP header, WebSocket frame, SOCKS address, UDP bookkeeping, cipher packet, and
payload relay costs.

## Workloads and reproducible commands

The proxy-facing gate uses loopback HTTP and SOCKS5 requests, while microbenchmarks
are used only to explain individual costs. The direct echo case is not a proxy gate.
Representative workloads are:

- short-lived HTTP connections with a 4 KiB payload;
- short-lived SOCKS5 connections with a 4 KiB payload;
- encrypted Shadowsocks traffic when an accelerated or pure-Python cipher is
available;
- long-lived bidirectional relay traffic;
- parser and setup microbenchmarks with fixed input fixtures.

Baseline commands:

```text
python -m unittest discover -s tests -p 'test_*.py'
python -O -m unittest discover -s tests -p 'test_*.py'
python -m pytest -q
python -m compileall -q pproxy tests
python tests/benchmark_http_headers.py --iterations 10000 --extra-headers 4
python tests/benchmark_proxy.py --requests 1000 --concurrency 8 --payload-size 4096 --warmup 5
python -m build --wheel
```

The same interpreter, dependency set, workload, and machine must be used for before
and after measurements. At least five repeated samples are required for a decision;
median and variation are recorded. A runtime change proceeds only when the relevant
proxy workload shows a stable improvement of at least 5%, or a clearly documented
memory/CPU reduction with no throughput or latency regression.

## Deliberately deferred changes

The following are not implicit consequences of this inventory:

- making uvloop mandatory;
- removing pure-Python cipher support or requiring accelerated cryptography;
- removing protocol auto-detection or public compatibility facades;
- removing legacy reader methods or private optional-backend adapters;
- changing wire formats, cipher framing, authentication, or lifecycle semantics.

The only currently approved breaking cleanup is removal of the redundant `setup.py`
after the Phase 0 and Phase 1 gates have passed and PEP 517/Git installation has been
validated.
39 changes: 39 additions & 0 deletions docs/MIGRATION.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# Migration Notes

## Build and installation interface

The redundant `setup.py` compatibility shim was removed after the project was
validated with the PEP 517 configuration in `pyproject.toml`. This is the only
breaking change in the follow-up modernization work.

Use the supported Git installation form:

```text
python -m pip install "git+https://github.com/<owner>/<repository>.git"
```

For a local checkout, use:

```text
python -m pip install .
python -m pip install -e .
python -m build --wheel
```

Replace old commands as follows:

| Old command | Replacement |
| --- | --- |
| `python setup.py install` | `python -m pip install .` |
| `python setup.py develop` | `python -m pip install -e .` |
| `python setup.py bdist_wheel` | `python -m build --wheel` |
| `python setup.py sdist` | `python -m build --sdist` |

The package name, Python requirement, console entry point, optional extras, package
data, and runtime protocol behavior are unchanged. Existing `pproxy` CLI options,
URI syntax, public compatibility facades, wire formats, and cipher fallback policy
remain supported.

To roll back the build-interface change in a private checkout, revert the dedicated
`build: remove legacy setup.py shim` commit and reinstall the checkout. No runtime
state migration is required.
Loading