Repository navigation
feat(mm): dual-backend multimodal HTTP client (httpx + aiohttp) - #8646
Conversation
2c56fe9 to
94a3bbd
Compare
94a3bbd to
d5c8305
Compare
d5c8305 to
1dd6ad6
Compare
1dd6ad6 to
f8079a4
Compare
fb52df2 to
71023c7
Compare
58efdf2 to
99b4649
Compare
2d4d06e to
41a97b9
Compare
|
Caution Review failedAn error occurred during the review process. Please try again later. WalkthroughRefactors the multimodal HTTP layer from a single Changes
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 11
🧹 Nitpick comments (2)
components/src/dynamo/common/http/args.py (1)
50-58: ⚡ Quick winFail fast on invalid
DYN_MM_HTTP_*values with explicit range checks.Current parsing accepts values like negative timeouts/concurrency (and potentially invalid pool sizes), which defers failures to downstream client construction/runtime. Add explicit validation (e.g.,
> 0or>= 0as appropriate) and raiseValueErrorwith the env var name.As per coding guidelines, “Fail fast: don’t swallow errors …”.
Also applies to: 116-131
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@components/src/dynamo/common/http/args.py` around lines 50 - 58, The _env_float and _env_int helpers currently accept any numeric string (including negative or empty) and defer invalid ranges; update these functions and the analogous parsing at lines ~116-131 to validate values according to semantics (e.g., timeouts/concurrency must be > 0, pool sizes must be >= 0) and raise ValueError including the environment variable name when the parsed numeric value is out of the allowed range or when parsing fails; ensure you still handle absent/empty values by returning the provided default, but for non-empty values perform parsing and explicit range checks and raise ValueError(f"{name}") on invalid input so callers like the HTTP client construction fail fast.components/src/dynamo/common/http/base.py (1)
101-104: ⚡ Quick winDon’t use
assertfor the terminal-body contract here.In optimized runs this check disappears, so a buggy backend can return
Noneand silently violate thebytescontract. Raise an explicit exception instead of relying onassert.Suggested fix
if redirect_to is None: # Subclass must return bytes on terminal (2xx or 3xx-without-Location). - assert body is not None + if body is None: + raise MmHttpConnectionError( + f"Backend returned no body for terminal response: {current}" + ) return bodyAs per coding guidelines: "Watch for anti-patterns: ... and using assert for runtime validation."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@components/src/dynamo/common/http/base.py` around lines 101 - 104, Replace the use of assert in the terminal-body contract: inside the branch where redirect_to is None (the terminal response case) check if body is None and raise an explicit exception (e.g., ValueError or TypeError) with a clear message that the backend returned a non-bytes/None body, instead of using assert; keep the existing return body behavior once validated so callers still get the bytes payload from this function.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@benchmarks/multimodal/http/report.py`:
- Line 1: Add the repository-standard SPDX copyright/license header above the
module docstring in this file; insert the same copyright comment block used in
other Python modules (a copyright line with the year and owner followed by the
SPDX-License-Identifier) so the file has the standard header before the
triple-quoted docstring.
In `@benchmarks/multimodal/http/runner.py`:
- Around line 1-7: This file is missing the repository's standard SPDX license
header; add the standard SPDX header comment at the very top of the file (above
the existing module docstring) so the copyright check passes—update the top of
the module (the current triple-quoted docstring block in runner.py) to be
preceded by the repo's SPDX header comment exactly as used in other files.
- Around line 32-38: Replace the broad except in _timed_fetch so you only catch
the normalized multimodal HTTP base exception produced by fetch_bytes (the
specific base exception type used by your multimodal HTTP layer, e.g.,
MultimodalHTTPError or MultimodalHTTPException) and return a benchmark sample
for that case; all other exceptions must not be swallowed—allow them to
propagate (or re-raise) so the run fails fast. Locate _timed_fetch and update
the except Exception block to except <NormalizedHTTPBaseException> as e: return
(elapsed, type(e).__name__) and remove the broad catch so unexpected errors from
fetch_bytes surface.
In `@benchmarks/multimodal/http/server_lifecycle.py`:
- Around line 1-5: Add the standard repository SPDX header to the top of this
new module so CI copyright checks pass: open
benchmarks/multimodal/http/server_lifecycle.py and insert the same
SPDX-FileCopyrightText and SPDX-License-Identifier header used elsewhere in the
repo (copy from an existing source file) above the module docstring, ensuring
the header exactly matches the project's canonical format.
In `@benchmarks/multimodal/http/stats.py`:
- Line 1: Add the repository's standard SPDX copyright/license header block at
the top of benchmarks/multimodal/http/stats.py (before the module docstring) so
CI recognizes the file; update the file header to include the SPDX-Identifier
and copyright owner lines used across the repo, ensuring the header appears
above the existing module docstring that describes aggregation of RunResult
samples into a Summary (avg, p50, p90, p99).
In `@benchmarks/multimodal/http/sweep.py`:
- Around line 1-16: This new module is missing the repository SPDX header; add
the standard repo SPDX header line(s) (the canonical SPDX-License-Identifier and
any required copyright tag used across the repo) immediately at the top of this
file before the opening module docstring (the triple-quoted string), so the file
begins with the SPDX header followed by the existing docstring.
- Around line 97-106: The sweep currently only validates args.requests but not
parsed rates/means; because run_one() divides by request_rate, passing zero or
negative values will crash or produce invalid schedules. In _run_sweep(), after
parsing rates via _parse_float_list(args.request_rate, "--request-rate") and
means via _parse_float_list(args.server_processing_time_means_ms,
"--server-processing-time-means-ms"), validate that every rate > 0 and every
mean >= 0 (or > 0 if negatives are disallowed); if any invalid values are found,
print a clear error to stderr and return a non-zero exit code (same style as the
existing --requests check). This prevents ZeroDivisionError in run_one() and
avoids negative scheduling from invalid means.
In `@components/src/dynamo/common/http/httpx_client.py`:
- Around line 68-76: The httpx AsyncClient in _build_client currently uses
default trust_env=True causing it to honor environment proxy and SSL variables;
change the AsyncClient instantiation in _build_client to pass trust_env=False so
behavior matches the aiohttp backend and avoids ambient proxy/SSL env
interference (leave other args like timeout, follow_redirects, and limits as-is,
still referencing self._per_call_timeout and self._args.max_connections /
self._args.max_keepalive).
In `@components/src/dynamo/common/tests/http/test_http_facade.py`:
- Around line 129-136: The test constructs strict =
UrlValidationPolicy(allow_private_ips=False) but leaves allow_http at its
default (False), so the rejection might be due to HTTP being disallowed rather
than the private-IP rule; update the policy construction to explicit
allow_http=True (e.g., UrlValidationPolicy(allow_private_ips=False,
allow_http=True)) so the test for fetch_body_or_redirect (patched) and
mm_http.fetch_bytes targets the private-IP rejection only.
In `@components/src/dynamo/common/tests/multimodal/conftest.py`:
- Around line 13-21: Remove the hard dependency on pytest_asyncio by replacing
its import and decorator with the standard pytest fixture: delete the import of
pytest_asyncio and change `@pytest_asyncio.fixture`(autouse=True) to
`@pytest.fixture`(autouse=True) in the conftest files that define the
_close_shared_http_client async fixture (look for the async function named
_close_shared_http_client and the close_http_client call) and apply the same
change in both multimodal and http conftest files so async fixtures run using
pytest's asyncio_mode="auto".
In `@components/src/dynamo/common/tests/multimodal/test_image_loader.py`:
- Line 177: The pytest.raises call uses a regular string for the regex in match
("scheme|not allowed") which triggers RUF043; update the pytest.raises
invocation (the pytest.raises(...) call in the multimodal image loader test) to
pass a raw regex literal r"scheme|not allowed" for the match parameter so the
regex metacharacter is treated correctly and the linter warning is resolved.
---
Nitpick comments:
In `@components/src/dynamo/common/http/args.py`:
- Around line 50-58: The _env_float and _env_int helpers currently accept any
numeric string (including negative or empty) and defer invalid ranges; update
these functions and the analogous parsing at lines ~116-131 to validate values
according to semantics (e.g., timeouts/concurrency must be > 0, pool sizes must
be >= 0) and raise ValueError including the environment variable name when the
parsed numeric value is out of the allowed range or when parsing fails; ensure
you still handle absent/empty values by returning the provided default, but for
non-empty values perform parsing and explicit range checks and raise
ValueError(f"{name}") on invalid input so callers like the HTTP client
construction fail fast.
In `@components/src/dynamo/common/http/base.py`:
- Around line 101-104: Replace the use of assert in the terminal-body contract:
inside the branch where redirect_to is None (the terminal response case) check
if body is None and raise an explicit exception (e.g., ValueError or TypeError)
with a clear message that the backend returned a non-bytes/None body, instead of
using assert; keep the existing return body behavior once validated so callers
still get the bytes payload from this function.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: d5ee02dc-1401-4ab6-9820-bdd69b34a161
📒 Files selected for processing (28)
benchmarks/multimodal/http/__init__.pybenchmarks/multimodal/http/report.pybenchmarks/multimodal/http/runner.pybenchmarks/multimodal/http/server_lifecycle.pybenchmarks/multimodal/http/stats.pybenchmarks/multimodal/http/sweep.pycomponents/src/dynamo/common/http/__init__.pycomponents/src/dynamo/common/http/aiohttp_client.pycomponents/src/dynamo/common/http/args.pycomponents/src/dynamo/common/http/base.pycomponents/src/dynamo/common/http/httpx_client.pycomponents/src/dynamo/common/http/url_validator.pycomponents/src/dynamo/common/multimodal/audio_loader.pycomponents/src/dynamo/common/multimodal/http_client.pycomponents/src/dynamo/common/multimodal/image_loader.pycomponents/src/dynamo/common/multimodal/video_loader.pycomponents/src/dynamo/common/tests/http/conftest.pycomponents/src/dynamo/common/tests/http/test_aiohttp_client.pycomponents/src/dynamo/common/tests/http/test_http_facade.pycomponents/src/dynamo/common/tests/http/test_httpx_client.pycomponents/src/dynamo/common/tests/http/test_url_validator.pycomponents/src/dynamo/common/tests/multimodal/conftest.pycomponents/src/dynamo/common/tests/multimodal/test_audio_loader.pycomponents/src/dynamo/common/tests/multimodal/test_image_loader.pycomponents/src/dynamo/common/tests/multimodal/test_video_loader.pycomponents/src/dynamo/vllm/multimodal_utils/__init__.pycontainer/deps/requirements.common.txtpyproject.toml
💤 Files with no reviewable changes (3)
- components/src/dynamo/common/http/url_validator.py
- components/src/dynamo/vllm/multimodal_utils/init.py
- components/src/dynamo/common/multimodal/http_client.py
9ca81d5 to
3b5e65a
Compare
3b5e65a to
9ca81d5
Compare
krishung5
left a comment
There was a problem hiding this comment.
Thanks for PR! My comments are non-blocking.
indrajit96
left a comment
There was a problem hiding this comment.
LGTM!
NIT:
Another docs related issue codex was able to flag
1. Stale doc reference
- Old:
docs/features/multimodal/README.md:54points atdynamo.common.multimodal.url_validator. - New: validator now lives at
dynamo.common.http.url_validator; the doc still names the old path. - Fix: update the dotted path in the README — one-line change.
indrajit96
left a comment
There was a problem hiding this comment.
LGTM!
Thanks for working on this appreciate it! :)
Under high-fanout workloads (one request → 100 image URLs) the httpx
backend hits httpx.PoolTimeout because httpcore's pool maintenance is
O(queue_size × pool_size) per add/remove. aiohttp's connector queues
natively in O(1) and stays close to the offered rate well past httpx
saturation.
This change hoists the multimodal HTTP client out of
dynamo.common.multimodal.http_client into dynamo.common.http as a
backend-neutral facade (fetch_bytes / close_http_client) over a small
ABC with two concrete subclasses: AiohttpClient (default) and
HttpxClient. Backend selection: DYN_MM_HTTP_BACKEND={aiohttp,httpx}.
* AiohttpClient is the new default; ClientSession + TCPConnector with
limit_per_host=0 (single-origin fan-out is the use case).
* HttpxClient keeps a process-wide DYN_MM_HTTP_CONCURRENCY semaphore
in front of the pool so a saturated client doesn't push PoolTimeout
up the stack.
* Operator-tunable env vars (DYN_MM_HTTP_MAX_CONNECTIONS,
DYN_MM_HTTP_READ_TIMEOUT, DYN_MM_HTTP_CONNECT_TIMEOUT,
DYN_MM_HTTP_POOL_TIMEOUT, DYN_MM_HTTP_CONCURRENCY,
DYN_MM_HTTP_KEEPALIVE_TIMEOUT, DYN_MM_HTTP_MAX_KEEPALIVE) live in
args.py as the single source of truth.
* Loaders (image, audio, video) consume the facade; per-loader HTTP
shims removed.
* Tests reorganized into tests/http/ + tests/multimodal/, per-backend
unit suites + facade tests.
* Benchmark harness under benchmarks/multimodal/http/ (sweep, runner,
stats, report) drives the comparison empirically.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
… into aiohttp Two reviewer-driven follow-ups, bundled because they reshape the same operator surface. 1. Rename ``read_timeout_override`` → ``per_call_timeout_override``; add ``DYN_MM_HTTP_TIMEOUT`` env var with ``DYN_MM_HTTP_READ_TIMEOUT`` kept as a deprecated alias. The old name was misleading on aiohttp, which has no separate read component — the override always landed on ``ClientTimeout.total``. Per-backend semantics are now spelled out in args.py (httpx caps ``Timeout.read`` so connect/pool stay independent; aiohttp caps ``ClientTimeout.total``). 2. Plumb ``connect_timeout`` (5.0s default) into aiohttp's ``ClientTimeout.sock_connect`` so a stuck TCP+TLS handshake fast-fails on its own budget. Without this, the prior aiohttp backend would burn the full per-call timeout (30s/60s) before any byte arrives — a regression vs. the old httpx-only setup, which had ``Timeout.connect=5s`` independent of ``read``. ``connect_timeout`` is now a shared field, not httpx-only. Pool timeout, concurrency semaphore, and keepalive_timeout stay backend-specific (aiohttp's connector queues natively, so the httpx PoolTimeout / semaphore story doesn't apply). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
… ConfigBase/ArgGroup
Four reviewer-driven follow-ups, bundled because they all reshape the
same public surface.
* Drop the ``Mm`` prefix on the public types — the facade lives in
``dynamo.common.http`` and is generic enough to back any web fetch,
not just multimodal callers. Renames:
MmHttpClient → HttpClient
MmHttpError → HttpError
MmHttpTimeout → HttpTimeoutError
MmHttpConnectionError → HttpConnectionError
MmHttpStatusError → HttpStatusError
* Replace the ``assert body is not None`` in
``HttpClient._fetch_with_revalidation`` with a real ``raise
HttpError(...)``. Asserts are stripped under -O; this is a contract
violation by the subclass and deserves an exception.
* Rename ``fetch_body_or_redirect`` → ``_fetch_body_or_redirect``. It
was always a subclass-implementation contract used only by the
parent's redirect loop, never a public API. The two per-backend
unit tests that called it directly are reworked to exercise the
contract through the public ``fetch_bytes(url, policy=...)`` path.
The facade tests still patch the seam by name (acceptable for
testing the parent class's redirect-loop logic).
* Adopt the shared Dynamo config-group concept for the env vars.
``HttpArgs`` (frozen dataclass + handrolled ``_env_float`` / ``_env_int``)
is replaced by ``HttpConfigBase(ConfigBase)`` + ``HttpArgGroup(ArgGroup)``.
Env vars now flow through the same ``add_argument`` /
``env_or_default`` plumbing the rest of the codebase uses, and
components that want CLI flags (``--mm-http-max-connections`` etc.)
can register the group directly in their argparse. ``from_env()``
is preserved as the env-only entry point.
Behavior unchanged: ``DYN_MM_HTTP_*`` env vars resolve to the same
defaults, ``DYN_MM_HTTP_READ_TIMEOUT`` is still honored as the
deprecated alias for ``DYN_MM_HTTP_TIMEOUT``, and the
``max_keepalive=0 → match max_connections`` heuristic now applies on
both env and CLI paths.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Relocate ``args.py`` to ``dynamo/common/configuration/groups/http_args.py`` so ``HttpArgGroup`` is discoverable next to the other ArgGroups (router, kv-router, runtime, aic-perf). A component that wants HTTP-client CLI flags can now compose this group the same way it composes ``RouterArgGroup``. Pure relocation, no behavior change: the contents of args.py are preserved verbatim (``HttpConfigBase``, ``HttpArgGroup``, ``from_env``, ``_nullable_float``). ``from_env`` stays in this module because the HTTP client's primary callers (image / audio / video loaders) don't own an argparse — that asymmetry is now documented inline. ``dynamo.common.http`` continues to re-export ``HttpConfigBase``, ``HttpArgGroup``, and ``from_env`` so existing ``from dynamo.common.http import …`` callers keep working. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…HTTP_* The HTTP fetch client used to live in ``dynamo.common.multimodal.http_client``; it has since hoisted to ``dynamo.common.http`` and is generic enough to back any web fetch, not just multimodal. Drop the residual "MM" framing from the public surface to match. * Env vars ``DYN_MM_HTTP_*`` → ``DYN_HTTP_*`` (BACKEND, MAX_CONNECTIONS, TIMEOUT, CONNECT_TIMEOUT, MAX_KEEPALIVE, POOL_TIMEOUT, CONCURRENCY, KEEPALIVE_TIMEOUT). Legacy ``DYN_MM_HTTP_*`` names are still honored via ``_apply_legacy_env_aliases``: if the canonical ``DYN_HTTP_*`` isn't set but a legacy alias is, the value is mirrored across and a one-time deprecation warning is emitted. Keeps deployments that predate the rename working. * CLI flags ``--mm-http-*`` → ``--http-*`` (no back-compat needed; the CLI flag surface is new in this PR). * argparse group label "Multimodal HTTP Options" → "HTTP Fetch Options". * Docstrings, README title, and shrunken top-level doc in ``http_args.py`` reframe the client as generic HTTP fetch rather than multimodal-specific. * Trim ``http_args.py``'s top docstring — per-field comments inline on the dataclass + per-flag help text on ``add_argument`` calls are the canonical place to look; the redundant module-level env-var listing is gone. Tests: existing facade tests now use ``DYN_HTTP_BACKEND``; one new test verifies that legacy ``DYN_MM_HTTP_BACKEND`` still selects the backend correctly. Local run: 75/75 http + 75/75 multimodal pass. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The previous rename commit (a0c618d) carried back-compat aliases for ``DYN_MM_HTTP_BACKEND``, ``DYN_MM_HTTP_TIMEOUT``, and ``DYN_MM_HTTP_KEEPALIVE_TIMEOUT`` — none of which existed in the deleted ``dynamo.common.multimodal.http_client`` module. They were introduced and renamed inside this PR's branch history, never deployed under the ``DYN_MM_HTTP_*`` form. Trim ``_LEGACY_ENV_ALIASES`` to the six env vars that genuinely shipped in the predecessor module: ``DYN_MM_HTTP_CONNECT_TIMEOUT``, ``DYN_MM_HTTP_READ_TIMEOUT``, ``DYN_MM_HTTP_POOL_TIMEOUT``, ``DYN_MM_HTTP_MAX_CONNECTIONS``, ``DYN_MM_HTTP_MAX_KEEPALIVE``, ``DYN_MM_HTTP_CONCURRENCY``. Drop the no-back-compat-needed claims from the facade docstring and README. Replace the ``test_legacy_mm_http_backend_env_var_still_honored`` test with one that exercises a real legacy env var (``DYN_MM_HTTP_MAX_CONNECTIONS``). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Why
Under high concurrency/workload, e.g. one request with 100 HTTP images, we're experiencing httpx.PoolTimeout.
There have been reports that aiohttp supports high concurrency better than httpx
https://github.com/encode/httpcore/blob/master/httpcore/_async/connection_pool.py#L303-L309
my read is, the function is called
for each call, it's O(queue_size * pool_size) complexity
What Change
Added a new aiohttp-base implementation
Benchmark
I sweep across different request rate, server processing time
aiohttpandhttpxshow the same performance when request pool is not saturated-
aiohttpoutperformshttpxunder high request rate (500 rps) --Summary by CodeRabbit
Release Notes
New Features
Bug Fixes
Refactor
Chores