Skip to content

fix(media): bound local reads and invalidate cleaned attachment paths - #130885

Merged
steipete merged 1 commit into
mainfrom
steipete/media-cache-bounded-reads
Aug 27, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/media-cache-bounded-reads

Conversation

@steipete

Copy link
Copy Markdown
Contributor

What Problem This Solves

Four violations of one invariant — local media file reads must respect the caller's byte limit, exactly as the remote branch already does — plus a cache lifecycle leak, all in src/media-understanding:

  1. Unbounded explicit-image local input: runtime.ts read local files through readLocalFileSafely with no maxBytes (installed @openclaw/fs-safe confirms omitted limits do a whole-file readFile), while the remote path used the cache with DEFAULT_MAX_BYTES.image. History (538605ff44d) shows a helper substitution, not an unlimited-input contract.
  2. TOCTOU allocation before rejection: attachments.cache.ts local reads checked the opened stat, then did a full handle.readFile(), then checked length — a growing file was fully loaded before rejection (measured: 4,164 bytes consumed with maxBytes 68).
  3. Wrong-direction default: getPath made maxBytes optional, defaulting to Infinity, and truthiness checks ignored a zero limit. The only production caller already supplies the resolved limit.
  4. Stale path after cleanup: cleanup() cleared cleanup responsibility but left tempPath, so a post-cleanup getPath returned a deleted file's path.

Why This Change Was Made

The attachment cache is the canonical local byte-read owner, so the fix consolidates rather than guards: the explicit-image local branch and its separate MIME read path in runtime.ts are deleted and routed through the same cache policy as the remote API (the explicit-file selected-directory allowance is preserved via localPathRoots; history 9f2b760d336/5d1f7bf0589 confirms that policy is intentional). Cache local reads keep opened-handle + canonical-root checks and now use the existing readFileHandleBounded helper (consumes at most maxBytes + 1 bytes). getPath.maxBytes is required and zero-enforced. The cleanup callback invalidates its own tempPath only (guarded so retained callbacks cannot invalidate a later restaged file, preserving the failed-staging retry chain from fd3a919063b).

User Impact

An oversized or concurrently-growing local attachment can no longer be fully loaded into memory before rejection, the local and remote image-description APIs now enforce the same byte limit, and a cleaned-up attachment can no longer hand a deleted temp path to a provider CLI.

Evidence

  • Regressions fail pre-fix (production files replayed at exact base): 6 failed — growth read 4,164 bytes with limit 68; zero limits accepted nonempty paths; both cleanup routes returned deleted paths; oversized local image accepted. Post-fix focused run: 40 passed.
  • Full suite src/media-understanding: 527 passed, 5 platform skips, re-run green on rebased head 4bd4cd8c303. An obsolete readFile-only mock test ("enforces maxBytes after reading local attachments", history 566fb73d9da) was replaced by a real-file growth test measuring actual bytes consumed at the filesystem boundary.
  • Production LOC −21 (+14/−35); tests +131. Remote fetch limits, retry policy, SSRF behavior, provider selection, SDK exports/types, and persistence unchanged; sibling bounded-read call sites (apply.ts, agent-turn-attachments.ts, provider entries) verified already compliant.
  • Targeted test typecheck (includes the required getPath.maxBytes type assertion), oxlint, oxfmt, git diff --check, and the eight post-typecheck repo guards (schema-version, database-first, media-download helper, sidecar loaders, import cycles, webhook body order, pairing guards) all pass. check-changed's aggregate lane stops at a pre-existing UI e2e type error on main (ui/src/e2e/sidebar-interactions.e2e.test.ts:45, TS2339 from 9b4d4d08cf7, reproduced at exact base with media files unchanged) — separate follow-up.
  • Fresh Codex autoreview of the final diff: clean, no actionable findings.
  • Named follow-ups (deliberately out of scope): transcript-output whole-file read in runner.entries.ts (output-resource policy, review-required); getPath does not claim to freeze externally mutable files for the consuming CLI (existing contract preserved).

@clawsweeper

clawsweeper Bot commented Aug 27, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@steipete
steipete marked this pull request as ready for review August 27, 2026 11:29
@openclaw-barnacle openclaw-barnacle Bot added size: M maintainer Maintainer-authored PR labels Aug 27, 2026
@steipete
steipete force-pushed the steipete/media-cache-bounded-reads branch from 4bd4cd8 to 341571e Compare August 27, 2026 11:34
@clawsweeper clawsweeper Bot added merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Aug 27, 2026
@clawsweeper

clawsweeper Bot commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 27, 2026, 8:09 AM ET / 12:09 UTC.

ClawSweeper review

What this changes

The PR routes explicit local image reads through the attachment cache, bounds cache file reads by the caller’s byte limit, requires that limit for path staging, and clears deleted temporary paths after cleanup.

Merge readiness

⚠️ Ready for maintainer review - 3 items remain

Keep this maintainer-authored PR open for merge review: current main still has the unbounded local-image path, while the proposed cache-owner repair is coherent and has no discrete correctness finding.

Priority: P2
Reviewed head: 341571e534d3303058dcd50fa7e0f63fd932931f
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The patch is a focused owner-boundary repair with relevant regressions and no actionable correctness finding.
Proof confidence 🌊 off-meta tidepool Not applicable: The PR is maintainer-authored, so the external-contributor real-behavior-proof gate does not apply; its body nevertheless records focused after-fix regression results.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The PR is maintainer-authored, so the external-contributor real-behavior-proof gate does not apply; its body nevertheless records focused after-fix regression results.
Evidence reviewed 6 items Current-main gap: Current main still makes maxBytes optional for staged attachment paths and substitutes an unlimited read when it is omitted.
Current-main explicit-image path: Current main reads a local explicit image through readLocalFileSafely without passing the documented image byte limit.
Cache-owner repair: The PR sends explicit image input through the attachment cache with DEFAULT_MAX_BYTES.image, and the cache uses the established bounded file-handle read before returning bytes.
Findings None None.
Security None None.

Live Verification

Command: node scripts/run-vitest.mjs src/media-understanding/runtime.local-input.test.ts

Result: PASS (completed)

[test] starting test/vitest/vitest.media-understanding.config.ts

 RUN  v4.1.11 /tmp/clawsweeper-live-proof-130885-HjgRcF/target

 ✓  media-understanding  src/media-understanding/runtime.local-input.test.ts (3 tests) 33ms

 Test Files  1 passed (1)
      Tests  3 passed (3)
   Start at  12:10:14
   Duration  9.07s (transform 7.17s, setup 52ms, import 8.67s, tests 33ms, environment 0ms)

[test] passed 1 Vitest shard in 14.83s

Assertions:

  • PASS expect_output: runtime.local-input.test.ts

How this fits together

Media-understanding converts local or remote attachments into bounded buffers or temporary paths for provider runtimes. The attachment cache owns local file safety and cleanup before image or CLI providers consume an attachment.

flowchart LR
  A[Local image reference] --> B[Image input preparation]
  B --> C[Attachment cache]
  C --> D{Within byte limit?}
  D -->|Yes| E[Buffer or temporary path]
  D -->|No| F[Size rejection]
  E --> G[Provider runtime]
Loading

Decision needed

Question Recommendation
Should explicit local image descriptions adopt the documented 10 MB input limit even when an existing caller previously relied on an unbounded read? Adopt the documented limit: Merge the cache-owner repair so explicit local image descriptions match the established 10 MB image input policy.

Why: The implementation is internally coherent, but accepting rejection of previously unlimited local files is an upgrade-policy choice for maintainers.

Before merge

  • Resolve merge risk (P1) - Existing explicit local-image calls above 10 MB will now reject rather than be read without a limit; this aligns with the documented image default but is an intentional compatibility change.
  • Complete next step (P2) - A maintainer must accept the compatibility consequence of enforcing the documented image limit on explicit local input before merge.
Agent review details

Security

None.

PR surface

Source -21, Tests +131. Total +110 across 6 files.

View PR surface stats
Area Files Added Removed Net
Source 2 14 35 -21
Tests 4 199 68 +131
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 6 213 103 +110

Review metrics

Metric Value Why it matters
Production versus test delta production −21, tests +131 The repair removes the duplicate unbounded image-read path while adding boundary regressions for growth, zero limits, cleanup, and explicit local input.

Merge-risk options

Maintainer options:

  1. Accept the documented image limit (recommended)
    Merge with the explicit acknowledgement that previously unlimited local images above 10 MB will now receive the normal size rejection.
  2. Pause for a different compatibility policy
    Keep the PR open if maintainers want explicit image descriptions to retain a distinct limit or migration path.

Technical review

Best possible solution:

Adopt the attachment cache as the single owner of local image reads and merge after maintainers accept the documented 10 MB limit for explicit local image input.

Do we have a high-confidence way to reproduce the issue?

Yes in source: current main’s explicit local-image path calls an unbounded reader, while current-main staged-path code falls back to Infinity when maxBytes is omitted. The PR adds focused regression coverage, though this read-only review did not execute it.

Is this the best way to solve the issue?

Yes. The attachment cache already owns local attachment resolution and the sibling local-media access path already uses the same bounded file-handle helper, so consolidating here avoids parallel safety policies.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against baa3c3e6846d.

Labels

Label justifications:

  • P2: This repairs bounded local media handling with limited operator blast radius.
  • merge-risk: 🚨 compatibility: Explicit local image descriptions that previously loaded files above the documented 10 MB default will now reject them.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: The PR is maintainer-authored, so the external-contributor real-behavior-proof gate does not apply; its body nevertheless records focused after-fix regression results.

Evidence

What I checked:

Likely related people:

  • steipete: The supplied PR and shallow current-history boundary both associate Peter Steinberger with the present media-cache implementation and repair; deeper pre-boundary provenance is unavailable locally. (role: recent area contributor; confidence: medium; commits: d18b0a966141, 341571e534d3; files: src/media-understanding/attachments.cache.ts, src/media-understanding/runtime.ts, src/media/local-media-access.ts)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Record the maintainer decision on the intentional 10 MB compatibility change before merge.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (1 earlier review cycle)
  • reviewed 2026-08-27T11:42:09.511Z sha 341571e :: needs maintainer review before merge. :: none

@steipete
steipete merged commit 9bd50c8 into main Aug 27, 2026
208 checks passed
@steipete
steipete deleted the steipete/media-cache-bounded-reads branch August 27, 2026 12:59
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

maintainer Maintainer-authored PR merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: M status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant