Skip to content

test: LLM transport + fallback-chain coverage (llm.py 54% → 69%)#11

Merged
gesh75 merged 1 commit into
mainfrom
test/coverage-llm-web
Jun 10, 2026
Merged

test: LLM transport + fallback-chain coverage (llm.py 54% → 69%)#11
gesh75 merged 1 commit into
mainfrom
test/coverage-llm-web

Conversation

@gesh75

@gesh75 gesh75 commented Jun 10, 2026

Copy link
Copy Markdown
Owner

Summary

Coverage wave for the riskiest untested code: the LLM fallback chain routes to the paid Anthropic API, and every transport body was uncovered.

16 new tests pin:

  • Fallback order ollama → local → claude; provider=claude tries claude first; success short-circuits the chain
  • claude-only never falls back — it short-circuits around the _PROVIDERS table; the first draft of this test patched the table and accidentally made a real API call, which is exactly why this file now arms a network tripwire (autouse fixture replaces _SESSION with an object that pytest.fails on any unmocked call and swaps the real API key out)
  • Prompt-caching payloadsystem block carries cache_control: {type: ephemeral} (pins the PR fix: close analyze_site sanitize bypass + harden web API + perf wins #6 cost fix)
  • Per-provider last_errors recording for HTTP errors, timeouts, connection failures, empty responses; success clears the error; missing key never POSTs
  • <think>-block + reasoning-preamble cleaning; OpenAI-shape extraction variants (reasoning_content fallback)

State isolation via deep-copy restore (the nested last_errors dict made shallow snapshots leak between tests — a latent issue the review flagged).

Test plan

  • ruff check clean
  • 294/294 tests pass, zero network access (tripwire-enforced)
  • CI matrix green

🤖 Generated with Claude Code

Summary by Sourcery

Increase LLM transport and fallback-chain test coverage and document the expanded test suite.

Documentation:

  • Update changelog and README to reflect the increased test count and new LLM transport coverage.

Tests:

  • Add unit tests covering LLM transport behaviors, provider fallback ordering, claude-only no-fallback semantics, prompt-caching payload, error recording, and OpenAI-style response extraction, with a network tripwire to prevent real API calls.
  • Expand the overall test suite from 278 to 294 tests.

The fallback chain routes to the PAID Anthropic API and every transport
was untested. Pins: fallback order (ollama->local->claude), provider=
claude tries claude first, claude-only NEVER falls back (it short-
circuits around the _PROVIDERS table — found because the first version
of that test accidentally made a real API call), prompt-caching payload
shape (system block cache_control: ephemeral), per-provider last_errors
recording on HTTP/timeout/connection/empty failures, no-key guard never
POSTs, <think>-block + reasoning-preamble cleaning, OpenAI-shape
extraction variants.

A module-wide autouse fixture deep-copy-restores llm._state, replaces
the API key, and arms a network tripwire (_SESSION that pytest.fails on
any unmocked call) so no test in this file can ever touch the network.

Tests: 278 -> 294
@sourcery-ai

sourcery-ai Bot commented Jun 10, 2026

Copy link
Copy Markdown

Reviewer's Guide

Adds a comprehensive test suite for the LLM transports and fallback chain, including a network tripwire fixture, prompt-caching payload checks, error-recording behavior, and fallback ordering semantics, and updates docs to reflect the increased test count and coverage.

Sequence diagram for LLM fallback-chain behavior under tests

sequenceDiagram
  participant Caller
  participant LLM
  participant Ollama
  participant Local
  participant Claude

  Caller->>LLM: send request
  alt [provider is ollama or default]
    LLM->>Ollama: forward to Ollama
    alt [success]
      Ollama-->>LLM: return response
    else [failure]
      LLM->>Local: forward to Local
      alt [success]
        Local-->>LLM: return response
      else [failure]
        LLM->>Claude: forward to Claude
        Claude-->>LLM: return response
      end
    end
  else [provider is claude]
    LLM->>Claude: forward to Claude
    Claude-->>LLM: return response
  end
Loading

File-Level Changes

Change Details Files
Introduce an LLM transport + fallback-chain test module that fully mocks network access, verifies fallback semantics, prompt-caching payloads, error recording, text cleaning, and OpenAI-style response extraction.
  • Add an autouse fixture that deep-copies and restores llm._state, replaces the real session with a network tripwire, and swaps in a non-real Anthropic API key
  • Define scripted fake Session and Response helpers to capture requests and drive success/error outcomes deterministically
  • Add tests for _clean behavior around blocks, reasoning preambles, and normal text
  • Add ollama transport tests for success path cleaning/last_errors clearing and for HTTP, timeout/connection, and empty-response error recording
  • Add Claude transport tests for missing API key behavior (no POST, last_errors message), prompt-caching payload structure and headers, and HTTP error recording
  • Add fallback-chain tests for disabled short-circuiting, default provider fallback order, claude provider short-circuiting, claude-only no-fallback behavior, and all-providers-fail returning None
  • Add OpenAI-shape extraction tests to cover empty inputs, standard message content, and reasoning_content fallback
tests/test_llm_transports.py
Document the expanded LLM test coverage and updated test counts.
  • Update the changelog with a Tests section describing the new LLM transport and fallback-chain coverage and suite size increase
  • Update README badges and copy to reflect 294 passing tests instead of 278
CHANGELOG.md
README.md

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 1 issue

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="tests/test_llm_transports.py" line_range="51-56" />
<code_context>
+        return self._payload
+
+
+class _Session:
+    """Scripted fake for llm._SESSION — returns/raises per call."""
+
+    def __init__(self, *outcomes):
+        self.outcomes = list(outcomes)
+        self.calls: list[dict] = []
+
+    def post(self, url, **kwargs):
</code_context>
<issue_to_address>
**nitpick (testing):** Consider asserting that _Session has no remaining scripted outcomes at the end of a test.

Right now `_Session` pops from `self.outcomes` but never checks that all scripted outcomes were used, so over‑scripting (e.g. two outcomes but only one call) can go unnoticed. Consider adding a helper (or `__del__`/context manager check) used in tests to assert that `self.outcomes` is empty after the expected calls, so tests fail when some scripted behavior isn’t exercised.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment on lines +51 to +56
class _Session:
"""Scripted fake for llm._SESSION — returns/raises per call."""

def __init__(self, *outcomes):
self.outcomes = list(outcomes)
self.calls: list[dict] = []

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nitpick (testing): Consider asserting that _Session has no remaining scripted outcomes at the end of a test.

Right now _Session pops from self.outcomes but never checks that all scripted outcomes were used, so over‑scripting (e.g. two outcomes but only one call) can go unnoticed. Consider adding a helper (or __del__/context manager check) used in tests to assert that self.outcomes is empty after the expected calls, so tests fail when some scripted behavior isn’t exercised.

@gesh75
gesh75 merged commit 05905a9 into main Jun 10, 2026
4 checks passed
@gesh75
gesh75 deleted the test/coverage-llm-web branch June 10, 2026 11:39
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