Skip to content

refactor(inference): share budget, final-log and attempt primitives across lanes (PF-05) - #5811

Closed
lidge-jun wants to merge 12 commits into
feat/pf03-protocol-planfrom
feat/pf05-inference-primitives
Closed

lidge-jun wants to merge 12 commits into
feat/pf03-protocol-planfrom
feat/pf05-inference-primitives

Conversation

@lidge-jun

@lidge-jun lidge-jun commented Sep 25, 2026 •

Copy link
Copy Markdown
Owner

Summary

PF-05 of the protocol-first-class unit (devlog/_plan/260924_protocol_first_class/020_engine_and_codecs.md#pf-05-shared-inference-primitives). Stacked on #5810 (PF-03).

Behavior-preserving refactor: the execution primitives that the Responses pipeline, native Chat and Messages each rebuilt by hand move into src/server/inference/, so the native lanes in later packets reuse one owner instead of copying it.

  • context.ts — createInferenceSendBudget(req, logCtx), the single construction of the ingress send budget with its spend tracker. Still only built when no budget is inherited (options.sendBudget ?? …), so a combo child keeps the parent's holder.
  • final-log.ts — createFinalRequestLog(logIds, logCtx), finish-once ownership of the final request row; replaces the finalizeNativeLog / finalize / nativeLogged closures in Chat, native Chat and Messages.
  • attempt.ts — beginInferenceAttempt, wrapping attempt opening, identity sealing and finishing in their original order; adopted by native Chat.
  • client-wire.ts — markClientWire / clientWireOf (unused until PF-07/PF-09).
  • handleNativeChatCompletions splits into runNativeChatAttempt (send loop, key failover, 429 replay, relay, usage) and the wrapper that opens the attempt and owns the final log, so a combo child can later run a native attempt whose log belongs to the parent.
  • src/server/responses/core.ts shrinks 210 → 198 (cap 210): one line from the budget import, eleven from grouping its compatibility re-exports per owner module (same exported names).

Deliberately not converted: the combo child attempt (different shape — own child log, parent attempt list, late seal; PF-07 owns it) and native Chat's send budget (it only attaches a spend tracker; switching would add budget behavior).

Reviewer notes on ordering: the final-log once-flag now settles even without logIds (nothing reads it; rows written are unchanged); native Chat finishLog writes upstreamError after the finished() check and before finish (equivalent — the redaction cannot throw).

Verification

  • bun x tsc --noEmit: exit 0 on this head.

  • bun run structure:check: passed.

  • Tests (tests/server/inference-*.test.ts) were written and registered, and tests/helpers/responses-core-source.ts updated for the changed core.ts imports, but run in the full local suite below.

  • Full local run on the stack head (feat(protocols): protocol paths as a first-class concern — PF-01..PF-12 #5820, which contains this change): bun run test — the only failures are Lab CL-03/CL-07/CL-08/SEC-02 and release helper timeouts, which fail identically on a checkout without this stack (local environment), plus service/toggle cases that pass when run alone; cd gui && bun test --isolate tests — 2398 pass, 0 fail.

  • CI on this head: all required checks pass.

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.

@lidge-jun
lidge-jun requested a review from Ingwannu as a code owner September 25, 2026 03:30
@coderabbitai

coderabbitai Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

🗂️ Base branches to auto review (2)
  • ^dev$
  • ^preview$

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

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

Review profile: ASSERTIVE

Plan: Advanced

Run ID: 18a59523-c7d8-4ff1-b7b2-27cf6937926a

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

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.

@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-25T03:33:08.026568Z 243fd58 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 added the chore Maintenance, CI, tests, refactors, or build changes (not a user-facing bug or feature). label Sep 25, 2026
@github-actions

Copy link
Copy Markdown
Contributor

✅ Deterministic PR hygiene checks passed.

@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 for the PF-05 layer on exact head 243fd58eb06567879c215b7099090259294a3cad, relative to its PF-03 base.

The extracted send-budget, attempt, final-log, and response-identity primitives preserve the existing ownership boundaries. Native Chat still owns its spend tracker, active attempt, first-wins final row, retries, failover, relay, and usage; the split exposes execution without silently creating a second final-log owner.

Focused validation under a 2-CPU / 4 GiB cgroup passed: 80 tests, 0 failures across all four new primitive suites and the relevant native Chat policy, spend, image, role, finish, and eligibility suites.

This approval is not merge-readiness for the stack. The PR still targets the PF-03 branch, and current CI fails because PF-03 added /api/protocols and /api/protocols/plan without adding their headless CLI parity disposition. PF-01 through PF-03 also have active changes-requested reviews; PF-05 must remain behind those corrected bases and obtain a green exact-head run before merge.

@lidge-jun

Copy link
Copy Markdown
Owner Author

리뷰 · 우선순위 50 / 80

이 PR은 세 입구가 각자 복사해 쓰던 준비 동작을 한곳으로 모은다. Responses, 채팅 완성, Messages가 요청 로그를 끝내는 코드가 같았고, 그 코드를 src/server/inference/로 옮겼다. 보내는 예산을 만드는 일, 시도를 여는 일, 로그를 한 번만 적는 일도 같이 옮겼다. 문장 순서는 이전과 같다.

네이티브 채팅은 둘로 나뉜다. handleNativeChatCompletions가 시도를 열고 로그의 주인을 정한다. runNativeChatAttempt는 보내기, 키 교체, 429 재시도, 중계, 사용량을 돌리고, 결과는 받은 finishLog에만 알린다. 나중에 콤보 자식이 부모 로그에 적을 수 있게 하려는 자리다.

클라이언트 회선 표시도 만들어 두었다. 아직 호출하는 곳이 없다. 계획의 PF-07과 PF-09가 쓸 자리다.

베이스는 #5810의 feat/pf03-protocol-plan이다. 같은 내용의 다른 열린 PR은 없다. src/types.ts를 나누는 변경은 없다. src/server/responses/core.ts는 210줄에서 198줄이 됐다. 밖으로 내보내는 이름은 같고, 줄만 주인 파일끼리 묶었다. 타입 검사는 통과했다.

라인 - CI test 2/4 6/43 배치, tests/cli/cli-headless-parity.test.ts 509행 — 기대한 목록은 빈 배열인데 /api/protocols와 /api/protocols/plan이 들어 있다. gates의 GUI 테스트는 api.plan.routeKind가 없어서 실패한다 (gui/tests/fr-localization.test.ts 250행). 이 파일들은 이 diff에 없다. 부모 #5810도 gates와 test 2/4가 실패한다.

라인 - tests/server/inference-client-wire.test.ts — 통과한 샤드 1, 3, 4 로그에는 inference-attempt, inference-final-log, inference-send-budget만 있다. 세 파일은 통과했다. 회선 표시 테스트 이름은 네 샤드 로그 어디에도 없다. 샤드 2는 6/43에서 멈춰 로그가 거기서 끝난다.

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

enforce-target은 베이스가 dev일 때만 통과한다. 이 PR의 베이스를 지금 dev로 바꾸면 #5810과의 스택이 풀린다. 부모가 dev에 들어간 뒤에 이 브랜치를 옮기면 된다.

계획 표는 네이티브 채팅의 예산도 createInferenceSendBudget으로 바꾸라고 적었다. 이 PR은 src/server/chat-native.ts 259행에서 지출 추적만 붙인다. 예산 홀더까지 만들면 보내기 상한이 새로 생긴다. 그 선택은 지금 동작을 지키는 쪽이다. 계획 문장을 고칠지, 다음 패킷에서 홀더를 넣을지 정해 달라.

콤보 자식의 시도 열기는 이 PR이 안 건드린다. 계획 표에는 들어 있고, 본문은 PF-07이 가져간다고 적었다.

너의 추천

방향은 유지해라. 닫을 중복 PR은 없다. 베이스를 dev로 되돌리지 마라. 빨간 CLI와 GUI 검사는 #5810에서 고쳐라. 이 패킷에서 로그로 확인된 세 테스트는 통과했다. 회선 표시 테스트는 실패한 샤드 뒤에 남아 실행 기록이 없다. 그 파일은 16줄이다. 샤드가 초록이 된 뒤 한 번 보이면 충분하다.

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

The ingress-owned send holder is built in one place: default guarded policy and this
request's spend tracker as observer. Responses core and later native lanes share it.
Three ingress files hand-roll the same once-flag around addFinalRequestLog. One owner
lets a native attempt hand its final row to whichever caller owns the request.
Opening an attempt is four ordered writes on the log context plus identity sealing;
the handle keeps them together so a new lane cannot skip or reorder one.
Lets an ingress tell a body already in its own client wire from a Responses body it
still has to convert. Nothing marks responses yet.
…context

Same construction, same short-circuit on an inherited holder. core.ts no longer imports
request-spend directly, so the owner inventory drops it: the import graph from core.ts is
what the module-boundary test compares against.
…tLog

Same once-claim, same fields, same call sites; the local flag and its closure go.
Both the caller-forward passthrough and the routed replay used the same once-flag
closure; the shared owner keeps their fields and call order unchanged.
The four context writes and the identity seal run in the original order, before any
effort normalization or send.
The native finishLog still records the redacted failure text before the row, once;
only the once-flag moves to the shared owner.
…apper

The wrapper opens the attempt and owns the final log row; runNativeChatAttempt runs the
effort normalization, send loop, key failover, 429 replay, relay and usage and reports
every outcome through the finishLog it is given. A combo child can then run a native
attempt whose final row belongs to the parent. Statement order is unchanged.
Same names from the same owners, one statement per module. core.ts sits at its size
cap and the native Chat combo work needs headroom there.
@lidge-jun
lidge-jun force-pushed the feat/pf05-inference-primitives branch from 243fd58 to 70c2c84 Compare September 25, 2026 04:32
@devin-ai-integration devin-ai-integration Bot added the priority: P3 Low: new provider/client integration, large or experimental feature (>2000 LOC or >50 files), RFC/ro label Sep 25, 2026
@devin-ai-integration

Copy link
Copy Markdown
Contributor

Maintainer triage: priority: P3 — protocol-first-class series PF-05 (behavior-preserving refactor).

Criteria (P3): Low: new provider/client integration, large or experimental feature (>2000 LOC or >50 files), RFC/roadmap, or long-stale branch.

Related / overlapping PRs:

lidge-jun added a commit that referenced this pull request Sep 25, 2026
…12 (#5820)

Squash of the protocol-first-class stack #5808, #5809, #5810, #5811, #5812, #5813, #5814, #5815, #5816, #5817, #5819 and #5820. Every new lane sits behind a protocols.rollout switch that defaults off.
@lidge-jun

Copy link
Copy Markdown
Owner Author

Landed in dev as part of the single squash of the protocol-first-class stack: #5820 (0f4c8d4).

@lidge-jun lidge-jun closed this Sep 25, 2026
@lidge-jun
lidge-jun deleted the feat/pf05-inference-primitives branch September 26, 2026 01:54
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). priority: P3 Low: new provider/client integration, large or experimental feature (>2000 LOC or >50 files), RFC/ro

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants