Skip to content

Backends don't handle exceptions properly during generation #432

Closed

Description

@planetf1

Backends don't handle exceptions properly during generation

Description

When generation fails with an exception (e.g., OOM, CUDA error, model failure), backends crash with confusing errors instead of propagating the original exception cleanly.

Root cause: The core framework (base.py:323-331) correctly detects and stores exceptions in the chunk stream during astream() processing. It's designed to re-raise the exception after cleanup (base.py:360-361). However, before it can do that, it passes ALL chunks (including exceptions) to the backend's processing() function. None of the backend implementations check for exception chunks - they all assume chunks are valid response objects and try to access attributes that don't exist on Exception objects.

Affected backends: HuggingFace, Ollama, OpenAI, vLLM, Watsonx, LiteLLM (all 6 backends)

Example Error

When a generation fails with Exception("Oops!"), users see:

AttributeError: 'Exception' object has no attribute 'sequences'
  File "mellea/backends/huggingface.py", line 896, in processing
    chunk.sequences[0, input_ids.shape[1] :], skip_special_tokens=True

Instead of the actual error:

Exception: Oops!

This makes debugging real failures (OOM, CUDA errors, model issues) much harder since the root cause is hidden behind the AttributeError.

Technical Details

The framework's astream() loop processes chunks like this:

  1. Detects exception in chunk stream (base.py:323-327)
  2. Stores it to re-raise later
  3. Calls processing() on ALL chunks including the exception (base.py:329-331) ← crashes here
  4. Never reaches the re-raise logic (base.py:360-361)

Steps to Reproduce

Run test_error_during_generate_with_lock in test/backends/test_huggingface.py. The test expects to see "Oops!" but instead gets "'Exception' object has no attribute 'sequences'".

Expected Behavior

The original exception should propagate cleanly to the caller with its original message intact.

Proposed Fix

Add exception handling to processing() in all backend files to skip exception chunks (they'll be re-raised by the framework). Example for HuggingFace:

async def processing(
    self, mot: ModelOutputThunk, chunk: str | GenerateDecoderOnlyOutput, input_ids
):
    """Process the returned chunks or the complete response."""
    # Skip exception chunks - they'll be re-raised later by the framework
    if isinstance(chunk, Exception):
        return
        
    if mot._underlying_value is None:
        mot._underlying_value = ""
    # ... rest of function

Similar changes needed in:

  • mellea/backends/huggingface.py (line 881)
  • mellea/backends/ollama.py (line 546)
  • mellea/backends/openai.py (line 688)
  • mellea/backends/vllm.py (line 387)
  • mellea/backends/watsonx.py (line 403)
  • mellea/backends/litellm.py (line 360)

Additional Context

Activity

  1. jakelorocco commented on Feb 10, 2026

    @jakelorocco
    Contributor

    I think this error was actually introduced by the PR to add telemetry spans which catches the exception and waits to act on it. @nrfulton, did you have a fix for this in your branch?

    Either way, we should:

    1. decide on an error handling strategy (ie do we want partially completed model output thunks...)
    2. add a non-generative unit test to cover this code path; this wasn't caught since the test that would've caught this was part of the generative tests that are skipped by CI
  2. planetf1 commented on Feb 10, 2026

    @planetf1
    ContributorAuthor

    Possible kind of test we could add -> https://github.com/generative-computing/mellea/pull/433/changes (we can't merge until the underlying code is fixed)

    This tries to validate an instant failure, a failure after several chunks (assuming partial output is ok), and that exceptions are re-raised.

    Since it affects all back ends we could parameterize the test as that's cleanest -as we'd want to test them all?

  3. guicho271828 commented on Feb 11, 2026

    @guicho271828
    Contributor

    I am also blocked by this issue to some extent.

  4. planetf1 commented on Mar 4, 2026

    @planetf1
    ContributorAuthor

    Came up again in a related form while investigating test flakiness in #573.

    generate_from_raw in OllamaModelBackend uses asyncio.gather(..., return_exceptions=True)
    to run N requests concurrently. Any exception from the gather (timeout, ResponseError,
    network error) is caught in the loop and silently converted to ModelOutputThunk(value=""),
    with the exception stored only in result._generate_log.extra["error"].

    This is distinct from the streaming path described above — it's in the non-streaming batch
    path — but the effect is the same: failures are invisible to the caller.

    Discovered because tests asserting result.value is not None passed even when requests
    were silently failing (empty string is not None). Once assertions were tightened to
    assert all(r.value for r in results), the failures became visible.

    Added a FancyLogger.warning() at the exception site as a temporary measure. The proper
    fix (public error field on ModelOutputThunk, as discussed above) would cover both
    the streaming and batch paths.

    I think I'll take a look at this (tomorrow...)

  5. planetf1 commented on Mar 6, 2026

    @planetf1
    ContributorAuthor

    The primary bug reported here — backends crashing with AttributeError when an exception chunk was passed to processing() — is fixed by #580. That PR restructures astream() in base.py to raise exceptions immediately, before any backend processing() or post_process() call. The proposed per-backend isinstance(chunk, Exception) guards are no longer needed.

    The secondary concern (Ollama's generate_from_raw silently converting batch exceptions into ModelOutputThunk(value="")) is a separate issue on a different code path, not addressed by #580. Will raise in new issue

    Closing in favour of #580.

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions