Skip to content

feat(accounts): add manual routing policy - #553

Closed
Komzpa wants to merge 24 commits into
Soju06:mainfrom
Komzpa:feature/manual-account-routing-policy-clean
Closed

Komzpa wants to merge 24 commits into
Soju06:mainfrom
Komzpa:feature/manual-account-routing-policy-clean

Conversation

@Komzpa

@Komzpa Komzpa commented May 6, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • Add a focused per-account manual routing policy: burn_first, normal, and preserve.
  • Add per-additional-quota routing policy overrides: inherit, burn_first, normal, and preserve.
  • Default the codex_spark additional quota limit to burn_first, so Spark quota can be burned independently while standard Codex calls keep using ordinary account routing.
  • Apply account and additional-quota policy after model/additional-quota eligibility filtering and before ordinary usage/reset/capacity balancing.
  • Expose account policy through the accounts API/dashboard controls, and additional-quota policy through routing settings plus account usage badges.
  • Keep OAuth re-authorization of a deactivated exact account identity in-place instead of creating __copyN when import-without-overwrite is enabled.
  • Document the selection contract with an OpenSpec change.

Relationship to #545 and #567

This is the narrow version of the account-priority/routing behavior discussed in #545. It intentionally avoids the reset-display, quota-appearance, Docker/dev-deploy, and broader dashboard sorting changes from that PR so the routing contract can be reviewed independently.

#567 builds on this PR for opportunistic worker admission and traffic classes. The Spark/additional-quota routing policy lives here so the policy UI and routing contract are reviewed together with manual account routing.

Re-auth behavior

importWithoutOverwrite still preserves active duplicate imports as separate __copyN accounts. A re-authorized account with the same generated account id that is currently deactivated is treated as healing that account: fresh tokens/status/plan are written to the existing row, while manual routing policy and account history stay attached to the original account.

Validation

  • openspec validate add-manual-account-routing-policy --strict --no-interactive
  • /home/kom/proj/codex-lb/.venv/bin/python -m ruff check app/core/balancer/logic.py app/db/models.py app/db/alembic/versions/20260509_010000_add_additional_quota_routing_policies.py app/modules/proxy/load_balancer.py app/modules/settings app/modules/accounts app/modules/usage/additional_quota_keys.py tests/unit/test_load_balancer.py tests/integration/test_load_balancer_integration.py tests/integration/test_settings_api.py tests/integration/test_additional_usage_flow.py
  • /home/kom/proj/codex-lb/.venv/bin/python -m pytest tests/unit/test_load_balancer.py tests/integration/test_load_balancer_integration.py tests/integration/test_settings_api.py tests/integration/test_additional_usage_flow.py tests/integration/test_migrations.py -q
  • cd frontend && bun run test -- src/features/settings/schemas.test.ts src/features/settings/components/routing-settings.test.tsx src/features/accounts/components/account-usage-panel.test.tsx
  • cd frontend && bun run build
  • uv run ty check
  • /home/kom/proj/codex-lb/.venv/bin/python -m ruff format --check ... && git diff --check
  • Previously for the original routing-policy/re-auth scope: bun run typecheck, bun run lint, and targeted OAuth/repository tests listed in earlier revisions of this PR.

Note: full openspec validate --specs --strict --no-interactive still fails on current main for pre-existing placeholder Purpose text; that is fixed separately in #552 and is not included here to keep this PR based directly on main.

Related issues

@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: 4f9d00d6a5

ℹ️ 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 app/modules/accounts/mappers.py Resolved
@Komzpa
Komzpa force-pushed the feature/manual-account-routing-policy-clean branch from 4f9d00d to 414d16b Compare May 6, 2026 11:03
@Komzpa
Komzpa force-pushed the feature/manual-account-routing-policy-clean branch from 09a0580 to 22e62ff Compare May 7, 2026 04:06
@Soju06

Soju06 commented May 9, 2026

Copy link
Copy Markdown
Owner

@codex review

@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: a9d1dc2a1c

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

@Soju06

Soju06 commented May 9, 2026

Copy link
Copy Markdown
Owner

Thanks @Komzpa -- the policy/health-tier ordering, the OAuth re-auth heal path, and the codex_spark default-burn_first decision all look right. Codex review landed two P2 input-validation findings that I think are worth folding in before merge given the routing contract is touching the accounts API and settings update paths:

P2 -- normalize legacy account.routing_policy in the mapper

account.routing_policy flows through accounts/mappers.py verbatim. The frontend schema now validates routingPolicy as a strict enum (normal | burn_first | preserve), so any pre-existing row, manual SQL edit, or rolled-back deploy that left a value outside that set will make GET /api/accounts fail schema validation and break the dashboard accounts page entirely. Treat anything outside the enum as normal at the mapper boundary:

_VALID_ROUTING_POLICIES = {"normal", "burn_first", "preserve"}

def _coerce_routing_policy(value: str | None) -> str:
    if value not in _VALID_ROUTING_POLICIES:
        return "normal"
    return value

Then call _coerce_routing_policy(account.routing_policy) in the mapper. The migration default is "normal" so today's data is fine, but downgrade/upgrade cycles or operator overrides should not be able to brick the page.

P2 -- reject invalid additional_quota_routing_policies entries

The override normalizer in app/modules/usage/additional_quota_keys.py:243 silently drops unknown quota keys and coerces unknown policy values to "inherit". So a typo like {"codex_spark": "burnfrist"} returns 200 from the settings update endpoint and silently disables the burn_first default for Spark -- the operator thinks they re-applied the same policy with a typo and traffic shape silently changes.

The accounts mapper case is about tolerating historical bad data, but settings updates are new user input -- those should fail loud:

  • Unknown quota slug -\u003e raise a 422-style ClientPayloadError listing valid slugs (or at least the registered ones from config/additional_quota_registry.json).
  • Unknown policy value -\u003e raise a 422-style ClientPayloadError listing inherit | burn_first | normal | preserve.

The existing settings update flow already handles ValidationError paths, so wiring a clean error message is straightforward. Tests:

def test_additional_quota_policy_rejects_unknown_slug()
def test_additional_quota_policy_rejects_unknown_policy_value()

These should each assert a 422 (or whatever shape the existing settings update uses for client validation) and that the stored additional_quota_routing_policies_json is unchanged.

Not blocking

The OpenSpec change, the migrations, and the routing-policy pool wiring all look right. Only the two input-validation P2s above. Once those are in I'll re-run @codex review. Holding the merge until the new commit lands.

(Heads-up: #555 is still red in your stack -- one unit test on test_stream_responses_suppresses_duplicate_http_tool_call_bursts -- already commented there. Doesn't block this PR; #553 is independent.)

@chatgpt-codex-connector

Copy link
Copy Markdown

To use Codex here, create an environment for this repo.

@Komzpa

Komzpa commented May 16, 2026

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

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

@Komzpa Komzpa added 🤖 codex: ok [@codex review] says no issues found. and removed 🤖 codex: ok [@codex review] says no issues found. labels May 16, 2026
@Komzpa

Komzpa commented May 18, 2026

Copy link
Copy Markdown
Collaborator Author

@codex review

@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: 3131a8f6bc

ℹ️ 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 on lines +529 to +530
latest_primary = additional_filter.latest_primary
latest_secondary = additional_filter.latest_secondary

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Keep additional-quota windows out of persisted account status

When effective_limit_name is set, this path feeds additional_usage snapshots into latest_primary/latest_secondary, and those states are later persisted via _persist_selection_state() as canonical accounts.status/reset_at. That means an additional-quota request can overwrite standard quota state (e.g., flip a standard QUOTA_EXCEEDED account back to ACTIVE because the additional pool is under 100%), which then incorrectly re-enables regular Codex routing until another standard usage refresh runs. This regression is introduced here because pre-change persistence was based on standard usage_history, not the additional pool.

Useful? React with 👍 / 👎.

@Komzpa Komzpa added 🤖 codex: needs work [@codex review] raised an issue and removed 🤖 codex: needs work [@codex review] raised an issue labels May 18, 2026
@Komzpa

Komzpa commented May 18, 2026

Copy link
Copy Markdown
Collaborator Author

@codex review

@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: 6f498212dc

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

@@ -136,6 +155,8 @@ async def load_selection_inputs() -> _SelectionInputs:
runtime_accounts=selection_inputs.runtime_accounts,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Carry persist flag when rebuilding selection inputs

When exclude_account_ids is set, this branch rebuilds _SelectionInputs but omits persist_standard_quota_status, so it silently falls back to the dataclass default (True). For additional-quota-gated routing, _load_selection_inputs intentionally sets this flag to False; dropping it here re-enables _persist_selection_state and can write standard account status changes during additional-quota selection retries (the path used with additional_limit_name plus exclusions in ProxyService._select_account_with_budget). This can corrupt normal quota/status state and should preserve the original flag.

Useful? React with 👍 / 👎.

@Komzpa Komzpa added the 🤖 codex: needs work [@codex review] raised an issue label May 18, 2026
@Komzpa
Komzpa force-pushed the feature/manual-account-routing-policy-clean branch from 87dad14 to 32a3103 Compare May 20, 2026 15:49
@Komzpa
Komzpa force-pushed the feature/manual-account-routing-policy-clean branch from 32a3103 to bcf8ff6 Compare May 20, 2026 16:17
@Soju06 Soju06 added the 🤖 codex: needs work [@codex review] raised an issue label May 21, 2026
@Soju06

Soju06 commented May 21, 2026

Copy link
Copy Markdown
Owner

Maintainer cleanup: closing this as stale / no longer merge-ready against the current main.

This PR has been open across substantial main-branch churn and is currently carrying at least one stale signal (conflicts/blocked or failing checks, outstanding codex: needs work, draft/old branch state, or overlap with newer/current implementation). Keeping it open is making the PR queue harder to reason about.

If the change is still needed, please open a fresh, focused PR rebased on current main with green CI and a clean Codex review.

@Soju06 Soju06 closed this May 21, 2026
@Komzpa Komzpa added needs rebase Needs rebase or conflict repair against current main stale No response from reporter; scheduled for close labels May 21, 2026
@Komzpa

Komzpa commented May 21, 2026

Copy link
Copy Markdown
Collaborator Author

Revived on a maintainer-owned branch as #761 because this PR head has maintainerCanModify=false and cannot be updated here. Keeping credit to the original implementation in the replacement PR.

@Komzpa Komzpa added superseded Replaced by another PR, issue track, or merged implementation and removed 🤖 codex: needs work [@codex review] raised an issue needs rebase Needs rebase or conflict repair against current main labels May 21, 2026
@Soju06 Soju06 added the 🤖 codex: needs work [@codex review] raised an issue label May 21, 2026
@Komzpa Komzpa removed the 🤖 codex: needs work [@codex review] raised an issue label May 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

stale No response from reporter; scheduled for close superseded Replaced by another PR, issue track, or merged implementation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Account priority Feature request: allow manual account priority / ordered fallback routing

2 participants