Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(embedding): honour REPOWISE_EMBEDDING_TIMEOUT in every embedder (#1475)
Sergei Iakhnitskiie0a1e6be08cf
diff --git a/docs/reference/CONFIG.md b/docs/reference/CONFIG.mdindex 3d6e10db5..571eeb520 100644--- a/docs/reference/CONFIG.md+++ b/docs/reference/CONFIG.md@@ -630,8 +630,9 @@ store would be rebuilt from scratch, discarding what the reindex just built.`REPOWISE_EMBEDDING_MODEL` overrides the model for whichever embedder isactive. `REPOWISE_EMBEDDING_DIMS` and `REPOWISE_EMBEDDING_TIMEOUT` apply the-same way; the `OLLAMA_EMBEDDING_*` variants below are Ollama-specific-equivalents.+same way; the provider-prefixed variants below (`OPENAI_*`, `GEMINI_*`,+`OLLAMA_*`, `OPENROUTER_*`) narrow a setting to one embedder and take+precedence over the shared name.---@@ -691,10 +692,13 @@ The `.repowise/.env` file is gitignored automatically.| `REPOWISE_EMBEDDER` | Embedder: `gemini`, `openai`, `ollama`, `openrouter`, or `mock` || `REPOWISE_EMBEDDING_MODEL` | Embedding model, applies to any embedder || `REPOWISE_EMBEDDING_DIMS` | Embedding output dimensions (optional; inferred from the model otherwise) |-| `REPOWISE_EMBEDDING_TIMEOUT` | Embed request timeout in seconds |+| `REPOWISE_EMBEDDING_TIMEOUT` | Embed request timeout in seconds (default: `30` for `ollama`, `10` elsewhere). Raise it for a local endpoint — one request embeds a whole batch, and an expired batch is reported only as `N/N items failed to embed`. An unparseable value warns and keeps the default |+| `OPENAI_EMBEDDING_TIMEOUT` | As above, `openai` only; takes precedence over the shared variable |+| `GEMINI_EMBEDDING_TIMEOUT` | As above, `gemini` only |+| `OPENROUTER_EMBEDDING_TIMEOUT` | As above, `openrouter` only || `OLLAMA_EMBEDDING_MODEL` | Ollama embedding model (also selects the `ollama` embedder) || `OLLAMA_EMBEDDING_DIMS` | Ollama embedding output dimensions (optional; inferred from the model otherwise) |-| `OLLAMA_EMBEDDING_TIMEOUT` | Ollama embed request timeout in seconds (default: `30`); raise it for long pages on slow local models |+| `OLLAMA_EMBEDDING_TIMEOUT` | As above, `ollama` only; raise it for long pages on slow local models |### Server and databasediff --git a/packages/cli/src/repowise/cli/providers/embedders.py b/packages/cli/src/repowise/cli/providers/embedders.pyindex 7d96b0479..eff34357c 100644--- a/packages/cli/src/repowise/cli/providers/embedders.py+++ b/packages/cli/src/repowise/cli/providers/embedders.py@@ -15,15 +15,10 @@ def _embedder_kwargs(embedder_name: str) -> dict[str, Any]:dimensions = os.environ.get("OLLAMA_EMBEDDING_DIMS") or os.environ.get("REPOWISE_EMBEDDING_DIMS")- timeout = os.environ.get("OLLAMA_EMBEDDING_TIMEOUT") or os.environ.get(- "REPOWISE_EMBEDDING_TIMEOUT"- )if base_url:kwargs["base_url"] = base_urlif dimensions:kwargs["dimensions"] = int(dimensions)- if timeout:- kwargs["timeout"] = float(timeout)elif embedder_name == "gemini":dimensions = os.environ.get("REPOWISE_EMBEDDING_DIMS")if dimensions:diff --git a/packages/core/src/repowise/core/generation/concept_tree/planner.py b/packages/core/src/repowise/core/generation/concept_tree/planner.pyindex 6d13a1ef0..7098106d1 100644--- a/packages/core/src/repowise/core/generation/concept_tree/planner.py+++ b/packages/core/src/repowise/core/generation/concept_tree/planner.py@@ -396,6 +396,16 @@ async def name_groups(temperature=0.2,**_reasoning_kwargs(reasoning),)+ # A truncated reply parses to {} and decodes to the same deterministic+ # fallback an empty one does, so without this the two are+ # indistinguishable. Reasoning tokens count against the ceiling too, so+ # a thinking model can exhaust it having emitted no answer at all.+ if response.stop_reason == "max_tokens":+ logger.warning(+ "concept_outline_naming_truncated",+ groups=len(groups),+ provider_stop_reason=response.provider_stop_reason,+ )data = parse_json_object(getattr(response, "content", "") or "")except Exception as exc:logger.warning("concept_outline_naming_failed", error=str(exc))diff --git a/packages/core/src/repowise/core/providers/embedding/base.py b/packages/core/src/repowise/core/providers/embedding/base.pyindex eea245f4d..ed442ffac 100644--- a/packages/core/src/repowise/core/providers/embedding/base.py+++ b/packages/core/src/repowise/core/providers/embedding/base.py@@ -12,8 +12,75 @@ from __future__ import annotationsimport hashlibimport math+import os+import sysfrom typing import Protocol, runtime_checkable+import structlog++log = structlog.get_logger(__name__)+++def resolve_embedding_timeout(+ explicit: float | None, default: float, *, provider_env: str | None = None+) -> float:+ """Seconds allowed per embedding request.++ Precedence: explicit arg > ``provider_env`` > ``REPOWISE_EMBEDDING_TIMEOUT``+ > *default*. Raisable because against a local endpoint one request is GPU+ work, and an expired batch is not retried — it surfaces only as "N/N items+ failed to embed".++ A malformed *env* value warns and falls back; raising would reach+ ``build_embedder``'s ``except Exception`` and downgrade the run to a keyless+ 8-wide index. An invalid *explicit* argument is a caller bug and raises.+ """+ if explicit is not None:+ if isinstance(explicit, bool) or not isinstance(explicit, int | float):+ raise ValueError("timeout must be a positive number")+ if not math.isfinite(explicit) or explicit <= 0:+ raise ValueError("timeout must be a positive number")+ return float(explicit)+ names = [provider_env] if provider_env else []+ names.append("REPOWISE_EMBEDDING_TIMEOUT")+ invalid: list[tuple[str, str]] = []+ selected = default+ for name in names:+ raw = os.environ.get(name)+ if not raw:+ continue+ try:+ value = float(raw)+ except ValueError:+ value = math.nan+ # isfinite also rejects "inf" — a plausible way to ask for no limit, and+ # the one value that hangs a stalled endpoint forever.+ if math.isfinite(value) and value > 0:+ selected = value+ break+ # A value that failed to parse is not a value, so it must not consume+ # the narrower variable's precedence over the shared one.+ invalid.append((name, raw))+ for name, raw in invalid:+ _report_invalid_timeout(name, raw, selected)+ return selected+++def _report_invalid_timeout(var: str, raw: str, default: float) -> None:+ """Say it where the user will actually see it.++ The CLI pins structlog to ERROR unless ``-v``, so a warning here reaches+ nobody on the path that matters — and the symptom this variable exists to+ cure ("N/N items failed to embed") is exactly what a silently-ignored value+ produces. stderr matches how ``build_embedder`` reports the same class of+ misconfiguration.+ """+ log.warning("embedding_timeout_invalid", var=var, value=raw, using=default)+ print(+ f"{var}={raw!r} is not a positive number of seconds; using {default}s.",+ file=sys.stderr,+ )+@runtime_checkableclass Embedder(Protocol):diff --git a/packages/core/src/repowise/core/providers/embedding/gemini.py b/packages/core/src/repowise/core/providers/embedding/gemini.pyindex 849e3c121..0d9bd8fce 100644--- a/packages/core/src/repowise/core/providers/embedding/gemini.py+++ b/packages/core/src/repowise/core/providers/embedding/gemini.py@@ -29,6 +29,8 @@ import loggingimport mathimport os+from repowise.core.providers.embedding.base import resolve_embedding_timeout+# Suppress "Both GOOGLE_API_KEY and GEMINI_API_KEY are set" from google-genai SDK.# We resolve and pass the key explicitly, so the env-var conflict warning is noise.logging.getLogger("google_genai._api_client").setLevel(logging.ERROR)@@ -56,9 +58,11 @@ class GeminiEmbedder:model: str = "gemini-embedding-001",task_type: str = "SEMANTIC_SIMILARITY",output_dimensionality: int = 768,- timeout: float = _DEFAULT_TIMEOUT,+ timeout: float | None = None,) -> None:- self._api_key = api_key or os.environ.get("GEMINI_API_KEY") or os.environ.get("GOOGLE_API_KEY")+ self._api_key = (+ api_key or os.environ.get("GEMINI_API_KEY") or os.environ.get("GOOGLE_API_KEY")+ )if not self._api_key:raise ValueError("Gemini API key required. Pass api_key= or set GEMINI_API_KEY env var."@@ -66,7 +70,9 @@ class GeminiEmbedder:self._model = modelself._task_type = task_typeself._output_dimensionality = output_dimensionality- self._timeout = timeout+ self._timeout = resolve_embedding_timeout(+ timeout, self._DEFAULT_TIMEOUT, provider_env="GEMINI_EMBEDDING_TIMEOUT"+ )self._client: object | None = None # cached; created once on first embed()@propertydiff --git a/packages/core/src/repowise/core/providers/embedding/ollama.py b/packages/core/src/repowise/core/providers/embedding/ollama.pyindex 865977062..bbc87b1bf 100644--- a/packages/core/src/repowise/core/providers/embedding/ollama.py+++ b/packages/core/src/repowise/core/providers/embedding/ollama.py@@ -12,6 +12,8 @@ from typing import Anyimport httpx+from repowise.core.providers.embedding.base import resolve_embedding_timeout+_DEFAULT_BASE_URL = "http://localhost:11434"_DEFAULT_MODEL = "embeddinggemma"_DEFAULT_TIMEOUT = 30.0@@ -74,13 +76,8 @@ class OllamaEmbedder:)self._requested_dimensions = dimensions or (int(env_dimensions) if env_dimensions else None)self._dimensions = self._requested_dimensions or _infer_dimensions(self._model)- env_timeout = os.environ.get("OLLAMA_EMBEDDING_TIMEOUT") or os.environ.get(- "REPOWISE_EMBEDDING_TIMEOUT"- )- self._timeout = (- timeout- if timeout is not None- else (float(env_timeout) if env_timeout else _DEFAULT_TIMEOUT)+ self._timeout = resolve_embedding_timeout(+ timeout, _DEFAULT_TIMEOUT, provider_env="OLLAMA_EMBEDDING_TIMEOUT")@propertydiff --git a/packages/core/src/repowise/core/providers/embedding/openai.py b/packages/core/src/repowise/core/providers/embedding/openai.pyindex 668445387..11a5a1269 100644--- a/packages/core/src/repowise/core/providers/embedding/openai.py+++ b/packages/core/src/repowise/core/providers/embedding/openai.py@@ -32,6 +32,8 @@ import mathimport osfrom typing import Any, ClassVar+from repowise.core.providers.embedding.base import resolve_embedding_timeout+class OpenAIEmbedder:"""OpenAI embedding model adapter implementing the repowise Embedder protocol.@@ -53,14 +55,15 @@ class OpenAIEmbedder:"text-embedding-ada-002": 1536,}- # Default timeout for embedding API calls (seconds).+ # Also bounds the query path, where the SDK retries twice — a bigger default+ # would triple into the caller's budget. Local endpoints raise it by env._DEFAULT_TIMEOUT: float = 10.0def __init__(self,api_key: str | None = None,model: str = "text-embedding-3-small",- timeout: float = _DEFAULT_TIMEOUT,+ timeout: float | None = None,base_url: str | None = None,dimensions: int | None = None,) -> None:@@ -71,7 +74,9 @@ class OpenAIEmbedder:)self._base_url = base_url or os.environ.get("OPENAI_BASE_URL")self._model = model- self._timeout = timeout+ self._timeout = resolve_embedding_timeout(+ timeout, self._DEFAULT_TIMEOUT, provider_env="OPENAI_EMBEDDING_TIMEOUT"+ )# When the user overrides the width, request that width from the API too,# so the returned vectors match the declaration instead of the model's# default — otherwise the store is sized to a width the vectors neverdiff --git a/packages/core/src/repowise/core/providers/embedding/openrouter.py b/packages/core/src/repowise/core/providers/embedding/openrouter.pyindex 8e3a3930b..b6caf5299 100644--- a/packages/core/src/repowise/core/providers/embedding/openrouter.py+++ b/packages/core/src/repowise/core/providers/embedding/openrouter.py@@ -19,6 +19,8 @@ import mathimport osfrom typing import ClassVar+from repowise.core.providers.embedding.base import resolve_embedding_timeout+class OpenRouterEmbedder:"""OpenRouter embedding adapter implementing the repowise Embedder protocol.@@ -48,7 +50,7 @@ class OpenRouterEmbedder:self,api_key: str | None = None,model: str = "google/gemini-embedding-001",- timeout: float = _DEFAULT_TIMEOUT,+ timeout: float | None = None,dimensions: int | None = None,) -> None:self._api_key = api_key or os.environ.get("OPENROUTER_API_KEY")@@ -65,7 +67,9 @@ class OpenRouterEmbedder:f"or pick a known model: {known}.")self._model = model- self._timeout = timeout+ self._timeout = resolve_embedding_timeout(+ timeout, self._DEFAULT_TIMEOUT, provider_env="OPENROUTER_EMBEDDING_TIMEOUT"+ )# Resolve declared width: explicit arg > REPOWISE_EMBEDDING_DIMS > _DIMS table.if dimensions is None:env = os.environ.get("REPOWISE_EMBEDDING_DIMS")diff --git a/tests/unit/generation/test_concept_outline.py b/tests/unit/generation/test_concept_outline.pyindex 5069c5c1c..f8dcd315c 100644--- a/tests/unit/generation/test_concept_outline.py+++ b/tests/unit/generation/test_concept_outline.py@@ -380,6 +380,8 @@ def test_a_trailing_number_stays_with_its_word():)assert deterministic_title(group) == "C4 Nodes"++class TestCycleNaming:"""A cycle page was titled by the hash of its members, which nothing searches for."""@@ -453,3 +455,36 @@ class TestCycleNaming:titles = _scc_titles([("scc-aaa", ["main.py"])])assert titles["scc-aaa"] == "Circular Dependency: scc-aaa"+++class TestTruncatedNamingIsVisible:+ """A ceiling hit must be said out loud.++ Truncation and a model that simply returned nothing produce the identical+ outline — the deterministic fallback — so without this the two are+ indistinguishable in a log, and the fixable one looks like the normal one.+ """++ class TruncatingProvider:+ async def generate(self, *, system_prompt, user_prompt, **kwargs):+ class R:+ content = '{"names": {"g1": {"title": "Half A' # cut mid-JSON+ stop_reason = "max_tokens"+ provider_stop_reason = "length"++ return R()++ @pytest.mark.asyncio+ async def test_a_truncated_reply_is_logged(self):+ from structlog.testing import capture_logs++ with capture_logs() as logs:+ _outline, report = await plan_outline(+ _inputs(), provider=self.TruncatingProvider(), params=TINY, repair=False+ )++ events = [entry["event"] for entry in logs]+ assert "concept_outline_naming_truncated" in events+ # The outline is still complete — this is a visibility fix, not a+ # behaviour change.+ assert report.coverage == 1.0diff --git a/tests/unit/test_persistence/test_embedding_timeout_resolution.py b/tests/unit/test_persistence/test_embedding_timeout_resolution.pynew file mode 100644index 000000000..a8140ba65--- /dev/null+++ b/tests/unit/test_persistence/test_embedding_timeout_resolution.py@@ -0,0 +1,87 @@+"""One policy for the embedding timeout, across every embedder.++`REPOWISE_EMBEDDING_TIMEOUT` is documented as applying to whichever embedder is+active, so the contract belongs here rather than in one provider's file: the+same precedence, the same rejection of values that would hang or expire+instantly, and the same refusal to turn a typo into a broken index.+"""++from __future__ import annotations++import pytest++from repowise.core.providers.embedding.base import resolve_embedding_timeout+from repowise.core.providers.embedding.ollama import OllamaEmbedder++pytest.importorskip("openai", reason="openai SDK not installed")++from repowise.core.providers.embedding.openai import OpenAIEmbedder+++def _clear(monkeypatch):+ for var in (+ "REPOWISE_EMBEDDING_TIMEOUT",+ "OPENAI_EMBEDDING_TIMEOUT",+ "OLLAMA_EMBEDDING_TIMEOUT",+ "GEMINI_EMBEDDING_TIMEOUT",+ "OPENROUTER_EMBEDDING_TIMEOUT",+ ):+ monkeypatch.delenv(var, raising=False)+++def test_shared_variable_applies(monkeypatch):+ _clear(monkeypatch)+ monkeypatch.setenv("REPOWISE_EMBEDDING_TIMEOUT", "180")+ assert resolve_embedding_timeout(None, 10.0, provider_env="OPENAI_EMBEDDING_TIMEOUT") == 180.0+++def test_provider_variable_wins(monkeypatch):+ _clear(monkeypatch)+ monkeypatch.setenv("REPOWISE_EMBEDDING_TIMEOUT", "180")+ monkeypatch.setenv("OPENAI_EMBEDDING_TIMEOUT", "45")+ assert resolve_embedding_timeout(None, 10.0, provider_env="OPENAI_EMBEDDING_TIMEOUT") == 45.0+++def test_a_malformed_provider_variable_reports_the_shared_value_that_won(monkeypatch, capsys):+ # A value that did not parse is not a value, so it cannot outrank a good one.+ _clear(monkeypatch)+ monkeypatch.setenv("REPOWISE_EMBEDDING_TIMEOUT", "180")+ monkeypatch.setenv("OPENAI_EMBEDDING_TIMEOUT", "45s")+ assert resolve_embedding_timeout(None, 10.0, provider_env="OPENAI_EMBEDDING_TIMEOUT") == 180.0+ stderr = capsys.readouterr().err+ assert "OPENAI_EMBEDDING_TIMEOUT='45s'" in stderr+ assert "using 180.0s" in stderr++[email protected]("bad", ["abc", "30s", "0", "-5", "inf", "nan", "1e400"])+def test_a_bad_value_keeps_the_default_and_reaches_stderr(monkeypatch, capsys, bad):+ # Falling back must not be quiet: the CLI filters structlog to ERROR without+ # -v, so a log line alone would leave the user with an unexplained+ # "N/N items failed to embed" — the symptom this variable exists to cure.+ _clear(monkeypatch)+ monkeypatch.setenv("REPOWISE_EMBEDDING_TIMEOUT", bad)+ assert resolve_embedding_timeout(None, 10.0) == 10.0+ assert "not a positive number of seconds" in capsys.readouterr().err++[email protected]("bad", ["abc", "30s", "inf", "-5"])+def test_no_embedder_is_destroyed_by_a_typo(monkeypatch, bad):+ # build_embedder turns a construction error into a keyless 8-wide store, so+ # raising anywhere here would silently end semantic search for a run that+ # worked before the variable was read at all.+ _clear(monkeypatch)+ monkeypatch.setenv("REPOWISE_EMBEDDING_TIMEOUT", bad)+ assert OpenAIEmbedder(api_key="k", model="local")._timeout == 10.0+ assert OllamaEmbedder(model="embeddinggemma")._timeout == 30.0+++def test_each_embedder_keeps_its_own_default(monkeypatch):+ _clear(monkeypatch)+ assert OpenAIEmbedder(api_key="k")._timeout == 10.0+ assert OllamaEmbedder()._timeout == 30.0+++def test_ollama_honours_the_shared_variable(monkeypatch):+ _clear(monkeypatch)+ monkeypatch.setenv("REPOWISE_EMBEDDING_TIMEOUT", "600")+ assert OllamaEmbedder()._timeout == 600.0diff --git a/tests/unit/test_persistence/test_openai_embedder.py b/tests/unit/test_persistence/test_openai_embedder.pyindex 54252c6aa..ab066965b 100644--- a/tests/unit/test_persistence/test_openai_embedder.py+++ b/tests/unit/test_persistence/test_openai_embedder.py@@ -82,6 +82,45 @@ def test_malformed_env_raises_the_same_message(monkeypatch):OpenAIEmbedder(api_key="k", model="local-embedder")+def test_timeout_from_shared_env(monkeypatch):+ monkeypatch.setenv("REPOWISE_EMBEDDING_TIMEOUT", "180")+ assert OpenAIEmbedder(api_key="k", model="local-embedder")._timeout == 180.0+++def test_provider_env_beats_shared_env(monkeypatch):+ monkeypatch.setenv("REPOWISE_EMBEDDING_TIMEOUT", "180")+ monkeypatch.setenv("OPENAI_EMBEDDING_TIMEOUT", "45")+ assert OpenAIEmbedder(api_key="k", model="local-embedder")._timeout == 45.0+++def test_explicit_timeout_beats_env(monkeypatch):+ monkeypatch.setenv("REPOWISE_EMBEDDING_TIMEOUT", "180")+ assert OpenAIEmbedder(api_key="k", model="local-embedder", timeout=5)._timeout == 5.0+++def test_hosted_default_is_unchanged(monkeypatch):+ # Pins the value, not the wiring: the env knob exists so this can stay put,+ # since it also bounds the retried query path.+ monkeypatch.delenv("REPOWISE_EMBEDDING_TIMEOUT", raising=False)+ monkeypatch.delenv("OPENAI_EMBEDDING_TIMEOUT", raising=False)+ assert OpenAIEmbedder(api_key="k")._timeout == 10.0++[email protected]("bad", ["abc", "30s", "0", "-5", "inf", "nan"])+def test_a_malformed_env_value_falls_back_instead_of_breaking_the_run(monkeypatch, bad):+ # build_embedder turns any construction error into a keyless 8-wide store,+ # so raising here would make a typo silently destroy retrieval for setups+ # that worked before the variable was honoured at all.+ monkeypatch.setenv("REPOWISE_EMBEDDING_TIMEOUT", bad)+ assert OpenAIEmbedder(api_key="k", model="local-embedder")._timeout == 10.0++[email protected]("bad", [0, -5, float("inf"), float("nan"), True, "30"])+def test_an_invalid_explicit_timeout_raises(bad):+ with pytest.raises(ValueError, match="timeout must be a positive number"):+ OpenAIEmbedder(api_key="k", model="local-embedder", timeout=bad)++# ---------------------------------------------------------------------------# Embedding# ---------------------------------------------------------------------------@@ -211,8 +250,8 @@ async def test_embed_raises_when_api_returns_wrong_width_from_dims_table():await emb.embed(["hello"])msg = str(exc_info.value)- assert "3" in msg # actual width named- assert "_DIMS" in msg # points at the table, not the user+ assert "3" in msg # actual width named+ assert "_DIMS" in msg # points at the table, not the userasync def test_embed_raises_when_api_returns_wrong_width_with_user_override(monkeypatch):@@ -220,7 +259,7 @@ async def test_embed_raises_when_api_returns_wrong_width_with_user_override(monk# message should reference REPOWISE_EMBEDDING_DIMS so they know what to change.monkeypatch.setenv("REPOWISE_EMBEDDING_DIMS", "512")emb = OpenAIEmbedder(api_key="k", model="text-embedding-3-small")- assert emb.dimensions == 512 # from env override+ assert emb.dimensions == 512 # from env overridewith patch("openai.OpenAI") as mock_client:mock_client.return_value.embeddings.create.return_value = _make_mock_response(@@ -239,4 +278,3 @@ async def test_embed_width_check_is_skipped_for_empty_response():# must not fire on the empty list itself.emb = OpenAIEmbedder(api_key="k")assert await emb.embed([]) == []-