Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

fix(update): finish --full when a few pages fail, and stop truncating Ollama prompts (#2564)

Raghav Chamadiya8514f7070e01
diff --git a/docs/reference/CONFIG.md b/docs/reference/CONFIG.md
index 970272845..1ce14e019 100644
--- a/docs/reference/CONFIG.md
+++ b/docs/reference/CONFIG.md
@@ -784,6 +784,12 @@ export OLLAMA_BASE_URL="http://localhost:11434"
repowise init --provider ollama --model llama3.2
```
+Repowise sizes the model's context window (`num_ctx`) to each prompt, so pages
+are not cut to Ollama's small default window. Set `REPOWISE_OLLAMA_NUM_CTX` to
+pin it instead, for example to stay within a machine's memory. Requests are sent
+one at a time; if the server runs with `OLLAMA_NUM_PARALLEL` above 1, set the
+same value where you run repowise to send that many at once.
+
### LiteLLM (100+ providers)
```bash
@@ -920,6 +926,8 @@ The `.repowise/.env` file is gitignored automatically.
| `OPENAI_BASE_URL` | Override the OpenAI API base URL (used for vLLM/SGLang, 9router, and other compatible endpoints) |
| `GEMINI_BASE_URL` | Override the Gemini API base URL |
| `OLLAMA_BASE_URL` | Ollama server URL (default: `http://localhost:11434`) |
+| `REPOWISE_OLLAMA_NUM_CTX` | Fixed Ollama context window; unset sizes it to each prompt |
+| `OLLAMA_NUM_PARALLEL` | Ollama requests repowise sends at once (default: 1) |
| `DEEPSEEK_BASE_URL` | Override the DeepSeek API base URL |
| `KIMI_BASE_URL` | Override the Kimi API base URL |
| `LITELLM_BASE_URL` | Override the LiteLLM proxy base URL |
diff --git a/packages/cli/src/repowise/cli/commands/upgrade_flow.py b/packages/cli/src/repowise/cli/commands/upgrade_flow.py
index 66c5529ea..a6767fb03 100644
--- a/packages/cli/src/repowise/cli/commands/upgrade_flow.py
+++ b/packages/cli/src/repowise/cli/commands/upgrade_flow.py
@@ -384,15 +384,19 @@ async def _run_upgrade(
generation_config=config,
selection_out=generation_scope,
)
- from repowise.core.generation.models import count_stub_fallbacks
+ from repowise.core.generation.models import (
+ STUB_FALLBACK_ERROR,
+ count_stub_fallbacks,
+ is_stub_fallback,
+ )
+ # A page the model failed keeps its placeholder, which `repowise generate`
+ # refills. Failing the run over it would discard every page that succeeded.
stub_fallbacks = count_stub_fallbacks(generated_pages)
- if stub_fallbacks:
- await engine.dispose()
- raise RuntimeError(
- f"Model generation returned {stub_fallbacks} fallback page(s); "
- "the prior index remains active and the upgrade can be retried"
- )
+ stub_reasons = sorted(
+ {str(p.metadata.get(STUB_FALLBACK_ERROR, "")).strip() for p in generated_pages if is_stub_fallback(p)}
+ - {""}
+ )
if checkpoint:
checkpoint("generation")
@@ -570,10 +574,24 @@ async def _run_upgrade(
"next_command": "repowise reindex" if vector_store is None else None,
},
"embedding_error": embedding_error,
+ "stub_fallbacks": stub_fallbacks,
+ "stub_reasons": stub_reasons,
},
)
+def _report_placeholders(count: int, reasons: list[str]) -> None:
+ """Name the pages the model failed and the command that refills them."""
+ if not count:
+ return
+ lines = "".join(f" [dim]· {r[:160]}[/dim]\n" for r in reasons[:3])
+ console.print(
+ f"[yellow]{count} page(s) could not be written by the model[/yellow] "
+ f"and kept a placeholder rendered from structure.\n{lines}"
+ " Run [bold]repowise generate[/bold] to write just those pages."
+ )
+
+
def upgrade_to_full(
repo_path: Path,
*,
@@ -860,6 +878,7 @@ def upgrade_to_full(
f"[bold green]Upgrade complete[/bold green] in {elapsed:.1f}s — "
f"{len(generated_pages)} pages generated, git tier now FULL."
)
+ _report_placeholders(outcome.get("stub_fallbacks", 0), outcome.get("stub_reasons", []))
if outcome["search"]["semantic"] != "available":
console.print(
"[yellow]Semantic search is unavailable.[/yellow] Set an embedder key and run "
diff --git a/packages/core/src/repowise/core/providers/llm/ollama.py b/packages/core/src/repowise/core/providers/llm/ollama.py
index a5e2f7047..5c026d935 100644
--- a/packages/core/src/repowise/core/providers/llm/ollama.py
+++ b/packages/core/src/repowise/core/providers/llm/ollama.py
@@ -20,10 +20,14 @@ Usage:
from __future__ import annotations
+import asyncio
+import contextlib
+import json
import os
from collections.abc import AsyncIterator
from typing import Any
+import httpx
import structlog
from openai import AsyncOpenAI
from tenacity import RetryError, retry
@@ -34,18 +38,17 @@ from repowise.core.providers.llm.base import (
GeneratedResponse,
ProviderError,
ProviderModelOption,
+ RateLimitError,
ensure_reasoning_supported,
fallback_model_option,
+ normalize_stop_reason,
+ parse_retry_after,
provider_retry_stop,
provider_retry_wait,
provider_should_retry,
record_generation_cost,
)
-from repowise.core.providers.llm.openai_compat import (
- completion_to_response,
- stream_openai_chat,
- translate_openai_errors,
-)
+from repowise.core.providers.llm.openai_compat import stream_openai_chat
from repowise.core.rate_limiter import RateLimiter
from repowise.core.reasoning import ReasoningMode
@@ -53,6 +56,10 @@ log = structlog.get_logger(__name__)
_DEFAULT_BASE_URL = "http://localhost:11434"
_OLLAMA_REASONING_MODES: tuple[ReasoningMode, ...] = ("off",)
+_MIN_NUM_CTX = 8192
+# Streamed, so the read timeout bounds silence between chunks, not the whole
+# page. It still has to cover prompt evaluation, which streams nothing.
+_STREAM_TIMEOUT = httpx.Timeout(1200.0, connect=10.0)
def _normalize_base_url(url: str) -> str:
@@ -63,11 +70,9 @@ def _normalize_base_url(url: str) -> str:
return url
-def _ollama_reasoning_kwargs(reasoning: ReasoningMode) -> dict[str, Any]:
- """Translate a validated repowise reasoning intent to Ollama kwargs."""
- if reasoning == "off":
- return {"reasoning_effort": "none"}
- return {}
+def _positive_int_env(name: str) -> int | None:
+ raw = os.environ.get(name, "").strip()
+ return int(raw) if raw.isdigit() and int(raw) > 0 else None
def _ollama_model_options(
@@ -129,7 +134,8 @@ def _ollama_model_options(
class OllamaProvider(BaseProvider):
"""Ollama provider for local, offline LLM inference.
- Uses Ollama's OpenAI-compatible endpoint. No API key required.
+ Generation uses Ollama's native chat API; streaming chat uses the
+ OpenAI-compatible endpoint. No API key required.
Args:
model: Ollama model name (e.g., 'qwen3.5:4b', 'llama3.2').
@@ -156,8 +162,13 @@ class OllamaProvider(BaseProvider):
self._client = AsyncOpenAI(
api_key="ollama", base_url=_normalize_base_url(resolved_base_url)
)
+ self._native_url = self._base_url.removesuffix("/v1")
self._model = model
self._rate_limiter = rate_limiter
+ self._fixed_num_ctx = _positive_int_env("REPOWISE_OLLAMA_NUM_CTX")
+ self._num_ctx = _MIN_NUM_CTX
+ self._parallel = _positive_int_env("OLLAMA_NUM_PARALLEL") or 1
+ self._slots: tuple[asyncio.AbstractEventLoop, asyncio.Semaphore] | None = None
@property
def provider_name(self) -> str:
@@ -171,7 +182,7 @@ class OllamaProvider(BaseProvider):
return ("auto", *_OLLAMA_REASONING_MODES)
def available_model_options(self) -> tuple[ProviderModelOption, ...]:
- return _ollama_model_options(self._base_url, self._model)
+ return _ollama_model_options(self._native_url, self._model)
async def generate(
self,
@@ -189,8 +200,7 @@ class OllamaProvider(BaseProvider):
reasoning,
_OLLAMA_REASONING_MODES,
detail=(
- "Ollama maps reasoning='off' to reasoning_effort='none' "
- "through its OpenAI-compatible chat completions API."
+ "Ollama maps reasoning='off' to think=false on its chat API."
),
)
if self._rate_limiter:
@@ -244,28 +254,112 @@ class OllamaProvider(BaseProvider):
request_id: str | None,
reasoning: ReasoningMode,
) -> GeneratedResponse:
- request_kwargs: dict[str, Any] = {
- "model": self._model,
- "max_tokens": max_tokens,
+ # The native endpoint, because the OpenAI-compatible one ignores
+ # num_ctx and silently cuts every prompt to the server's default window.
+ options = {
+ "num_predict": max_tokens,
"temperature": temperature,
+ "num_ctx": self._context_window(system_prompt, user_prompt, max_tokens),
+ }
+ payload: dict[str, Any] = {
+ "model": self._model,
"messages": [
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt},
],
+ "stream": True,
+ "options": options,
}
- request_kwargs.update(_ollama_reasoning_kwargs(reasoning))
- with translate_openai_errors("ollama"):
- response = await self._client.chat.completions.create(**request_kwargs)
-
- result = completion_to_response(response, include_total_tokens=False)
+ if reasoning == "off":
+ payload["think"] = False
+
+ content, final = await self._stream_native_chat(payload)
+ input_tokens = int(final.get("prompt_eval_count") or 0)
+ output_tokens = int(final.get("eval_count") or 0)
+ stop_reason, provider_stop_reason = normalize_stop_reason(final.get("done_reason"))
+ result = GeneratedResponse(
+ content=content,
+ input_tokens=input_tokens,
+ output_tokens=output_tokens,
+ cached_tokens=0,
+ stop_reason=stop_reason,
+ provider_stop_reason=provider_stop_reason,
+ usage={"prompt_tokens": input_tokens, "completion_tokens": output_tokens},
+ )
log.debug(
"ollama.generate.done",
input_tokens=result.input_tokens,
output_tokens=result.output_tokens,
+ num_ctx=options["num_ctx"],
request_id=request_id,
)
return result
+ async def _stream_native_chat(self, payload: dict[str, Any]) -> tuple[str, dict[str, Any]]:
+ """POST to /api/chat and return the streamed text and the final chunk."""
+ parts: list[str] = []
+ final: dict[str, Any] = {}
+ try:
+ async with (
+ self._request_slots(),
+ httpx.AsyncClient(timeout=_STREAM_TIMEOUT) as http,
+ http.stream("POST", f"{self._native_url}/api/chat", json=payload) as resp,
+ ):
+ if resp.status_code >= 400:
+ body = (await resp.aread()).decode("utf-8", errors="replace")[:500]
+ with contextlib.suppress(ValueError, KeyError, TypeError):
+ body = str(json.loads(body)["error"])
+ if resp.status_code == 429:
+ raise RateLimitError(
+ "ollama",
+ body,
+ status_code=429,
+ retry_after=parse_retry_after(resp.headers),
+ )
+ raise ProviderError("ollama", body, status_code=resp.status_code)
+ async for line in resp.aiter_lines():
+ if not line.strip():
+ continue
+ chunk = json.loads(line)
+ if chunk.get("error"):
+ raise ProviderError("ollama", str(chunk["error"]))
+ parts.append((chunk.get("message") or {}).get("content") or "")
+ if chunk.get("done"):
+ final = chunk
+ except httpx.HTTPError as exc:
+ raise ProviderError("ollama", f"{type(exc).__name__}: {exc}") from exc
+ except ValueError as exc:
+ raise ProviderError("ollama", f"unreadable response: {exc}") from exc
+ return "".join(parts), final
+
+ def _context_window(self, system_prompt: str, user_prompt: str, max_tokens: int) -> int:
+ """num_ctx that fits this request, never shrinking between calls.
+
+ Ollama reloads the model whenever num_ctx changes, so the window only
+ grows, in powers of two. Two characters per token overestimates prose
+ and all but the densest code.
+ """
+ if self._fixed_num_ctx:
+ return self._fixed_num_ctx
+ needed = (len(system_prompt) + len(user_prompt)) // 2 + max_tokens
+ window = _MIN_NUM_CTX
+ while window < needed:
+ window *= 2
+ self._num_ctx = max(self._num_ctx, window)
+ return self._num_ctx
+
+ def _request_slots(self) -> asyncio.Semaphore:
+ """Cap in-flight requests at what the server runs at once.
+
+ Requests past OLLAMA_NUM_PARALLEL queue inside the server, where the
+ wait counts against their timeout. Queueing here instead keeps the
+ timeout about generation. One semaphore per event loop.
+ """
+ loop = asyncio.get_running_loop()
+ if self._slots is None or self._slots[0] is not loop:
+ self._slots = (loop, asyncio.Semaphore(self._parallel))
+ return self._slots[1]
+
# --- ChatProvider protocol implementation ---
async def stream_chat(
diff --git a/tests/unit/cli/test_full_upgrade_state.py b/tests/unit/cli/test_full_upgrade_state.py
index cf93ee132..450f6e496 100644
--- a/tests/unit/cli/test_full_upgrade_state.py
+++ b/tests/unit/cli/test_full_upgrade_state.py
@@ -1,10 +1,12 @@
from __future__ import annotations
+import io
import subprocess
from pathlib import Path
from types import SimpleNamespace
import pytest
+from rich.console import Console
from repowise.cli.commands import upgrade_flow
from repowise.cli.helpers import load_state, save_state
@@ -146,3 +148,41 @@ def test_upgrade_cancellation_keeps_retryable_checkpoint(
assert state["full_upgrade"]["status"] == "resumable"
assert state["full_upgrade"]["retryable"] is True
assert state["full_upgrade"]["next_stage"] == "search"
+
+
+def test_upgrade_with_placeholder_pages_completes_and_names_the_fix(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ repo = _repo(tmp_path)
+ _provider(monkeypatch)
+ out = io.StringIO()
+ monkeypatch.setattr(upgrade_flow, "console", Console(file=out, width=200))
+
+ async def with_placeholders(*args, **kwargs):
+ for stage in ("git_backfill", "generation", "search", "health"):
+ kwargs["checkpoint"](stage)
+ return (
+ [],
+ 10,
+ {
+ "git_history_coverage": None,
+ "file_pages": {"configured_cap": None},
+ "search": {"full_text": "available", "semantic": "available", "next_command": None},
+ "embedding_error": None,
+ "stub_fallbacks": 2,
+ "stub_reasons": ["ollama: model runner has unexpectedly stopped"],
+ },
+ )
+
+ monkeypatch.setattr(upgrade_flow, "_run_upgrade", with_placeholders)
+ upgrade_flow.upgrade_to_full(
+ repo, provider_name=None, model=None, reasoning=None, concurrency=1, yes=True
+ )
+
+ state = load_state(repo)
+ assert state["full_upgrade"]["status"] == "complete"
+ assert state["git_tier"] == "full"
+ printed = out.getvalue()
+ assert "2 page(s) could not be written" in printed
+ assert "model runner has unexpectedly stopped" in printed
+ assert "repowise generate" in printed
diff --git a/tests/unit/test_providers/test_ollama_provider.py b/tests/unit/test_providers/test_ollama_provider.py
index af64c6a7e..f72ef4fb3 100644
--- a/tests/unit/test_providers/test_ollama_provider.py
+++ b/tests/unit/test_providers/test_ollama_provider.py
@@ -2,15 +2,14 @@
from __future__ import annotations
-from unittest.mock import AsyncMock, MagicMock
+import asyncio
+import json
import httpx
import pytest
pytest.importorskip("openai", reason="openai SDK not installed")
-from openai import APIConnectionError, APIError, APIStatusError, APITimeoutError
-
from repowise.core.providers.llm.base import ProviderError
from repowise.core.providers.llm.ollama import OllamaProvider
@@ -60,108 +59,173 @@ def test_available_model_options_reads_local_tags(monkeypatch):
assert llama.reasoning_modes == ("auto", "off")
-def _make_mock_chat_response(text: str = "# Doc\nContent.") -> MagicMock:
- usage = MagicMock()
- usage.prompt_tokens = 120
- usage.completion_tokens = 60
+_REAL_ASYNC_CLIENT = httpx.AsyncClient
- choice = MagicMock()
- choice.message.content = text
- response = MagicMock()
- response.choices = [choice]
- response.usage = usage
- return response
+def _serve(monkeypatch, handler) -> list[httpx.Request]:
+ """Route the provider's HTTP calls to ``handler`` and record each request."""
+ seen: list[httpx.Request] = []
+ async def recording(request: httpx.Request) -> httpx.Response:
+ seen.append(request)
+ response = handler(request, len(seen))
+ return await response if asyncio.iscoroutine(response) else response
-async def test_generate_auto_preserves_existing_request_shape():
- provider = OllamaProvider(model="test")
- provider._client.chat.completions.create = AsyncMock(return_value=_make_mock_chat_response())
+ monkeypatch.setattr(
+ httpx,
+ "AsyncClient",
+ lambda **kw: _REAL_ASYNC_CLIENT(transport=httpx.MockTransport(recording), **kw),
+ )
+ return seen
- await provider.generate("system", "user", reasoning="auto")
- request_kwargs = provider._client.chat.completions.create.await_args.kwargs
- assert "reasoning_effort" not in request_kwargs
+def _stream(text: str = "Generated wiki content") -> httpx.Response:
+ lines = [
+ {"message": {"role": "assistant", "content": text[:5]}, "done": False},
+ {"message": {"role": "assistant", "content": text[5:]}, "done": False},
+ {
+ "message": {"role": "assistant", "content": ""},
+ "done": True,
+ "done_reason": "stop",
+ "prompt_eval_count": 10,
+ "eval_count": 20,
+ },
+ ]
+ return httpx.Response(200, text="\n".join(json.dumps(line) for line in lines))
-async def test_generate_off_disables_reasoning():
- provider = OllamaProvider(model="test")
- provider._client.chat.completions.create = AsyncMock(return_value=_make_mock_chat_response())
+def _body(request: httpx.Request) -> dict:
+ return json.loads(request.content)
- await provider.generate("system", "user", reasoning="off")
- request_kwargs = provider._client.chat.completions.create.await_args.kwargs
- assert request_kwargs["reasoning_effort"] == "none"
+def _provider(base_url: str = "http://localhost:9999") -> OllamaProvider:
+ return OllamaProvider(model="test-model", base_url=base_url)
[email protected]("reasoning", ["none", "minimal", "low"])
-async def test_generate_rejects_unsupported_reasoning_modes(reasoning):
- provider = OllamaProvider(model="test")
- provider._client.chat.completions.create = AsyncMock()
+async def test_generate_uses_native_chat_with_a_context_window(monkeypatch):
+ seen = _serve(monkeypatch, lambda request, n: _stream())
+
+ result = await _provider().generate("system", "user", max_tokens=100)
+
+ assert str(seen[0].url) == "http://localhost:9999/api/chat"
+ body = _body(seen[0])
+ assert body["model"] == "test-model"
+ assert body["stream"] is True
+ assert body["options"]["num_predict"] == 100
+ assert body["options"]["num_ctx"] == 8192
+ assert "think" not in body
+ assert result.content == "Generated wiki content"
+ assert (result.input_tokens, result.output_tokens) == (10, 20)
+ assert (result.stop_reason, result.provider_stop_reason) == ("end_turn", "stop")
+
+async def test_base_url_with_v1_suffix_still_reaches_native_api(monkeypatch):
+ seen = _serve(monkeypatch, lambda request, n: _stream())
+ await _provider("http://localhost:9999/v1").generate("s", "u", max_tokens=10)
+ assert str(seen[0].url) == "http://localhost:9999/api/chat"
+
+
+async def test_generate_off_disables_thinking(monkeypatch):
+ seen = _serve(monkeypatch, lambda request, n: _stream())
+ await _provider().generate("system", "user", reasoning="off")
+ assert _body(seen[0])["think"] is False
+
+
[email protected]("reasoning", ["none", "minimal", "low"])
+async def test_generate_rejects_unsupported_reasoning_modes(monkeypatch, reasoning):
+ seen = _serve(monkeypatch, lambda request, n: _stream())
with pytest.raises(ProviderError, match=f"reasoning='{reasoning}' is not supported"):
- await provider.generate("system", "user", reasoning=reasoning)
+ await _provider().generate("system", "user", reasoning=reasoning)
+ assert seen == []
- provider._client.chat.completions.create.assert_not_called()
+async def test_context_window_grows_to_fit_and_never_shrinks(monkeypatch):
+ seen = _serve(monkeypatch, lambda request, n: _stream())
+ provider = _provider()
-async def _assert_generate_wraps(exc: Exception) -> None:
- """Drive ``generate`` with a client that raises ``exc`` and assert the
- error is caught and re-raised as a provider-tagged ``ProviderError``.
+ await provider.generate("s", "x" * 40_000, max_tokens=4096)
+ await provider.generate("s", "short", max_tokens=100)
- Shared by the #445 regression cases below: only ``APIStatusError`` used to
- be caught, so timeout/connection errors escaped uncaught, skipped tenacity
- (which retries ``ProviderError`` only), and surfaced as
- ``page_generation_failed``.
- """
- provider = OllamaProvider(model="test", base_url="http://localhost:9999")
- provider._rate_limiter = None
- provider._client.chat.completions.create = AsyncMock(side_effect=exc)
- with pytest.raises(ProviderError) as exc_info:
- await provider.generate(system_prompt="", user_prompt="", max_tokens=10)
- assert "ollama" in str(exc_info.value)
+ assert [_body(r)["options"]["num_ctx"] for r in seen] == [32768, 32768]
-def _status_error() -> APIStatusError:
- resp = AsyncMock()
- resp.status_code = 500
- return APIStatusError("Internal Server Error", response=resp, body="")
+async def test_context_window_env_override(monkeypatch):
+ monkeypatch.setenv("REPOWISE_OLLAMA_NUM_CTX", "12000")
+ seen = _serve(monkeypatch, lambda request, n: _stream())
+ await _provider().generate("s", "x" * 60_000, max_tokens=4096)
+ assert _body(seen[0])["options"]["num_ctx"] == 12000
-def _connection_error() -> APIConnectionError:
- request = httpx.Request("POST", "http://localhost:9999/v1/chat/completions")
- return APIConnectionError(message="Connection refused", request=request)
[email protected]("parallel, expected", [(None, 1), ("2", 2)])
+async def test_in_flight_requests_capped_at_server_parallelism(monkeypatch, parallel, expected):
+ if parallel is None:
+ monkeypatch.delenv("OLLAMA_NUM_PARALLEL", raising=False)
+ else:
+ monkeypatch.setenv("OLLAMA_NUM_PARALLEL", parallel)
+ in_flight = peak = 0
+
+ async def slow(request, n):
+ nonlocal in_flight, peak
+ in_flight += 1
+ peak = max(peak, in_flight)
+ await asyncio.sleep(0.02)
+ in_flight -= 1
+ return _stream()
+
+ _serve(monkeypatch, slow)
+ provider = _provider()
+ await asyncio.gather(*(provider.generate("s", "u", max_tokens=10) for _ in range(5)))
+
+ assert peak == expected
@pytest.mark.parametrize(
- "make_exc",
+ "exc",
[
- pytest.param(_status_error, id="api_status_error"),
- pytest.param(lambda: APITimeoutError("Request timed out"), id="api_timeout_error"),
- pytest.param(_connection_error, id="api_connection_error"),
+ pytest.param(httpx.ReadTimeout("timed out"), id="read_timeout"),
+ pytest.param(httpx.ConnectError("refused"), id="connect_error"),
],
)
-async def test_generate_wraps_openai_errors(make_exc):
- """Every ``openai.APIError`` subclass is wrapped as ``ProviderError`` (#445).
-
- ``APITimeoutError`` and ``APIConnectionError`` are NOT subclasses of
- ``APIStatusError``, so the old catch-only-``APIStatusError`` clause let them
- escape uncaught, skipping tenacity's retry loop entirely.
- """
- await _assert_generate_wraps(make_exc())
-
-
-async def test_all_openai_errors_are_subclasses_of_api_error():
- """Verify the class hierarchy: all OpenAI errors inherit from APIError."""
- resp = AsyncMock()
- resp.status_code = 500
- status_err = APIStatusError("err", response=resp, body="")
- timeout_err = APITimeoutError("timed out")
- request = httpx.Request("POST", "http://localhost:9999/v1/chat/completions")
- conn_err = APIConnectionError(message="refused", request=request)
-
- assert isinstance(status_err, APIError), "APIStatusError must be APIError"
- assert isinstance(timeout_err, APIError), "APITimeoutError must be APIError"
- assert isinstance(conn_err, APIError), "APIConnectionError must be APIError"
+async def test_transport_errors_are_retried(monkeypatch, exc):
+ def handler(request, n):
+ raise exc
+
+ seen = _serve(monkeypatch, handler)
+ with pytest.raises(ProviderError, match="ollama"):
+ await _provider().generate("s", "u", max_tokens=10)
+ assert len(seen) == 3
+
+
+async def test_server_error_is_retried(monkeypatch):
+ seen = _serve(monkeypatch, lambda request, n: httpx.Response(500, text="boom"))
+ with pytest.raises(ProviderError):
+ await _provider().generate("s", "u", max_tokens=10)
+ assert len(seen) == 3
+
+
+async def test_succeeds_after_a_timeout(monkeypatch):
+ def handler(request, n):
+ if n == 1:
+ raise httpx.ReadTimeout("first attempt timed out")
+ return _stream()
+
+ seen = _serve(monkeypatch, handler)
+ result = await _provider().generate("s", "u", max_tokens=10)
+ assert len(seen) == 2
+ assert result.content == "Generated wiki content"
+
+
[email protected]("status", [400, 404])
+async def test_client_errors_fail_fast(monkeypatch, status):
+ seen = _serve(monkeypatch, lambda request, n: httpx.Response(status, text="model not found"))
+ with pytest.raises(ProviderError) as exc_info:
+ await _provider().generate("s", "u", max_tokens=10)
+ assert len(seen) == 1
+ assert exc_info.value.status_code == status
+
+
+async def test_error_mid_stream_is_a_provider_error(monkeypatch):
+ body = json.dumps({"error": "model runner has unexpectedly stopped"})
+ _serve(monkeypatch, lambda request, n: httpx.Response(200, text=body))
+ with pytest.raises(ProviderError, match="unexpectedly stopped"):
+ await _provider().generate("s", "u", max_tokens=10)
diff --git a/tests/unit/test_providers/test_ollama_provider_timeout_integration.py b/tests/unit/test_providers/test_ollama_provider_timeout_integration.py
deleted file mode 100644
index ae5b5380d..000000000
--- a/tests/unit/test_providers/test_ollama_provider_timeout_integration.py
+++ /dev/null
@@ -1,203 +0,0 @@
-"""Integration test for Issue #445: APITimeoutError retry behavior.
-
-Tests the full chain: OllamaProvider._generate_with_retry → tenacity retry
-→ generate(). Verifies that APITimeoutError is wrapped as ProviderError
-and that tenacity actually retries (not just catches).
-"""
-
-from __future__ import annotations
-
-from unittest.mock import AsyncMock
-
-import httpx
-import pytest
-
-pytest.importorskip("openai", reason="openai SDK not installed")
-
-from openai import (
- APIConnectionError,
- APIStatusError,
- APITimeoutError,
- AuthenticationError,
-)
-
-from repowise.core.providers.llm.base import ProviderError
-from repowise.core.providers.llm.ollama import OllamaProvider
-
-
-async def test_ollama_retries_on_timeout():
- """Verify tenacity retries N times before giving up on APITimeoutError.
-
- With the fix, APITimeoutError gets caught, wrapped as ProviderError,
- and retried by tenacity up to _MAX_RETRIES (3) times.
- """
- p = OllamaProvider(model="test-model", base_url="http://localhost:9999")
- p._rate_limiter = None
-
- # Track how many times the client is called
- call_count = 0
-
- async def timeout_side_effect(*args, **kwargs):
- nonlocal call_count
- call_count += 1
- raise APITimeoutError(f"Request timed out (attempt {call_count})")
-
- p._client.chat.completions.create = AsyncMock(side_effect=timeout_side_effect)
-
- with pytest.raises(ProviderError) as exc_info:
- await p.generate(system_prompt="", user_prompt="", max_tokens=10)
-
- # Tenacity should have retried _MAX_RETRIES times (= 3)
- assert call_count == 3, (
- f"Expected 3 retries before ProviderError, got {call_count}. Fix may not be working."
- )
- assert "ollama" in str(exc_info.value)
-
-
-async def test_ollama_retries_on_connection_error():
- """Same as above but with APIConnectionError."""
- p = OllamaProvider(model="test-model", base_url="http://localhost:9999")
- p._rate_limiter = None
-
- call_count = 0
-
- async def conn_error_side_effect(*args, **kwargs):
- nonlocal call_count
- call_count += 1
- request = httpx.Request("POST", "http://localhost:9999/v1/chat/completions")
- raise APIConnectionError(
- message=f"Connection refused (attempt {call_count})",
- request=request,
- )
-
- p._client.chat.completions.create = AsyncMock(side_effect=conn_error_side_effect)
-
- with pytest.raises(ProviderError) as exc_info:
- await p.generate(system_prompt="", user_prompt="", max_tokens=10)
-
- assert call_count == 3, (
- f"Expected 3 retries before ProviderError, got {call_count}. Fix may not be working."
- )
- assert "ollama" in str(exc_info.value)
-
-
-async def test_ollama_succeeds_on_retry():
- """Verify that after a timeout failure, the retry succeeds and returns a result.
-
- This mimics the real-world scenario: Ollama is overloaded, first request
- times out, but the retry succeeds.
- """
- from openai.types.chat import ChatCompletion, ChatCompletionMessage
- from openai.types.chat.chat_completion import Choice
- from openai.types.completion_usage import CompletionUsage
-
- p = OllamaProvider(model="test-model", base_url="http://localhost:9999")
- p._rate_limiter = None
-
- call_count = 0
-
- async def flaky_side_effect(*args, **kwargs):
- nonlocal call_count
- call_count += 1
- if call_count == 1:
- raise APITimeoutError("First attempt timed out")
- # Second attempt succeeds
- return ChatCompletion(
- id="test",
- model="test-model",
- object="chat.completion",
- created=1234567890,
- choices=[
- Choice(
- finish_reason="stop",
- index=0,
- message=ChatCompletionMessage(
- role="assistant",
- content="Generated wiki content",
- ),
- )
- ],
- usage=CompletionUsage(
- prompt_tokens=10,
- completion_tokens=20,
- total_tokens=30,
- ),
- )
-
- p._client.chat.completions.create = AsyncMock(side_effect=flaky_side_effect)
-
- result = await p.generate(system_prompt="", user_prompt="Test", max_tokens=10)
-
- assert call_count == 2, f"Expected 2 calls (1 fail + 1 retry), got {call_count}"
- assert result.content == "Generated wiki content"
- assert result.input_tokens == 10
- assert result.output_tokens == 20
- assert result.stop_reason == "end_turn"
- assert result.provider_stop_reason == "stop"
-
-
-async def test_ollama_does_not_retry_invalid_request():
- """Verify 400 (invalid request) fails immediately without retries.
-
- Issue #445 point 3: non-retryable errors must fail fast. The shared
- retry policy treats 400/401/403/404/405/413/422 as non-retryable, so
- the client is called exactly once.
- """
- p = OllamaProvider(model="test-model", base_url="http://localhost:9999")
- p._rate_limiter = None
-
- call_count = 0
-
- async def bad_request_side_effect(*args, **kwargs):
- nonlocal call_count
- call_count += 1
- resp = httpx.Response(
- 400,
- request=httpx.Request("POST", "http://localhost:9999/v1/chat/completions"),
- )
- raise APIStatusError("Bad Request", response=resp, body=None)
-
- p._client.chat.completions.create = AsyncMock(side_effect=bad_request_side_effect)
-
- with pytest.raises(ProviderError) as exc_info:
- await p.generate(system_prompt="", user_prompt="", max_tokens=10)
-
- assert call_count == 1, (
- f"Non-retryable 400 must fail immediately, but was called {call_count} times."
- )
- assert "ollama" in str(exc_info.value)
-
-
-async def test_ollama_does_not_retry_authentication_error():
- """Verify 401 (authentication) fails immediately without retries.
-
- Issue #445 point 3: authentication errors must not burn retry attempts.
- """
- p = OllamaProvider(model="test-model", base_url="http://localhost:9999")
- p._rate_limiter = None
-
- call_count = 0
-
- async def auth_error_side_effect(*args, **kwargs):
- nonlocal call_count
- call_count += 1
- resp = httpx.Response(
- 401,
- request=httpx.Request("POST", "http://localhost:9999/v1/chat/completions"),
- )
- raise AuthenticationError("Unauthorized", response=resp, body=None)
-
- p._client.chat.completions.create = AsyncMock(side_effect=auth_error_side_effect)
-
- with pytest.raises(ProviderError) as exc_info:
- await p.generate(system_prompt="", user_prompt="", max_tokens=10)
-
- assert call_count == 1, (
- f"Authentication error must fail immediately, but was called {call_count} times."
- )
- assert "ollama" in str(exc_info.value)