Skip to content

fix(responses): keep caller cancellations out of upstream failure logs (carry of #3515) - #3541

Merged
lidge-jun merged 4 commits into
devfrom
codex/260905-carry-3515
Sep 4, 2026
Merged

fix(responses): keep caller cancellations out of upstream failure logs (carry of #3515)#3541
lidge-jun merged 4 commits into
devfrom
codex/260905-carry-3515

Conversation

@lidge-jun

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

Copy link
Copy Markdown
Owner

Summary

When the caller aborts a native Responses request, the relay logged it as an upstream 502 and penalized the provider pool. This carry classifies caller aborts as 499 in src/server/relay.ts / src/server/responses/core.ts while a genuine upstream reset still logs 502. The original PR carries an APPROVED review from @Ingwannu on its exact head 4f09faf5d.

Supersedes #3515 (maintainer carry: GitHub reports the original CONFLICTING after the tests/<domain>/ migration, while git merge-tree is clean; the carry is the PR head merged with origin/dev, no source edits).

Stack (wp1 merge train, independent layers — each targets dev):

# PR Layer Review focus
1 this carry of #3515 this PR's diff only

Unit: devlog/_plan/260905_open_work_closeout/ (010, 011).

Verification

  • bun run typecheck — exit 0 on the carry head.
  • bun test tests/server/server-auth.test.ts — tests/server/server-auth.test.ts — 105 pass / 0 fail (paired 499/502 regressions).
  • Original PR CI on 3515's exact head was full-matrix green; exact-head CI on this branch is the merge gate.

Checklist

  • Targets dev
  • Focused regression test present and green
  • Original author credited via Co-authored-by trailer

Co-authored-by: VXNCXNX 93332837+VXNCXNX@users.noreply.github.com

Summary by CodeRabbit

  • Bug Fixes
    • Improved handling of cancelled streaming requests, ensuring client cancellations are recorded as status 499 with a client_cancel reason.
    • Prevented client cancellations from incorrectly counting as upstream failures or penalizing pooled accounts.
    • Preserved accurate reporting and account failure tracking when upstream streams terminate unexpectedly.
  • Documentation
    • Documented cancellation handling and outcomes for native HTTP/SSE passthrough responses.

@lidge-jun
lidge-jun requested a review from Ingwannu as a code owner September 4, 2026 22:39
@lidge-jun lidge-jun added the bug Something isn't working label Sep 4, 2026
@github-actions

github-actions Bot commented Sep 4, 2026

Copy link
Copy Markdown
Contributor

Deterministic PR hygiene checks passed.

@coderabbitai

coderabbitai Bot commented Sep 4, 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: 8a7dcfed-e40f-4316-8d81-0961a4bd4158

📥 Commits

Reviewing files that changed from the base of the PR and between 980a9fb and 696847c.

📒 Files selected for processing (4)
  • docs-site/src/content/docs/reference/proxy-formats.md
  • src/server/relay.ts
  • src/server/responses/core.ts
  • tests/server/server-auth.test.ts

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


📝 Walkthrough

Walkthrough

Native passthrough now detects request cancellation earlier, preserves upstream terminal outcomes during bounded draining, and distinguishes client cancellation from upstream failure. Tests and reference documentation cover the resulting status, logging, usage, and account-pool behavior.

Changes

Native passthrough outcome handling

Layer / File(s) Summary
Passthrough cancellation signal handling
src/server/responses/core.ts, src/server/relay.ts
The inspection consumer combines request abort and client disconnect signals. The relay re-checks client state after reads and before classifying read errors.
Passthrough outcome validation
tests/server/server-auth.test.ts, docs-site/src/content/docs/reference/proxy-formats.md
Tests verify 499 client_cancel without pool penalties and 502 terminal with a recorded stream failure. The reference documentation describes these outcomes.

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

Merge Risk: ⚪ Minimal · up to 69684

Native passthrough requests now record caller cancellations as 499 without penalizing provider accounts, while genuine upstream resets remain 502 failures. The paired regression coverage supports the intended distinction, with no remaining merge-readiness risk identified.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 2 functions across 3 files. (1 skipped: 1… 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 describes the main change: caller cancellations are excluded from upstream failure logs in Responses handling. The issue reference is relevant, although optional.
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 50.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 2 functions across 3 files. (1 skipped: 1 unsupported.)

  • 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/260905-carry-3515

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

리뷰 · 우선순위 74 / 80

이 PR은 호출자가 native Responses 스트리밍 요청을 중간에 끊었을 때, 그 끊김이 업스트림 실패(502)처럼 기록되고 계정 풀 페널티까지 먹는 버그를 고치는 유지자 캐리입니다. 원본은 #3515이고, 그 exact head 4f09faf5d@Ingwannu APPROVED가 이미 붙어 있습니다. GitHub는 원본을 CONFLICTING으로 보여 주지만(대개 tests/<domain>/ 레이아웃 이동 이후 경로 표시 문제), 본문대로 git merge-tree는 깨끗하고 이 브랜치는 origin/dev에 원본 헤드를 합친 뒤 소스 편집 없이 올린 캐리입니다. 현재 dev HEAD는 980a9fbed(#3537 Astra 설정·Fast 가격 정렬)인데, 이 변경은 src/server/relay.ts / src/server/responses/core.ts의 native HTTP/SSE tee 검사 경로만 건드리고 카탈로그·가격 표면과는 겹치지 않습니다.

왜 중요한지 한 줄로 말하면, 클라이언트가 탭을 닫거나 AbortController로 요청을 취소하는 일은 정상 동작인데, 그걸 업스트림 리셋과 같은 실패로 세면 풀 헬스(consecutiveFailures)가 가짜로 나빠지고 멀쩡한 계정이 밀려납니다. 고친 내용은 세 겹입니다. 첫째, responses/core.ts에서 검사 펌프에 넘기는 clientGoneSignalclientGone.signal만 쓰지 않고 options.abortSignalAbortSignal.any로 합칩니다. Bun에서는 응답 body cancel 훅보다 요청 abort가 fetch body read를 먼저 깨뜨릴 수 있어서, body cancel만 보면 호출자 취소를 놓칩니다. 둘째, relay.tsstartBoundedInspectionPump는 read가 끝난 직후와 catch 절에서 clientGoneSignal?.aborted를 다시 보고 markClientGone()을 호출합니다. abort 리스너가 아직 안 돌았을 때도 신호 자체로 분류하겠다는 뜻입니다. 셋째, 회귀 테스트 두 개가 짝으로 들어갑니다. 호출자 abort는 로그·usage가 status: 499, closeReason: "client_cancel"이고 풀 페널티가 0인지, 업스트림이 진짜로 끊기면 여전히 502streamAborted와 failure streak +1인지 각각 고정합니다. docs의 proxy-formats.md에도 같은 규칙을 한 단락으로 적어 두었습니다.

원본 PR CI는 exact head에서 풀 매트릭스가 초록이었고, 이 캐리 쪽은 작성 시점 기준 hygiene·react-doctor·storage policy·일부 npm-global/테스트 샤드가 이미 통과 중이며 나머지 매트릭스는 아직 pending입니다. enforce-target은 fail처럼 보이지만 실제로는 cancelled 잡이라 게이트 실패로 읽지 않는 편이 맞습니다. 캐리 커밋에 Co-authored-by: VXNCXNX가 들어가 있어 원저자 크레딧도 본문 체크리스트와 맞습니다. 점수 74는 “이미 APPROVED된 독립 버그픽스를 신선도 게이트 안으로 다시 올린 캐리”이고, 카탈로그 대공사나 타입 스플릿에 묶이지 않아 지금 dev에 바로 올릴 가치가 큽니다. 다만 캐리 헤드 자체 CI가 전부 끝나기 전에는 merge 버튼만 누르지 말고, 초록 확인 후 합치는 쪽이 안전합니다.

라인 - src/server/responses/core.ts (inspectionConsumerOptions) - tee 검사 경로에만 AbortSignal.any([clientGone.signal, options.abortSignal])를 붙였고, 위쪽 eager rewrite 경로는 이전처럼 body-side cancel만 본다. Ingwannu 리뷰도 “native HTTP tee inspection path only”라고 못 박았으니 의도는 맞지만, eager 경로에서 요청 abort만으로 같은 오분류가 나는지 한 번만 확인하면 좋다.
라인 - src/server/relay.ts (reader.read 직후 / catch) - clientGoneSignal?.aborted 재검사는 Bun race를 막는 핵심인데, markClientGone()이 이미 돌았으면 멱등인지(중복 카운터·이중 abort)는 기존 구현에 맡긴다. 새 버그는 안 보이지만 리뷰어가 한 번 훑을 지점이다.
경로/심볼 - tests/server/server-auth.test.ts 신규 두 케이스 - 호출자 abort는 response.body.cancel() 없이 caller.abort()만 해서 실제 레이스를 재현한다. 업스트림 리셋 케이스는 Promise.withResolvers로 컨트롤러를 잡은 뒤 error()로 끊는다. 짝 테스트라 한쪽만 있으면 회귀가 다시 열리니 둘 다 유지해야 한다.
경로/심볼 - #3515 - GitHub mergeable은 CONFLICTING이지만 캐리 본문은 merge-tree clean이라고 한다. 이 PR이 랜딩되면 원본은 Landed via #3541 at <commit> + landed-via-maintainer로 닫는 게 저장소 규칙이다, 열어 두면 open PR 수가 또 부풀다.

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

  • 캐리 헤드 Cross-platform CI가 전부 초록이 된 뒤에 바로 merge할지, 아니면 원본 #3515를 CONFLICTING 해소 후 재베이스할지(권장하지 않음 — 캐리가 이미 그 역할).
  • eager rewrite 경로에도 같은 AbortSignal.any를 넓힐지, 이번 스코프는 tee 경로만으로 끝낼지.
  • 랜딩 직후 #3515를 landed-via-maintainer로 즉시 닫을지(닫아야 함).

너의 추천
캐리 헤드 CI가 초록이면 #3541을 dev에 merge하고, 이어서 #3515에 Landed via #3541 at <sha> 코멘트·landed-via-maintainer 라벨을 붙인 뒤 completed/superseded로 닫아라. 소스 재편집이나 원본 재베이스는 하지 마라. eager 경로 확대는 별 이슈/후속 PR로 남겨도 된다.

이 댓글은 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.

Revalidated the carry at exact head 696847cd4f11d2657e4aceda4c30708fe1ab53b0. It preserves the already-reviewed cancellation boundary and paired regressions at the current test path: caller abort remains 499 client_cancel with no pool penalty, while a genuine upstream reset remains a 502 failure.

All jobs in Cross-platform CI run 33926437244 are green, and the exact-head CodeRabbit review has no actionable finding. The remaining pending target-check duplicate has an already-successful exact-head counterpart and the PR targets dev. Approved.

@lidge-jun

Copy link
Copy Markdown
Owner Author

Maintainer admin merge (ruleset bypass recorded per MAINTAINERS.md): carry of #3515, exact-head CI green on 696847c (28 pass / 2 skipped / 0 fail; APPROVED review from @Ingwannu on the original exact head). wp1 of the 260905 open-work closeout.

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.

3 participants