Skip to content

perf(adapters): avoid eager Unicode schema cloning - #4526

Draft
luvs01 wants to merge 1 commit into
lidge-jun:devfrom
luvs01:agent/unicode-schema-cow-20260913
Draft

perf(adapters): avoid eager Unicode schema cloning#4526
luvs01 wants to merge 1 commit into
lidge-jun:devfrom
luvs01:agent/unicode-schema-cow-20260913

Conversation

@luvs01

@luvs01 luvs01 commented Sep 13, 2026

Copy link
Copy Markdown
Contributor

Summary

Unicode pattern normalization eagerly cloned every visited container and queued a closure for each sibling even when returning the original input on a no-op. Traverse iteratively and copy only containers on paths where an unsupported scalar pattern is removed. Unchanged siblings retain identity, the input stays unchanged, and existing name-bag, literal-value, protected-subtree and encrypted-marker behavior is preserved.

This is an allocation optimization, not a hard memory bound or a uniformly faster implementation. In isolated synthetic 25,000-field processes, three repeated runs measured median peak RSS of about 69→54 MiB for no-op input and 90→62 MiB with one changed pattern. Median invocation time was about 17.2→13.0 ms for no-op input, but 15.1→19.3 ms for changed input. Peak RSS includes the runtime and input; these measurements do not establish production frequency or total application savings. Schema size still determines traversal and changed-container copying cost.

Verification

  • Two new regressions failed before the change because unaffected object and array siblings were cloned. They pass after the change and also verify input preservation and literal/name-bag handling.
  • bun test tests/adapters/openai/openai-chat-hardening.test.ts tests/responses/openai-responses-passthrough.test.ts: 290 pass, 0 fail, 200,888 assertions, including existing deep-schema and wire-contract cases.
  • bun run typecheck, bun run structure:check, bun run privacy:scan, and git diff --check: passed.
  • All eight mapped adapter structure owners reference the canonical allocation contract. Public schema semantics and configuration are unchanged; no user-facing documentation build was needed.
  • Full cross-platform CI is pending for this head. No whole-suite success is inferred from the focused checks.

Checklist

  • Scope stays focused and avoids unrelated cleanup.
  • Docs or release notes were updated when needed.
  • Security-sensitive changes were reviewed for secrets, auth, and unsafe defaults.

Review readiness checklist

  • All CI tests are green on my local testing.
  • I pushed my PR to the latest dev commit.
  • I resolved all correct Codex and CodeRabbit findings.
  • My PR is ready for review.

Co-authored-by: luvs01 27862058+luvs01@users.noreply.github.com

Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com>
@coderabbitai

coderabbitai Bot commented Sep 13, 2026

Copy link
Copy Markdown
Contributor

Important

Draft PR not reviewed

Draft PRs are not automatically reviewed by default.

  • Trigger a manual review

To automatically review draft PRs, update your CodeRabbit configuration:

reviews:
  auto_review:
    drafts: true

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.

@github-actions

Copy link
Copy Markdown
Contributor

Deterministic PR hygiene checks passed.

@github-actions github-actions Bot added the enhancement New feature or request label Sep 13, 2026
@github-actions

Copy link
Copy Markdown
Contributor

⏳ DRAFT

  • review readiness checklist open (0/4 boxes ticked).

What to do

  • Tick all four boxes in the PR description once you're done (currently 0/4).

Review readiness checklist

  • ⬜ All CI tests are green on my local testing.
  • ⬜ I pushed my PR to the latest dev commit.
  • ⬜ I resolved all correct Codex and CodeRabbit findings.
  • ⬜ My PR is ready for review.

0/4 boxes ticked.

This PR stays in draft until every box above is ticked.

@lidge-jun

Copy link
Copy Markdown
Owner

리뷰 · 우선순위 52 / 80

이 PR은 src/adapters/responses-tool-schema.ts 안의 stripUnicodePropertyPatterns를 고칩니다. 지금 dev(HEAD df7dc1be5, 2.54.0)에서는 이 함수가 스키마를 돌면서 방문하는 모든 객체·배열을 미리 복사하고, 형제마다 할당 클로저를 쌓습니다. 그래서 실제로 \p{…} / \P{…} 패턴을 하나도 안 지워도, 필드가 많은 툴 스키마면 출력 트리를 통째로 새로 만듭니다. openai-chat.tsopenai-responses.ts가 요청마다 이 경로를 타므로, 큰 Artifact/툴 스키마에서는 피크 RSS와 할당이 불필요하게 커집니다.

이번 변경은 동작을 바꾸지 않는 복사 시점 최적화입니다. 스택으로 활성 경로만 따라가고, 실제로 패턴을 지운 조상 컨테이너만 복사합니다(copy-on-write). 안 바뀐 형제 객체는 같은 참조를 유지하고, 아무 것도 안 지웠으면 입력 객체 그대로를 반환합니다. name bag(properties 등), const/enum 같은 리터럴, patternProperties/not/oneOf 같은 보존 서브트리, 그리고 별도인 stripResponsesOnlyEncryptedMarker 계약은 그대로입니다. 작성자가 밝힌 측정도 정직합니다. no-op 쪽은 RSS·시간이 줄지만, 패턴을 실제로 지우는 입력은 시간이 조금 늘 수 있다고 적어 두었습니다. 하드 힙 한도가 아니라 할당을 줄이는 최적화라는 점도 structure/transports/byte-accounting.md에 맞게 적혀 있습니다.

구조 문서 여덟 곳이 같은 한 줄을 가리키도록 갱신된 것은 이 저장소의 structure owner 매핑 규칙과 맞습니다. 회귀 테스트 두 개는 “넓은 스키마에서 안 바뀐 형제 정체성 유지”와 “배열 경로·리터럴 보존”을 직접 잠급니다. base는 지금 dev tip과 같고(df7dc1be5), mergeable입니다.

다만 이 PR은 아직 draft입니다. CodeRabbit도 draft라서 리뷰를 건너뛰었고, hygiene/label/enforce-target만 통과한 상태입니다. 작성자도 전체 크로스플랫폼 CI는 아직이라고 적었습니다. 라벨은 enhancement인데 내용은 perf라서, 준비되면 chore/perf 쪽에 가깝게 보이면 됩니다.

라인 - src/adapters/responses-tool-schema.ts stripUnicodePropertyPatterns - 예전 구현은 방문 컨테이너를 전부 eager clone했습니다. 새 구현은 삭제가 난 경로만 clone합니다. 의미는 같아 보이지만, draft 해제 전에 hosted CI(특히 openai-chat-hardening + openai-responses-passthrough)가 초록인지 한 번 더 확인하는 편이 안전합니다.
라인 - 같은 파일의 ownEntries - Object.entries 대신 for…in + hasOwnProperty입니다. 일반 스키마 객체에서는 보통 같지만, 열거 가능한 상속 키가 섞인 이상 입력에서는 예전과 미묘히 달라질 여지는 있습니다. 실무 스키마는 대개 plain object라 위험은 낮습니다.
라인 - 작성자 측정 문단 - changed-path median이 15.1→19.3 ms로 느려질 수 있다고 명시했습니다. no-op 핫패스가 주 목표면 괜찮지만, “항상 더 빠르다”로 홍보하면 안 됩니다.
경로/심볼 - PR draft 상태 - 머지 버튼 전에 Ready for review + 전체 CI가 필요합니다. 지금 tip hygiene만으로는 부족합니다.
경로/심볼 - structure/** 여덟 파일 동일 문장 - structure:check 통과용으로 보이며 내용은 맞습니다. 본문 중복이 거슬리면 나중에 한 owner로만 모아도 되지만, 이번 범위에서 막을 이유는 없습니다.

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

  • draft를 언제 ready로 올릴지, 전체 CI를 이 PR head에서 반드시 돌릴지
  • changed-path가 약간 느려지는 트레이드오프를 2.54 라인에 그대로 받을지
  • enhancement 라벨을 유지할지, perf/chore로 맞출지

너의 추천
draft를 유지한 채 전체 CI가 초록이 되면 Ready로 올리고 머지하세요. 의미 변경이 없고 dev tip 기준이라 충돌도 없습니다. 지금은 머지하지 마세요. CI와 draft 해제가 먼저입니다.

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

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

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants