Repository navigation
fix: first image turn spikes gateway memory and adds seconds of latency when the active model already declares image input - #159232
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs maintainer review before merge. Reviewed October 6, 2026, 6:48 AM ET / 10:48 UTC (Revision 10). ClawSweeper reviewWhat this changesThe media-understanding runner uses the active model’s explicitly configured image support to avoid loading the full model catalog, with regression coverage for precedence and fallback behavior. Merge readiness✅ Ready for maintainer review Keep open: current main still incurs the catalog load, and the merged companion optimization addresses a different cost. The prior provider-precedence finding is resolved; no blocking patch defect remains. Priority: P1 Review scores
Verification
How this fits togetherMedia understanding processes incoming attachments before the agent replies. It decides whether to describe an image separately or pass it directly to the active model. flowchart TD
A[Incoming image] --> B[Media understanding]
C[Active model configuration] --> B
B --> D{Explicit native image support}
D -->|Yes| E[Native image delivery]
D -->|Unknown| F[Model catalog lookup]
F --> E
F --> G[Separate image description]
Before mergeNone. Agent review detailsSecurityNone. PR surfaceSource +20, Tests +255. Total +275 across 2 files. View PR surface stats
Review metrics
Technical reviewBest possible solution: Use authored image capability when runtime resolution will honor it, retaining catalog fallback and existing explicit image-processing controls. Do we have a high-confidence way to reproduce the issue? Yes: current-main source still unconditionally reads the catalog when this native-vision check runs, and the contributor supplies fresh-process photo-turn traces. This review verified the path from source without executing it. Is this the best way to solve the issue? Yes: the shortcut reuses configured-model selection and aligns its affirmative answer with runtime image input, while preserving existing fallback and override paths. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 8dc04b001e10. LabelsLabel changes: No label changes. Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (9 earlier review cycles; latest 8 shown)
|
51b30fe to
7485ccd
Compare
|
@clawsweeper re-review Addressed the P1/P2 items ("run the new regression test in the repository toolchain and report its cost"). On the new head |
|
🦞👀 Re-review progress:
|
7485ccd to
aeffe78
Compare
32918d0 to
d9be501
Compare
d9be501 to
45c0e0a
Compare
45c0e0a to
78ce51b
Compare
…cy when the active model already declares image input activeModelSupportsNativeVision always loaded the full model catalog to decide native-vision support, even when the active model's own configured input already says "image". Answer from the configured row first, selected the way runtime model resolution selects it (exact provider key before the normalized fallback, then the literal model row), so the shortcut never disagrees with the attach check. metadataSource: "models-add" rows are excluded because runtime may prefer discovered input over them. Adds runner.native-vision-catalog-skip.test.ts covering the declared-image fast path, the unchanged catalog fallback (text-only config, no models.providers, models-add rows), disagreeing-catalog / MiniMax / two-image-model cases, and exact-vs-cased provider key precedence.
78ce51b to
8ce6fd8
Compare
|
Closing. Re-measured on current main from source (BASE Thanks to ClawSweeper for the provider-key precedence catch along the way. |
Closes #159231
What Problem This Solves
Fixes: the first turn carrying an image pays a full model-catalog load (a dedicated worker thread),
with the extra resident memory and latency that brings, even when the active model's own
configuration already declares that it accepts images. On a local Docker rig this was the first
photo turn for an agent in a fresh gateway process: +283.7 MiB peak RSS and 6603 ms
elapsedMsunpatched vs. +70.9 MiB and 1616 ms with this change (medians of 5, no in-process instrumentation;
rig numbers, not a real deployment — see Evidence for the staging-deployment numbers).
User Impact
Any deployment whose active model config already declares image support (the common case for a
native multimodal model) stops paying that first-image-turn memory/latency spike. Deployments that
rely on catalog-derived vision detection (no explicit
inputdeclared) see no change — that fallbackpath is untouched.
Why This Change Was Made
explicitImageModelVisionStatus(same file, used for explicit image-model overrides) alreadyanswers this from the configured model before ever loading the catalog.
activeModelSupportsNativeVision— the function actually consulted for the common case, a plainactive-model turn — never took that shortcut. This change gives it one, reading the configured row
the way runtime model resolution selects it:
the same order as
resolveConfiguredProviderConfig(
src/agents/embedded-agent-runner/model.configured-overrides.ts:201-208);findConfiguredProviderModel, the helper runtime uses for the sameselection (
src/config/model-provider-config.ts:14), accepted only when it is the literal rowfor the active model id (runtime gives the literal row precedence,
:79).If that row declares
input: ["image"]and is not markedmetadataSource: "models-add", returntrueimmediately; otherwise fall through to the existing catalog-based path unchanged. The difftouches only
activeModelSupportsNativeVision(plus one import); no shared helper changes.The shortcut answers the same question the attach check will. A
truehere makesrunCapabilityskip image understanding and hand the image to the primary model, so it must onlybe
truewhen the image will actually be attached.Why the shortcut can never cause the image to be dropped (attach-check trace, MiniMax and
tools.media.modelsinteractions)The attach check is
detectAndLoadPromptImages, which returns no images unless the runtime model'sparams.model.input?.includes("image")(src/agents/embedded-agent-runner/run/images.ts:252). Thatruntime
inputnormally comes from the same configured row the shortcut reads. For a model definedonly in
models.providers,buildInlineProviderModelsandcompleteInlineProviderModelset it fromthe row's
input(src/agents/embedded-agent-runner/model.inline-provider.ts:164-169and:196-201, throughresolveProviderModelInput, which takes a configured array over any fallback,:105). For a model that also has discovered or catalog metadata,applyConfiguredProviderOverridespasses the configured row'sinputfirst and the discoveredinputonly as the fallback (src/agents/embedded-agent-runner/model.configured-overrides.ts:503-508).So a row that declares
"image"yields a runtime model that declares"image", and the attach checkkeeps the image.
The exception is a row marked
metadataSource: "models-add"(the schema's "models added byCLI/catalog tooling" marker,
src/config/zod-schema.core.ts:301-302;openclaw doctoralso stampsit on legacy
openai-codexrows so official OpenAI Codex metadata can override it,src/commands/doctor/shared/legacy-config-core-normalizers.ts:338-346). When the resolver asks toprefer discovered metadata (
preferDiscoveredModelMetadata, set atsrc/agents/embedded-agent-runner/model.ts:271andmodel.registry-resolution.ts:284),applyConfiguredProviderOverridesdrops such a row as the metadata source(
model.configured-overrides.ts:452-455), so the discoveredinputwins and may lack"image". A shortcuttruethere could skip image understanding while the attach check then dropsthe image, losing it silently. The shortcut therefore never fires for a
models-addrow; those rowstake the unchanged catalog path. The sibling
explicitImageModelVisionStatusis left as it is.More shapes worth being explicit about:
CUSTOMandcustomconfigured and the activeprovider
custom, runtime resolves the exactcustomkey, so the shortcut reads that same row:if only
CUSTOMdeclares"image", the shortcut misses and the catalog answers (regression case"an exact provider key wins over a differently cased key"); if only
customdeclares it, theshortcut fires. A normalized-only lookup would have answered from
CUSTOMhere and skipped imageunderstanding for an image the attach check then drops.
row reached only through alias/canonical matching makes the shortcut miss (falling through to the
unchanged catalog path) — never a false positive, because a miss always defers to the exact same
catalog lookup that ran before this change.
(
isMinimaxVlmProvider(activeProvider) && !/^MiniMax-M3(\b|[-.])/i.test(model) => return false),not before it: a MiniMax provider whose active model isn't
MiniMax-M3(.x)still returnsfalseimmediately, with no catalog load and without ever reaching the configured-row lookup — even if
that model's own config row declares
input: ["image"](true for MiniMax M2.x rows).tools.media.models). When that array is set,runCapability's own skip branch is gated by!hasExplicitImageUnderstandingConfig(...), so thisfix's shortcut can never cause the native-vision skip-and-hand-natively path to fire in that case —
that guard is untouched by this diff.
Bound: one extra synchronous config lookup (provider key, then model row) per call — no new I/O,
no new catalog read, no change to any other branch's control flow.
This is additive, but not return-value-neutral in one case, deliberately: when the active model's
own config row (not marked
models-add) declaresinput: ["image"]but the model catalog is silentabout it or actively disagrees (an unlisted model, a stale/failed catalog fetch, or a catalog entry
that itself lists the same model as text-only), the function today answers
falseeven though theruntime model will declare
"image"and the attach check will keep the image (see the collapsedsection above). This fix answers
trueinstead, matching the in-file precedent:explicitImageModelVisionStatus(same file, immediately above this function) already gives theconfigured
inputarray priority over the catalog for the equivalent explicit-image-model decision.Every other outcome is unchanged.
Evidence
Rig: a local Docker container rig (not upstream CI), cgroup v1, memory capped at
-m 1g— therig numbers below are sandbox numbers, not measurements from a real deployment by themselves; a staging-deployment
measurement follows separately.
Call-path proof — a scratch copy of the built
dist/runner-*.jswith one additiveconsole.erroratthe top of
activeModelSupportsNativeVision, bind-mounted into a fresh container for one proof turn(
docker logs -tprefix removed):The worker is created 18 ms after the function is entered; the text-only warm-up turn on the same
container logged neither line. A stack captured at
Workerconstruction stops atWorkerTaskPool.start(async chain), so the caller attribution rests on this pair of lines.Clean A/B, 5 fresh containers unpatched vs. 5 fresh containers with this fix's shortcut applied as a
dist patch, each used once for a text warm-up and then one photo turn, no in-process instrumentation
(median of 5; gateway RSS sampled every 0.1 s for 150 s;
+Peakis the highest sample over eachrun's own pre-photo baseline RSS during the first image turn — after the turn, RSS stays at about
that level;
elapsedMsis the photo turn's own HTTP round-trip). The dist patch did not include themodels-addguard or the exact-provider-key selection; the rig's config has a single provider keyand its row carries no
metadataSource, so neither would have changed any of these runs:Smaller (3+3) call-path/frequency capture under a worker-tracing preload, and the control run with the shortcut deliberately missing
Separate, smaller (3+3) capture with the
trace-workers.cjspreload loaded (needed to observeWorkerconstruction directly), used only for call-path/frequency evidence, not for sizing — thatpreload alone inflates the photo-turn peak by about 115 MiB (isolated separately against this same
patched state: +70.9 MiB clean vs. +186.1 MiB with only the preload added), so its own elapsedMs and
RSS readings run higher than the clean table above. Raw lines behind that capture (verbatim;
docker logs -tprefix removed). Photo-turn HTTP results, unpatched containersrig-vpA1..rig-vpA3then patched containers
rig-vpB1..rig-vpB3:RestartCount=0and the original gateway pid alive at the end of every run in this capture. OpenClaw'sown memory watchdog on the two unpatched runs that crossed its critical threshold (no patched run
logged
level=critical):decoded_bytesidentical across every run confirms the image still reaches the model natively eitherway — this change affects only how the native-vision decision is made, not what the model
receives.
Control run with the patch applied and the active model's
inputhot-reloaded to["text"]only,so the shortcut must miss. Observed lines, in order: the reload, the worker's creation (the catalog
path ran), no primary-model native skip, a call to
openai/gpt-5.6-sol— an image model OpenClawresolved automatically; the rig config names no such model — answered
401(the rig had no OpenAIcredentials), and the worker's exit:
code=1withthreadId=-1is the exit code Node'sworker.terminate()produces, which is howWorkerTaskPoolretires a worker; it is not by itself a sign of an error. The fallback model callstarted 2 ms before that exit, so the probe had already returned. This run shows only that the
shortcut misses when
inputlacks"image"and the catalog path still runs; it does not exercise thecase where config declares
"image"and the catalog disagrees.Same fix, measured on a real staging deployment (a test environment running the same image, not the rig) (real Telegram photo delivered through the
deployment's own channel-inbound turn path, not the rig above; Azure VM host, cgroup v2, container
memory limit 1200 MiB; OpenClaw 2026.9.2 with this fix and a companion lazy-provider-registry fix (#159234, since merged to main)
both applied as build-time patches; uninstrumented — VmRSS and
/proc/<pid>/taskof the realopenclaw-gatewayprocess sampled at 1 Hz): first photo (960×1280 JPEG, 143,737 bytes) on a freshgateway process — baseline 436.5 MiB, peak +58.2 MiB, settled at 120 s +54.3 MiB, gateway thread
count 11 → 11 (no catalog worker started); a second assistant on the same host sent two photos on one
gateway process, thread count stayed 11 throughout. The same host's own pre-fix measurement (earlier
deployment, OpenClaw 2026.9.2 with neither this fix nor the companion fix, same photo shape
~960×1280, ~145 KB): gateway RSS went 425.7 → 718.3 MiB (+292.6 MiB) on one photo; on a heavier
assistant the same photo pushed the gateway over that deployment's 1200 MiB container memory limit
and the kernel OOM-killed it (
oom-kill: constraint=CONSTRAINT_MEMCG ... task=openclaw-gatewa ... Killed process ... (openclaw-gatewa) anon-rss:1187204kB). These staging-deployment numbers are thecombined effect of both fixes together, stated plainly as such; the per-fix split (this fix alone
vs. both together) comes from the rig A/B above, where this fix alone already accounts for almost all
of the saving.
Repository regression test, run in upstream CI on the current head
8ce6fd85(repo toolchain,Node 24.19.0, vitest 5.0.1):
runner.native-vision-catalog-skip.test.tspassed 10/10 inchecks-node-changed-3.
Verbatim, with the shard prefix removed:
Provider-key precedence (the ClawSweeper P1 raised on
aeffe782/32918d0f/d9be501b) is fixedin this head. The two "exact provider key" cases above are the requested
CUSTOM-before-customregression and its mirror. Against the previous shortcut, those two cases and the "second declared
image model" case fail and the other seven pass (
Tests 3 failed | 7 passed (10), local run).Locally on this head,
runner.native-vision-catalog-skip.test.tsplus the siblingrunner.vision-skip.test.tspass 22/22,pnpm tsgo:corereports no errors, and the mock-exportratchet,
oxfmt --check,oxlint, andgit diff --checkare clean.Rebase onto current
main. The branch was rebased frommain@32dcd029ontomain@a81b9cd7. This picked up twomainchanges that this PR adapts to:resolveConfiguredImageModelwithresolveConfiguredImageModelId. This PR nolonger touches that helper; see "Why This Change Was Made".
// mock-isolation:annotations.
CI status of the current head: all checks pass, including
openclaw/ci-gate(60 passed, therest skipped as not applicable).