Skip to content

fix(serve): invalid max_error and set bounds answer 422 before inference, with a code - #62

Merged
rkinas merged 1 commit into
rkinas:mainfrom
pawelkiszczak:pr/422-before-inference
Nov 2, 2026
Merged

rkinas merged 1 commit into
rkinas:mainfrom
pawelkiszczak:pr/422-before-inference

Conversation

@pawelkiszczak

@pawelkiszczak pawelkiszczak commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Closes #61

What

  • Reject non-numeric act.max_error and threshold-objective set bounds that cannot convert to int() during request parsing, before model inference.
  • Add code to failed responses: INVALID_REQUEST for 422, OUT_OF_MEMORY for 503, and INTERNAL_ERROR for 500. Keep the existing error field unchanged and add one-item detail only for 422 responses.

Why

Clients can correct invalid requests without invoking the model and can identify failure categories programmatically.

Compatibility

Successful response bodies are unchanged. Error bodies retain error and add code; 422 bodies additionally add detail. Malformed JSON follows the existing RequestError path and receives INVALID_REQUEST.

Tests run

  • uv run --no-sync pytest -q tests/test_http_status.py tests/test_server.py — 80 passed.
  • uv run --no-sync pytest -q -x — 764 passed, 53 skipped, 1 warning.
  • uvx [email protected] check --select E9,F63,F7,F82 --target-version py310 . — failed on existing F821 Undefined name kpos in untouched basal/gemma4.py:471.

Summary by Sourcery

Validate malformed serving requests before inference and provide machine-readable error classifications.

Bug Fixes:

  • Reject invalid max_error values and threshold set bounds during request validation so malformed requests return 422 before model inference.

Enhancements:

  • Add stable error codes for invalid requests, out-of-memory failures, and internal server errors while preserving existing error messages.
  • Include structured body-location validation details in 422 responses.

Documentation:

  • Document the new error codes and 422 response details in the API reference and release notes.

Tests:

  • Expand HTTP error coverage for invalid parameters, structured error responses, and prevention of inference on rejected requests.

@sourcery-ai

sourcery-ai Bot commented Oct 28, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

The PR moves invalid max_error and threshold set-bound failures into request parsing/validation so inference is not started, and standardizes all failed HTTP responses with machine-readable codes while adding body-level detail for 422 errors; successful responses and the existing error message remain unchanged.

Sequence diagram for pre-inference request validation and coded errors

sequenceDiagram
    participant Client
    participant Server as HTTP server
    participant Validation as Request validation
    participant Model as Model inference

    Client->>Server: POST /v1/systemone or /v1/basal
    Server->>Validation: act_spec()
    Validation->>Validation: float(max_error)
    Validation->>Validation: validate(min, max)
    alt Invalid max_error or set bound
        Validation-->>Server: RequestError or ValueError
        Server-->>Client: 422 {error, code: INVALID_REQUEST, detail}
    else Valid request
        Validation-->>Server: Validated request
        Server->>Model: Run inference
        Model-->>Server: Result or failure
        alt Out of memory
            Server-->>Client: 503 {error, code: OUT_OF_MEMORY}
        else Other server error
            Server-->>Client: 500 {error, code: INTERNAL_ERROR}
        end
    end
Loading

Flow diagram for standardized HTTP failure responses

flowchart TD
    Failure[Request or server failure] --> Status{HTTP status}
    Status -->|422| Invalid[INVALID_REQUEST<br/>error + detail]
    Status -->|503| Memory[OUT_OF_MEMORY<br/>error]
    Status -->|500| Internal[INTERNAL_ERROR<br/>error]
Loading

File-Level Changes

Change Details Files
Reject invalid request parameters during parsing and validation, before model inference.
  • Coerce and validate act max_error as a numeric value.
  • Validate threshold-objective min and max bounds through integer conversion.
  • Raise request errors with field-specific messages for invalid values.
basal/server.py
basal/sets.py
tests/test_http_status.py
Add stable machine-readable categories and validation details to HTTP error responses.
  • Map 422, 503, and 500 responses to INVALID_REQUEST, OUT_OF_MEMORY, and INTERNAL_ERROR.
  • Add one body-location detail item to 422 responses while preserving error messages.
  • Cover malformed and runtime error response shapes without changing successful responses.
basal/server.py
docs/API.md
tests/test_http_status.py
Document the new serving error contract and unreleased behavior.
  • Document error codes and 422 detail semantics in the API reference.
  • Record pre-inference validation and response changes in the release notes.
docs/API.md
docs/WHATS_NEW.md

Assessment against linked issues

Issue Objective Addressed Explanation
#61 Reject non-numeric act.max_error and threshold-objective min/max values that cannot convert to integers during request parsing, before model inference. ✅
#61 Add stable machine-readable codes to failed HTTP responses while preserving the existing error field, and include a body-location detail on 422 responses. ✅
#61 Preserve successful response bodies so valid requests remain compatible with the prior version. ✅

Possibly linked issues


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 2 issues

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

## Individual Comments

### Comment 1
<location path="basal/server.py" line_range="287" />
<code_context>
+    max_error = q.get("max_error")
+    if max_error is not None:
+        try:
+            max_error = float(max_error)
+        except (TypeError, ValueError, OverflowError):
+            raise RequestError(f"question {name!r}: max_error must be a number") from None
</code_context>
<issue_to_address>
**Invalid targets reach inference**

When an `act` request supplies a boolean, non-finite value, or numeric `max_error` outside `(0, 1)`, `float(max_error)` accepts these values, so `act_spec` passes them to inference; `certified` finds no matching threshold, causing a defer action to be selected or a `RequestError`/422 only after inference.

Reject boolean, non-finite, and out-of-range `max_error` values in `act_spec` before inference.
</issue_to_address>

### Comment 2
<location path="docs/API.md" line_range="84-85" />
<code_context>
   - **503**: the GPU ran out of memory (CUDA, MPS or Metal). The server frees the failed request's memory, so a retry,
     later or on another server, may succeed;
   - **500**: any other server error.
+  Every error body also has a `code`: `INVALID_REQUEST` (422), `OUT_OF_MEMORY` (503) or `INTERNAL_ERROR` (500).
+  A 422 adds `detail`, a one-item body-location validation error; `error` retains the message.
 - `GET /v1/models` returns `{"models": [{"name", "description", "release_date", "mode", "early_exit",
   "temperature_per_prim"}]}` (`release_date` is the engine's release date, not the model's).
</code_context>
<issue_to_address>
**Error shape docs conflict**

When a client is implemented from the FORMAT2 or SERVING error descriptions, the current serving guides still say errors have only `{"error": ...}` and that 422, 503, and 500 share that body, so clients following those descriptions can reject the new `code` field and 422 `detail` field.

Update the current FORMAT2 and SERVING error descriptions to include `code` and explain that only 422 includes `detail`.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread basal/server.py
max_error = q.get("max_error")
if max_error is not None:
try:
max_error = float(max_error)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Medium · Invalid targets reach inference

When an act request supplies a boolean, non-finite value, or numeric max_error outside (0, 1), float(max_error) accepts these values, so act_spec passes them to inference; certified finds no matching threshold, causing a defer action to be selected or a RequestError/422 only after inference.

Reject boolean, non-finite, and out-of-range max_error values in act_spec before inference.

Prompt for AI agents
In `basal/server.py` at line 287:

**Invalid targets reach inference**

When an `act` request supplies a boolean, non-finite value, or numeric `max_error` outside `(0, 1)`, `float(max_error)` accepts these values, so `act_spec` passes them to inference; `certified` finds no matching threshold, causing a defer action to be selected or a `RequestError`/422 only after inference.

Reject boolean, non-finite, and out-of-range `max_error` values in `act_spec` before inference.

Comment thread docs/API.md
Comment on lines +84 to +85
Every error body also has a `code`: `INVALID_REQUEST` (422), `OUT_OF_MEMORY` (503) or `INTERNAL_ERROR` (500).
A 422 adds `detail`, a one-item body-location validation error; `error` retains the message.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚪ Low · Error shape docs conflict

When a client is implemented from the FORMAT2 or SERVING error descriptions, the current serving guides still say errors have only {"error": ...} and that 422, 503, and 500 share that body, so clients following those descriptions can reject the new code field and 422 detail field.

Update the current FORMAT2 and SERVING error descriptions to include code and explain that only 422 includes detail.

Prompt for AI agents
In `docs/API.md` at lines 84-85:

**Error shape docs conflict**

When a client is implemented from the FORMAT2 or SERVING error descriptions, the current serving guides still say errors have only `{"error": ...}` and that 422, 503, and 500 share that body, so clients following those descriptions can reject the new `code` field and 422 `detail` field.

Update the current FORMAT2 and SERVING error descriptions to include `code` and explain that only 422 includes `detail`.

@rkinas

rkinas commented Oct 28, 2026

Copy link
Copy Markdown
Owner

Thank you, Paweł! Planned for basal 2.5: we are merging this into the 2.5 release branch now, after our checks (full CPU suite, success responses byte-identical, error texts unchanged). The PR will close when 2.5 is published on main.

@rkinas
rkinas merged commit b5f84d5 into rkinas:main Nov 2, 2026
1 check passed
rkinas added a commit that referenced this pull request Nov 2, 2026
… version

CONTRIBUTING.md credits the 2.5 pull requests as the release notes' community line lists them (Paweł Kiszczak
#52, #62, #64, #66, #68, #71, #73, #75; Marcin Brzeżański #56; Grzegorz Brzezinka #76, #78) and adds Dariusz
Koryto (#53, #58, #59, #60 and #55); the README's list names him too. docs/changes/README.md and the
changelog.py help use 2.5.1, the next release, as the example.
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.

Reject invalid request fields before inference and identify error responses

2 participants