3350 Commits

Author SHA1 Message Date
Benoit Chesneau
1af599769f docs: regenerate settings.md 2026-02-01 03:11:42 +01:00
Benoit Chesneau
1d0df29796 feat(dirty): add class attribute workers support and e2e tests
- Add get_app_workers_attribute() to read workers class attribute
- Update _parse_app_specs() to check class attribute when no config override
- Add Docker-based e2e tests for per-app worker allocation
- Add test apps: HeavyModelApp (workers=2), LightweightApp
- Add unit tests for get_app_workers_attribute function
- Add integration tests for class attribute detection
2026-02-01 03:04:35 +01:00
Benoit Chesneau
8559854b4f feat(dirty): add per-app worker allocation for memory optimization
Allow dirty apps to specify how many workers should load them, enabling
significant memory savings for heavy applications like ML models.

- Add `workers` class attribute to DirtyApp (None = all workers)
- Add `parse_dirty_app_spec()` to parse "module:Class:N" format
- Add `DirtyNoWorkersAvailableError` for app-specific error handling
- Update DirtyArbiter with per-app worker tracking and routing
- Maintain backward compatibility when no dirty_apps configured

Example: 8 workers x 10GB model = 80GB RAM needed
With workers=2: 2 x 10GB = 20GB RAM (75% savings)

Configuration formats:
- Class attribute: `workers = 2` on DirtyApp subclass
- Config format: `module:class:N` (e.g., `myapp.ml:HugeModel:2`)
2026-02-01 02:40:09 +01:00
Benoit Chesneau
1591a6c773 fix: iPad mobile menu and documentation link warnings
- Fix mobile side menu not displaying on iPad by keeping site_nav
  content but hiding sidebar on desktop via CSS
- Fix broken links in asgi.md and guides/http2.md
- Add HTTP/2 guide to navigation
2026-01-30 01:29:45 +01:00
Benoit Chesneau
bca7c6fce9 fix: sync eventlet deprecation notice in config.py 2026-01-28 13:58:12 +01:00
Benoit Chesneau
490817d149 docs: update changelog for 25.0.0
- Add ALPN fix for gevent/eventlet workers
- Add eventlet worker deprecation notice
- Update HTTP/2 feature to mention gevent example
- Remove eventlet from HTTP/2 supported workers list
2026-01-28 13:43:54 +01:00
Benoit Chesneau
315e7bde80 fix(http2): ALPN negotiation for gevent/eventlet workers
- Add explicit do_handshake() in base_async.py before ALPN check
  when do_handshake_on_connect is False
- Mark eventlet worker as deprecated (removal in 26.0)
- Add HTTP/2 gevent example with Docker and tests
- Update documentation to reflect eventlet deprecation
- Remove eventlet websocket example (gevent version exists)

The ALPN fix ensures HTTP/2 works correctly with gevent and eventlet
workers when do_handshake_on_connect config is False (the default).
Without explicit handshake, selected_alpn_protocol() returns None.
2026-01-28 13:42:48 +01:00
Benoit Chesneau
200977bc0b docs: update 25.0.0 changelog with all changes since 24.0
- Fix PR references for HTTP/2 and Early Hints (#3468)
- Add uWSGI protocol support for ASGI worker (#3467)
- Add bug fixes: setproctitle, 100-continue, macOS segfault
- Add changes: remove obsolete Makefile targets (#3471)
2026-01-28 11:45:36 +01:00
Benoit Chesneau
d6dcb686de
Merge pull request #3468 from benoitc/feature/http2-support
Add HTTP/2 support (RFC 7540) and HTTP 103 Early Hints (RFC 8297)
2026-01-28 10:25:31 +01:00
Benoit Chesneau
fba07af47c
Merge pull request #3471 from adk-swisstopo/makefile
Remove obviously broken make targets.
2026-01-27 17:00:27 +01:00
Benoit Chesneau
6cc20d3a71 fix(http2): fix pylint errors in connection modules
- Reorder exception handlers: specific exceptions before ProtocolError
- Extract _wait_for_flow_control_window() to reduce return statements
- Refactor flow control waiting to avoid too-many-return-statements
2026-01-27 16:57:39 +01:00
Benoit Chesneau
49193223d5 docs(http2): add performance tuning section
- Add three tuning profiles: Conservative, Balanced, High Concurrency
- Document pros/cons and trade-offs for each HTTP/2 setting
- Add Linux kernel tuning parameters for high concurrency
- Add Docker-specific tuning recommendations
- Include benchmark results from h2load testing
2026-01-27 16:11:05 +01:00
Benoit Chesneau
34dc8b8fad docs(http2): add RFC compliance, security, and testing sections
- Add RFC compliance table covering RFC 7540, 9113, 7541, 8297
- Document security considerations and built-in protections
- Add recommended security-hardened configuration example
- Document compliance testing with h2spec and nghttp2 tools
- Note that Server Push is intentionally not implemented
2026-01-27 15:42:53 +01:00
Benoit Chesneau
4e3245a0df fix(http2): achieve 100% h2spec compliance (146/146 tests)
- Send GOAWAY with correct error codes for protocol violations
- Handle StreamClosedError and FlowControlError gracefully
- Return False instead of raising for missing/closed streams
- Handle flow control window overflow per RFC 7540
- Fix reader race condition and add h2 exception handling
- Wait for WINDOW_UPDATE when flow control window is zero/negative
- Use h2 exception's error_code for INITIAL_WINDOW_SIZE violations
2026-01-27 15:42:42 +01:00
Benoit Chesneau
fa5e319f15 docs(http2): add ASGI example demonstrating priority and trailers
Add complete HTTP/2 example in examples/http2_features/:
- ASGI app showing priority access and trailer sending
- Test script using raw h2 library for HTTP/2 testing
- Docker setup for easy testing
- Documentation update referencing the example

The example demonstrates:
- Reading http.response.priority extension in ASGI scope
- Sending http.response.trailers messages
- Multiple streams on the same connection
2026-01-27 13:15:36 +01:00
Benoit Chesneau
0f298e4838 feat(http2): add response trailer support 2026-01-27 12:33:12 +01:00
Benoit Chesneau
655716a181 feat(http2): add stream priority support (RFC 7540 Section 5.3) 2026-01-27 11:44:33 +01:00
Benoit Chesneau
251d8ebe51 fix(http2): validate frame size per RFC 7540 (16384-16777215) 2026-01-27 10:51:29 +01:00
Benoit Chesneau
a3185d9384 fix: update HTTP/2 settings version to 25.0.0
HTTP/2 is being released in 25.0.0, not 24.0.0
2026-01-27 10:07:42 +01:00
Benoit Chesneau
df5d7ad6d2 fix: resolve ruff lint warnings in HTTP/2 code
- Remove unused imports in test files
- Rename loop variable to avoid shadowing sock import
- Remove unused ssock variable in conftest
2026-01-27 10:03:54 +01:00
Benoit Chesneau
17b3786186 Update test to expect :authority override per RFC 9113 2026-01-27 09:59:35 +01:00
Benoit Chesneau
66d0880c74 Address PR #3468 review feedback
- Guard early_hints callback against calls after response started
- Fix :authority precedence over Host header per RFC 9113 section 8.3.1
- Add nginx early_hints documentation link
- Use standard port 443 in curl examples
2026-01-27 09:59:35 +01:00
Benoit Chesneau
ed94da449c Fix pylint issues in HTTP/2 module
- Add pylint disable comments for global-statement in lazy import pattern
- Remove unnecessary pass statements in error subclasses
- Remove useless return None at end of _handle_request_received methods
2026-01-27 09:59:35 +01:00
Benoit Chesneau
9306db1d20 Fix lint issues: remove unused imports 2026-01-27 09:59:35 +01:00
Benoit Chesneau
955893b6ab Add HTTP/2 documentation
- Add docs/content/guides/http2.md with comprehensive HTTP/2 guide
  - Quick start and requirements
  - Configuration options and settings
  - Worker compatibility matrix
  - HTTP 103 Early Hints usage for WSGI and ASGI
  - Production deployment with nginx
  - Troubleshooting guide
- Update docs/content/asgi.md to reflect HTTP/2 support
- Update docs/content/2026-news.md with 25.0.0 release featuring
  HTTP/2 and Early Hints
- Regenerate docs/content/reference/settings.md with HTTP/2 settings
2026-01-27 09:59:35 +01:00
Benoit Chesneau
75b46bf6cf Add HTTP 103 Early Hints support (RFC 8297)
Implement HTTP 103 Early Hints as modern replacement for HTTP/2 Server Push.
This allows servers to send resource hints before the final response,
enabling browsers to preload assets in parallel.

WSGI support:
- Add wsgi.early_hints callback to environ dict
- Apps can call environ['wsgi.early_hints'](headers) to send 103 responses
- Silently ignored for HTTP/1.0 clients (don't support 1xx responses)

ASGI support:
- Handle http.response.informational message type
- Apps can await send({"type": "http.response.informational", "status": 103, ...})

HTTP/2 support:
- Add send_informational() method to HTTP2ServerConnection
- Add async send_informational() method to AsyncHTTP2Connection
- Wire up early hints in gthread worker for HTTP/2 requests

Includes unit tests and Docker integration tests for all protocols.
2026-01-27 09:57:32 +01:00
Benoit Chesneau
780e2cf055 Add HTTP/2 tests
Unit tests for HTTP/2 implementation:
- test_http2_stream.py: Stream state management tests
- test_http2_request.py: Request interface tests
- test_http2_connection.py: Connection handling tests
- test_http2_async_connection.py: Async connection tests
- test_http2_config.py: Configuration tests
- test_http2_alpn.py: ALPN negotiation tests
- test_http2_errors.py: Error handling tests
- test_http2_integration.py: Integration tests

Docker integration tests:
- Full HTTP/2 testing environment with nginx proxy
- Direct connection tests and proxy tests
- Concurrent stream tests
- Protocol behavior tests
- Error handling tests
- Header handling tests
- Performance tests
2026-01-27 09:57:32 +01:00
Benoit Chesneau
fe18960cd1 Add HTTP/2 worker integration
Integrate HTTP/2 support with gunicorn workers:

- sync worker: Add warning that HTTP/2 is not supported
- gthread worker: Full HTTP/2 support
  - ALPN negotiation with explicit handshake for deferred SSL
  - HTTP/2 connection lifecycle management
  - Per-stream request handling with WSGI
- AsyncHTTP2Connection: Async version for ASGI workers
  - Same features as sync version with async/await
  - Proper flow control with chunked data sending
- ASGI worker: HTTP/2 support via AsyncHTTP2Connection
- AsyncWorker base: HTTP/2 connection handling
- tornado worker: Add warning that HTTP/2 is not supported

Also exports helper functions from http2 module.
2026-01-27 09:57:01 +01:00
Benoit Chesneau
89a0a46722 Add HTTP/2 core protocol implementation
Core classes for HTTP/2 server-side protocol handling:

- HTTP2Stream: Stream state management matching RFC 7540 Section 5.1
  - StreamState enum for proper lifecycle tracking
  - Request/response tracking and body buffering
  - Pseudo-header extraction for :method, :path, etc.
  - Proper state transitions for half-close semantics

- HTTP2Request: Request interface compatibility layer
  - Wraps HTTP2Stream for worker consumption
  - HTTP2Body provides file-like interface for request body
  - Converts HTTP/2 pseudo-headers to standard attributes
  - Transforms lowercase headers to uppercase for WSGI
  - Adds HOST header from :authority pseudo-header

- HTTP2ServerConnection: h2 library integration
  - Lazy import of h2 for graceful degradation
  - Connection initialization with configurable settings
  - Stream management for concurrent requests
  - Event handling for HEADERS, DATA, RST_STREAM, GOAWAY
  - Response sending with proper frame generation
  - Flow control window management with chunked data sending

- get_parser() extension for HTTP/2 dispatch
2026-01-27 09:57:01 +01:00
Benoit Chesneau
c711d9fb6f Add HTTP/2 dependency and configuration
- Add optional h2 dependency for HTTP/2 support
- Add http2 module skeleton with availability check and errors
- Add HTTP/2 configuration settings (max_concurrent_streams,
  initial_window_size, max_frame_size, max_header_list_size)
- Add ALPN support to SSL context for HTTP/2 negotiation
2026-01-27 09:57:01 +01:00
Adrien Kunysz
e6911192ff Remove obsolete Makefile targets.
The `test` and `coverage` targets rely on `setup.py` which was removed "about
10 years ago". There is apparently no interest in fixing them. This change
removes them to avoid confusion.

As per https://github.com/benoitc/gunicorn/issues/3386
2026-01-27 09:46:42 +01:00
Benoit Chesneau
1fe9e5816e
Merge pull request #3460 from benoitc/feature/dirty-arbiters
feat: add dirty arbiters for long-running blocking operations
2026-01-27 09:45:05 +01:00
Benoit Chesneau
891990befa docs(dirty): update streaming from future to current feature 2026-01-26 09:39:46 +01:00
Benoit Chesneau
bbae34b951
Fix setproctitle initialization with systemd socket activation (#3465)
Force early setproctitle initialization by calling getproctitle()
immediately after import. This ensures setproctitle captures the
argv/environ memory layout before systemd.listen_fds() modifies
the environment by removing LISTEN_FDS and LISTEN_PID.

Without this fix, if LISTEN_FDS is the first environment variable,
setproctitle fails to detect argv correctly and silently fails.

Fixes #3430
2026-01-25 15:18:04 +01:00
Benoit Chesneau
29830ccc2f Increase CI timeout for signal integration tests
PyPy signal handling can be slower in CI environments, so increase
the timeout from 30 to 60 seconds to avoid flaky test failures.
2026-01-25 15:08:05 +01:00
Benoit Chesneau
6575d86251 Add docker integration tests for simple ASGI (HTTP protocol)
Tests the ASGI worker with direct HTTP requests without uWSGI protocol.
Includes tests for GET, POST, query strings, path handling, keepalive,
large bodies, and custom headers.
2026-01-25 15:03:12 +01:00
Benoit Chesneau
47b1cb82b8 Fix missing _expected_100_continue attribute in UWSGIRequest
The wsgi.create() function expects req._expected_100_continue but
UWSGIRequest didn't have this attribute, causing an AttributeError.
Set to False since uWSGI runs behind a frontend server that handles
100-continue negotiation.
2026-01-25 14:51:40 +01:00
Benoit Chesneau
8663740907
Add uWSGI protocol support to ASGI worker (#3467)
Add uWSGI protocol support to ASGI worker

- Implements AsyncUWSGIRequest class extending sync UWSGIRequest to reuse parsing logic with async I/O
- ASGI protocol handler selects between HTTP and uWSGI based on --protocol config option
- Allows gunicorn's ASGI worker to receive requests from nginx using uwsgi_pass directive
- Includes unit tests and Docker integration tests
2026-01-25 14:45:07 +01:00
Benoit Chesneau
35559a87bd test: add conftest.py to fix tests module import path 2026-01-25 10:38:07 +01:00
Benoit Chesneau
d85be79102 docs: regenerate settings.md with dirty arbiter options 2026-01-25 10:33:38 +01:00
Benoit Chesneau
634290fc75 fix(dirty): resolve pylint warnings in dirty module 2026-01-25 10:29:52 +01:00
Benoit Chesneau
cc39ed922e examples(dirty): add streaming chat demo with SSE
Add a lightweight chat simulator demonstrating dirty worker streaming:
- Token-by-token SSE streaming via async generators
- FastAPI endpoint with browser UI
- Multiple canned responses based on keywords
- Docker deployment with docker-compose
- Integration tests for SSE protocol

Update docs/content/dirty.md to link to both examples.
2026-01-25 10:26:12 +01:00
Benoit Chesneau
ae8665c4d5 docs(dirty): expand architecture, signal handling, and health monitoring
- Enhance architecture diagram with Unix socket paths, signal flow, and
  heartbeat indicators
- Add process relationships table
- Expand signal handling section with flow diagram, comprehensive signal
  reference table, and async handling explanation
- Add new "Liveness and Health Monitoring" section covering heartbeat
  mechanism, timeout detection, parent death detection, orphan cleanup,
  and respawn behavior
- Add link to embedding service example
2026-01-25 10:23:25 +01:00
Benoit Chesneau
5e3c07d11d test(dirty): add Docker-based parent death integration tests
Add comprehensive Docker integration tests verifying dirty arbiter
lifecycle under realistic conditions:
- Parent death detection via ppid monitoring
- Orphan cleanup on restart
- Dirty arbiter respawning after crash
- Graceful shutdown with SIGTERM

Also fix race condition in manage_workers() by checking self.alive
before spawning new workers during shutdown.
2026-01-25 10:23:25 +01:00
Benoit Chesneau
79f85af55e fix(dirty): detect parent death and self-terminate
Add ppid monitoring to dirty arbiter's worker monitor loop. If the
main arbiter dies unexpectedly (SIGKILL, crash, OOM), the dirty
arbiter detects the parent change and shuts itself down gracefully.

This complements the existing orphan cleanup on startup.
2026-01-25 10:23:25 +01:00
Benoit Chesneau
b67ff0b31d test: fix warnings and flaky tests in dirty arbiter tests
- Close coroutines in mocked asyncio.run to prevent "never awaited" warning
- Fix flaky integration tests with proper async cleanup and try/finally
- Add uvloop to testing dependencies so uvloop test runs
- Add pytest warning filter for eventlet/asyncio incompatibility
2026-01-25 10:23:25 +01:00
Benoit Chesneau
e21d23bfa6 fix(dirty): add orphan cleanup via well-known PID file
When the main arbiter crashes and restarts, orphaned dirty arbiters
may continue running. This adds detection and cleanup:

- Add well-known PID file location based on proc_name
- Dirty arbiter writes PID on startup, removes on exit
- Main arbiter checks for orphans on fresh start (not USR2)
- Uses self.proc_name for USR2 compatibility (myapp vs myapp.2)

During USR2 upgrade, old and new dirty arbiters coexist with
separate PID files, preventing the old from removing the new's file.
2026-01-25 10:23:25 +01:00
Benoit Chesneau
f6418d4eb0 feat(dirty): add streaming support and async client benchmarks
Add support for streaming responses when dirty app actions return
generators (sync or async). This enables real-time delivery of
incremental results for use cases like LLM token generation.

Features:
- Streaming protocol with chunk/end/error message types
- Worker support for sync and async generators
- Arbiter forwarding of streaming messages
- Deadline-based timeout handling
- Async client streaming API

Protocol:
- Chunk messages (type: "chunk") contain partial data
- End messages (type: "end") signal stream completion
- Error messages can occur mid-stream

New files:
- benchmarks/dirty_streaming.py: Streaming benchmark suite
- tests/dirty/test_*_streaming*.py: Streaming test coverage
- docs/content/dirty.md: Streaming documentation with examples
2026-01-25 10:23:25 +01:00
Benoit Chesneau
62a29bd0e1 test(dirty): add multi-app routing tests
Add tests to verify that when multiple dirty apps are configured,
messages are correctly routed to the appropriate app based on app_path.

New files:
- tests/support_dirty_apps.py: CounterApp and EchoApp test apps
- tests/dirty/test_multi_app_routing.py: 13 routing tests covering
  app loading, routing, state separation, error handling, and
  concurrent requests
2026-01-25 10:23:25 +01:00
Benoit Chesneau
0e05c824e9 feat(examples): add FastAPI embedding service with Docker testing
Add a complete example demonstrating dirty workers with sentence-transformers
for text embeddings via FastAPI:

- EmbeddingApp DirtyApp that loads and manages the ML model
- FastAPI endpoints for /embed and /health
- Docker and docker-compose configuration
- Integration tests with numpy similarity checks
- GitHub Actions CI workflow
2026-01-25 10:23:25 +01:00