Skip to content

fix(ai): client timeouts, streamed response limits, model-resolution errors and dead round-robin state #960

Closed

Description

@dan-petty

Problem

The devsecops review session 20261001-224227 (2026-10-02, a path review of the whole repository with local models) raised 563 findings. A triage of every finding against release/v0.2.25 (c279c18) judged 489 false. Each of the 5 defects below was confirmed with code evidence and then upheld by a second agent that tried to refute it. The severities are re-rated; the review's own ratings were inflated.

Incomplete Documentation for ai.timeout Configuration (src/devops_cli/ai/client/unified.py:327, LOW, correctness)

  • Defect: The stated claim is weak: the row at docs/CONFIGURATION.md:90 accurately reflects timeout: float | None = None (settings.py:432), and an empty env column is not by itself a defect. The real problem is that the documented key does nothing for LLM requests. AIConfig.for_task copies override.timeout into the config (settings.py:489), but UnifiedLLMClient never reads self._config.timeout. Its read timeout is read=self._request_timeout_seconds or DEFAULT_HTTP_TIMEOUT_SECONDS (unified.py:327-330, 3600 s), and only the constructor argument sets it: the review runner passes the constant DEFAULT_REVIEW_TIMEOUT_SECONDS (review/runner.py:1560-1581) and every other caller passes nothing. The only consumer of ai.timeout is the embedding fallback (rag/embeddings.py:242-244). So ai.timeout and ai.tasks.{chat,metadata,analysis,verification,compose}.timeout are accepted, documented and silently …
  • Skeptic's ruling: The original claim, that an empty default or env cell is a doc defect, is weak. The triage's re-scoped defect is real, and I reproduced it. AIConfig.timeout (settings.py:432) and AITaskOverride.timeout (settings.py:391) are copied by for_task (settings.py:490), but no LLM request path reads them. LLMClient._request_timeout (ai/client/unified.py:327-330; the class is LLMClient, not 'UnifiedLLMClient') uses self._request_timeout_seconds or DEFAULT_HTTP_TIMEOUT_SECONDS (3600 s, …
  • Fix: In LLMClient._request_timeout, use read=self._request_timeout_seconds or self._config.timeout or DEFAULT_HTTP_TIMEOUT_SECONDS. In review/runner.py's client builder, pass request_timeout_seconds=DEFAULT_REVIEW_TIMEOUT_SECONDS only when the task config's timeout is None, so a configured analysis, verification or compose timeout wins. Optionally pass ai_cfg.timeout into create_ollama_model(timeout=...) in pydantic_ai_bridge._resolve_ollama_model. Give AIConfig.timeout and AITaskOverride.timeout a Field(description=...) naming the fallbacks (3600 s generally, 1200 s for reviews), so the generated CONFIGURATION.md row explains itself. Regenerate the docs.
  • Regression test: tests/test_ai_client_retries.py or a new tests/test_ai_client_timeout.py: cfg = AIConfig(timeout=5.0).for_task('analysis'); assert LLMClient(cfg, api_key='x', cache_enabled=False)._request_timeout().read == 5.0. Today it is 3600.0. Second case: AIConfig(tasks={'analysis': {'timeout': 7.0}}).for_task('analysis') gives read == 7.0. Third: build the review clients from Settings with ai.tasks.analysis.timeout=30 and assert clients.analysis._request_timeout().read == 30.0. Today it is 1200.0.

Insecure Response Size Validation Allows Bypass of Content-Length Check (src/devops_cli/ai/client/network.py:260, LOW, reliability)

  • Defect: The stated bypass (a negative or invalid Content-Length) is wrong: the len(response.content) > limit_bytes check at lines 268-271 still catches such a body. The size limit is nonetheless ineffective as a memory guard. Every caller fetches with non-streaming http_client.post(...) before calling read_limited_json: claude.py:74-83, openai.py:164-173, ollama.py:315-326. httpx2's non-streaming request reads the entire body into memory before returning, so the Content-Length check and the content check both run after the whole body is buffered. DEFAULT_AI_MAX_RESPONSE_BYTES = 50 MiB (defaults.py:78) therefore protects only json.loads, not memory. A model endpoint, or an on-path attacker on a plain-http LAN Ollama URL, can stream a multi-GB chunked reply and exhaust the CLI's memory.
  • Skeptic's ruling: The finding's stated bypass (a negative or non-numeric Content-Length) is refuted, because the len(response.content) > limit_bytes check still catches those bodies. The size cap is still ineffective as a memory guard. claude.py, openai.py and ollama.py all call non-streaming http_client.post(...), and httpx2's Client.send runs response.read() when stream=False (httpx2/_client.py ~988), so the whole body is buffered before read_limited_json runs. Reproduced with MockTransport: a …
  • Fix: Add post_limited_json(client, url, *, limit_bytes, **kw) in network.py. It uses with client.stream('POST', url, **kw) as r:, calls raise_for_status, rejects a numeric Content-Length above the limit up front, accumulates r.iter_bytes() and raises AIClientError as soon as the total exceeds the limit, then json.loads the bytes. Replace the claude, openai and ollama non-streaming post plus read_limited_json pairs with it, and format the limit in KB/MB correctly in the message.
  • Regression test: tests/test_ai_client_network.py::test_post_limited_json_stops_reading_past_limit: use an httpx2.MockTransport whose SyncByteStream yields 2000 chunks of 1 KB and counts the chunks pulled. Call the provider path (e.g. LLMClient ollama _ollama_messages with the transport injected via monkeypatched _shared_client) with DEFAULT_AI_MAX_RESPONSE_BYTES monkeypatched to 4096. Assert AIClientError is raised and chunks_pulled <= 5. Today all 2000 chunks are pulled before the check.

Broad Exception Handling in Model Resolution (src/devops_cli/ai/pydantic_ai_bridge.py:138, LOW, reliability)

  • Defect: _resolve_string_model wraps return _resolve_remote_inferred_model(model_str, active_settings) in except Exception: return model_str, with no log. Reproduced against the assess tree with ai.provider='openai' and ai.api_base_url='localhost:8000/v1' (missing scheme). The direct call raises InvalidURLError: Invalid openai URL scheme 'localhost', but _resolve_string_model returns the bare string 'openai:gpt-4o'. When pydantic-ai later infers that string, it builds OpenAIResponsesModel against https://api.openai.com/v1/ instead of the configured endpoint. The configuration error is hidden and the configured base_url/api_key are silently dropped. Depending on the environment, the user gets a misleading 'unknown provider' or missing-key error, or the review prompts go to the vendor's public endpoint. The same applies to SSRFBlockedError from a blocked gateway_url or portkey_url. …
  • Skeptic's ruling: I upheld this as a LOW reliability and code-quality issue. The triage overstated how far it reaches and the security angle.

What I confirmed against the assess tree (c279c18):

  • _resolve_string_model (src/devops_cli/ai/pydantic_ai_bridge.py:133-141) wraps _resolve_remote_inferred_model in a bare except Exception: return model_str with no log.
  • I ran it with provider=openai and api_base_url='localhost:8000/v1'. The direct call raises `InvalidURLError: Invalid openai URL scheme …
  • Fix: In _resolve_string_model, remove the blanket except Exception.
  • URL errors: let InvalidURLError and SSRFBlockedError (devops_cli.exceptions) propagate, or re-raise them as a configuration error that names the setting (ai.api_base_url, ai.gateway_url or ai.portkey_url).
  • Unknown model: catch only pydantic_ai.exceptions.UserError. Do not return the bare string. Raise a configuration error naming ai.provider and ai.model that carries pydantic-ai's 'Did you mean ...' hint, or map the configured ai.provider to a pydantic-ai prefix (openai -> 'openai:', claude -> 'anthropic:') before calling infer_model. Log the provider prefix and exception type, never the key.
  • Agent factory: narrow create_pydantic_ai_agent's except Exception (debug log only) so it does not swallow the re-raised config error.
  • Dead code: as part of feat(cli): blind exception handling policy #423, also decide whether …
  • Regression test: Add to tests/test_pydantic_ai_profiles_and_providers.py: test_remote_model_with_malformed_base_url_raises.
  1. Build Settings() with ai.provider='openai' and ai.api_base_url='localhost:8000/v1'.
  2. Monkeypatch devops_cli.ai.pydantic_ai_bridge._is_testing_mode_active to return False, so resolve_pydantic_ai_model does not short-circuit to TestModel.
  3. Assert pytest.raises(InvalidURLError) (or the new config error) around `resolve_pydantic_ai_model('openai:gpt-4o', …

Potential Race Condition in Global URL Index Access (src/devops_cli/ai/client/ollama.py:187, LOW, quality)

  • Defect: No race exists: a Python int read is atomic. The cited line is dead and wrong state, though. LLMClient._global_ollama_url_index = network.global_ollama_url_index (unified.py:154) copies the int once at import (0), and load_and_increment_rr_index rebinds the module global without ever updating the class attribute. getattr(self, "_global_ollama_url_index", network.global_ollama_url_index) (ollama.py:187-189) therefore always takes the stale class value and never reaches its fallback. self._ollama_url_index is never read by production code; its only reader is tests/test_ai_client_security.py:175, which sets the class attribute itself. The class aliases _ollama_active_lock, _ollama_semaphores, _ollama_sem_lock and _global_ollama_url_lock (unified.py:151-155) and the instance attribute _ollama_url_lock (unified.py:193) have no readers at all. They are leftovers from the …
  • Skeptic's ruling: The race claim is refuted: the attribute is a plain int read, and the real round-robin state is guarded by network.global_ollama_url_lock inside load_and_increment_rr_index. The triage's reframing as dead, misleading state holds, though. LLMClient._global_ollama_url_index = network.global_ollama_url_index copies 0 once at class creation, and load_and_increment_rr_index rebinds only the module global. So _get_ollama_urls_loop's `self._ollama_url_index = getattr(self, …
  • Fix: Delete the self._ollama_url_index = getattr(...) assignment in OllamaProviderMixin._get_ollama_urls_loop. Delete the class aliases _active_ollama_requests, _ollama_active_lock, _ollama_semaphores, _ollama_sem_lock, _global_ollama_url_index and _global_ollama_url_lock from LLMClient, and the instance attributes _ollama_url_index and _ollama_url_lock from __init__. Change test_ai_client_security.py to assert only the requested URL order, and test_ai_client_providers_and_embeddings.py:318 to read network.active_ollama_requests.
  • Regression test: tests/test_ai_client_security.py::test_llmclient_has_no_legacy_ollama_rr_state: assert that none of the names ['_global_ollama_url_index','_global_ollama_url_lock','_ollama_active_lock','_ollama_semaphores','_ollama_sem_lock','_active_ollama_requests'] is an attribute of LLMClient. Also assert that '_ollama_url_index' and '_ollama_url_lock' are not in vars(LLMClient(AIConfig(provider='ollama', ollama_urls=['http://a:11434','http://b:11434']))) after one _get_ollama_urls_loop() call. This …

Private Network Access Disabled by Default (config.example.yaml:110, LOW, config)

  • Defect: The false default is a deliberate SSRF guard, but the example config's own local defaults conflict with it. config.example.yaml:62 sets qdrant.url: http://localhost:6333, :63 sets ollama_urls: http://localhost:11434, rag.enabled: true, and :110 sets allow_private_network: false. validate_url (core/validation.py:296-315) sends any host that is not explicitly allowed to _enforce_non_private_ssrf, which also rejects loopback. QdrantClient.init calls validate_service_url(self.base_url, "Qdrant", allow=self.allow_private_network) (ai/rag/qdrant.py:163), and EmbeddingsEngine calls validate_service_url(base_url, "Ollama", allow=self.ai_config.allow_private_network) (ai/rag/embeddings.py:474, 642). The chat provider exempts loopback through _is_loopback_or_private_allowed (ai/providers/ollama.py:27-41). Checked with the env var unset: …
  • Skeptic's ruling: I could not refute this. I reproduced it on c279c18 with DEVOPS_CLI_AI_ALLOW_PRIVATE_NETWORK unset. validate_service_url('http://localhost:6333', 'Qdrant', allow=False) raises SSRFBlockedError, and so do localhost:11434 and 127.0.0.1:6333. QdrantClient('http://localhost:6333', api_key='x', allow_private_network=False) raises in init. The Ollama chat provider's _validate_ollama_url('http://localhost:11434', False) passes, because _is_loopback_or_private_allowed in ai/providers/ollama.py …
  • Fix: Add one explicit policy to core/validation, for example validate_configured_service_url(url, purpose, *, allow_private). It exempts loopback (localhost, 127.0.0.0/8, ::1) for URLs that come from the user's own config. RFC-1918, link-local and cloud-metadata hosts stay behind allow_private_network. Do NOT change validate_service_url's default: the HTTP broker (http/broker.py) and the tool-download path (commands/install_tools.py) use it for URLs that are not trusted config. Call the new function from QdrantClient.init and from the EmbeddingsEngine Ollama, OpenAI and gateway validation sites. Delete _LOOPBACK_HOSTS and _is_loopback_or_private_allowed in ai/providers/ollama.py, and the redundant validate_url(allow_private=True) in rag/investigator.py, so there is a single policy. Change the investigator/pipeline failure log from debug to a one-time warning, so a blocked RAG backend is …
  • Regression test: Write tests/test_rag_loopback_policy.py. With monkeypatch.delenv('DEVOPS_CLI_AI_ALLOW_PRIVATE_NETWORK'), load config.example.yaml into Settings and assert three things. QdrantClient(base_url=settings.qdrant.url, api_key='x', allow_private_network=settings.ai.allow_private_network) constructs without raising. EmbeddingsEngine(ai_config=settings.ai)._query_ollama_node_batch('http://localhost:11434', ['x']), with httpx2 mocked to return a 200 embeddings payload, returns vectors and does not raise …

Acceptance criteria

  • Each defect above is fixed as its Fix line describes, or the PR says why another fix is better.
  • Each has its Regression test: offline, failing on the base revision and passing after the fix.
  • Removed code goes without shims (pre-1.0), and docs that described it are corrected.
  • uv run devops ci passes.

Key questions

  • One PR for all of these? Yes (proposed). They share a module area and none needs a design decision; each fix is small.

Activity

  1. added this to the v0.2.25 milestone on Oct 2, 2026
  2. added
    type/bug
    scope/ai
    priority/p3-low
    on Oct 2, 2026
  3. dan-petty commented on Oct 3, 2026

    @dan-petty
    OwnerAuthor

    Closed by #1077, merged into release/v0.2.25.

    GitHub only acts on closing keywords when a pull request merges into the default branch, so this was closed by devops gh issues close-merged.

  4. added a commit that references this issue on Oct 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    priority/p3-lowscope/aitype/bug

    Type

    No type

    Projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions