Skip to content

fix(responses): refuse ambiguous OpenCode Go resets - #5446

Closed
luvs01 wants to merge 3 commits into
lidge-jun:devfrom
luvs01:fix/597-opencode-go-reset
Closed

luvs01 wants to merge 3 commits into
lidge-jun:devfrom
luvs01:fix/597-opencode-go-reset

Conversation

@luvs01

@luvs01 luvs01 commented Sep 21, 2026

Copy link
Copy Markdown
Collaborator

Motivation

  • Prevent ambiguous pre-header connection resets from causing automatic retries of non-idempotent OpenCode Go inference POSTs, which can duplicate provider-side work and consume quota.

Description

  • Remove the destination-scoped replaySafe: isOpenCodeGoDestination(route.provider) opt-in from the passthrough initial send so ambiguous resets continue to produce the fail-closed refusal or follow the operator-scoped ambiguous-resend policy.
  • Drop the now-unused import and update the passthrough test to assert that no inference leg is declared replaySafe.

Testing

  • bun test tests/responses/responses-passthrough-transient-policy.test.ts: 10 tests pass.

Summary by CodeRabbit

  • Bug Fixes

    • Initial passthrough requests now consistently refuse ambiguous connection resets before a response begins, including requests sent to OpenCode Go destinations.
    • Retry behavior remains bounded by the configured attempt limit, helping prevent duplicate upstream sends.
    • Failed requests in this scenario return the appropriate refusal response instead of being replayed.
  • Tests

    • Updated coverage to verify consistent handling across destinations and ensure only one physical send occurs before refusal.

@coderabbitai

coderabbitai Bot commented Sep 21, 2026

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

Understand this PR’s impact

Explore downstream dependencies and potential security impact with Blast Radius.

View blast radius →

Important

Review skipped

Review was skipped as selected files did not have any reviewable changes.

⚙️ Run configuration

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

Review profile: ASSERTIVE

Plan: Advanced

Run ID: 88093d22-6189-406c-819a-51983a1abe4a

📥 Commits

Reviewing files that changed from the base of the PR and between 92b74ec and faa2e53.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

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: ff0d85d3-c985-4392-a6c1-c145cc55c6ec

📥 Commits

Reviewing files that changed from the base of the PR and between 62ac159 and 92b74ec.

📒 Files selected for processing (2)
  • tests/responses/responses-passthrough-transient-policy.test.ts
  • tests/responses/responses-send-budget-counts.test.ts

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


📝 Walkthrough

Walkthrough

The initial passthrough send no longer enables replay-safe retries for OpenCode Go destinations. Ambiguous pre-header resets now use the fail-closed policy applied to other destinations. Tests verify the refusal response and one physical send.

Changes

Passthrough retry policy

Layer / File(s) Summary
Initial passthrough send policy
src/server/responses/passthrough-dispatch.ts, tests/responses/responses-passthrough-transient-policy.test.ts, tests/responses/responses-send-budget-counts.test.ts
The dispatcher removes the OpenCode Go check and replaySafe option from the initial fetchWithTransientRetry call. The tests replace the source-text assertion with an execution test that expects HTTP 429, upstream_reset_replay_refused, and exactly one physical send after ECONNRESET.

Priority: ⬇️ Low

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

Change: Bug fix

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 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: OpenCode Go now refuses ambiguous resets instead of automatically replaying them.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check. Docstring coverage is scoped to functions touched by this diff. Analyzed 0 functions across 2…
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.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • 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

Copy link
Copy Markdown
Contributor

Deterministic PR hygiene checks passed.

@github-actions github-actions Bot added bug Something isn't working review-ready labels Sep 21, 2026
@github-actions
github-actions Bot marked this pull request as ready for review September 21, 2026 10:02
@github-actions

github-actions Bot commented Sep 21, 2026

Copy link
Copy Markdown
Contributor

✅ READY

  • all PR quality gates passed.

Hygiene

Deterministic PR hygiene checks passed.

@lidge-jun

Copy link
Copy Markdown
Owner

리뷰 · 우선순위 36 / 80

이 PR은 OpenCode Go로 요청을 처음 보낼 때, 답이 오기 전에 연결이 끊기면 같은 요청을 자동으로 다시 보내던 예외를 없앱니다.

이틀 전 병합된 #5223이 그 예외를 넣었습니다. OpenCode Go가 추론 요청을 붙잡았다가 끊으면, 프록시는 "이미 처리됐을 수 있으니 다시 보내지 않는다"는 429를 돌려줬습니다. 한 사례는 18초 대기 뒤 한 번만 보내고, 사용자 목표가 exceeded retry limit으로 끊겼습니다. #5223은 처음 보내는 그 한 번에만, 횟수 한도 안에서 다시 보내게 했습니다. 이 목적지는 구독 추론만 받아서, 다시 보내도 계산이 두 번 될 뿐이라는 이유였습니다.

이번 변경은 그 판단을 뒤집습니다. passthrough-dispatch.ts에서 replaySafe: isOpenCodeGoDestination(route.provider)와 안 쓰게 된 import를 뺐습니다. 답이 오기 전에 연결이 끊기면 다른 목적지와 같습니다. 운영자가 재전송을 켜 두었고 본문을 다시 보내도 되는 경우에만 한 번 더 보내고, 아니면 거절 429(upstream_reset_replay_refused)입니다. 답을 받은 뒤 다시 보내는 구간은 원래 이 예외가 없었습니다. 테스트는 이 파일 안에 replaySafe: 글자가 없는지만 보도록 바뀌었습니다.

라인 tests/responses/responses-passthrough-transient-policy.test.ts:187 - 테스트는 소스에서 replaySafe:가 0번인지만 셉니다. OpenCode Go로 답이 오기 전에 끊겼을 때 거절이 나오는지는 실행하지 않습니다. 그 글자 없이 같은 옵션을 넘기면 테스트는 통과합니다.

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

운영자가 재전송을 켜지 않으면, #5223이 막으려던 끊김이 다시 납니다. OpenCode Go가 답을 주기 전에 연결을 닫으면 자동 재시도가 없고, 클라이언트는 거절 429를 받습니다. 그 대가로, 이미 처리된 추론을 한 번 더 보내 할당량을 쓰는 일은 기본값에서 막힙니다. 기본을 거절로 둘지, 예전처럼 처음 한 번만 다시 보낼지는 여기서 정해야 합니다.

너의 추천

추론 요청은 같은 본문을 두 번 보내면 제공자 일이 두 번 될 수 있어서, 무조건 다시 보내는 예외를 빼는 쪽을 추천합니다. 베이스는 dev입니다. types.ts/config.ts 분할과 겹치지 않고, 이미 병합된 #5223의 반대라서 닫을 중복 PR은 없습니다. 병합 전에 "거절 429가 기본이어도 된다"만 확인하면 됩니다. 테스트는 글자 수 대신, 그 끊김이 거절로 끝나는 실행 한 건이 있으면 나중에 옵션이 다른 이름으로 돌아와도 잡힙니다.

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

@abhisheksharma2411 abhisheksharma2411 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Correctness over availability is the right default here — an ambiguous pre-header reset on a non-idempotent inference POST can duplicate provider-side work and burn quota, and no amount of "the destination is flaky" justifies replaying it. I traced the mechanism rather than assuming it, and the removal does land where you say:

with the option gone, opts.replaySafe is undefined, so upstream-retry.ts:622's if (opts.replaySafe === true) falls to the else — which returns replayRefusalResponse() unless claimAmbiguousResend() grants the operator allowance. Fail-closed by default, operator policy still reachable, and the evidence-returning path (rather than throwing) is preserved so an outer catch can't turn it back into a replayable 502. That's exactly the shape the comment claims.

Also checked that this doesn't strand anything:

  • replaySafe stays in use where it's genuinely true — the vision, web-search and image-bridge sidecars (src/vision/*, src/web-search/*, src/images/loop.ts:623). Those are idempotent side-calls, so the option keeps earning its place.
  • isOpenCodeGoDestination is still referenced at src/providers/key-failover.ts:595, so dropping the import here leaves no dead export.

One change I'd ask for: the new assertion is stronger than the invariant.

expect(occurrences(passthroughDispatchPacked, "replaySafe:")).toBe(0);

dense() strips whitespace, so this forbids the literal substring replaySafe: anywhere in the module — including replaySafe: false. That's the explicit fail-closed declaration: the safest thing a future author could write, and the guard rejects it. Someone hardening this leg by stating the property outright instead of relying on undefined gets a red test with a message that reads as if they'd reintroduced the replay.

The invariant you actually want is "no inference leg is declared replay-safe", so I'd assert against the affirmative forms:

expect(occurrences(passthroughDispatchPacked, "replaySafe:true")).toBe(0);
expect(occurrences(passthroughDispatchPacked, "replaySafe:isOpenCodeGoDestination")).toBe(0);

Same protection against the regression this PR is guarding, without outlawing the defensive spelling.

Related, and worth a sentence somewhere: the guard is file-scoped. If the opt-in ever moves behind a helper — a replayPolicyFor(route) that returns true for Go — passthrough-dispatch.ts stays clean and the test keeps passing while the behaviour comes back. Not a reason to change the test, just worth knowing what it does and doesn't cover.

One question rather than a finding. The comment you're removing described a live symptom: Go stalls-then-drops inference sends, surfacing as refused 429s, and the bounded replay was absorbing that. Refusing is the correct answer, but it's a user-visible one — those turns now fail where they previously recovered. Is there a tracking issue for the underlying Go behaviour, and is the operator-scoped ambiguous-resend policy documented anywhere a Go subscriber would find it? Otherwise this trades a silent duplication risk for a visible failure with no signposted remedy, which is still the right trade but a worse experience than it needs to be.

Nothing blocking beyond the assertion.

Per review on lidge-jun#5446: replace the replaySafe source-string count with an execution test that drops the connection before the answer on an opencode.ai/zen/go destination and asserts the 429 upstream_reset_replay_refused with exactly one send.
@github-actions
github-actions Bot marked this pull request as draft September 21, 2026 20:52
@luvs01

luvs01 commented Sep 21, 2026

Copy link
Copy Markdown
Collaborator Author

Review feedback applied on 92b74ecb: replaced the replaySafe: source-string count with an execution test - an OpenCode Go destination refuses an ambiguous pre-answer reset instead of replaying in responses-send-budget-counts.test.ts; it asserts the 429 upstream_reset_replay_refused with exactly one send on the wire. Tests: 26 pass across both files.

@abhisheksharma2411 abhisheksharma2411 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This is better than what I suggested. I proposed tightening the source assertion to the affirmative forms (replaySafe:true, replaySafe:isOpenCodeGoDestination); you replaced it with an execution test instead, which closes both concerns rather than one:

const response = await handleResponses(responsesRequest("go/model-go"), config, logCtx);
expect(response.status).toBe(429);
expect((await response.json()).error.code).toBe("upstream_reset_replay_refused");
expect(sends).toBe(1);

sends === 1 is the assertion that matters — it pins "exactly one send reached the wire", which is the actual property, not a spelling of it.

I checked the file-scoping concern I raised rather than assuming the new test covers it. It does. Reintroducing the opt-in inline and under its own name on the initial send:

claimAmbiguousResend: claimPreHeaderResend,
replaySafe: true,

fails two tests in responses-send-budget-counts.test.ts (no replay or target hop after an ambiguous reset, both the combo=false and combo=true cases). A source-text guard in passthrough-dispatch.ts would only have caught it while the opt-in lived in that file; this catches it wherever it comes back from, which was the gap I flagged.

Verified at 92b74ecb: bun test --isolate tests/responses/responses-send-budget-counts.test.ts tests/responses/responses-passthrough-transient-policy.test.ts26 pass / 0 fail, matching your number.

The pointer comment left behind in the old location is a nice touch — it sends the next reader to the test that actually holds the contract instead of leaving a gap where an assertion used to be.

Nothing outstanding from me. The open question about the underlying Go stalls-then-drops behaviour is for the maintainers, not a blocker on this.

@github-actions
github-actions Bot marked this pull request as ready for review September 22, 2026 03:04
@luvs01

luvs01 commented Sep 22, 2026

Copy link
Copy Markdown
Collaborator Author

Consolidated into #5553 as a single related-function aggregate.

Source head: faa2e5336d0b1fdd2ccc317265df09845526f6a7. Replacement head: 67c4f579e4fb5201dcd36be225ee54306d78e63e.

Implementation 62ac159 and its execution-test follow-up 92b74ec match carried b8f9a45 and 808dd85 by stable patch ID with source authors retained. The dev merge adds no remerge-resolution delta. The final aggregate preserves all 27 prepared contribution files byte-for-byte after merging current dev. Its 604 distinct focused tests include one-send OpenCode Go refusal plus the combined fallback/account no-replay cases. Default refusal availability remains an explicit pre-merge policy question on #5553; full-suite completion, exact-head hosted CI and security review remain pending. No merge or release is claimed.

Closing this duplicate standalone review entry as part of the requested consolidation after verifying coverage. This is not a merge or release claim; remaining integration checks and reviews are tracked on the replacement. Original branches are retained.

@luvs01 luvs01 closed this Sep 22, 2026
lidge-jun added a commit that referenced this pull request Sep 23, 2026
…y work (#5608)

* docs(devlog): plan the L5 luvs01 Responses and usage bundle

Record the disposition, provenance and ordered carry recipe for #5474, #5305, #5434, #5560, #5542, #5553, #5562 and #5556.

* fix(usage): verify OAuth rotation before withheld attribution

(cherry picked from commit 1ac1ba0)

* test(oauth): cover the eligible-target positive case and gate assertion

(cherry picked from commit f6778bf)

* fix(oauth): require a live two-account roster before withheld attribution

The eligibility probe added for #5434 could report an alternate when the failed account had been removed and one stored account remained, because it skipped the roster-size guard that rotation applies. Read the roster once, apply the same guard, and describe the probe as applying no cooldown rather than as non-mutating.

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

* fix(adapters): close Grok continuation and normalized tool catalog gaps

Keep the existing request shape, scope external Cursor continuations to the
current user request, repair ctc_ ids for xAI, and rebuild a full replay when
a checkpoint no longer fits the envelope. Invalid or unreadable inputs fail
closed to the previous safe default with debug diagnostics.

This is the net change of two source commits. Their empty-catalog selector
edit to src/adapters/xai-web-search.ts is omitted because dev already carries
that rule (b20acc7, #5376), and the temporary test additions to capped files
are replaced by the final extracted test files.

(cherry picked from commit 71a9fe5)
(cherry picked from commit ffd50f4)
Refs #5350, #5560

* fix(cursor): preserve continuation scope and avoid false repetition recovery

(cherry picked from commit 5a99d4d)
(cherry picked from commit 31f21f0)

* fix(responses): lower undeclared historical custom tools when the destination denies them

Routed lowering collected only current custom declarations, so a compacted or replayed custom_tool_call leaked to xAI-like gateways as the native item type and came back as a misleading 422 missing id. Convert protocol-history items from the top-level input without expanding the live catalog, request full replay for orphan results, and fail closed before serializing leftovers.

Co-authored-by: Cursor <cursoragent@cursor.com>
(cherry picked from commit 5da2883)
(cherry picked from commit a326b67)

* test(responses): split historical custom-tool replay coverage off the passthrough ratchet cap

openai-responses-passthrough.test.ts is already at its 4809-line ceiling. Keep the new wire fixtures in a responses-prefixed file so the layout seed resolves it without raising a cap.

Co-authored-by: Cursor <cursoragent@cursor.com>
(cherry picked from commit 6f43794)
(cherry picked from commit 7e8fb09)

* fix(responses): reject malformed historical custom calls

(cherry picked from commit 52f7448)
(cherry picked from commit 57407be)

* fix(responses): bind historical outputs to custom calls

(cherry picked from commit 5654b41)
(cherry picked from commit c7781bf)

* fix(responses): reject duplicate historical call ids

(cherry picked from commit dc948dc)
(cherry picked from commit fbecefa)

* fix(xai): preserve stateful tool output continuations

(cherry picked from commit 4edc411)
(cherry picked from commit 82a5f6d)

* fix(xai): keep replay-miss reasoning cleanup independent of output repair

Co-Authored-By: Epinephrine <luvs01@hanmail.net>
(cherry picked from commit 67ccd8d)
(cherry picked from commit aac783f)

* test(responses): verify combined continuation boundaries

Exercise stateful output-only deltas, independent replay-miss reasoning cleanup,
capability-driven historical lowering, placeholder ordering, native item-ID
repair and preservation of the existing empty-catalog denial. Record the
combined history contract and register the carried and new regression files.

The layout-marker cleanup from e8e179f was
completed while resolving its preceding source commit onto the current map.
The existing dev selector normalization and role-fixture corrections remain
authoritative and are not replaced by weaker or duplicate source changes.

Co-authored-by: Yeonwoo Choi <32544727+twoimo@users.noreply.github.com>
Co-authored-by: maosisheng <maosisheng@gmail.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Epinephrine <luvs01@hanmail.net>
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
(cherry picked from commit 2ec0cd1)

* fix(responses): normalize wrapped MCP tool names

(cherry picked from commit b4c839b)
(cherry picked from commit f68b32646069d3e385748fc6c36848765c68e02e)
(cherry picked from commit e555e73)

* fix(responses): unwrap default apply patch aliases

(cherry picked from commit 453df76)
(cherry picked from commit d63ff542415895fa25f5599aad9dc632c80de92d)
(cherry picked from commit 7cbbf44)

* docs(structure): record default.-prefixed alias recovery in the freeform contract

The responses owners still claimed only bare exec/apply_patch calls accept alternate-field or outer-fence recovery; compileCodeModeHelperInput now also unwraps provider-invented default. aliases. Update runtime.md, transports/responses.md, providers/{chat-compat,kiro,xai-grok}.md.

Co-Authored-By: Epinephrine <luvs01@hanmail.net>
(cherry picked from commit 165ddd0)
(cherry picked from commit d0776e703681729e2ea447775e77397faab16f29)
(cherry picked from commit 19a2005)

* fix(responses): compile structured shell payloads sent to code-mode exec

(cherry picked from commit 9430bbd)
(cherry picked from commit 59bc70bc30f954eea5a63f8a6fcf4de4dcbfd865)
(cherry picked from commit 9662528)

* test(responses): verify combined tool normalization boundaries

Verify that default.apply_patch names and patch/content wrappers emit the same executable input through JSON and fragmented SSE. Move the carried decision record to unused ADR-0099 because current dev already owns ADR-0097; preserve both the structured code-mode shell and existing schema-bound flat-shell contracts.

Co-authored-by: kosta <kosta963@gmail.com>
Co-authored-by: Flowershangfromthebranches <152056395+Flowershangfromthebranches@users.noreply.github.com>
(cherry picked from commit 3da6366a60ac5964e8a8de43486125d72729f8c8)
(cherry picked from commit b57d7c5)

* fix(responses): refuse ambiguous OpenCode Go resets

(cherry picked from commit 62ac159)
(cherry picked from commit b8f9a45)

* test(responses): prove OpenCode Go pre-answer reset refusal by execution

Per review on #5446: replace the replaySafe source-string count with an execution test that drops the connection before the answer on an opencode.ai/zen/go destination and asserts the 429 upstream_reset_replay_refused with exactly one send.

(cherry picked from commit 92b74ec)
(cherry picked from commit 808dd85)

* fix(routing): isolate policy retry body snapshot

(cherry picked from commit 8e2a0fe)
(cherry picked from commit db854bf)

* test(routing): pin the retry snapshot against nested input mutation

(cherry picked from commit a240fc9)
(cherry picked from commit b037810)

* fix(responses): isolate policy compaction state

(cherry picked from commit 714119e)
(cherry picked from commit e6f9339)

* fix(tests): bound the cold-spawn warm-up child on a live event loop

The warm-up child was waited on through Bun.spawnSync, which made the spawn's
own timeout the only bound it could honour — and no bound at all when the
child or the primitive wedged: while a synchronous spawn blocks, the event
loop is dead, so the hook budget and the per-test timeout freeze inside the
same wait and nothing reports anything. Run 35511743422's macos 2/2 leg held
that shape for eighteen silent minutes inside client-connect.test.ts before
the job ceiling cut it and reported cancelled, which the ci gate reads as
failure.

The bound now lives on the parent's live loop: an asynchronous spawn, SIGKILL
at the existing derived deadline, a short reap grace, and the call settles
with or without the child's exit or EOF — so a descendant holding the pipes
or a child that outlives its kill cannot turn a warm-up into an unbounded
wait. A timed-out child now fails the warm-up by name instead of hanging the
job.

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
(cherry picked from commit aa9b889)
(cherry picked from commit f86a534)

* fix(responses): fail closed on synthetic or stale compaction source selectors

compactionRoutingKeepsProviderIdentity evaluated override.sourceModel as the
raw client selector, so a synthetic --fast/--effort form of a policy or combo
selector (ocx/primary--fast) missed resolvePolicyProfileId/resolveComboId and
fell through routeConcreteModel to the default provider. The same fallthrough
swallowed policy aliases renamed or deleted mid-conversation, since
config.routingProfiles is mutated in place. Both cases could wrongly report
identity match and let provider-private compaction state or caller credentials
cross a backend boundary.

Strip synthetic-row suffixes via parseSyntheticRowId before the identity
checks, and treat a source that only routes through the default provider as
unproven: it can never match a concrete identity.

Co-Authored-By: Epinephrine <luvs01@hanmail.net>
(cherry picked from commit 7e59315)
(cherry picked from commit 76b40f9)

* fix(codex): bind scoped quota suppression to alternate

(cherry picked from commit 23a3694)
(cherry picked from commit 385f338)

* fix(ci): restore core.ts to file-size ratchet cap

The scoped-quota re-export grew src/server/responses/core.ts past its committed 210-line cap (213). Collapse the two-name re-export back to one line; the file's export list already carries longer single-line statements.

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
(cherry picked from commit 559db16)
(cherry picked from commit feb0c16)

* fix(codex): record wrapped quota on suppressed moves and bind caller main

- record the normalized 429/402 outcome before returning no-alternate on a
  suppressed same-workspace move, so a 5xx-wrapped quota refusal still cools
  the refused account instead of reading as transient
- bind a request-owned `main` alternate by the caller credential's own
  workspace id (chatgpt-account-id header, else the bearer token's account
  claim) via callerCodexWorkspaceAccountId
- apply the same scoped-quota workspace gate to the single bounded alternate
  send in the native /responses/compact path
- cover all three in tests and update the transport doc

Co-Authored-By: Epinephrine <luvs01@hanmail.net>
(cherry picked from commit 5267593)
(cherry picked from commit 466c75c)

* test(server): move scoped-quota auth cases into a sibling file under the size cap

server-auth.test.ts grew to 4684 against a 4589 baseline cap, so the
file-size ratchet failed shard 3/4. The three scoped-quota suppression
cases move byte-for-byte into server-auth-scoped-quota.test.ts, and the
pool-retry harness they share is extracted to
tests/helpers/pool-retry-harness.ts (per-run OPENCODEX_HOME dir, so each
importing file keeps its own module state under bun test --isolate).

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
(cherry picked from commit b391c99)
(cherry picked from commit 9050722)

* fix(codex): re-check abort after the scoped-quota body read

The workspace classification in shouldRetryCodexScopedQuotaOnAlternate
reads the first response body asynchronously, so a client disconnect can
land after the earlier abort check but before the branch records the
first account, cancels its body, and sends the alternate. Re-check the
abort signal immediately after the await in both paths: compact returns
the 499 client_cancelled response after releasing the alternate lease,
and the regular path releases its permit and lease and returns
no-alternate while still recording the first account's real outcome.

Co-Authored-By: Epinephrine <luvs01@hanmail.net>
(cherry picked from commit c52b64b)
(cherry picked from commit b2eda92)

* fix(codex): release the discarded compact rejection body on abort

The 499 exits around the scoped-quota classification return a fresh
response while the first rejection's body is still open; cancel it so
the abandoned upstream connection and tee resources are released.

Co-Authored-By: Epinephrine <luvs01@hanmail.net>
(cherry picked from commit 813efcc)
(cherry picked from commit 1069b54)

* fix(codex): keep compact abort cleanup off the return path

upstream.body.cancel() can wait on a custom or stalled source; awaiting
it at the abort checkpoints would park the 499 reply on cleanup. Fire
it with the request's abort reason and swallow rejection, the same
best-effort shape bufferCompactResponse already uses.

Co-Authored-By: Epinephrine <luvs01@hanmail.net>
(cherry picked from commit 2d1ee69)
(cherry picked from commit 37a006e)

* test(responses): preserve terminal refusal across recovery boundaries

Exercise both operator-granted and default-denied reset paths through policy fallback and the alternate-account eligibility gate. Clarify that retries serialize the original body snapshot while identity metadata is established per attempt, and document synthetic compaction identity and transient replacement refusal.

(cherry picked from commit be1fee9)

* test(cursor): pin exact host-wrapper classification in continuation scope

The wire carries no provenance for compaction summaries or ambient browser state, and the Codex client detects stored summaries by the same exact prefix. Pin that a user message that is itself an exact wrapper stays in history while the preceding real request remains the labeled one, and document the rule next to the continuation contract.

Co-authored-by: Yeonwoo Choi <32544727+twoimo@users.noreply.github.com>

* test(server): prove a suppressed same-workspace alternate is never sent

Both credentials in the 5xx-wrapped scoped-quota case carry the same workspace header, so a negative check on the other account id could not fail. Assert the exact one-send sequence, and narrow the transport contract: suppression covers the in-request move, while later requests still select by per-account health.

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

* docs(devlog): record the L5 responses sequence outcome

* docs(devlog): amend the L5 search and usage plan after review

* fix(responses): isolate Cursor combo shadow calls

(cherry picked from commit 3e5a4dd)
(cherry picked from commit 7f45883)

* fix(responses): repair terminal-less bridged search legs

(cherry picked from commit 1fb6005)
(cherry picked from commit c4fa8c8)

* fix(responses): repair continuation legs and prove behavior in tests

(cherry picked from commit 3948970)
(cherry picked from commit 8d46989)

* fix(responses): close shadow combo intersection and continuation coverage

Apply the existing source-target non-intersection rule before early combo interception, and add production-path behavioral coverage for terminal-less continuation repair.

(cherry picked from commit 4bfcc0a)
(cherry picked from commit 3f3fdf1)

* test(web-search): preserve complete but open bridge-leg coverage

Carry the end-to-end handleResponses regression and transport contracts for repairing both the first and continuation search legs. The corresponding production changes are already preserved by the earlier terminal-repair carries; keep this broader integration coverage without applying that implementation twice.

Source commit: b1044e7
Co-authored-by: Epinephrine <luvs01@hanmail.net>

(cherry picked from commit 973a4ac)

* test(web-search): keep repaired replay within caller and serving scope

(cherry picked from commit bb49c9f)

* test(server): reap fixture ACL workers before removing failover homes

(cherry picked from commit ae52669)

* fix(responses): keep combo shadow interception on the dispatch pick

The carried early intersection check sampled a combo target with routeModel before dispatch. The combo loop then picked again, so the interception decision could follow a different target than the one sent, and a random or round-robin combo advanced its selection state for a probe. Restore the existing combo rule (a shadow call rewritten to a combo enters the combo) and its regression test, and keep the combo-child isolation marker.

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

* test(web-search): bind repaired-leg replay to a keyed caller principal

The repaired-leg replay assertion expected a shared keyless loopback principal, which the replay cache refuses by design: keyless loopback callers get no retained replay. Configure an inbound API key, derive the expected principal with the production resolver, pass the full loopback admission, and assert that a keyless caller cannot form a scope.

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

* fix(usage): restrict legacy -main provider collapse to Codex labels

A -main suffix was stripped from ANY provider name, so a configured provider like openrouter-main silently merged into openrouter in usage summaries and pricing fallback. Restrict the compatibility mapping to the known Codex provider labels (openai/chatgpt/openai-multi-main), matching codexAccountProviders.

(cherry picked from commit 89a9272)
(cherry picked from commit 0f0ef96)

* fix(cli): mark access-key usage unavailable when attribution is absent

Without attributionSince the server is reporting an empty or unreadable usage log, but the table still rendered 0 totals and never-used markers that are indistinguishable from real data. Show an unavailable marker spanning the usage columns instead, matching the ambiguous-union precedent.

(cherry picked from commit 3c3f14b)
(cherry picked from commit 83514c3)

* fix(cli): treat a malformed attributionSince as unavailable

typeof === 'string' accepted any value, so a malformed attributionSince made
usageAvailable true and printed usage cells plus an 'attribution since'
footer. Parse once, derive availability from the validated result, and reuse
it for the footer. Covers the malformed-string regression.

(cherry picked from commit e7584c3)
(cherry picked from commit 1380693)

* fix(gui): keep the app-server status read alive across Models tab switches

(cherry picked from commit 9e6870d)
(cherry picked from commit 5563577)

* fix(usage): bound persisted requestedModel selectors

Selectors are not length-bound at admission, so persist over-long values as a bounded prefix + sha256 digest of the full selector and encode the request-history requested_model filter input identically. Two selectors sharing the bounded prefix stay distinguishable instead of colliding on a truncated prefix.

(cherry picked from commit e3d0f9b)
(cherry picked from commit c8a9d1a)

* fix(spend): enforce ceilings on native chat sends

(cherry picked from commit 347204f)
(cherry picked from commit 823a7d2)

* fix(usage): preserve observation and native reservation boundaries

(cherry picked from commit 22ee516)

* test(usage): isolate native spend regressions within file caps

(cherry picked from commit 1a8d5f7)

* test(usage): drain fixture owners before removing Windows homes

(cherry picked from commit 2241d03)

* test(usage): batch canonical pagination fixture writes

(cherry picked from commit ddfef13)

* fix(cli): accept only an ISO-8601 UTC attributionSince

Date.parse accepts strings such as "0" and rolls impossible dates over, so a malformed attributionSince could still switch the key table to numeric usage and never-used cells. Require the ISO-8601 UTC shape the server emits and an instant that round-trips to the same second.

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

* docs(usage): state the aliasing limit of the idempotent selector encoding

Encoded requestedModel values must map to themselves because rows are normalized again on read, so a literal selector equal to another selector's persisted form shares its identity. Say so where the encoding is defined, and pin the behavior in the request-history test so the limit is deliberate rather than silent.

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

* docs(devlog): record the L5 search and usage outcome

* docs(devlog): record the L5 pull request

* docs(structure): keep runtime.md within its 600-line budget

The default.-prefixed freeform wording wrapped one extra line and pushed structure/runtime.md over the structure SSOT budget. Reflow the paragraph; the wording is unchanged.

* refactor(cursor): move current-request selection out of protobuf-request

The carried continuation-scope helpers brought src/adapters/cursor/protobuf-request.ts to 2,000 lines, the file-size threshold for files without a recorded cap. Move the current-request selection and its host-wrapper classification to a sibling module unchanged; the caller passes its text extractor.

Co-authored-by: Yeonwoo Choi <32544727+twoimo@users.noreply.github.com>

* docs(devlog): record the #5553 re-pin in the L5 plan

* docs(devlog): record the L5 original closures

* fix(usage): keep the native Chat spend estimate out of recorded usage

The native Chat spend reservation reused usageLogInputTokens for its input estimate. That field also feeds attempt usage, so native Chat attempts started recording an estimate-inflated input instead of the provider-reported counts (hosted CI: server-xai-oauth-401-replay and server-key-failover-e2e). Reserve the estimate through a spend-only spendInputEstimateTokens field; the reservation still charges it before each physical send.

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

* test(server): identify the suppressed alternate by its credential

Hosted CI showed the send layer retrying the refused account's transient 502 on the same credential, so an exact one-dispatch count was the wrong oracle. Both accounts share a workspace header; record the credential each physical send presents and assert the suppressed alternate's credential never appears.

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

* fix: close L5 retry, continuation, and history review gaps

Classify spend refusals on transient retry legs, keep Cursor retry provenance in checkpoint actions, and rebuild legacy history selectors into the bounded projection. Scope policy snapshots and correct warm-up deadline handling, with focused regressions and documentation.

* fix: retain policy fallback for decorated selectors

Normalize supported Fast and effort policy selectors before snapshot gating, restore a real policy-hop fixture, and align Cursor wire assertions with retry provenance guidance.

---------

Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com>
Co-authored-by: Yeonwoo Choi <32544727+twoimo@users.noreply.github.com>
Co-authored-by: twoimo <twoimo@twoimoui-MacBookPro.local>
Co-authored-by: maosisheng <maosisheng@gmail.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Epinephrine <luvs01@hanmail.net>
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: kosta <kosta963@gmail.com>
Co-authored-by: Flowershangfromthebranches <152056395+Flowershangfromthebranches@users.noreply.github.com>
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