fix(providers): update compaction retries in place (#6549)

* fix(providers): keep compaction retries in one status lifecycle

* refactor(providers): avoid redundant lifecycle copy on state reset
This commit is contained in:
chengyongru authored and GitHub committed 2026-11-03 18:17:45 +08:00
1 parent 80ac41b1f4
commit 3545539128
5 files changed
+196 -44

No files matched your search

+19 -11
View File
@@ -27,6 +27,7 @@ from nanobot.events import (
RetryWaitEvent,
)
from nanobot.llm_usage.types import LLMUsage as LLMUsage
from nanobot.providers.compaction import ProviderCompactionEvents, provider_compaction_scope
from nanobot.providers.generation import GenerationSettings as GenerationSettings
from nanobot.utils.cancellation import shield_and_drain
from nanobot.utils.helpers import sanitize_surrogates_deep
@@ -278,6 +279,8 @@ class ProviderCallContext:
response_is_fallback: bool = False
# A pre-request compactor must fit this budget before sending the pending input.
compaction_input_budget: int | None = None
# Owned by one retry chain, shared only by its provider attempts.
compaction: ProviderCompactionEvents | None = field(default=None, repr=False, compare=False)
@dataclass
@@ -1421,17 +1424,22 @@ class LLMProvider(ABC):
))
return response
return await self._run_with_retry(
attributed_call,
kw,
original_messages,
retry_mode=retry_mode,
on_retry_wait=on_retry_wait,
on_retry_exhausted=on_retry_exhausted,
on_retry_status=on_retry_status,
should_retry_guard=should_retry_guard,
on_stream_recover=on_stream_recover,
)
context = kw.get("provider_context")
events = context.events if isinstance(context, ProviderCallContext) else NO_EVENTS
async with provider_compaction_scope(events) as compaction:
if isinstance(context, ProviderCallContext):
kw["provider_context"] = replace(context, compaction=compaction)
return await self._run_with_retry(
attributed_call,
kw,
original_messages,
retry_mode=retry_mode,
on_retry_wait=on_retry_wait,
on_retry_exhausted=on_retry_exhausted,
on_retry_status=on_retry_status,
should_retry_guard=should_retry_guard,
on_stream_recover=on_stream_recover,
)
@classmethod
def _extract_retry_after(cls, content: str | None) -> float | None:
+50
View File
@@ -0,0 +1,50 @@
from __future__ import annotations
import asyncio
from collections.abc import AsyncGenerator
from contextlib import asynccontextmanager
from dataclasses import replace
from typing import Literal
from uuid import uuid4
from nanobot.events import CompactionReason, ContextCompactionEvent, EventSink
from nanobot.utils.cancellation import shield_and_drain
class ProviderCompactionEvents:
"""Keep one compaction pending across attempts in a provider retry chain."""
def __init__(self, events: EventSink) -> None:
self._events = events
self._active: ContextCompactionEvent | None = None
async def start(self, reason: CompactionReason) -> str:
if self._active is None:
self._active = ContextCompactionEvent(uuid4().hex, "started", reason=reason)
await self._events.emit(self._active)
return self._active.compaction_id
async def finish(self, phase: Literal["succeeded", "failed", "cancelled"]) -> None:
if self._active is None:
return
event = replace(self._active, phase=phase)
self._active = None
await shield_and_drain(self._events.emit(event))
@asynccontextmanager
async def provider_compaction_scope(
events: EventSink,
existing: ProviderCompactionEvents | None = None,
) -> AsyncGenerator[ProviderCompactionEvents]:
if existing is not None:
yield existing
return
compaction = ProviderCompactionEvents(events)
try:
yield compaction
except asyncio.CancelledError:
await compaction.finish("cancelled")
raise
finally:
await compaction.finish("failed")
+20 -27
View File
@@ -11,7 +11,6 @@ import re
import ssl
from collections.abc import Awaitable, Callable
from typing import Any, cast
from uuid import uuid4
import httpx
from loguru import logger
@@ -20,7 +19,7 @@ from oauth_cli_kit.providers import OPENAI_CODEX_PROVIDER
from oauth_cli_kit.storage import FileTokenStorage
from nanobot import __version__
from nanobot.events import NO_EVENTS, ContextCompactionEvent
from nanobot.events import NO_EVENTS
from nanobot.providers.base import (
CONTEXT_SAFETY_BUFFER,
LLMProvider,
@@ -29,6 +28,7 @@ from nanobot.providers.base import (
ProviderCallContext,
ProviderConversationState,
)
from nanobot.providers.compaction import provider_compaction_scope
from nanobot.providers.images import prepare_inline_images
from nanobot.providers.oauth_catalog_cache import (
OAuthCatalogAuthRequiredError,
@@ -51,7 +51,6 @@ from nanobot.providers.openai_responses.state import (
)
from nanobot.providers.openai_responses.websocket import ResponsesWebSocketError
from nanobot.providers.registry import ProviderModelSpec, find_by_name
from nanobot.utils.cancellation import shield_and_drain
from nanobot.utils.helpers import estimate_prompt_tokens
DEFAULT_CODEX_URL = "https://chatgpt.com/backend-api/codex/responses"
@@ -365,37 +364,31 @@ class OpenAICodexProvider(LLMProvider):
if self.supports_native_compaction(model) and replayed and sanitized_state is not None:
stage = "codex_compaction"
async def send_compaction(request: dict[str, Any]) -> LLMResponse:
nonlocal native_compaction_event_id
compaction_id = uuid4().hex
try:
await events.emit(ContextCompactionEvent(compaction_id, "started", reason="provider_native"))
async with provider_compaction_scope(
events, provider_context.compaction if provider_context else None,
) as compaction:
async def send_compaction(request: dict[str, Any]) -> LLMResponse:
nonlocal native_compaction_event_id
compaction_id = await compaction.start("provider_native")
compacted = await _send(
request,
emit_deltas=False,
trace_name="codex_compaction",
validate=responses_compaction_items,
)
except (Exception, asyncio.CancelledError) as exc:
await shield_and_drain(events.emit(ContextCompactionEvent(
compaction_id,
"cancelled" if isinstance(exc, asyncio.CancelledError) else "failed",
reason="provider_native",
)))
raise
native_compaction_event_id = compaction_id
await shield_and_drain(events.emit(ContextCompactionEvent(compaction_id, "succeeded", reason="provider_native")))
return compacted
native_compaction_event_id = compaction_id
await compaction.finish("succeeded")
return compacted
native_compaction_state = await self._responses.compact_before_request(
body, state=sanitized_state,
provider=self._responses_state_provider(), model=_strip_model_prefix(model),
context_window_tokens=(
provider_context.context_window_tokens if provider_context else None
),
max_output_tokens=max_tokens, input_budget=input_budget,
send=send_compaction,
)
native_compaction_state = await self._responses.compact_before_request(
body, state=sanitized_state,
provider=self._responses_state_provider(), model=_strip_model_prefix(model),
context_window_tokens=(
provider_context.context_window_tokens if provider_context else None
),
max_output_tokens=max_tokens, input_budget=input_budget,
send=send_compaction,
)
if input_budget is not None:
estimated = estimate_prompt_tokens([{
+86 -4
View File
@@ -1159,8 +1159,87 @@ async def test_codex_compacts_state_at_ninety_percent_before_next_request(
@pytest.mark.asyncio
@pytest.mark.parametrize("stream", [False, True])
@pytest.mark.parametrize("outcome", ["succeeded", "failed", "cancelled"])
async def test_codex_compaction_retries_share_one_lifecycle(monkeypatch, stream, outcome) -> None:
_mock_codex_token(monkeypatch)
provider = OpenAICodexProvider(default_model="openai-codex/gpt-5.6-sol")
state_provider = provider._responses_state_provider()
state = build_responses_state(
provider=state_provider, model="gpt-5.6-sol",
input_items=[{"type": "message", "role": "user", "content": "old"}],
output_items=[{"type": "reasoning", "encrypted_content": "opaque"}],
)
notices: list[ContextCompactionEvent] = []
attempts = 0
generations = 0
waiting = asyncio.Event()
async def observe(event) -> None:
if isinstance(event, ContextCompactionEvent):
notices.append(event)
async def fake_request(_url, _headers, body, **_kwargs):
nonlocal attempts, generations
if body["input"][-1].get("type") != "compaction_trigger":
generations += 1
return provider_base.LLMResponse(content="done")
attempts += 1
if outcome != "succeeded" or attempts <= 2:
raise httpx.ReadTimeout("synthetic compaction timeout")
return provider_base.LLMResponse(content=None, provider_state=build_responses_state(
provider=state_provider, model="gpt-5.6-sol", input_items=body["input"],
output_items=[{"type": "compaction", "encrypted_content": "compacted"}],
))
async def retry_wait(*_args, **_kwargs) -> None:
waiting.set()
assert [notice.phase for notice in notices] == ["started"]
if outcome == "cancelled":
await asyncio.Future()
monkeypatch.setattr("nanobot.providers.openai_codex_provider._request_codex", fake_request)
monkeypatch.setattr(provider, "_sleep_with_heartbeat", retry_wait)
context = provider_base.ProviderCallContext(
conversation_state=state.with_pending_messages([{"role": "user", "content": "new"}]),
context_window_tokens=4000, compaction_input_budget=10000, events=EventSink(observe),
)
call = provider.chat_stream_with_retry if stream else provider.chat_with_retry
task = asyncio.create_task(call(
[{"role": "user", "content": "new"}], max_tokens=5, provider_context=context,
))
if outcome == "cancelled":
await asyncio.wait_for(waiting.wait(), timeout=2)
task.cancel()
with pytest.raises(asyncio.CancelledError):
await task
else:
response = await task
assert response.finish_reason == ("stop" if outcome == "succeeded" else "error")
assert attempts == (3 if outcome == "succeeded" else len(provider._CHAT_RETRY_DELAYS) + 1)
assert generations == (1 if outcome == "succeeded" else 0)
if outcome == "succeeded":
assert response.provider_compaction_event_id == notices[0].compaction_id
assert [notice.phase for notice in notices] == ["started", outcome]
assert len({notice.compaction_id for notice in notices}) == 1
assert all(notice.reason == "provider_native" for notice in notices)
if outcome == "succeeded":
first_id = notices[0].compaction_id
notices.clear()
response = await call(
[{"role": "user", "content": "new"}], max_tokens=5, provider_context=context,
)
assert [notice.phase for notice in notices] == ["started", "succeeded"]
assert notices[0].compaction_id != first_id
assert response.provider_compaction_event_id == notices[0].compaction_id
@pytest.mark.asyncio
@pytest.mark.parametrize("retry", [False, True])
async def test_codex_disables_unsupported_native_compaction_and_continues(
monkeypatch,
monkeypatch, retry,
) -> None:
_mock_codex_token(monkeypatch)
provider = OpenAICodexProvider(default_model="openai-codex/gpt-5.6-sol")
@@ -1212,7 +1291,8 @@ async def test_codex_disables_unsupported_native_compaction_and_continues(
fake_request,
)
response = await provider.chat(
call = provider.chat_with_retry if retry else provider.chat
response = await call(
[{"role": "user", "content": "new"}],
max_tokens=5,
provider_context=provider_base.ProviderCallContext(
@@ -1235,8 +1315,9 @@ async def test_codex_disables_unsupported_native_compaction_and_continues(
@pytest.mark.asyncio
@pytest.mark.parametrize("retry", [False, True])
@pytest.mark.parametrize("cancel_during", ["compaction", "terminal", "generation"])
async def test_codex_native_compaction_terminal_survives_cancellation(monkeypatch, cancel_during) -> None:
async def test_codex_native_compaction_terminal_survives_cancellation(monkeypatch, cancel_during, retry) -> None:
_mock_codex_token(monkeypatch)
provider = OpenAICodexProvider(default_model="openai-codex/gpt-5.6-sol")
state_provider = provider._responses_state_provider()
@@ -1270,7 +1351,8 @@ async def test_codex_native_compaction_terminal_survives_cancellation(monkeypatc
))
monkeypatch.setattr("nanobot.providers.openai_codex_provider._request_codex", fake_request)
task = asyncio.create_task(provider.chat(
call = provider.chat_with_retry if retry else provider.chat
task = asyncio.create_task(call(
[{"role": "user", "content": "new"}], max_tokens=5,
provider_context=provider_base.ProviderCallContext(
conversation_state=state.with_pending_messages([{"role": "user", "content": "new"}]),
+21 -2
View File
@@ -181,7 +181,7 @@ test("idle compaction stays singular across live updates, thread refresh and col
backend.healthy();
});
test("pre-request compaction precedes the answer in live output and history replay", async ({ page }) => {
test("pre-request compaction stays in place through retries and precedes the answer in history", async ({ page }) => {
const { backend, body } = await openFixture(page);
const base = closedTurn("before-native", "Previous question", "Previous answer.");
await backend.release(await backend.read(), history(base));
@@ -190,14 +190,33 @@ test("pre-request compaction precedes the answer in live output and history repl
const compact: ThreadProjectionEvent = { ...at(TURN, 2, "activity"), event: "context_compaction", compaction_id: "native-before-answer", phase: "succeeded" };
await backend.send(question);
await backend.send({ event: "context_compaction", chat_id: A, compaction_id: "native-before-answer", phase: "started" });
const notice = body.locator("[data-context-compaction]");
await expect(notice).toHaveCount(1);
await notice.evaluate((element) => { element.setAttribute("data-retry-notice", "original"); });
for (const attempt of [1, 2]) {
await backend.send({ event: "retry_status", chat_id: A, state: "waiting", attempt,
max_attempts: 4, error_kind: "timeout", retry_after_s: 1 });
await expect(notice).toHaveCount(1);
await expect(notice).toHaveAttribute("data-context-compaction", "started");
await expect(notice).toHaveAttribute("data-retry-notice", "original");
}
await backend.send(compact);
await expect(notice).toHaveCount(1);
await expect(notice).toHaveAttribute("data-context-compaction", "succeeded");
await backend.send(delta(3, LIVE));
await backend.send(end(4, LIVE, "live-wire"));
const complete: ThreadProjectionEvent = { ...at(TURN, 5, "complete"), event: "turn_end" };
await backend.send(complete);
await expectBefore(body, "Context compacted", LIVE);
const completed = history([...base, question, compact, end(4, LIVE, "live-wire"), complete]);
backend.refreshThread();
await backend.release(await backend.read(A, null, 1), history([...base, question, compact, end(4, LIVE, "live-wire"), complete]));
await backend.release(await backend.read(A, null, 1), completed);
await expect(body.locator('[data-context-compaction="succeeded"]')).toHaveCount(1);
await expectBefore(body, "Context compacted", LIVE);
await page.reload();
await backend.ready();
await backend.release(await backend.read(A, null, 2), completed);
await expect(body.locator("[data-context-compaction]")).toHaveCount(1);
await expect(body.locator('[data-context-compaction="succeeded"]')).toHaveCount(1);
await expectBefore(body, "Context compacted", LIVE);
backend.healthy();