Skip to content

refactor(anthropic): isolate the image normalize codec and cache (split S03 L1/3) - #3567

Closed
lidge-jun wants to merge 2 commits into
devfrom
codex/split-adapters-anthropic-image-normalize
Closed

refactor(anthropic): isolate the image normalize codec and cache (split S03 L1/3)#3567
lidge-jun wants to merge 2 commits into
devfrom
codex/split-adapters-anthropic-image-normalize

Conversation

@lidge-jun

@lidge-jun lidge-jun commented Sep 5, 2026

Copy link
Copy Markdown
Owner

Summary

  • Pure move: the Anthropic image codec — tier ladder, size/pixel caps, the module-level normalize cache with its accounting counters and test/memory-budget hooks, the Bun encode/validate functions, and processAt (src/adapters/anthropic-image-normalize.ts:25–66, 71–261, 282–347) — moves verbatim to src/adapters/anthropic-image-codec.ts (304 lines). anthropic-image-normalize.ts keeps the message walker and target normalizer (228 lines) and re-exports all 13 moved public names, so every existing import path (10 consumers) keeps working. The mutable cache state now has exactly one owner.
  • Why: 518-line file over the 400-line module limit; codec/cache and message-walking are separate concerns. Zero behavior change — the cache, its eviction, the encoder counter and the synchronous budget callback timing are untouched.
  • Plan and evidence: devlog/_plan/260905_now_split_train/080_adapters_anthropic_image_normalize.md; rules 003_parent_decisions.md (PURE-MOVE-SIZE-01).

Stack (S03 adapters-anthropic; merge bottom-up):

# PR Branch Base Review focus
3 TBD codex/split-adapters-anthropic-b codex/split-adapters-anthropic-a anthropic.ts (b)
2 TBD codex/split-adapters-anthropic-a codex/split-adapters-anthropic-image-normalize anthropic.ts (a)
1 this PR codex/split-adapters-anthropic-image-normalize ← you are here dev image codec + cache ownership

Base: dev. Review this PR's diff only (3 files, +327/−298; non-move diff: 2 codec imports, 8 wiring lines, 6 export modifiers, 15 test lines). Move-aware view: git diff --color-moved=dimmed-zebra dev...HEAD.

Verification

  • bun run typecheck → exit 0
  • Focused: anthropic-image-normalize, anthropic-image-retry, anthropic-image-retry-e2e, kiro-images, claude-native-passthrough, app-owned-memory → 80 pass / 0 fail
  • Red-drives, then restored: cacheGet forced to miss fails the cache-hit assertion (anthropic-image-normalize.test.ts:213); skipping sentinel accounting in cachePut fails :91.
  • bun run privacy:scan → passed
  • rg for original-path importers: 10 (unchanged); residual declares no cache state.
  • New test: reset/stats hooks are the same function objects via both paths; residual source has no top-level cache Map or encode counter.
  • Full suite on the remote CI host (lidge) at this exact SHA: recorded in the devlog doc.

Checklist

  • Scope stays focused and avoids unrelated cleanup.
  • Docs or release notes were updated when needed (devlog unit records the layer; no user-facing change).
  • Security-sensitive changes were reviewed for secrets, auth, and unsafe defaults (image bomb/size caps moved byte-for-byte; no policy change).

Summary by CodeRabbit

  • New Features

    • Added robust image normalization for Anthropic-compatible image inputs.
    • Supports automatic resizing and JPEG quality adjustment to meet format, dimension, and size limits.
    • Preserves compatible images when they pass validation.
    • Handles invalid or corrupted image data safely.
  • Bug Fixes

    • Improved repeated image processing through caching, helping reduce unnecessary encoding work and memory usage.

@lidge-jun
lidge-jun requested a review from Ingwannu as a code owner September 5, 2026 01:05
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 5, 2026

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review Completed 2026-09-05T01:08:48.296645Z c1d4367 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@github-actions

github-actions Bot commented Sep 5, 2026

Copy link
Copy Markdown
Contributor

Deterministic PR hygiene checks passed.

@github-actions github-actions Bot added the chore Maintenance, CI, tests, refactors, or build changes (not a user-facing bug or feature). label Sep 5, 2026
@coderabbitai

coderabbitai Bot commented Sep 5, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Team

Run ID: ba09ae85-6d3b-4c92-9479-058cc82a190f

📥 Commits

Reviewing files that changed from the base of the PR and between 4dde2db and c1d4367.

📒 Files selected for processing (3)
  • src/adapters/anthropic-image-codec.ts
  • src/adapters/anthropic-image-normalize.ts
  • tests/adapters/anthropic/anthropic-image-normalize.test.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 5 remain after this review.


📝 Walkthrough

Walkthrough

The PR extracts Anthropic image normalization into a codec module. The codec owns tier processing, validation, JPEG encoding, byte-weighted LRU caching, memory-budget hooks, and test seams. The normalize module re-exports the codec API, and tests verify shared state ownership.

Changes

Anthropic image normalization

Layer / File(s) Summary
Codec contracts and cache ownership
src/adapters/anthropic-image-codec.ts
Defines tier specifications, normalization types, cache limits, byte-weighted LRU operations, memory-budget integration, statistics, reset, and eviction hooks.
Image encoding and tier processing
src/adapters/anthropic-image-codec.ts
Adds Bun-based image validation and JPEG encoding. processAt walks the tier ladder, handles pass-through and encoded results, caches misses, and returns failures for invalid input or processing errors.
Normalize module integration and seam validation
src/adapters/anthropic-image-normalize.ts, tests/adapters/anthropic/anthropic-image-normalize.test.ts
Moves codec state out of the normalize module, re-exports the codec API, and verifies shared test-hook identity and codec-owned state.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Merge Risk: ⚪ Minimal · up to c1d43

The image normalization codec is extracted while existing normalize-module imports remain available and cache ownership is consolidated. No concrete current-head merge-blocking risk remains.

Sequence Diagram(s)

sequenceDiagram
  participant Caller
  participant processAt
  participant Cache
  participant BunImage
  Caller->>processAt: Submit base64 image and tier position
  processAt->>Cache: Read cached tier result
  processAt->>BunImage: Validate native payload or encode JPEG
  BunImage-->>processAt: Return validation result or encoded image
  processAt->>Cache: Store pass, encoded, or miss result
  processAt-->>Caller: Return normalization result
Loading
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 12 functions across 3 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: isolating the Anthropic image normalization codec and cache into a separate module.
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.
  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/split-adapters-anthropic-image-normalize

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@lidge-jun

Copy link
Copy Markdown
Owner Author

리뷰 · 우선순위 71 / 80

이 PR은 adapters-anthropic 스플릿 열차 S03의 맨 아래 칸(L1/3) 입니다. 지금 dev HEAD(4dde2db97, package 2.43.0)의 src/adapters/anthropic-image-normalize.ts518줄이라 모듈 400줄 한도를 넘습니다. 파일 안에는 (1) 티어 사다리·크기/픽셀 캡·모듈 단위 normalize 캐시와 회계 카운터·Bun encode/validate·processAt 같은 코덱/캐시와 (2) 메시지/타깃을 걸어 다니며 예산을 맞추는 워커(walker) 가 한곳에 있습니다. 이 변경은 코덱·캐시 블록을 src/adapters/anthropic-image-codec.ts(304줄)로 그대로 옮기고, 원래 파일은 walker(228줄)만 남긴 뒤 공개 이름 13개를 re-export해서 기존 import 경로(10곳)를 깨지 않습니다. 캐시 Map과 encode 카운터의 소유자는 코덱 파일 하나로 줄어듭니다. 행동 변경 없음이 목표이고, base가 dev 직접이라 아래층 스택(#3561#3565)과 무관하게 올릴 수 있는 칸입니다. 본문이 가리키는 계획(devlog/_plan/260905_now_split_train/080_adapters_anthropic_image_normalize.md, PURE-MOVE-SIZE-01)과도 맞습니다. 포커스 스위트 80 pass·red-drive·privacy:scan 주장이 있고, 새 테스트는 reset/stats 훅이 두 경로에서 같은 함수 객체인지와 residual에 캐시 Map/encodeCalls가 없는지 고정합니다. CI는 이 글을 쓰는 시점에 여러 잡이 pending이라 초록 확인 뒤 합치는 게 안전합니다.

src/adapters/anthropic-image-codec.ts - dev에서는 bunImageEncode/bunImageValidate/processAt가 모듈 내부였는데, 이동 후 export로 열렸습니다. residual과 시임 테스트가 쓰려면 필요하지만, 공개 표면이 넓어졌습니다. 의도된 시임이면 괜찮고, 아니면 테스트만 쓰는 이름을 좁히는 후속을 생각해 볼 수 있습니다.

src/adapters/anthropic-image-normalize.ts 30–32 - codec에서 가져오는 import가 세 줄로 갈라져 있고, IMAGE_NORMALIZE_CONCURRENCY·MAX_INPUT_*가 re-export 줄과 import 줄에 겹칩니다. 동작엔 문제 없고 정리 수준입니다.

src/adapters/anthropic-image-normalize.ts re-export - 기존 소비자(anthropic.ts, kiro-images.ts, 테스트)가 예전 경로를 유지하도록 한 장치가 분명합니다. 캐시 상태 이중 소유가 없다는 점이 이 층의 핵심입니다.

tests/adapters/anthropic/anthropic-image-normalize.test.ts - 훅 identity + residual에 top-level Map/encodeCalls 없음을 검사합니다. PURE-MOVE에서 회귀를 잡는 값이 있습니다.

경로 S03 L2/L3 (TBD) - 위층은 이 브랜치를 base로 쌓습니다. 이 칸이 먼저 초록이어야 기차가 앞으로 갑니다.

메인테이너의 판단이 필요한 지점

  • processAt/encode/validate를 계속 public export로 둘지 vs 테스트 전용으로 좁힐지
  • S03 위층(anthropic.ts a/b)과 머지 간격을 둘지, 이 칸만 바로 올릴지
  • CI pending이 길면 exact-head 호스트 스위트 기록만으로 머지할지

너의 추천
CI가 초록이면 그대로 dev에 머지해도 되는 순수 이동 층입니다. 단독 base=dev라 아래 oauth/claude 스택과 무관합니다. 랜딩 후 S03 L2를 이 브랜치 위에 이어 붙이면 됩니다. types/config 스플릿 무효화·close-don't-rebase 대상 아님.

이 댓글은 grok-bot이 작성했습니다

@Ingwannu Ingwannu left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved on exact head c1d436738c5fb012b666cc15e87e777a66e7648d. The codec/cache extraction preserves all facade bindings, keeps the mutable normalization cache under one module owner, and introduces no new dependency cycle. Independent isolated verification exercised the real Bun.Image path and cache/accounting seam at 25/25; exact-head cross-platform CI and CodeRabbit are green with no unresolved thread.

@lidge-jun

Copy link
Copy Markdown
Owner Author

Landed via #3668 at 6585e6a

@lidge-jun

Copy link
Copy Markdown
Owner Author

Superseded by aggregate PR #3668, admin-merged into dev as 6585e6a after exact-head CI and tested-tree verification. This original PR was not individually merged; its rebased content and historical records were consolidated in #3668. The original branch is preserved. Further unimplemented debt layers remain deferred.

@lidge-jun lidge-jun closed this Sep 5, 2026
@lidge-jun lidge-jun added the landed-via-maintainer Original PR closed after landing via a maintainer merge train label Sep 5, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

chore Maintenance, CI, tests, refactors, or build changes (not a user-facing bug or feature). landed-via-maintainer Original PR closed after landing via a maintainer merge train

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants