perf(multimodal): bound-concurrent attachment reference normalization
Summary
prepare_messages_for_providernow resolves the[IMAGE:…]/[FILE:…]references inside a user message with a bounded-concurrentbufferedfan-out (K=4) instead of one strictly-serialawaitper reference.- Order- and error-preserving:
bufferedyields in input order, so the rebuilt message lines its markers back up exactly as the serial loop did, and the first error by index is still the one surfaced. - Single-reference messages (the common case) cost nothing extra; the win shows up when a message carries several remote image/file URLs.
Problem
Each reference is an independent HTTP fetch (remote http(s) source, up to a 30s timeout) or a local-disk read. The old code awaited them one at a time:
for reference in image_refs {
let data_uri = normalize_image_reference(&reference, image_config, max_image_bytes, &remote_client).await?;
normalized_image_refs.push(data_uri);
}
// …same serial shape for file_refs
So a chat turn whose message embeds N remote URLs blocked for the sum of all N fetches before the provider call could start — a directly user-perceptible latency hit on multimodal turns.
Solution
Materialize the per-reference futures and drive them through a bounded buffered:
let image_futs: Vec<_> = image_refs
.iter()
.map(|reference| normalize_image_reference(reference, image_config, max_image_bytes, &remote_client))
.collect();
let image_results: Vec<anyhow::Result<String>> =
futures::stream::iter(image_futs).buffered(REF_FETCH_CONCURRENCY).collect().await;
let mut normalized_image_refs = Vec::with_capacity(image_results.len());
for result in image_results {
normalized_image_refs.push(result?);
}
- Order preserved:
buffered(K)emits result[i] for input[i], so the reassembled[IMAGE:…]/[FILE:…]markers keep their original positions. - Error semantics preserved: collecting in order and pushing with
?returns the lowest-index error, exactly like the old short-circuit. (Later references may be fetched and discarded — no observable difference to the caller.) - Bounded:
REF_FETCH_CONCURRENCY = 4caps sockets opened against a single host; N=1 just drives one future. - The futures are collected into a
Vecbeforestream::iter— handing it a lazyMapadaptor trips the "implementation of Send is not general enough" HRTB error.
Submission Checklist
- [x] Tests added or updated (happy path + at least one failure / edge case) — added
prepare_messages_preserves_image_order_under_concurrent_fetch: writes five distinct local PNGs (more thanREF_FETCH_CONCURRENCY, so the concurrency window wraps), runsprepare_messages_for_provider, and asserts the rebuilt image refs equal the expected data URIs in input order. Existing order/limit/rejection tests (36 total in the module) continue to pass. - [x] Diff coverage ≥ 80% — the changed lines are the two
bufferedfan-outs inprepare_messages_for_provider, exercised by the new ordering test plus the existing image/file/mixed normalization tests. - [x] N/A: Coverage matrix — behaviour-preserving perf change, no feature rows added/removed/renamed.
- [x] N/A: feature IDs — no matrix feature affected.
- [x] No new external network dependencies introduced (no new endpoints; same
remote_client, same per-reference fetch, just concurrent). - [x] N/A: manual smoke checklist — internal multimodal message-prep path, no release-cut surface.
- [x] N/A: no linked issue — proactive performance improvement.
Impact
- Runtime: Rust core agent multimodal pipeline (
prepare_messages_for_provider). - Latency: a multimodal message with N references now resolves them in ~
ceil(N/4)round-trips instead of N. No change for single-reference messages. - No migration, security, or compatibility implications; per-reference validation (size, MIME, remote-fetch gate, untrusted-channel hardening) is untouched.
Related
- Closes:
- Follow-up PR(s)/TODOs:
AI Authored PR Metadata
Linear Issue
- Key: N/A
- URL: N/A
Commit & Branch
- Branch: perf/multimodal-bounded-refs
Validation Run
- [x] N/A:
pnpm --filter openhuman-app format:check— no app/ changes - [x] N/A:
pnpm typecheck— no TypeScript changes - [x] Focused tests:
cargo test --lib agent::multimodal(36 passed, incl. new ordering test) - [x] Rust fmt:
cargo fmt -p openhuman - [x] Lib check clean:
cargo check --lib(no errors; pre-existing unused-import warnings only) - [x] N/A: Tauri fmt/check — no shell changes
Validation Blocked
- command: N/A
- error: N/A
- impact: N/A
Behavior Changes
- Intended behavior change: none (perf-only; same normalized output, same validation, same error surfaced)
- User-visible effect: lower latency on chat turns whose message carries multiple image/file references
Parity Contract
- Legacy behavior preserved: each reference goes through the identical
normalize_image_reference/normalize_file_reference; output order and the first-by-index error are unchanged. - Guard/fallback/dispatch parity checks: image-count / file-count gates, remote-fetch disable, oversize, unsupported-MIME, and untrusted-channel hardening all run exactly as before (they live inside the per-reference normalizers and the pre-loop count checks, none of which moved).
Duplicate / Superseded PR Handling
- Duplicate PR(s): N/A
- Canonical PR: N/A
- Resolution: N/A
Summary by CodeRabbit
-
Performance
- Optimized message processing to fetch image and file attachments concurrently with a bounded concurrency limit, preserving original attachment order and surfacing the first error promptly.
-
Tests
- Added a test that verifies attachment ordering is preserved when attachments are normalized concurrently.
No actionable comments were generated in the recent review. 🎉
ℹ️ Recent review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: e8587e45-245d-477e-8b41-ae759cce58ca
📥 Commits
Reviewing files that changed from the base of the PR and between 53121da82e9ac9dfb7be2bf8718a50714a1e3622 and 64eb0601cbc379490d2117262859c051761dbe7e.
📒 Files selected for processing (1)
src/openhuman/agent/multimodal.rs
🚧 Files skipped from review as they are similar to previous changes (1)
- src/openhuman/agent/multimodal.rs
📝 Walkthrough
Walkthrough
prepare_messages_for_provider now normalizes image and file attachment references with bounded concurrency (REF_FETCH_CONCURRENCY = 4) using futures::stream::buffered, preserving input order and short-circuiting on the first error. A regression test asserts image marker order is preserved under concurrent fetch.
Changes
Bounded-concurrency attachment resolution
| Layer / File(s) | Summary |
|---|---|
Concurrency infrastructure src/openhuman/agent/multimodal.rs |
StreamExt imported and REF_FETCH_CONCURRENCY constant (4) defined to enable and configure bounded concurrent attachment normalization. |
Bounded-concurrency attachment resolution src/openhuman/agent/multimodal.rs |
Image and file reference resolution refactored from sequential await loops to futures::stream::iter(...).buffered(REF_FETCH_CONCURRENCY) pipelines; rustdoc updated to describe ordering and error propagation semantics. |
Order preservation regression test src/openhuman/agent/multimodal_tests.rs |
New prepare_messages_preserves_image_order_under_concurrent_fetch test constructs five PNGs, embeds them as [IMAGE:...] markers, runs preparation with concurrent normalization, and asserts normalized data-URI refs retain original order. |
Estimated code review effort
🎯 3 (Moderate) | ⏱️ ~20 minutes
Poem
🐰 Concurrency hops with bounded grace, Four tasks dance in their rightful place, Order preserved through the async race, Little bytes march on, each in place, A rabbit cheers for tidy pace!
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
| Check name | Status | Explanation |
|---|---|---|
| Description Check | ✅ Passed | Check skipped - CodeRabbit’s high-level summary is enabled. |
| Title check | ✅ Passed | The pull request title 'perf(multimodal): bound-concurrent attachment reference normalization' directly and accurately describes the main change: introducing bounded-concurrent (limit of 4) resolution of attachment references instead of serial awaiting. |
| Docstring Coverage | ✅ Passed | Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. |
| Linked Issues check | ✅ Passed | Check skipped because no linked issues were found for this pull request. |
| Out of Scope Changes check | ✅ Passed | Check skipped because no linked issues were found for this pull request. |
✏️ 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 @coderabbitai help to get the list of available commands and usage tips.
We're shipping a image analyzer agent so this will be redudnat. but thanks for the PR. super appreciates.