Skip to content

refactor(chatCore): extrai núcleo puro de persistCodexQuotaState (#3501) - #4492

Merged
diegosouzapw merged 1 commit into
release/v3.8.33from
refactor/qg-chatcore-codexquota
Jun 21, 2026
Merged

diegosouzapw merged 1 commit into
release/v3.8.33from
refactor/qg-chatcore-codexquota

Conversation

@diegosouzapw

Copy link
Copy Markdown
Owner

O quê

Próximo incremento da decomposição do god-file chatCore.ts (QG v2 Fase 9 T5, #3501). Extrai o núcleo puro de persistCodexQuotaState para o novo leaf open-sse/handlers/chatCore/codexQuota.ts (buildCodexQuotaPersistence).

Stacked sobre o #4491 (que está stacked sobre o #4477). Base aponta para refactor/qg-chatcore-keyhealth; o GitHub re-aponta a cadeia automaticamente conforme os pais mergeiam.

Como (preservação de comportamento)

  • Extração parcial pura: buildCodexQuotaPersistence parseia os headers de quota → snapshot codexQuotaState, faz passthrough do providerSpecificData existente e, num 429 cuja janela (dual-window) passou do threshold de exaustão, registra codexScopeRateLimitedUntil[scope] + codexExhaustedWindow, retornando a mensagem de debug-log (em vez de emiti-la).
  • O handler mantém as partes impuras byte-idênticas e na mesma ordem: emite o exhaustionLog retornado → invalidateCodexQuotaCache em todo 429 (connectionId é garantido pelo early-return) → updateProviderConnection → mutação de credentials.providerSpecificData.
  • Imports órfãos (parseCodexQuotaHeaders / getCodexModelScope / getCodexDualWindowCooldownMs) migram para o leaf; isCompactResponsesEndpoint permanece (usado no site de passthrough).

Gates

  • file-size: chatCore.ts 5055→5019 (shrink −36); baseline ratchetado.
  • complexity: 1905 = baseline 1905 (neutro).
  • typecheck:core: exit 0.
  • Testes: tests/unit/chatcore-codex-quota.test.ts — 5 casos (sem-headers→null, snapshot+passthrough do existing data, 429 com cooldown+janela+log, merge do codexScopeRateLimitedUntil preservando outros escopos, 429 abaixo do threshold = no-op). chatcore-imports-cleanly ✓ + integração codex (executor-codex + sse-auth) 107/107 + 139/139 na suíte chatcore (excluído só o translation-paths flaky pré-existente).

Extração de god-file sem mudança de comportamento em runtime.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@gemini-code-assist gemini-code-assist Bot 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.

Code Review

This pull request refactors open-sse/handlers/chatCore.ts by extracting the pure logic of persistCodexQuotaState into a new helper function buildCodexQuotaPersistence in open-sse/handlers/chatCore/codexQuota.ts, accompanied by unit tests in tests/unit/chatcore-codex-quota.test.ts. The review feedback highlights two key areas for improvement: first, protecting against a potential TypeError when assigning credentials.providerSpecificData if credentials is undefined; second, enhancing the purity and determinism of buildCodexQuotaPersistence by deriving the absolute reset time directly from the quota headers instead of recalculating it using Date.now() and cooldownMs.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

});

credentials.providerSpecificData = nextProviderData;
credentials.providerSpecificData = built.nextProviderData;

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.

high

Se credentials for nulo ou indefinido, a atribuição direta a credentials.providerSpecificData lançará um TypeError e quebrará o handler da requisição. Como credentials é acessado defensivamente com encadeamento opcional (optional chaining) na linha 771, devemos também proteger esta atribuição para evitar possíveis falhas em tempo de execução.

      if (credentials) {
        credentials.providerSpecificData = built.nextProviderData;
      }

if (status === 429) {
const { cooldownMs, window: exhaustedWindow } = getCodexDualWindowCooldownMs(quota);
if (cooldownMs > 0) {
const scopeUntil = new Date(Date.now() + cooldownMs).toISOString();

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.

medium

Reconstruir scopeUntil adicionando Date.now() a cooldownMs introduz um pequeno desvio de relógio (clock drift) e não-determinismo, pois cooldownMs foi originalmente computado como resetTime - Date.now(). Como buildCodexQuotaPersistence deve ser uma função pura, podemos determinar o tempo de reset absoluto diretamente de quota.resetAt7d ou quota.resetAt5h com base em exhaustedWindow, recorrendo ao cálculo relativo apenas se necessário.

Suggested change
const scopeUntil = new Date(Date.now() + cooldownMs).toISOString();
const resetAt = exhaustedWindow === "7d" ? quota.resetAt7d : quota.resetAt5h;
const scopeUntil = resetAt ? new Date(resetAt).toISOString() : new Date(Date.now() + cooldownMs).toISOString();

Move a construção do payload de persistCodexQuotaState para o novo leaf puro
open-sse/handlers/chatCore/codexQuota.ts (buildCodexQuotaPersistence): parseia
os headers de quota do Codex no snapshot codexQuotaState, faz passthrough do
providerSpecificData existente e, num 429 cuja janela (dual-window) passou do
threshold de exaustão, registra o cooldown por escopo (codexScopeRateLimitedUntil)
+ codexExhaustedWindow, retornando a mensagem de debug-log.

O handler mantém as partes impuras byte-idênticas e na mesma ordem: emitir o
exhaustionLog retornado, invalidateCodexQuotaCache em todo 429 (connectionId é
garantido pelo early-return), depois updateProviderConnection + mutação de
credentials. Imports órfãos (parseCodexQuotaHeaders/getCodexModelScope/
getCodexDualWindowCooldownMs) migram para o leaf; isCompactResponsesEndpoint
permanece (usado no site de passthrough).

chatCore.ts 5055->5019 (shrink -36); baseline file-size ratchetado.
complexity 1905=1905 (neutro). Coberto por
tests/unit/chatcore-codex-quota.test.ts (5 casos: sem-headers null,
snapshot+passthrough, 429 cooldown+janela+log, merge do scope-map, 429
abaixo-do-threshold no-op).
@diegosouzapw
diegosouzapw force-pushed the refactor/qg-chatcore-codexquota branch from 368b433 to b12c80f Compare June 21, 2026 17:19
@diegosouzapw
diegosouzapw merged commit b28f6e9 into release/v3.8.33 Jun 21, 2026
3 checks passed
@diegosouzapw diegosouzapw mentioned this pull request Jun 22, 2026
tkgo11 pushed a commit to tkgo11/OmniRoute that referenced this pull request Sep 23, 2026
…uzapw#4492, diegosouzapw#3501)

Rebuilt onto release/v3.8.33. Extracts persistCodexQuotaState into a pure leaf (chatCore/codexQuota.ts). Integrated into release/v3.8.33.
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