Skip to content

improve: reuse validated attachment read handles - #139168

Merged
steipete merged 1 commit into
mainfrom
codex/perf10-attachment-cache
Sep 5, 2026
Merged

steipete merged 1 commit into
mainfrom
codex/perf10-attachment-cache

Conversation

@steipete

@steipete steipete commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Reading a cold local media attachment opened and closed the same file twice: once to validate its path and metadata, then again to obtain the bytes needed by the provider.

Why This Change Was Made

The attachment cache now transfers the already validated descriptor to its bounded reader, which closes it in finally. Path-only consumers close it immediately; a later request for bytes still reopens a previously cached path safely. The separate cold-validation and cached-read error mappings are preserved so URL and media-store fallback behavior stays unchanged.

User Impact

A cold local attachment needs one open/close cycle instead of two. Local-root checks, file identity/symlink checks, actual-read byte limits, MIME classification, and temporary staging cleanup remain in place. Production is 18 lines smaller; tests add 21 net lines.

Evidence

  • Eighteen synthetic real-filesystem scenarios matched baseline results and consumed-byte totals, including root escape, symlink/directory/missing input, file growth, read/open failures, cached paths, alias recovery, and byte-limit enforcement.
  • Across 600 cold reads, opens and closes fell from 1,200 each to 600 each. Median time per 200 reads was 98.927 → 60.566 ms on this Mac; this is a filesystem microbenchmark, not Gateway/provider latency proof.
  • Three descriptor-lifetime cases failed against original production code and passed after the change. Focused validation passed 83 tests across five files; five Windows-only cases were skipped on macOS.
  • The installed @openclaw/fs-safe 0.8.1 contract was inspected directly: safe open validates descriptor/path identity, and bounded read consumes at most maxBytes + 1 without closing the caller-owned handle. Formatting/diff checks and managed P0–P2 review passed. Native Windows and current-head hosted CI are not asserted by this local packet.

Latest review disposition

Both pre-merge dependency-verification requests (P1/P2) and the identical Rank-up move in the latest review are complete. Independent maintainer-side inspection of the installed, pinned @openclaw/fs-safe 0.8.1 implementation confirmed the required ownership contract:

  • dist/root-impl.js:80–186 (openVerifiedLocalFile) validates the regular file, opened descriptor identity, current path identity, and resolved canonical path identity. Failed validation closes the handle; success transfers a still-open handle. openLocalFileSafely at lines 455–457 returns that verified result.
  • dist/bounded-read.js:39–46 (readFileHandleBounded) reads from the current offset, consumes at most maxBytes + 1, and leaves closure to its caller. The cache closes transferred or freshly reopened handles in finally, closes failed preparation, and closes path-only handles immediately.
  • Source identity (SHA-256): root-impl.js = 1d2dd3ba081d5fea1f7b73250c6c29ad591bbc4e8fac88fb1ed5ab7a4985e619; bounded-read.js = 73e939b611bb80f839ee49730119ee163e7884cb17b85e8d5eb4048ca08ece80.

The existing 18 real-filesystem scenarios have identical before/after outcomes and consumed-byte totals, with every acquired descriptor closed. Focused validation passed 83 tests; five Windows-only cases remain unexecuted on macOS. Hosted CI passed on exact head 9de04ff5d6ab6912fb6ddecee12014a61b73f23c. This supplies the dependency evidence unavailable to the automated reviewer; it requires no source change or relaxation of the safety contract.

@clawsweeper

clawsweeper Bot commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added size: M maintainer Maintainer-authored PR labels Sep 5, 2026
@steipete
steipete marked this pull request as ready for review September 5, 2026 15:12
@clawsweeper clawsweeper Bot added P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. 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 Sep 5, 2026
@clawsweeper

clawsweeper Bot commented Sep 5, 2026

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 5, 2026, 12:41 PM ET / 16:41 UTC.

ClawSweeper review

What this changes

Reuse the validated file handle when reading local attachments, close it at the consuming boundary, and extend tests for successful, growing, and failed reads.

Merge readiness

⛔ Blocked before merge - 2 items remain

Keep open: this remains a useful optimization absent from current main and the latest release. No introduced correctness defect was found; independent dependency-contract verification remains incomplete.

Priority: P3
Reviewed head: 9de04ff5d6ab6912fb6ddecee12014a61b73f23c

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused, net-negative refactor with relevant lifecycle coverage and no concrete blocking finding.
Proof confidence 🌊 off-meta tidepool Not applicable: The supplied repository state identifies a maintainer-authored internal refactor, exempt from ordinary contributor proof requirements. Reported Mac filesystem scenarios exercise the relevant cache behavior without claiming Gateway or provider latency gains.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The supplied repository state identifies a maintainer-authored internal refactor, exempt from ordinary contributor proof requirements. Reported Mac filesystem scenarios exercise the relevant cache behavior without claiming Gateway or provider latency gains.
Evidence reviewed 10 items Introduced scope and merge identity: The complete introduced delta affects only the attachment cache and its test. The inspected test-merge commit records the pinned base followed by the exact PR head, and its cache diff preserves the same proposed change.
Handle ownership and fallback preservation: Read the complete cache module. Preparation closes failed validations; buffer reads close transferred or reopened handles in finally; both path-only branches close newly prepared handles. Cold-validation error mapping remains outside the cached-read catch, preserving existing recovery distinctions.
Focused regression coverage: The extended real-filesystem test checks one open, matching closes, exact consumed bytes, and preserved read errors across unchanged, growing, and read-failure cases. Existing tests also cover URL fallback, store aliases, canonicalization rejection, Windows file URLs, and staging cleanup. Tests were inspected, not executed.
Findings None None.
Security None None.

How this fits together

The attachment cache supplies media bytes to understanding providers and file paths to command-line tools. It checks local access and size limits, supports remote fallback, and owns temporary-file cleanup.

flowchart TD
  A[Attachment reference] --> B[Attachment cache]
  B --> C[Validate local file and roots]
  C --> D[Bounded read using validated handle]
  C --> E[Path-only consumer]
  C -->|Unavailable local source| F[Store alias or remote fallback]
  D --> G[Close handle and classify bytes]
  G --> H[Media provider]
  F --> H
Loading

Before merge

  • Resolve merge risk (P1) - The descriptor-identity and caller-owned bounded-read contracts of @openclaw/fs-safe 0.8.1 remain independently unverified because dependency source was unavailable to this reviewer.
  • Complete next step (P2) - Have a reviewer inspect @openclaw/fs-safe 0.8.1 descriptor validation and caller-owned bounded-read semantics before merge.
Agent review details

Security

None.

PR surface

Source -18, Tests +21. Total +3 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 63 81 -18
Tests 1 62 41 +21
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 125 122 +3

Review metrics

Metric Value Why it matters
Production versus test LOC Production −18; tests +21 net lines The refactor removes the separate reader method while expanding the existing lifecycle regression without production growth.
Cold-read descriptor cycles 2 → 1 open/close cycles Source and focused assertions directly target the redundant filesystem operation.

Merge-risk options

Maintainer options:

  1. Decide the mitigation before merge
    Keep handle ownership within each cache operation, preserving root checks, bounded reads, fallback semantics, and immediate closure for path-only consumers.
  2. Pause or close
    Do not merge this PR until maintainers decide whether the risk is worth taking.

Technical review

Best possible solution:

Keep handle ownership within each cache operation, preserving root checks, bounded reads, fallback semantics, and immediate closure for path-only consumers.

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

Not applicable to a functional bug: current-main source directly establishes the redundant cold-file open. This read-only review did not execute tests or benchmarks.

Is this the best way to solve the issue?

Unclear overall until dependency verification is complete; the cache-local refactor otherwise fits the ownership boundary better than a new reader API or a long-lived descriptor cache.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add P3: This is a bounded internal performance cleanup with no demonstrated broken user workflow.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: The supplied repository state identifies a maintainer-authored internal refactor, exempt from ordinary contributor proof requirements. Reported Mac filesystem scenarios exercise the relevant cache behavior without claiming Gateway or provider latency gains.

Label justifications:

  • P3: This is a bounded internal performance cleanup with no demonstrated broken user workflow.
  • 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 supplied repository state identifies a maintainer-authored internal refactor, exempt from ordinary contributor proof requirements. Reported Mac filesystem scenarios exercise the relevant cache behavior without claiming Gateway or provider latency gains.

Evidence

What I checked:

  • Introduced scope and merge identity: The complete introduced delta affects only the attachment cache and its test. The inspected test-merge commit records the pinned base followed by the exact PR head, and its cache diff preserves the same proposed change. (src/media-understanding/attachments.cache.ts:261, 0101ce7be182)
  • Handle ownership and fallback preservation: Read the complete cache module. Preparation closes failed validations; buffer reads close transferred or reopened handles in finally; both path-only branches close newly prepared handles. Cold-validation error mapping remains outside the cached-read catch, preserving existing recovery distinctions. (src/media-understanding/attachments.cache.ts:261, 9de04ff5d6ab)
  • Focused regression coverage: The extended real-filesystem test checks one open, matching closes, exact consumed bytes, and preserved read errors across unchanged, growing, and read-failure cases. Existing tests also cover URL fallback, store aliases, canonicalization rejection, Windows file URLs, and staging cleanup. Tests were inspected, not executed. (src/media-understanding/attachments.cache.test.ts:99, 9de04ff5d6ab)
  • Callers and sibling implementation: Provider execution consumes getBuffer, CLI execution consumes getPath, and the enclosing media pipeline performs cleanup. The separate local-media reader already uses the same safe-open, root-check, bounded-read, finally-close pattern; its distinct inbound-root and hardlink policy makes replacing the cache with that reader inappropriate. (src/media/local-media-access.ts:216, 9de04ff5d6ab)
  • Current-main necessity: Current main still validates and closes a cold file in ensureLocalStat, then opens it again in readLocalBuffer. Its cache source is unchanged from the pinned merge base. (src/media-understanding/attachments.cache.ts:266, ac4c669dc5ae)
  • Latest-release comparison: The supplied latest release, v2026.9.1, and fetched main both contain cache blob ad5a90cab2d273ee04fc8aff247f9ac641205468. Neither contains this handle-reuse optimization. (src/media-understanding/attachments.cache.ts:266, ad6fe23aecb9)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Ayaan Zaidi: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rank-up moves

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

  • Complete independent inspection of the pinned fs-safe safe-open and bounded-read contracts.

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.

@steipete
steipete merged commit 7c6253e into main Sep 5, 2026
253 checks passed
@steipete
steipete deleted the codex/perf10-attachment-cache branch September 5, 2026 16:56
@steipete

steipete commented Sep 5, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

vincentkoc added a commit to aniruddhaadak80/openclaw that referenced this pull request Sep 5, 2026
* commit '3e4becea5e2ce38ede69e8ecf5302805ecbfc09c':
  refactor: simplify outbound message execution context (openclaw#139107)
  fix(models): keep ordinary chat selections session-scoped (openclaw#139232)
  docs: slim root agent instructions and clarify testing scope (openclaw#139236)
  test(agents): give the sibling-drain completion wait a tolerance on slow runners (openclaw#139176)
  refactor(workboard): use canonical queries for card-tree writes (openclaw#139106)
  fix(canvas): recognize versioned macOS nodes (openclaw#138958)
  fix: load GitHub connections without a default agent (openclaw#139222)
  fix(memory): explain unsafe legacy host-event path recovery (openclaw#139195)
  refactor(talk): centralize typed voice session queries (openclaw#139103)
  fix(cli): preserve command dispatch and structured errors (openclaw#139067)
  refactor(agents): consolidate reply failure summaries (openclaw#139175)
  fix(auth): keep an unset default model unchanged during login (openclaw#139218)
  perf(media): reuse validated attachment read handles (openclaw#139168)
  refactor(channels): simplify account configuration updates (openclaw#139096)
  refactor(android): remove unused updater export root (openclaw#139198)
  fix(gateway): stop admitting post-ready producers during close (openclaw#139092)
  fix(gateway): expose agent hook completion outcomes (openclaw#139155)
  fix(config): return the saved configuration after plugin install commits (openclaw#139203)
  fix(android): reduce repeated retries to unreachable gateways (openclaw#138732)
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

maintainer Maintainer-authored PR P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. 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