Skip to content

fix(chat): count split Unicode bytes exactly - #5845

Merged
lidge-jun merged 3 commits into
devfrom
fix/chat-collector-byte-accounting
Sep 25, 2026
Merged

lidge-jun merged 3 commits into
devfrom
fix/chat-collector-byte-accounting

Conversation

@Ingwannu

@Ingwannu Ingwannu commented Sep 25, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • replace the fixed split-surrogate byte adjustment in the buffered Chat collector with a runtime-measured differential
  • keep incremental accounting equal to full-string UTF-8 sizing on Bun versions that price isolated surrogates differently
  • preserve constant-time append accounting without re-encoding the retained prefix
  • apply the corrected accounting to content, reasoning, and refusal collectors through their shared helper
  • document the Unicode accounting decision in ADR-0112

Verification

  • split-surrogate collector success/failure regression: 1 passed, 0 failed, 4 assertions on Bun 1.3.14
  • success retained exactly 12 bytes across three completed emoji fields; failure released to 0 bytes
  • structure SSOT gate: passed
  • privacy scan: passed
  • checks ran one at a time with CPUQuota at 75% or lower, MemoryMax at 1536 MiB or lower, no swap, low I/O weight, and bounded task counts
  • full local suite and build were intentionally not run under the conservative host ceiling; exact-head Bun 1.4 CI remains required

Compatibility

  • complete BMP text and already-joined Unicode retain their existing byte accounting
  • the change performs three tiny byte-length measurements only at a genuine split surrogate boundary
  • no wire shape, output content, or error contract changes
  • no Go counterpart was identified for this TypeScript Chat collector path; reviewer confirmation is requested before merge

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.

Summary by CodeRabbit

  • Bug Fixes
    • Improved UTF-8 byte accounting when streamed text splits a Unicode character across chunks, helping ensure content is retained and budgeted accurately across runtimes.
  • Documentation
    • Clarified how split-character byte accounting works for streamed chat responses.

@Ingwannu
Ingwannu requested a review from lidge-jun as a code owner September 25, 2026 10:44
@Ingwannu

Copy link
Copy Markdown
Owner Author

@lidge-jun @Wibias Please review the runtime-independent split-surrogate byte differential. This fixes Bun 1.3 undercount while preserving Bun 1.4 exact accounting. @codex review

@coderabbitai

coderabbitai Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository: lidge-jun/opencodex/.coderabbit.yaml

Review profile: ASSERTIVE

Plan: Advanced

Run ID: fb5527b6-7777-42c0-b7a6-5ea4330910ab

📥 Commits

Reviewing files that changed from the base of the PR and between 7acec81 and 6243e37.

📒 Files selected for processing (3)
  • structure/INDEX.md
  • structure/manifest.json
  • structure/transports/byte-accounting.md

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


📝 Walkthrough

Walkthrough

The Chat collector now calculates the UTF-8 byte adjustment for a surrogate pair split across streamed fragments from the runtime-measured sizes of the joined pair and isolated code units. The test and documentation describe this accounting rule.

Changes

Chat collector UTF-8 accounting

Layer / File(s) Summary
Measured split-surrogate adjustment
src/chat/outbound.ts, tests/responses/chat-completions-endpoint.test.ts, structure/decisions/ADR-0112-chat-collector-unicode-accounting.md, structure/transports/byte-accounting.md, structure/INDEX.md, structure/manifest.json
appendedUtf8Bytes replaces the fixed two-byte correction with a measured size difference when streamed fragments join a surrogate pair. The test budgets for three complete emoji scalars. The ADR and transport documentation describe the accounting rule; the source-to-document map and manifest include the transport documentation.

Priority: ⬇️ Low

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Bug fix

Merge Risk: ⚪ Minimal · up to 6243e

The buffered Chat fields measure the split-pair byte cost and release retained charges after an upstream failure. No concrete user-impacting regression is evident.

Architecture Summary

Architecture risk: 🔵 Low · up to 7acec

The change affects 3 systems.

Changed systems: src, structure, tests

Architecture concerns
No architecture-level concerns identified.

Review details

Systems and components

  • observed — src (service) was modified; 1 changed file maps to changed impact.
  • observed — structure (service) was modified; 2 changed files map to changed impact.
  • observed — tests (service) was modified; 1 changed file maps to changed impact.

Before / after behavior

  • observed — Modified behavior in src/chat/outbound.ts: appendedUtf8Bytes replaces the fixed two-byte correction for a split surrogate pair with a measured join delta: the encoded size of the joined pair minus the encoded sizes of each isolated surrogate.
  • observed — Modified behavior in structure/decisions/ADR-0112-chat-collector-unicode-accounting.md: Adds an ADR recording the split-surrogate accounting decision, its contract link, alternatives, and stated constraints: use runtime-measured byte lengths rather than a fixed two-byte subtraction or re-encoding the prefix; perform the adjustment only when a streamed boundary joins a surrogate pair.
  • observed — Modified behavior in structure/transports/byte-accounting.md: Documents the buffered Chat collector’s runtime-measured accounting for split surrogate pairs across retained content, reasoning, and refusal fields, and adds a link to ADR-0112.
  • observed — Modified behavior in tests/responses/chat-completions-endpoint.test.ts: The test replaces the fixed 12-byte budget expectation with 3 * Buffer.byteLength("😀") and adds comments describing the completed-scalar sizing case.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 1 functions across 2 files. (3 skipped: 3 … 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: exact byte accounting for split Unicode surrogate pairs in the Chat collector.
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.
Full details: Docstring Coverage

Explanation

Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 1 functions across 2 files. (3 skipped: 3 unsupported.)

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
🛠️ Fix failing CI checks 💡
  • Commit to this branch
  • Create a new PR

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 github-actions Bot added the intake: hygiene-blocked Deterministic PR hygiene checks failed label Sep 25, 2026
@github-actions

Copy link
Copy Markdown
Contributor

⚠️ Deterministic hygiene checks failed.

  • missing_regression_test — Behavior changed under src/ or gui/src/ without a test change. Add focused coverage or obtain test-exception-approved.

@github-actions github-actions Bot added the bug Something isn't working label Sep 25, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 25, 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-25T10:47:07.680370Z 62c3464 Manual request
ℹ️ 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 25, 2026 •

Copy link
Copy Markdown
Contributor

✅ READY

  • all PR quality gates passed.

Hygiene

✅ Deterministic PR hygiene checks passed.

@github-actions
github-actions Bot marked this pull request as draft September 25, 2026 10:44
@github-actions github-actions Bot removed the intake: hygiene-blocked Deterministic PR hygiene checks failed label Sep 25, 2026
@github-actions
github-actions Bot marked this pull request as ready for review September 25, 2026 10:45

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 62c3464fbc

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread structure/transports/byte-accounting.md Resolved
@lidge-jun

Copy link
Copy Markdown
Owner

리뷰 · 우선순위 47 / 80

채팅 답변이 조각으로 들어올 때, 이모지 하나가 두 조각으로 갈라지면 바이트를 실제 글자와 같게 세는 PR이에요.

모을 때마다 앞에서 모은 글자를 통째로 다시 재지 않아요. 새 조각 길이만 더해요. 앞 조각 끝이 이모지 앞쪽이고 새 조각이 뒤쪽이면, 예전에는 무조건 2바이트를 뺐어요. 그 2는 반쪽을 3바이트로 세는 런타임에서만 맞아요. 작성자가 Bun 1.3.14에서 확인했어요. 그 고정 값은 실제보다 적게 세요. 적게 세면 번역 예산이 그만큼 느슨해져요.

이제는 붙은 글자 하나와, 떨어진 반쪽 둘의 길이를 그 자리에서 재요. 그 차이를 더하면, 반쪽을 몇 바이트로 치든 다 모은 글자와 같아져요. 본문, 생각, 거절이 이 함수를 같이 써요. 도중에 실패하면 잡아 둔 바이트는 0으로 돌아와요.

테스트는 이모지 세 칸이 그 런타임의 완성 글자 크기 세 배인지 봐요. 기준 브랜치는 dev예요. 같은 수정으로 열린 다른 PR은 없어요. Go로 된 같은 함수는 검색에서 안 나왔어요.

src/claude/outbound.ts:117 - 갈라진 이모지에서 아직 무조건 2를 빼요. 이 PR은 이 줄을 안 고쳐요.
src/adapters/kiro/stream.ts:92 - 같은 2바이트 빼기가 그대로예요.
src/adapters/openai-responses/passthrough.ts:191 - 주석이 반쪽을 3바이트라고 정해 두고, 붙으면 2를 빼요.

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

채팅만 고치고 위 세 파일은 나중으로 둘지 정해 주세요. 세 파일도 번역 예산을 같은 방식으로 적게 세요. 작성자가 물은 Go 코드는 이 저장소에서 찾지 못했어요. 없다고 보고 넘어가도 돼요.

CI의 test 2/4는 stall watchdog fails the turn like the bridge에서 JSON이 중간에 끊겨 실패했어요. 입력은 waiting이라 이번 이모지 계산을 타지 않아요. 한 번 더 돌려 보면 돼요.

너의 추천

채팅 계산은 맞아요. 합치기 전에 세 파일의 2 빼기를 채팅과 같은 측정으로 바꾸세요. 각 파일의 그 줄만 바꾸면 됩니다. 중복으로 닫을 PR은 없어요.

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

@lidge-jun
lidge-jun merged commit 76a52cb into dev Sep 25, 2026
33 of 35 checks passed
@lidge-jun
lidge-jun deleted the fix/chat-collector-byte-accounting branch September 25, 2026 16:28
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants