Skip to content

Add opt-in upstream pooling and account capacity limits - #29

Merged
maiphucgiang merged 1 commit into
mainfrom
perf/upstream-pooling-capacity
Sep 16, 2026
Merged

maiphucgiang merged 1 commit into
mainfrom
perf/upstream-pooling-capacity

Conversation

@maiphucgiang

@maiphucgiang maiphucgiang commented Sep 16, 2026

Copy link
Copy Markdown
Owner

Changes

  • Add opt-in, lifespan-owned HTTP/1.1 clients for trusted upstream origins, with bounded pools, no retained cookies and request-scoped authentication. Existing proxy, timeout and replay behavior is preserved, including fresh-client connection retry.
  • Add per-process account capacity leases, held through response completion and released on failover/cancellation, including late worker completion. Full accounts cannot bypass strict bindings or spill from a free tier into paid accounts.
  • Expose CLI/environment/WebUI settings and credential capacity metrics; defaults remain keepalive=false and account limit=0. Synchronize Compose, the environment template and both advanced guides.

Verification

  • All 51 backend test scripts pass, including 19 resource tests and two new startup/precedence tests.
  • Real loopback TCP test: two successful requests use one connection with pooling, versus two with the legacy path.
  • Isolated native Uvicorn deployment passes all three protocols and both response modes, quota rejection without an upstream call, real downstream disconnect/capacity recovery, settings modes and pool shutdown.
  • Synthetic credentials and disposable SQLite only; no live upstream-account or production-latency claim. No dependencies or version changes (1.2.6).

Rollback

Set the account limit to 0; disable keepalive and restart. Before downgrading source, remove new CLI options and restore a compatible control-store backup without the new persisted keys.

Summary by Sourcery

Enable opt-in upstream connection pooling and enforce account-level inference capacity limits without changing the default routing or request behavior.

New Features:

  • Add opt-in bounded HTTP/1.1 connection pooling for trusted upstream origins while preserving request-scoped authentication, cookie isolation, and existing retry behavior.
  • Add configurable per-process, per-account in-flight capacity limits with safe lease handling across completion, cancellation, and failover.
  • Expose connection pooling and account capacity settings through CLI, environment variables, WebUI configuration, Compose, and credential metrics.

Enhancements:

  • Preserve routing, free-tier preference, strict bindings, proxy handling, timeout behavior, and replay semantics while introducing pooled upstream resources and capacity accounting.

Deployment:

  • Synchronize Compose and environment configuration for the new runtime settings and document rollback requirements.

Documentation:

  • Document connection reuse, account capacity behavior, configuration precedence, metrics, defaults, and operational constraints in both advanced guides.

Tests:

  • Add coverage for connection reuse and isolation, retry behavior, lifecycle shutdown, atomic capacity reservations, cancellation recovery, failover release, and configuration precedence and validation.

Own bounded cookie-free clients in the ASGI lifespan and release account-scoped leases on completion, failover and cancellation. Preserve strict routes, free-first admission and existing replay rules.

Expose compatible defaults through CLI, environment and WebUI settings. Validate all 51 backend test scripts, real loopback TCP reuse, and isolated native deployment with real client disconnects. Keep version 1.2.6.
@sourcery-ai

sourcery-ai Bot commented Sep 16, 2026

Copy link
Copy Markdown

Reviewer's Guide

Adds opt-in trusted-origin HTTP connection pooling and cancellation-safe, per-process account capacity leases, integrated into credential routing and request ownership while preserving existing proxy, timeout, retry, failover, and routing behavior; configuration, metrics, documentation, and comprehensive resource tests are included.

Flow diagram for per-account capacity admission and release

flowchart TD
    A[Generation request] --> B[Select credential within existing routing rules]
    B --> C{Account capacity available?}
    C -- No --> D[503 credential_concurrency_limit]
    C -- Yes --> E[Acquire CredentialLease]
    E --> F[Perform inference and failover if needed]
    F --> G{Request completes, cancels, or rotates account?}
    G --> H[release_credential]
    H --> I[Capacity available again]
    C -. Limit 0 .-> E
Loading

File-Level Changes

Change Details Files
Introduces lifespan-scoped, bounded HTTP/1.1 client pools for trusted upstream origins while preserving fresh-client fallback and retry semantics.
  • Creates one cookie-rejecting client per trusted origin and event loop with bounded connection limits and shutdown cleanup.
  • Propagates request-owned clients through middleware context and uses them only when keepalive is enabled.
  • Falls back to a fresh client for the retry attempt and retains existing timeout, proxy, authentication, and replay behavior.
app/inference_resources.py
app/upstream_io.py
converter.py
tests/test_inference_resources.py
Adds atomic per-process account capacity leasing across request lifetimes, failover, cancellation, and late worker completion.
  • Reserves capacity during credential selection without bypassing strict bindings or free-tier routing precedence.
  • Uses idempotent leases and request resource ownership to release on completion, cancellation, failure, failover, and post-disconnect worker completion.
  • Returns a dedicated 503 capacity error and exposes per-credential in-flight metrics.
app/inference_resources.py
converter.py
tests/test_inference_resources.py
Exposes the new controls through runtime configuration and documents their defaults, precedence, operational behavior, and rollback.
  • Adds restart-scoped keepalive and hot per-account capacity settings with CLI, environment, persisted-setting, and WebUI support.
  • Keeps defaults at keepalive=false and account limit=0, with validation and CLI-over-environment/saved-setting precedence tests.
  • Synchronizes Compose, environment coverage, and English/Chinese advanced documentation.
app/settings.py
converter.py
docker-compose.yml
docs/advanced.md
docs/advanced.zh-CN.md
tests/test_environment_config.py
tests/test_inference_resources.py

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 16, 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-16T15:51:41.515134Z 843376f PR opened
🔒 Security Review Completed 2026-09-16T15:54:44.999100Z 843376f 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.

@sourcery-ai sourcery-ai 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.

Hey - I've found 1 issue

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="app/settings.py" line_range="46-49" />
<code_context>
                           minimum=0, maximum=10),
     "retry_write_timeout": _item(False, "boolean", "写超时参与重放",
                                  env="CODEBUDDY2API_RETRY_WRITE_TIMEOUT"),
+    "upstream_keepalive": _item(False, "boolean", "上游连接复用", mode="restart",
+                                env="CODEBUDDY2API_UPSTREAM_KEEPALIVE"),
+    "max_inflight_per_account": _item(0, "integer", "单账号在途上限(0 不限制)",
+                                      env="CODEBUDDY2API_MAX_INFLIGHT_PER_ACCOUNT", minimum=0, maximum=10000),
     "audit_max_bytes": _item(256 * 1024 * 1024, "integer", "审计明细预算", minimum=1024**2, maximum=1024**4),
     "audit_retention_days": _item(30, "integer", "审计明细保留天数", minimum=1, maximum=36500),
</code_context>
<issue_to_address>
**nitpick:** .env.example is not updated with CODEBUDDY2API_UPSTREAM_KEEPALIVE or CODEBUDDY2API_MAX_INFLIGHT_PER_ACCOUNT, so the environment template does not document the two newly exposed runtime settings despite the PR claiming the template is synchronized.

**Triggers:** When operators configure the service from the supplied environment template.

**Suggested fix:** Add both environment variables, with their false/0 defaults, to `.env.example`.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. If the pooled client or request-scoped lease handling is wrong, authentication headers or upstream connection state could be exposed across requests, or valid inference traffic could be rejected until capacity is released; requests already sent or data exposed would not be undone by reverting. Reverting would stop the new pooling and capacity behavior for future requests, but would not repair those already-occurred effects.


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread app/settings.py
Comment on lines +46 to +49
"upstream_keepalive": _item(False, "boolean", "上游连接复用", mode="restart",
env="CODEBUDDY2API_UPSTREAM_KEEPALIVE"),
"max_inflight_per_account": _item(0, "integer", "单账号在途上限(0 不限制)",
env="CODEBUDDY2API_MAX_INFLIGHT_PER_ACCOUNT", minimum=0, maximum=10000),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

nitpick: .env.example is not updated with CODEBUDDY2API_UPSTREAM_KEEPALIVE or CODEBUDDY2API_MAX_INFLIGHT_PER_ACCOUNT, so the environment template does not document the two newly exposed runtime settings despite the PR claiming the template is synchronized.

Triggers: When operators configure the service from the supplied environment template.

Suggested fix: Add both environment variables, with their false/0 defaults, to .env.example.

@maiphucgiang
maiphucgiang merged commit 1e6f297 into main Sep 16, 2026
8 of 9 checks passed
@maiphucgiang
maiphucgiang deleted the perf/upstream-pooling-capacity branch September 16, 2026 22:29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant