← pod_r5_v1h

fastapi_14306

failed CONTEXT UNSUBMITTED agent_error · 50 tool calls · 212 s · fastapi/fastapi

Task input

🚸  Improve tracebacks by adding endpoint metadata

Today, when validation errors occur, error messages don't indicate what endpoint caused the problem, which can make debugging difficult. 

This PR adds endpoint context metadata to validation error messages to show the filepath (clickable in IDEs!) and line number, function name and HTTP method and route where applicable. The endpoint context is extracted once per endpoint and then cached to avoid any additional performance overhead on subsequent requests. Just to double check, I also ran a rough benchmark (100k requests):
```
Baseline (without changes):     0.0006s
Uncached:     					1.3281s (13.28µs per request)
**Cached**:       				0.0060s (0.06µs per request)
```

Endpoint context only appears in the exception's string representation (server logs). It is **not** exposed to clients in HTTP responses. Clients still receive the standard 422 response with validation error details.

## Examples

### ResponseValidationError

**Before:**
```
fastapi.exceptions.ResponseValidationError: 1 validation error:
  {'type': 'missing', 'loc': ('response', 'id'), 'msg': 'Field required', 'input': {'name': 'Widget'}}
```

**After:**
```
fastapi.exceptions.ResponseValidationError: 1 validation error:
  {'type': 'missing', 'loc': ('response', 'id'), 'msg': 'Field required', 'input': {'name': 'Widget'}}

  File "/Users/savannah/work/fastapi/capture_real_examples.py", line 43, in create_item
    POST /items/
```

### RequestValidationError

**Before:**
```
fastapi.exceptions.RequestValidationError: 1 validation error:
  {'type': 'int_parsing', 'loc': ('path', 'user_id'), 'msg': 'Input should be a valid integer, unable to parse string as an integer', 'input': 'invalid'}
```

**After:**
```
fastapi.exceptions.RequestValidationError: 1 validation error:
  {'type': 'int_parsing', 'loc': ('path', 'user_id'), 'msg': 'Input should be a valid integer, unable to parse string as an integer', 'input': 'invalid'}

  File "/Users/savannah/work/fastapi/capture_real_examples.py", line 38, in get_user
    GET /users/{user_id}
```

### WebSocketRequestValidationError

**Before:**
```
fastapi.exceptions.WebSocketRequestValidationError: 1 validation error:
  {'type': 'int_parsing', 'loc': ('path', 'item_id'), 'msg': 'Input should be a valid integer, unable to parse string as an integer', 'input': 'invalid'}
```

**After:**
```
fastapi.exceptions.WebSocketRequestValidationError: 1 validation error:
  {'type': 'int_parsing', 'loc': ('path', 'item_id'), 'msg': 'Input should be a valid integer, unable to parse string as an integer', 'input': 'invalid'}

  File "/Users/savannah/work/fastapi/capture_real_examples.py", line 48, in websocket_endpoint
    WS /ws/{item_id}
```

Tool calls (50)

#ToolArgumentsResult
1run_command
{
 "command": "grep -rn \"ResponseValidationError\" \"fastapi/exceptions.py\""
}
{"status": "ok", "stdout": "fastapi/exceptions.py:175:class ResponseValidationError(ValidationException):\n", "stderr": "", "exit_code": 0}
full
{"status": "ok", "stdout": "fastapi/exceptions.py:175:class ResponseValidationError(ValidationException):\n", "stderr": "", "exit_code": 0}
2run_command
{
 "command": "grep -rn \"RequestValidationError\" \"fastapi/exceptions.py\""
}
{"status": "ok", "stdout": "fastapi/exceptions.py:165:class RequestValidationError(ValidationException):\nfastapi/exceptions.py:171:class WebSocketRequestValida
full
{"status": "ok", "stdout": "fastapi/exceptions.py:165:class RequestValidationError(ValidationException):\nfastapi/exceptions.py:171:class WebSocketRequestValidationError(ValidationException):\n", "stderr": "", "exit_code": 0}
3run_command
{
 "command": "sed -n '150,200p' fastapi/exceptions.py"
}
{"status": "ok", "stdout": "class DependencyScopeError(FastAPIError):\n \"\"\"\n A dependency declared that it depends on another dependency with an invalid\n (
full
{"status": "ok", "stdout": "class DependencyScopeError(FastAPIError):\n    \"\"\"\n    A dependency declared that it depends on another dependency with an invalid\n    (narrower) scope.\n    \"\"\"\n\n\nclass ValidationException(Exception):\n    def __init__(self, errors: Sequence[Any]) -> None:\n        self._errors = errors\n\n    def errors(self) -> Sequence[Any]:\n        return self._errors\n\n\nclass RequestValidationError(ValidationException):\n    def __init__(self, errors: Sequence[Any], *, body: Any = None) -> None:\n        super().__init__(errors)\n        self.body = body\n\n\nclass WebSocketRequestValidationError(ValidationException):\n    pass\n\n\nclass ResponseValidationError(ValidationException):\n    def __init__(self, errors: Sequence[Any], *, body: Any = None) -> None:\n        super().__init__(errors)\n        self.body = body\n\n    def __str__(self) -> str:\n        message = f\"{len(self._errors)} validation errors:\\n\"\n        for err in self._errors:\n            message += f\"  {err}\\n\"\n        return message\n", "stderr": "", "exit_code": 0}
4run_command
{
 "command": "grep -rn \"ResponseValidationError\" . --include=\"*.py\" | grep -v \"exceptions.py\" | head -20"
}
{"status": "ok", "stdout": "./tests/test_filter_pydantic_sub_model/test_filter_pydantic_sub_model_pv1.py:2:from fastapi.exceptions import ResponseValidationErro
full
{"status": "ok", "stdout": "./tests/test_filter_pydantic_sub_model/test_filter_pydantic_sub_model_pv1.py:2:from fastapi.exceptions import ResponseValidationError\n./tests/test_filter_pydantic_sub_model/test_filter_pydantic_sub_model_pv1.py:29:    with pytest.raises(ResponseValidationError) as err:\n./tests/test_response_model_as_return_annotation.py:5:from fastapi.exceptions import FastAPIError, ResponseValidationError\n./tests/test_response_model_as_return_annotation.py:282:    with pytest.raises(ResponseValidationError) as excinfo:\n./tests/test_response_model_as_return_annotation.py:288:    with pytest.raises(ResponseValidationError) as excinfo:\n./tests/test_response_model_as_return_annotation.py:320:    with pytest.raises(ResponseValidationError) as excinfo:\n./tests/test_response_model_as_return_annotation.py:326:    with pytest.raises(ResponseValidationError) as excinfo:\n./tests/test_response_model_as_return_annotation.py:404:    with pytest.raises(ResponseValidationError) as excinfo:\n./tests/test_response_model_as_return_annotation.py:410:    with pytest.raises(ResponseValidationError) as excinfo:\n./tests/test_validate_response.py:5:from fastapi.exceptions import ResponseValidationError\n./tests/test_validate_response.py:54:    with pytest.raises(ResponseValidationError):\n./tests/test_validate_response.py:59:    with pytest.raises(ResponseValidationError):\n./tests/test_validate_response.py:78:    with pytest.raises(ResponseValidationError):\n./tests/test_validate_response.py:83:    with pytest.raises(ResponseValidationError):\n./tests/test_validate_response_dataclass.py:5:from fastapi.exceptions import ResponseValidationError\n./tests/test_validate_response_dataclass.py:42:    with pytest.raises(ResponseValidationError):\n./tests/test_validate_response_dataclass.py:47:    with pytest.raises(ResponseValidationError):\n./tests/test_validate_response_dataclass.py:52:    with pytest.raises(ResponseValidationError):\n./tests/test_filter_pydantic_sub_model_pv
5run_command
{
 "command": "grep -rn \"RequestValidationError\" fastapi/utils.py fastapi/routing.py fastapi/applications.py"
}
{"status": "ok", "stdout": "fastapi/routing.py:50: RequestValidationError,\nfastapi/routing.py:52: WebSocketRequestValidationError,\nfastapi/routing.py:347: val
full
{"status": "ok", "stdout": "fastapi/routing.py:50:    RequestValidationError,\nfastapi/routing.py:52:    WebSocketRequestValidationError,\nfastapi/routing.py:347:            validation_error = RequestValidationError(\nfastapi/routing.py:423:            validation_error = RequestValidationError(\nfastapi/routing.py:453:            raise WebSocketRequestValidationError(\nfastapi/applications.py:24:from fastapi.exceptions import RequestValidationError, WebSocketRequestValidationError\nfastapi/applications.py:988:            RequestValidationError, request_validation_exception_handler\nfastapi/applications.py:991:            WebSocketRequestValidationError,\n", "stderr": "", "exit_code": 0}
6run_command
{
 "command": "sed -n '330,460p' fastapi/routing.py"
}
{"status": "ok", "stdout": " if body_bytes:\n json_body: Any = Undefined\n content_type_value = request.headers.get(\"content-type\")\n if not content_type_valu
full
{"status": "ok", "stdout": "                    if body_bytes:\n                        json_body: Any = Undefined\n                        content_type_value = request.headers.get(\"content-type\")\n                        if not content_type_value:\n                            json_body = await request.json()\n                        else:\n                            message = email.message.Message()\n                            message[\"content-type\"] = content_type_value\n                            if message.get_content_maintype() == \"application\":\n                                subtype = message.get_content_subtype()\n                                if subtype == \"json\" or subtype.endswith(\"+json\"):\n                                    json_body = await request.json()\n                        if json_body != Undefined:\n                            body = json_body\n                        else:\n                            body = body_bytes\n        except json.JSONDecodeError as e:\n            validation_error = RequestValidationError(\n                [\n                    {\n                        \"type\": \"json_invalid\",\n                        \"loc\": (\"body\", e.pos),\n                        \"msg\": \"JSON decode error\",\n                        \"input\": {},\n                        \"ctx\": {\"error\": e.msg},\n                    }\n                ],\n                body=e.doc,\n            )\n            raise validation_error from e\n        except HTTPException:\n            # If a middleware raises an HTTPException, it should be raised again\n            raise\n        except Exception as e:\n            http_error = HTTPException(\n                status_code=400, detail=\"There was an error parsing the body\"\n            )\n            raise http_error from e\n\n        # Solve dependencies and run path operation function, auto-closing dependencies\n        errors: List[Any] = []\n        async_exit_stack = request.sc
7run_command
{
 "command": "grep -n \"raise WebSocketRequestValidationError\" fastapi/routing.py"
}
{"status": "ok", "stdout": "453: raise WebSocketRequestValidationError(\n", "stderr": "", "exit_code": 0}
full
{"status": "ok", "stdout": "453:            raise WebSocketRequestValidationError(\n", "stderr": "", "exit_code": 0}
8run_command
{
 "command": "sed -n '440,460p' fastapi/routing.py"
}
{"status": "ok", "stdout": " async def app(websocket: WebSocket) -> None:\n async_exit_stack = websocket.scope.get(\"fastapi_inner_astack\")\n assert isinstance
full
{"status": "ok", "stdout": "    async def app(websocket: WebSocket) -> None:\n        async_exit_stack = websocket.scope.get(\"fastapi_inner_astack\")\n        assert isinstance(async_exit_stack, AsyncExitStack), (\n            \"fastapi_inner_astack not found in request scope\"\n        )\n        solved_result = await solve_dependencies(\n            request=websocket,\n            dependant=dependant,\n            dependency_overrides_provider=dependency_overrides_provider,\n            async_exit_stack=async_exit_stack,\n            embed_body_fields=embed_body_fields,\n        )\n        if solved_result.errors:\n            raise WebSocketRequestValidationError(\n                _normalize_errors(solved_result.errors)\n            )\n        assert dependant.call is not None, \"dependant.call must be a function\"\n        await dependant.call(**solved_result.values)\n\n    return app\n\n", "stderr": "", "exit_code": 0}
9run_command
{
 "command": "grep -rn \"serialize_response\" fastapi/routing.py"
}
{"status": "ok", "stdout": "fastapi/routing.py:215:async def serialize_response(\nfastapi/routing.py:407: content = await serialize_response(\n", "stderr": "",
full
{"status": "ok", "stdout": "fastapi/routing.py:215:async def serialize_response(\nfastapi/routing.py:407:                content = await serialize_response(\n", "stderr": "", "exit_code": 0}
10run_command
{
 "command": "sed -n '215,260p' fastapi/routing.py"
}
{"status": "ok", "stdout": "async def serialize_response(\n *,\n field: Optional[ModelField] = None,\n response_content: Any,\n include: Optional[IncEx] = None,
full
{"status": "ok", "stdout": "async def serialize_response(\n    *,\n    field: Optional[ModelField] = None,\n    response_content: Any,\n    include: Optional[IncEx] = None,\n    exclude: Optional[IncEx] = None,\n    by_alias: bool = True,\n    exclude_unset: bool = False,\n    exclude_defaults: bool = False,\n    exclude_none: bool = False,\n    is_coroutine: bool = True,\n) -> Any:\n    if field:\n        errors = []\n        if not hasattr(field, \"serialize\"):\n            # pydantic v1\n            response_content = _prepare_response_content(\n                response_content,\n                exclude_unset=exclude_unset,\n                exclude_defaults=exclude_defaults,\n                exclude_none=exclude_none,\n            )\n        if is_coroutine:\n            value, errors_ = field.validate(response_content, {}, loc=(\"response\",))\n        else:\n            value, errors_ = await run_in_threadpool(\n                field.validate, response_content, {}, loc=(\"response\",)\n            )\n        if isinstance(errors_, list):\n            errors.extend(errors_)\n        elif errors_:\n            errors.append(errors_)\n        if errors:\n            raise ResponseValidationError(\n                errors=_normalize_errors(errors), body=response_content\n            )\n\n        if hasattr(field, \"serialize\"):\n            return field.serialize(\n                value,\n                include=include,\n                exclude=exclude,\n                by_alias=by_alias,\n                exclude_unset=exclude_unset,\n                exclude_defaults=exclude_defaults,\n                exclude_none=exclude_none,\n", "stderr": "", "exit_code": 0}
11run_command
{
 "command": "grep -rn \"ResponseValidationError\" fastapi/routing.py"
}
{"status": "ok", "stdout": "fastapi/routing.py:51: ResponseValidationError,\nfastapi/routing.py:248: raise ResponseValidationError(\n", "stderr": "", "exit_code
full
{"status": "ok", "stdout": "fastapi/routing.py:51:    ResponseValidationError,\nfastapi/routing.py:248:            raise ResponseValidationError(\n", "stderr": "", "exit_code": 0}
12run_command
{
 "command": "grep -rn \"dependant\" fastapi/routing.py | head -20"
}
{"status": "ok", "stdout": "fastapi/routing.py:41: get_dependant,\nfastapi/routing.py:42: get_flat_dependant,\nfastapi/routing.py:43: get_parameterless_sub_depe
full
{"status": "ok", "stdout": "fastapi/routing.py:41:    get_dependant,\nfastapi/routing.py:42:    get_flat_dependant,\nfastapi/routing.py:43:    get_parameterless_sub_dependant,\nfastapi/routing.py:277:    *, dependant: Dependant, values: Dict[str, Any], is_coroutine: bool\nfastapi/routing.py:281:    assert dependant.call is not None, \"dependant.call must be a function\"\nfastapi/routing.py:284:        return await dependant.call(**values)\nfastapi/routing.py:286:        return await run_in_threadpool(dependant.call, **values)\nfastapi/routing.py:290:    dependant: Dependant,\nfastapi/routing.py:304:    assert dependant.call is not None, \"dependant.call must be a function\"\nfastapi/routing.py:305:    is_coroutine = dependant.is_coroutine_callable\nfastapi/routing.py:377:            dependant=dependant,\nfastapi/routing.py:386:                dependant=dependant,\nfastapi/routing.py:436:    dependant: Dependant,\nfastapi/routing.py:447:            dependant=dependant,\nfastapi/routing.py:456:        assert dependant.call is not None, \"dependant.call must be a function\"\nfastapi/routing.py:457:        await dependant.call(**solved_result.values)\nfastapi/routing.py:477:        self.dependant = get_dependant(\nfastapi/routing.py:481:            self.dependant.dependencies.insert(\nfastapi/routing.py:483:                get_parameterless_sub_dependant(depends=depends, path=self.path_format),\nfastapi/routing.py:485:        self._flat_dependant = get_flat_dependant(self.dependant)\n", "stderr": "", "exit_code": 0}
13run_command
{
 "command": "grep -rn \"class Dependant\" ."
}
{"status": "ok", "stdout": "./fastapi/dependencies/models.py:32:class Dependant:\n", "stderr": "", "exit_code": 0}
full
{"status": "ok", "stdout": "./fastapi/dependencies/models.py:32:class Dependant:\n", "stderr": "", "exit_code": 0}
14run_command
{
 "command": "sed -n '30,80p' fastapi/dependencies/models.py"
}
{"status": "ok", "stdout": "\n@dataclass\nclass Dependant:\n path_params: List[ModelField] = field(default_factory=list)\n query_params: List[ModelField] = fiel
full
{"status": "ok", "stdout": "\n@dataclass\nclass Dependant:\n    path_params: List[ModelField] = field(default_factory=list)\n    query_params: List[ModelField] = field(default_factory=list)\n    header_params: List[ModelField] = field(default_factory=list)\n    cookie_params: List[ModelField] = field(default_factory=list)\n    body_params: List[ModelField] = field(default_factory=list)\n    dependencies: List[\"Dependant\"] = field(default_factory=list)\n    name: Optional[str] = None\n    call: Optional[Callable[..., Any]] = None\n    request_param_name: Optional[str] = None\n    websocket_param_name: Optional[str] = None\n    http_connection_param_name: Optional[str] = None\n    response_param_name: Optional[str] = None\n    background_tasks_param_name: Optional[str] = None\n    security_scopes_param_name: Optional[str] = None\n    own_oauth_scopes: Optional[List[str]] = None\n    parent_oauth_scopes: Optional[List[str]] = None\n    use_cache: bool = True\n    path: Optional[str] = None\n    scope: Union[Literal[\"function\", \"request\"], None] = None\n\n    @cached_property\n    def oauth_scopes(self) -> List[str]:\n        scopes = self.parent_oauth_scopes.copy() if self.parent_oauth_scopes else []\n        # This doesn't use a set to preserve order, just in case\n        for scope in self.own_oauth_scopes or []:\n            if scope not in scopes:\n                scopes.append(scope)\n        return scopes\n\n    @cached_property\n    def cache_key(self) -> DependencyCacheKey:\n        scopes_for_cache = (\n            tuple(sorted(set(self.oauth_scopes or []))) if self._uses_scopes else ()\n        )\n        return (\n            self.call,\n            scopes_for_cache,\n            self.computed_scope or \"\",\n        )\n\n    @cached_property\n    def _uses_scopes(self) -> bool:\n        if self.own_oauth_scopes:\n            return True\n        if self.security_scopes_param_name is not None:\n            return True\n        if self._is_security_sche
15run_command
{
 "command": "grep -rn \"inspect\" fastapi/ | head -20"
}
{"status": "ok", "stdout": "fastapi/dependencies/models.py:1:import inspect\nfastapi/dependencies/models.py:13: from inspect import iscoroutinefunction\nfastapi
full
{"status": "ok", "stdout": "fastapi/dependencies/models.py:1:import inspect\nfastapi/dependencies/models.py:13:    from inspect import iscoroutinefunction\nfastapi/dependencies/models.py:21:    unwrapped = inspect.unwrap(_impartial(call))\nfastapi/dependencies/models.py:109:        if inspect.isgeneratorfunction(\nfastapi/dependencies/models.py:111:        ) or inspect.isgeneratorfunction(_unwrapped_call(self.call)):\nfastapi/dependencies/models.py:113:        if inspect.isclass(_unwrapped_call(self.call)):\nfastapi/dependencies/models.py:118:        if inspect.isgeneratorfunction(\nfastapi/dependencies/models.py:120:        ) or inspect.isgeneratorfunction(_unwrapped_call(dunder_call)):\nfastapi/dependencies/models.py:125:        if inspect.isgeneratorfunction(\nfastapi/dependencies/models.py:127:        ) or inspect.isgeneratorfunction(_unwrapped_call(dunder_unwrapped_call)):\nfastapi/dependencies/models.py:135:        if inspect.isasyncgenfunction(\nfastapi/dependencies/models.py:137:        ) or inspect.isasyncgenfunction(_unwrapped_call(self.call)):\nfastapi/dependencies/models.py:139:        if inspect.isclass(_unwrapped_call(self.call)):\nfastapi/dependencies/models.py:144:        if inspect.isasyncgenfunction(\nfastapi/dependencies/models.py:146:        ) or inspect.isasyncgenfunction(_unwrapped_call(dunder_call)):\nfastapi/dependencies/models.py:151:        if inspect.isasyncgenfunction(\nfastapi/dependencies/models.py:153:        ) or inspect.isasyncgenfunction(_unwrapped_call(dunder_unwrapped_call)):\nfastapi/dependencies/models.py:161:        if inspect.isroutine(_impartial(self.call)) and iscoroutinefunction(\nfastapi/dependencies/models.py:165:        if inspect.isroutine(_unwrapped_call(self.call)) and iscoroutinefunction(\nfastapi/dependencies/models.py:169:        if inspect.isclass(_unwrapped_call(self.call)):\n", "stderr": "", "exit_code": 0}
16run_command
{
 "command": "sed -n '1,30p' fastapi/dependencies/models.py"
}
{"status": "ok", "stdout": "import inspect\nimport sys\nfrom dataclasses import dataclass, field\nfrom functools import cached_property, partial\nfrom typing im
full
{"status": "ok", "stdout": "import inspect\nimport sys\nfrom dataclasses import dataclass, field\nfrom functools import cached_property, partial\nfrom typing import Any, Callable, List, Optional, Union\n\nfrom fastapi._compat import ModelField\nfrom fastapi.security.base import SecurityBase\nfrom fastapi.types import DependencyCacheKey\nfrom typing_extensions import Literal\n\nif sys.version_info >= (3, 13):  # pragma: no cover\n    from inspect import iscoroutinefunction\nelse:  # pragma: no cover\n    from asyncio import iscoroutinefunction\n\n\ndef _unwrapped_call(call: Optional[Callable[..., Any]]) -> Any:\n    if call is None:\n        return call  # pragma: no cover\n    unwrapped = inspect.unwrap(_impartial(call))\n    return unwrapped\n\n\ndef _impartial(func: Callable[..., Any]) -> Callable[..., Any]:\n    while isinstance(func, partial):\n        func = func.func\n    return func\n\n\n", "stderr": "", "exit_code": 0}
17run_command
{
 "command": "sed -n '30,100p' fastapi/dependencies/models.py"
}
{"status": "ok", "stdout": "\n@dataclass\nclass Dependant:\n path_params: List[ModelField] = field(default_factory=list)\n query_params: List[ModelField] = fiel
full
{"status": "ok", "stdout": "\n@dataclass\nclass Dependant:\n    path_params: List[ModelField] = field(default_factory=list)\n    query_params: List[ModelField] = field(default_factory=list)\n    header_params: List[ModelField] = field(default_factory=list)\n    cookie_params: List[ModelField] = field(default_factory=list)\n    body_params: List[ModelField] = field(default_factory=list)\n    dependencies: List[\"Dependant\"] = field(default_factory=list)\n    name: Optional[str] = None\n    call: Optional[Callable[..., Any]] = None\n    request_param_name: Optional[str] = None\n    websocket_param_name: Optional[str] = None\n    http_connection_param_name: Optional[str] = None\n    response_param_name: Optional[str] = None\n    background_tasks_param_name: Optional[str] = None\n    security_scopes_param_name: Optional[str] = None\n    own_oauth_scopes: Optional[List[str]] = None\n    parent_oauth_scopes: Optional[List[str]] = None\n    use_cache: bool = True\n    path: Optional[str] = None\n    scope: Union[Literal[\"function\", \"request\"], None] = None\n\n    @cached_property\n    def oauth_scopes(self) -> List[str]:\n        scopes = self.parent_oauth_scopes.copy() if self.parent_oauth_scopes else []\n        # This doesn't use a set to preserve order, just in case\n        for scope in self.own_oauth_scopes or []:\n            if scope not in scopes:\n                scopes.append(scope)\n        return scopes\n\n    @cached_property\n    def cache_key(self) -> DependencyCacheKey:\n        scopes_for_cache = (\n            tuple(sorted(set(self.oauth_scopes or []))) if self._uses_scopes else ()\n        )\n        return (\n            self.call,\n            scopes_for_cache,\n            self.computed_scope or \"\",\n        )\n\n    @cached_property\n    def _uses_scopes(self) -> bool:\n        if self.own_oauth_scopes:\n            return True\n        if self.security_scopes_param_name is not None:\n            return True\n        if self._is_security_sche
18run_command
{
 "command": "sed -n '100,180p' fastapi/dependencies/models.py"
}
{"status": "ok", "stdout": " @cached_property\n def _security_dependencies(self) -> List[\"Dependant\"]:\n security_deps = [dep for dep in self.dependencies if
full
{"status": "ok", "stdout": "    @cached_property\n    def _security_dependencies(self) -> List[\"Dependant\"]:\n        security_deps = [dep for dep in self.dependencies if dep._is_security_scheme]\n        return security_deps\n\n    @cached_property\n    def is_gen_callable(self) -> bool:\n        if self.call is None:\n            return False  # pragma: no cover\n        if inspect.isgeneratorfunction(\n            _impartial(self.call)\n        ) or inspect.isgeneratorfunction(_unwrapped_call(self.call)):\n            return True\n        if inspect.isclass(_unwrapped_call(self.call)):\n            return False\n        dunder_call = getattr(_impartial(self.call), \"__call__\", None)  # noqa: B004\n        if dunder_call is None:\n            return False  # pragma: no cover\n        if inspect.isgeneratorfunction(\n            _impartial(dunder_call)\n        ) or inspect.isgeneratorfunction(_unwrapped_call(dunder_call)):\n            return True\n        dunder_unwrapped_call = getattr(_unwrapped_call(self.call), \"__call__\", None)  # noqa: B004\n        if dunder_unwrapped_call is None:\n            return False  # pragma: no cover\n        if inspect.isgeneratorfunction(\n            _impartial(dunder_unwrapped_call)\n        ) or inspect.isgeneratorfunction(_unwrapped_call(dunder_unwrapped_call)):\n            return True\n        return False\n\n    @cached_property\n    def is_async_gen_callable(self) -> bool:\n        if self.call is None:\n            return False  # pragma: no cover\n        if inspect.isasyncgenfunction(\n            _impartial(self.call)\n        ) or inspect.isasyncgenfunction(_unwrapped_call(self.call)):\n            return True\n        if inspect.isclass(_unwrapped_call(self.call)):\n            return False\n        dunder_call = getattr(_impartial(self.call), \"__call__\", None)  # noqa: B004\n        if dunder_call is None:\n            return False  # pragma: no cover\n        if inspect.isasyncgenfunction(\n            _im
19run_command
{
 "command": "sed -n '180,220p' fastapi/dependencies/models.py"
}
{"status": "ok", "stdout": " return False # pragma: no cover\n if iscoroutinefunction(\n _impartial(dunder_unwrapped_call)\n ) or iscoroutinefunction(_unwrapped
full
{"status": "ok", "stdout": "            return False  # pragma: no cover\n        if iscoroutinefunction(\n            _impartial(dunder_unwrapped_call)\n        ) or iscoroutinefunction(_unwrapped_call(dunder_unwrapped_call)):\n            return True\n        return False\n\n    @cached_property\n    def computed_scope(self) -> Union[str, None]:\n        if self.scope:\n            return self.scope\n        if self.is_gen_callable or self.is_async_gen_callable:\n            return \"request\"\n        return None\n", "stderr": "", "exit_code": 0}
20run_command
{
 "command": "grep -rn \"import inspect\" fastapi/exceptions.py"
}
{"status": "error", "error_type": "CommandError", "error_message": "", "details": {"stdout": "", "stderr": "", "exit_code": 1}}
full
{"status": "error", "error_type": "CommandError", "error_message": "", "details": {"stdout": "", "stderr": "", "exit_code": 1}}
21run_command
{
 "command": "sed -n '1,150p' fastapi/exceptions.py"
}
{"status": "ok", "stdout": "from typing import Any, Dict, Optional, Sequence, Type, Union\n\nfrom annotated_doc import Doc\nfrom pydantic import BaseModel, crea
full
{"status": "ok", "stdout": "from typing import Any, Dict, Optional, Sequence, Type, Union\n\nfrom annotated_doc import Doc\nfrom pydantic import BaseModel, create_model\nfrom starlette.exceptions import HTTPException as StarletteHTTPException\nfrom starlette.exceptions import WebSocketException as StarletteWebSocketException\nfrom typing_extensions import Annotated\n\n\nclass HTTPException(StarletteHTTPException):\n    \"\"\"\n    An HTTP exception you can raise in your own code to show errors to the client.\n\n    This is for client errors, invalid authentication, invalid data, etc. Not for server\n    errors in your code.\n\n    Read more about it in the\n    [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/).\n\n    ## Example\n\n    ```python\n    from fastapi import FastAPI, HTTPException\n\n    app = FastAPI()\n\n    items = {\"foo\": \"The Foo Wrestlers\"}\n\n\n    @app.get(\"/items/{item_id}\")\n    async def read_item(item_id: str):\n        if item_id not in items:\n            raise HTTPException(status_code=404, detail=\"Item not found\")\n        return {\"item\": items[item_id]}\n    ```\n    \"\"\"\n\n    def __init__(\n        self,\n        status_code: Annotated[\n            int,\n            Doc(\n                \"\"\"\n                HTTP status code to send to the client.\n                \"\"\"\n            ),\n        ],\n        detail: Annotated[\n            Any,\n            Doc(\n                \"\"\"\n                Any data to be sent to the client in the `detail` key of the JSON\n                response.\n                \"\"\"\n            ),\n        ] = None,\n        headers: Annotated[\n            Optional[Dict[str, str]],\n            Doc(\n                \"\"\"\n                Any headers to send to the client in the response.\n                \"\"\"\n            ),\n        ] = None,\n    ) -> None:\n        super().__init__(status_code=status_code, detail=detail, headers=headers
22run_command
{
 "command": "sed -n '150,185p' fastapi/exceptions.py"
}
{"status": "ok", "stdout": "class DependencyScopeError(FastAPIError):\n \"\"\"\n A dependency declared that it depends on another dependency with an invalid\n (
full
{"status": "ok", "stdout": "class DependencyScopeError(FastAPIError):\n    \"\"\"\n    A dependency declared that it depends on another dependency with an invalid\n    (narrower) scope.\n    \"\"\"\n\n\nclass ValidationException(Exception):\n    def __init__(self, errors: Sequence[Any]) -> None:\n        self._errors = errors\n\n    def errors(self) -> Sequence[Any]:\n        return self._errors\n\n\nclass RequestValidationError(ValidationException):\n    def __init__(self, errors: Sequence[Any], *, body: Any = None) -> None:\n        super().__init__(errors)\n        self.body = body\n\n\nclass WebSocketRequestValidationError(ValidationException):\n    pass\n\n\nclass ResponseValidationError(ValidationException):\n    def __init__(self, errors: Sequence[Any], *, body: Any = None) -> None:\n        super().__init__(errors)\n        self.body = body\n\n    def __str__(self) -> str:\n        message = f\"{len(self._errors)} validation errors:\\n\"\n        for err in self._errors:\n            message += f\"  {err}\\n\"\n        return message\n", "stderr": "", "exit_code": 0}
23run_command
{
 "command": "python3 - <<'PY'\nimport inspect\nfrom dataclasses import dataclass\nfrom typing import Optional, Any\n\n@dataclass\nclass Dependant:\n    call: Optional[Any] = None\n    path: Optional[str] = None\n\ndef get_endpoint_context(dependant: Dependant, method: str = \"GET\") -> str:\n    if dependant.call is None:\n        return \"\"\n    \n    try:\n        # This is a simplified version of what we might do\n        # In reality, we need to handle partials and unwrapping\n        call = dependant.call\n        # Handle partials\n        while hasattr(call, 'func'):\n            call = call.func\n        \n        # Unwrap\n        call = inspect.unwrap(call)\n        \n        frame = inspect.getframeinfo(call)\n        filename = frame.filename\n        lineno = frame.lineno\n        func_name = call.__name__ if hasattr(call, '__name__') else str(call)\n        \n        route = dependant.path or \"unknown\"\n        \n        return f\"\\n\\n  File \\\"{filename}\\\", line {lineno}, in {func_name}\\n    {method} {route}\"\n    except Exception as e:\n        return \"\"\n\n# Mock Dependant\ndef mock_func(): pass\ndep = Dependant(call=mock_func, path=\"/items/\")\nprint(get_endpoint_context(dep, \"POST\"))\nPY\n"
}
{"status": "ok", "stdout": "\n", "stderr": "", "exit_code": 0}
full
{"status": "ok", "stdout": "\n", "stderr": "", "exit_code": 0}
24run_command
{
 "command": "python3 - <<'PY'\nimport inspect\nimport os\n\ndef mock_func():\n    pass\n\nprint(f\"File: {inspect.getfile(mock_func)}\")\nprint(f\"Line: {inspect.getsourcelines(mock_func)[1]}\")\nPY\n"
}
{"status": "error", "error_type": "CommandError", "error_message": "Traceback (most recent call last):\n File \"<stdin>\", line 8, in <module>\n File \"/Users/j
full
{"status": "error", "error_type": "CommandError", "error_message": "Traceback (most recent call last):\n  File \"<stdin>\", line 8, in <module>\n  File \"/Users/jp/.local/share/uv/python/cpython-3.13.15-macos-aarch64-none/lib/python3.13/inspect.py\", line 1254, in getsourcelines\n    lines, lnum = findsource(object)\n                  ~~~~~~~~~~^^^^^^^^\n  File \"/Users/jp/.local/share/uv/python/cpython-3.13.15-macos-aarch64-none/lib/python3.13/inspect.py\", line 1089, in findsource\n    raise OSError('could not get source code')\nOSError: could not get source code\n", "details": {"stdout": "File: <stdin>\n", "stderr": "Traceback (most recent call last):\n  File \"<stdin>\", line 8, in <module>\n  File \"/Users/jp/.local/share/uv/python/cpython-3.13.15-macos-aarch64-none/lib/python3.13/inspect.py\", line 1254, in getsourcelines\n    lines, lnum = findsource(object)\n                  ~~~~~~~~~~^^^^^^^^\n  File \"/Users/jp/.local/share/uv/python/cpython-3.13.15-macos-aarch64-none/lib/python3.13/inspect.py\", line 1089, in findsource\n    raise OSError('could not get source code')\nOSError: could not get source code\n", "exit_code": 1}}
25run_command
{
 "command": "grep -rn \"RequestValidationError(\" fastapi/routing.py"
}
{"status": "ok", "stdout": "fastapi/routing.py:347: validation_error = RequestValidationError(\nfastapi/routing.py:423: validation_error = RequestValidationErro
full
{"status": "ok", "stdout": "fastapi/routing.py:347:            validation_error = RequestValidationError(\nfastapi/routing.py:423:            validation_error = RequestValidationError(\nfastapi/routing.py:453:            raise WebSocketRequestValidationError(\n", "stderr": "", "exit_code": 0}
26run_command
{
 "command": "grep -rn \"ResponseValidationError(\" fastapi/routing.py"
}
{"status": "ok", "stdout": "fastapi/routing.py:248: raise ResponseValidationError(\n", "stderr": "", "exit_code": 0}
full
{"status": "ok", "stdout": "fastapi/routing.py:248:            raise ResponseValidationError(\n", "stderr": "", "exit_code": 0}
27run_command
{
 "command": "sed -n '340,360p' fastapi/routing.py"
}
{"status": "ok", "stdout": " if subtype == \"json\" or subtype.endswith(\"+json\"):\n json_body = await request.json()\n if json_body != Undefined:\n body = jso
full
{"status": "ok", "stdout": "                                if subtype == \"json\" or subtype.endswith(\"+json\"):\n                                    json_body = await request.json()\n                        if json_body != Undefined:\n                            body = json_body\n                        else:\n                            body = body_bytes\n        except json.JSONDecodeError as e:\n            validation_error = RequestValidationError(\n                [\n                    {\n                        \"type\": \"json_invalid\",\n                        \"loc\": (\"body\", e.pos),\n                        \"msg\": \"JSON decode error\",\n                        \"input\": {},\n                        \"ctx\": {\"error\": e.msg},\n                    }\n                ],\n                body=e.doc,\n            )\n            raise validation_error from e\n        except HTTPException:\n", "stderr": "", "exit_code": 0}
28run_command
{
 "command": "sed -n '410,430p' fastapi/routing.py"
}
{"status": "ok", "stdout": " include=response_model_include,\n exclude=response_model_exclude,\n by_alias=response_model_by_alias,\n exclude_unset=response_mode
full
{"status": "ok", "stdout": "                    include=response_model_include,\n                    exclude=response_model_exclude,\n                    by_alias=response_model_by_alias,\n                    exclude_unset=response_model_exclude_unset,\n                    exclude_defaults=response_model_exclude_defaults,\n                    exclude_none=response_model_exclude_none,\n                    is_coroutine=is_coroutine,\n                )\n                response = actual_response_class(content, **response_args)\n                if not is_body_allowed_for_status_code(response.status_code):\n                    response.body = b\"\"\n                response.headers.raw.extend(solved_result.response.headers.raw)\n        if errors:\n            validation_error = RequestValidationError(\n                _normalize_errors(errors), body=body\n            )\n            raise validation_error\n\n        # Return response\n        assert response\n        return response\n", "stderr": "", "exit_code": 0}
29run_command
{
 "command": "sed -n '240,260p' fastapi/routing.py"
}
{"status": "ok", "stdout": " value, errors_ = await run_in_threadpool(\n field.validate, response_content, {}, loc=(\"response\",)\n )\n if isinstance(errors_,
full
{"status": "ok", "stdout": "            value, errors_ = await run_in_threadpool(\n                field.validate, response_content, {}, loc=(\"response\",)\n            )\n        if isinstance(errors_, list):\n            errors.extend(errors_)\n        elif errors_:\n            errors.append(errors_)\n        if errors:\n            raise ResponseValidationError(\n                errors=_normalize_errors(errors), body=response_content\n            )\n\n        if hasattr(field, \"serialize\"):\n            return field.serialize(\n                value,\n                include=include,\n                exclude=exclude,\n                by_alias=by_alias,\n                exclude_unset=exclude_unset,\n                exclude_defaults=exclude_defaults,\n                exclude_none=exclude_none,\n", "stderr": "", "exit_code": 0}
30run_command
{
 "command": "grep -rn \"get_dependant\" fastapi/routing.py"
}
{"status": "ok", "stdout": "fastapi/routing.py:41: get_dependant,\nfastapi/routing.py:477: self.dependant = get_dependant(\nfastapi/routing.py:630: self.dependa
full
{"status": "ok", "stdout": "fastapi/routing.py:41:    get_dependant,\nfastapi/routing.py:477:        self.dependant = get_dependant(\nfastapi/routing.py:630:        self.dependant = get_dependant(\n", "stderr": "", "exit_code": 0}
31run_command
{
 "command": "grep -rn \"Route\" fastapi/routing.py"
}
{"status": "ok", "stdout": "fastapi/routing.py:71: BaseRoute,\nfastapi/routing.py:462:class APIWebSocketRoute(routing.WebSocketRoute):\nfastapi/routing.py:504:c
full
{"status": "ok", "stdout": "fastapi/routing.py:71:    BaseRoute,\nfastapi/routing.py:462:class APIWebSocketRoute(routing.WebSocketRoute):\nfastapi/routing.py:504:class APIRoute(routing.Route):\nfastapi/routing.py:533:        callbacks: Optional[List[BaseRoute]] = None,\nfastapi/routing.py:536:            Callable[[\"APIRoute\"], str], DefaultPlaceholder\nfastapi/routing.py:572:            current_generate_unique_id: Callable[[APIRoute], str] = (\nfastapi/routing.py:673:class APIRouter(routing.Router):\nfastapi/routing.py:675:    `APIRouter` class, used to group *path operations*, for example to structure\nfastapi/routing.py:677:    in another `APIRouter` (ultimately included in the app).\nfastapi/routing.py:685:    from fastapi import APIRouter, FastAPI\nfastapi/routing.py:688:    router = APIRouter()\nfastapi/routing.py:758:            Optional[List[BaseRoute]],\nfastapi/routing.py:772:            Optional[List[BaseRoute]],\nfastapi/routing.py:823:            Type[APIRoute],\nfastapi/routing.py:829:                [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router).\nfastapi/routing.py:832:        ] = APIRoute,\nfastapi/routing.py:900:            Callable[[APIRoute], str],\nfastapi/routing.py:986:        route_class_override: Optional[Type[APIRoute]] = None,\nfastapi/routing.py:987:        callbacks: Optional[List[BaseRoute]] = None,\nfastapi/routing.py:990:            Callable[[APIRoute], str], DefaultPlaceholder\nfastapi/routing.py:1065:        callbacks: Optional[List[BaseRoute]] = None,\nfastapi/routing.py:1067:        generate_unique_id_function: Callable[[APIRoute], str] = Default(\nfastapi/routing.py:1115:        route = APIWebSocketRoute(\nfastapi/routing.py:1167:        from fastapi import APIRouter, FastAPI, WebSocket\nfastapi/routing.py:1170:        router = APIRouter()\nfastapi/routing.py:1202:        router: Annotated[\"APIRouter\", Doc(\"The `APIRouter` t
32run_command
{
 "command": "sed -n '504,540p' fastapi/routing.py"
}
{"status": "ok", "stdout": "class APIRoute(routing.Route):\n def __init__(\n self,\n path: str,\n endpoint: Callable[..., Any],\n *,\n response_model: Any = Def
full
{"status": "ok", "stdout": "class APIRoute(routing.Route):\n    def __init__(\n        self,\n        path: str,\n        endpoint: Callable[..., Any],\n        *,\n        response_model: Any = Default(None),\n        status_code: Optional[int] = None,\n        tags: Optional[List[Union[str, Enum]]] = None,\n        dependencies: Optional[Sequence[params.Depends]] = None,\n        summary: Optional[str] = None,\n        description: Optional[str] = None,\n        response_description: str = \"Successful Response\",\n        responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,\n        deprecated: Optional[bool] = None,\n        name: Optional[str] = None,\n        methods: Optional[Union[Set[str], List[str]]] = None,\n        operation_id: Optional[str] = None,\n        response_model_include: Optional[IncEx] = None,\n        response_model_exclude: Optional[IncEx] = None,\n        response_model_by_alias: bool = True,\n        response_model_exclude_unset: bool = False,\n        response_model_exclude_defaults: bool = False,\n        response_model_exclude_none: bool = False,\n        include_in_schema: bool = True,\n        response_class: Union[Type[Response], DefaultPlaceholder] = Default(\n            JSONResponse\n        ),\n        dependency_overrides_provider: Optional[Any] = None,\n        callbacks: Optional[List[BaseRoute]] = None,\n        openapi_extra: Optional[Dict[str, Any]] = None,\n        generate_unique_id_function: Union[\n            Callable[[\"APIRoute\"], str], DefaultPlaceholder\n        ] = Default(generate_unique_id),\n    ) -> None:\n        self.path = path\n        self.endpoint = endpoint\n", "stderr": "", "exit_code": 0}
33run_command
{
 "command": "python3 - <<'PY'\nimport inspect\nimport os\nfrom functools import partial\n\ndef get_endpoint_context(endpoint, method: str, path: str):\n    try:\n        # Handle partials\n        while isinstance(endpoint, partial):\n            endpoint = endpoint.func\n        \n        # Unwrap\n        endpoint = inspect.unwrap(endpoint)\n        \n        # Try to get source information\n        try:\n            frame = inspect.getframeinfo(endpoint)\n            filename = frame.filename\n            lineno = frame.lineno\n        except Exception:\n            filename = \"unknown\"\n            lineno = 0\n            \n        func_name = getattr(endpoint, \"__name__\", str(endpoint))\n        \n        return f\"\\n\\n  File \\\"{filename}\\\", line {lineno}, in {func_name}\\n    {method} {path}\"\n    except Exception as e:\n        return \"\"\n\ndef test_endpoint():\n    pass\n\nprint(f\"Test: {get_endpoint_context(test_endpoint, 'GET', '/test')}\")\nPY\n"
}
{"status": "ok", "stdout": "Test: \n\n File \"unknown\", line 0, in test_endpoint\n GET /test\n", "stderr": "", "exit_code": 0}
full
{"status": "ok", "stdout": "Test: \n\n  File \"unknown\", line 0, in test_endpoint\n    GET /test\n", "stderr": "", "exit_code": 0}
34run_command
{
 "command": "python3 - <<'PY'\nimport inspect\nimport os\nfrom functools import partial\n\ndef get_endpoint_context(endpoint, method: str, path: str):\n    try:\n        while isinstance(endpoint, partial):\n            endpoint = endpoint.func\n        endpoint = inspect.unwrap(endpoint)\n        \n        # use inspect.getsourcefile or inspect.getfile\n        try:\n            filename = inspect.getfile(endpoint)\n        except Exception:\n            filename = \"unknown\"\n            \n        try:\n            # Use inspect.getsourcelines\n            lineno = inspect.getsourcelines(endpoint)[1]\n        except Exception:\n            lineno = 0\n            \n        func_name = getattr(endpoint, \"__name__\", str(endpoint))\n        \n        return f\"\\n\\n  File \\\"{filename}\\\", line {lineno}, in {func_name}\\n    {method} {path}\"\n    except Exception as e:\n        return \"\"\n\ndef test_endpoint():\n    pass\n\nprint(f\"Test: {get_endpoint_context(test_endpoint, 'GET', '/test')}\")\nPY\n"
}
{"status": "ok", "stdout": "Test: \n\n File \"<stdin>\", line 0, in test_endpoint\n GET /test\n", "stderr": "", "exit_code": 0}
full
{"status": "ok", "stdout": "Test: \n\n  File \"<stdin>\", line 0, in test_endpoint\n    GET /test\n", "stderr": "", "exit_code": 0}
35run_command
{
 "command": "python3 - <<'PY'\nimport inspect\nimport os\nfrom functools import partial\n\ndef get_endpoint_context(endpoint, method: str, path: str):\n    try:\n        while isinstance(endpoint, partial):\n            endpoint = endpoint.func\n        endpoint = inspect.unwrap(endpoint)\n        \n        try:\n            filename = inspect.getfile(endpoint)\n        except Exception:\n            filename = \"unknown\"\n            \n        try:\n            # For functions defined in a module, getsourcelines should work\n            lineno = inspect.getsourcelines(endpoint)[1]\n        except Exception:\n            # Fallback to trying to get it from the code object\n            try:\n                lineno = endpoint.__code__.co_firstlineno\n            except Exception:\n                lineno = 0\n            \n        func_name = getattr(endpoint, \"__name__\", str(endpoint))\n        \n        return f\"\\n\\n  File \\\"{filename}\\\", line {lineno}, in {func_name}\\n    {method} {path}\"\n    except Exception as e:\n        return \"\"\n\ndef test_endpoint():\n    pass\n\nprint(f\"Test: {get_endpoint_context(test_endpoint, 'GET', '/test')}\")\nPY\n"
}
{"status": "ok", "stdout": "Test: \n\n File \"<stdin>\", line 32, in test_endpoint\n GET /test\n", "stderr": "", "exit_code": 0}
full
{"status": "ok", "stdout": "Test: \n\n  File \"<stdin>\", line 32, in test_endpoint\n    GET /test\n", "stderr": "", "exit_code": 0}
36run_command
{
 "command": "sed -n '160,180p' fastapi/exceptions.py"
}
{"status": "ok", "stdout": "\n def errors(self) -> Sequence[Any]:\n return self._errors\n\n\nclass RequestValidationError(ValidationException):\n def __init__(s
full
{"status": "ok", "stdout": "\n    def errors(self) -> Sequence[Any]:\n        return self._errors\n\n\nclass RequestValidationError(ValidationException):\n    def __init__(self, errors: Sequence[Any], *, body: Any = None) -> None:\n        super().__init__(errors)\n        self.body = body\n\n\nclass WebSocketRequestValidationError(ValidationException):\n    pass\n\n\nclass ResponseValidationError(ValidationException):\n    def __init__(self, errors: Sequence[Any], *, body: Any = None) -> None:\n        super().__init__(errors)\n        self.body = body\n\n    def __str__(self) -> str:\n", "stderr": "", "exit_code": 0}
37run_command
{
 "command": "python3 - <<'PY'\nfrom pathlib import Path\np = Path(\"fastapi/exceptions.py\"); s = p.read_text()\nold = \"\"\"class ValidationException(Exception):\n    def __init__(self, errors: Sequence[Any]) -> None:\n        self._errors = errors\n\n    def errors(self) -> Sequence[Any]:\n        return self._errors\"\"\"\nnew = \"\"\"class ValidationException(Exception):\n    def __init__(self, errors: Sequence[Any], endpoint_context: str = \"\") -> None:\n        self._errors = errors\n        self.endpoint_context = endpoint_context\n\n    def errors(self) -> Sequence[Any]:\n        return self._errors\"\"\"\nt = s.replace(old, new); p.write_text(t)\nPY\n"
}
{"status": "ok", "stdout": "", "stderr": "", "exit_code": 0}
full
{"status": "ok", "stdout": "", "stderr": "", "exit_code": 0}
38run_command
{
 "command": "sed -n '160,175p' fastapi/exceptions.py"
}
{"status": "ok", "stdout": " self.endpoint_context = endpoint_context\n\n def errors(self) -> Sequence[Any]:\n return self._errors\n\n\nclass RequestValidationE
full
{"status": "ok", "stdout": "        self.endpoint_context = endpoint_context\n\n    def errors(self) -> Sequence[Any]:\n        return self._errors\n\n\nclass RequestValidationError(ValidationException):\n    def __init__(self, errors: Sequence[Any], *, body: Any = None) -> None:\n        super().__init__(errors)\n        self.body = body\n\n\nclass WebSocketRequestValidationError(ValidationException):\n    pass\n\n\n", "stderr": "", "exit_code": 0}
39run_command
{
 "command": "python3 - <<'PY'\nfrom pathlib import Path\np = Path(\"fastapi/exceptions.py\"); s = p.read_text()\nold = \"\"\"class RequestValidationError(ValidationException):\n    def __init__(self, errors: Sequence[Any], *, body: Any = None) -> None:\n        super().__init__(errors)\n        self.body = body\"\"\"\nnew = \"\"\"class RequestValidationError(ValidationException):\n    def __init__(self, errors: Sequence[Any], *, body: Any = None, endpoint_context: str = \"\") -> None:\n        super().__init__(errors, endpoint_context=endpoint_context)\n        self.body = body\"\"\"\nt = s.replace(old, new); p.write_text(t)\nPY\n"
}
{"status": "ok", "stdout": "", "stderr": "", "exit_code": 0}
full
{"status": "ok", "stdout": "", "stderr": "", "exit_code": 0}
40run_command
{
 "command": "python3 - <<'PY'\nfrom pathlib import Path\np = Path(\"fastapi/exceptions.py\"); s = p.read_text()\nold = \"\"\"class WebSocketRequestValidationError(ValidationException):\n    pass\"\"\"\nnew = \"\"\"class WebSocketRequestValidationError(ValidationException):\n    def __init__(self, errors: Sequence[Any], *, endpoint_context: str = \"\") -> None:\n        super().__init__(errors, endpoint_context=endpoint_context)\"\"\"\nt = s.replace(old, new); p.write_text(t)\nPY\n"
}
{"status": "ok", "stdout": "", "stderr": "", "exit_code": 0}
full
{"status": "ok", "stdout": "", "stderr": "", "exit_code": 0}
41run_command
{
 "command": "python3 - <<'PY'\nfrom pathlib import Path\np = Path(\"fastapi/exceptions.py\"); s = p.read_text()\nold = \"\"\"class ResponseValidationError(ValidationException):\n    def __init__(self, errors: Sequence[Any], *, body: Any = None) -> None:\n        super().__init__(errors)\n        self.body = body\"\"\"\nnew = \"\"\"class ResponseValidationError(ValidationException):\n    def __init__(self, errors: Sequence[Any], *, body: Any = None, endpoint_context: str = \"\") -> None:\n        super().__init__(errors, endpoint_context=endpoint_context)\n        self.body = body\"\"\"\nt = s.replace(old, new); p.write_text(t)\nPY\n"
}
{"status": "ok", "stdout": "", "stderr": "", "exit_code": 0}
full
{"status": "ok", "stdout": "", "stderr": "", "exit_code": 0}
42run_command
{
 "command": "python3 - <<'PY'\nfrom pathlib import Path\np = Path(\"fastapi/exceptions.py\"); s = p.read_text()\nold = \"\"\"    def __str__(self) -> str:\n        message = f\\\"{len(self._errors)} validation errors:\\\\n\\\"\\\"\nnew = \"\"\"    def __str__(self) -> str:\n        message = f\\\"{len(self._errors)} validation errors:\\\\n\\\"\\\"\\\"\nt = s.replace(old, new); p.write_text(t)\nPY\n"
}
{"status": "error", "error_type": "CommandError", "error_message": " File \"<stdin>\", line 5\n new = \"\"\" def __str__(self) -> str:\n ^^^\nSyntaxError: inval
full
{"status": "error", "error_type": "CommandError", "error_message": "  File \"<stdin>\", line 5\n    new = \"\"\"    def __str__(self) -> str:\n                 ^^^\nSyntaxError: invalid syntax\n", "details": {"stdout": "", "stderr": "  File \"<stdin>\", line 5\n    new = \"\"\"    def __str__(self) -> str:\n                 ^^^\nSyntaxError: invalid syntax\n", "exit_code": 1}}
43run_command
{
 "command": "sed -n '180,200p' fastapi/exceptions.py"
}
{"status": "ok", "stdout": " self.body = body\n\n def __str__(self) -> str:\n message = f\"{len(self._errors)} validation errors:\\n\"\n for err in self._errors
full
{"status": "ok", "stdout": "        self.body = body\n\n    def __str__(self) -> str:\n        message = f\"{len(self._errors)} validation errors:\\n\"\n        for err in self._errors:\n            message += f\"  {err}\\n\"\n        return message\n", "stderr": "", "exit_code": 0}
44run_command
{
 "command": "python3 - <<'PY'\nfrom pathlib import Path\np = Path(\"fastapi/exceptions.py\"); s = p.read_text()\nold = \"\"\"    def __str__(self) -> str:\n        message = f\"{len(self._errors)} validation errors:\\\\n\"\n        for err in self._errors:\n            message += f\"  {err}\\\\n\"\n        return message\"\"\"\nnew = \"\"\"    def __str__(self) -> str:\n        message = f\"{len(self._errors)} validation errors:\\\\n\"\n        for err in self._errors:\n            message += f\"  {err}\\\\n\"\n        if self.endpoint_context:\n            message += f\"\\\\n{self.endpoint_context}\"\n        return message\"\"\"\nt = s.replace(old, new); p.write_text(t)\nPY\n"
}
{"status": "ok", "stdout": "", "stderr": "", "exit_code": 0}
full
{"status": "ok", "stdout": "", "stderr": "", "exit_code": 0}
45run_command
{
 "command": "sed -n '180,200p' fastapi/exceptions.py"
}
{"status": "ok", "stdout": " self.body = body\n\n def __str__(self) -> str:\n message = f\"{len(self._errors)} validation errors:\\n\"\n for err in self._errors
full
{"status": "ok", "stdout": "        self.body = body\n\n    def __str__(self) -> str:\n        message = f\"{len(self._errors)} validation errors:\\n\"\n        for err in self._errors:\n            message += f\"  {err}\\n\"\n        if self.endpoint_context:\n            message += f\"\\n{self.endpoint_context}\"\n        return message\n", "stderr": "", "exit_code": 0}
46run_command
{
 "command": "python3 - <<'PY'\nfrom pathlib import Path\np = Path(\"fastapi/routing.py\"); s = p.read_text()\nimport re\n\n# Find where to add the cache\n# Around line 462 (APIWebSocketRoute) and 504 (APIRoute)\n\n# Let's add a helper to compute endpoint context\nhelper_code = \"\"\"\ndef get_endpoint_context(endpoint: Any, method: str, path: str) -> str:\n    try:\n        while hasattr(endpoint, \"func\") and isinstance(endpoint, partial): # Not quite, partial is from functools\n            endpoint = endpoint.func\n        # But we don't have partial imported here yet in routing.py\n        # Let's use a more robust way or import it.\n\"\"\"\nPY\n"
}
{"status": "ok", "stdout": "", "stderr": "", "exit_code": 0}
full
{"status": "ok", "stdout": "", "stderr": "", "exit_code": 0}
47run_command
{
 "command": "sed -n '1,50p' fastapi/routing.py"
}
{"status": "ok", "stdout": "import dataclasses\nimport email.message\nimport functools\nimport inspect\nimport json\nfrom contextlib import AsyncExitStack, asyn
full
{"status": "ok", "stdout": "import dataclasses\nimport email.message\nimport functools\nimport inspect\nimport json\nfrom contextlib import AsyncExitStack, asynccontextmanager\nfrom enum import Enum, IntEnum\nfrom typing import (\n    Any,\n    AsyncIterator,\n    Awaitable,\n    Callable,\n    Collection,\n    Coroutine,\n    Dict,\n    List,\n    Mapping,\n    Optional,\n    Sequence,\n    Set,\n    Tuple,\n    Type,\n    Union,\n)\n\nfrom annotated_doc import Doc\nfrom fastapi import params, temp_pydantic_v1_params\nfrom fastapi._compat import (\n    ModelField,\n    Undefined,\n    _get_model_config,\n    _model_dump,\n    _normalize_errors,\n    lenient_issubclass,\n)\nfrom fastapi.datastructures import Default, DefaultPlaceholder\nfrom fastapi.dependencies.models import Dependant\nfrom fastapi.dependencies.utils import (\n    _should_embed_body_fields,\n    get_body_field,\n    get_dependant,\n    get_flat_dependant,\n    get_parameterless_sub_dependant,\n    get_typed_return_annotation,\n    solve_dependencies,\n)\nfrom fastapi.encoders import jsonable_encoder\nfrom fastapi.exceptions import (\n    FastAPIError,\n    RequestValidationError,\n", "stderr": "", "exit_code": 0}
48run_command
{
 "command": "python3 - <<'PY'\nfrom pathlib import Path\np = Path(\"fastapi/routing.py\"); s = p.read_text()\n\ndef get_endpoint_context(endpoint, method, path):\n    try:\n        while hasattr(endpoint, \"func\") and isinstance(endpoint, functools.partial):\n            endpoint = endpoint.func\n        endpoint = inspect.unwrap(endpoint)\n        try:\n            filename = inspect.getfile(endpoint)\n        except Exception:\n            filename = \"unknown\"\n        try:\n            lineno = inspect.getsourcelines(endpoint)[1]\n        except Exception:\n            try:\n                lineno = endpoint.__code__.co_firstlineno\n            except Exception:\n                lineno = 0\n        func_name = getattr(endpoint, \"__name__\", str(endpoint))\n        return f\"\\\\n\\\\n  File \\\"{filename}\\\", line {lineno}, in {func_name}\\\\n    {method} {path}\"\n    except Exception:\n        return \"\"\n\n# We need to insert this function into routing.py\n# Let's put it before APIRoute\n# And we need to make sure functools is imported.\nPY\n"
}
{"status": "ok", "stdout": "", "stderr": "", "exit_code": 0}
full
{"status": "ok", "stdout": "", "stderr": "", "exit_code": 0}
49run_command
{
 "command": "python3 - <<'PY'\nfrom pathlib import Path\np = Path(\"fastapi/routing.py\"); s = p.read_text()\n\nhelper_code = \"\"\"\ndef get_endpoint_context(endpoint: Any, method: str, path: str) -> str:\n    try:\n        while isinstance(endpoint, functools.partial):\n            endpoint = endpoint.func\n        endpoint = inspect.unwrap(endpoint)\n        try:\n            filename = inspect.getfile(endpoint)\n        except Exception:\n            filename = \"unknown\"\n        try:\n            lineno = inspect.getsourcelines(endpoint)[1]\n        except Exception:\n            try:\n                lineno = endpoint.__code__.co_firstlineno\n            except Exception:\n                lineno = 0\n        func_name = getattr(endpoint, \"__name__\", str(endpoint))\n        return f\"\\\\n\\\\n  File \\\"{filename}\\\", line {lineno}, in {func_name}\\\\n    {method} {path}\"\n    except Exception:\n        return \"\"\n\"\"\"\n\n# Insert before class APIRoute (around line 504)\n# We can use a marker or find the line.\nidx = s.find(\"class APIRoute(routing.Route):\")\nif idx != -1:\n    s = s[:idx] + helper_code + \"\\n\" + s[idx:]\n    p.write_text(s)\nPY\n"
}
{"status": "ok", "stdout": "", "stderr": "", "exit_code": 0}
full
{"status": "ok", "stdout": "", "stderr": "", "exit_code": 0}
50run_command
{
 "command": "sed -n '480,520p' fastapi/routing.py"
}
{"status": "ok", "stdout": " for depends in self.dependencies[::-1]:\n self.dependant.dependencies.insert(\n 0,\n get_parameterless_sub_dependant(depends=depend
full
{"status": "ok", "stdout": "        for depends in self.dependencies[::-1]:\n            self.dependant.dependencies.insert(\n                0,\n                get_parameterless_sub_dependant(depends=depends, path=self.path_format),\n            )\n        self._flat_dependant = get_flat_dependant(self.dependant)\n        self._embed_body_fields = _should_embed_body_fields(\n            self._flat_dependant.body_params\n        )\n        self.app = websocket_session(\n            get_websocket_app(\n                dependant=self.dependant,\n                dependency_overrides_provider=dependency_overrides_provider,\n                embed_body_fields=self._embed_body_fields,\n            )\n        )\n\n    def matches(self, scope: Scope) -> Tuple[Match, Scope]:\n        match, child_scope = super().matches(scope)\n        if match != Match.NONE:\n            child_scope[\"route\"] = self\n        return match, child_scope\n\n\n\ndef get_endpoint_context(endpoint: Any, method: str, path: str) -> str:\n    try:\n        while isinstance(endpoint, functools.partial):\n            endpoint = endpoint.func\n        endpoint = inspect.unwrap(endpoint)\n        try:\n            filename = inspect.getfile(endpoint)\n        except Exception:\n            filename = \"unknown\"\n        try:\n            lineno = inspect.getsourcelines(endpoint)[1]\n        except Exception:\n            try:\n                lineno = endpoint.__code__.co_firstlineno\n            except Exception:\n                lineno = 0\n", "stderr": "", "exit_code": 0, "budget_warning": "Only 10 tool call(s) remaining (50/60 used). Finalize your edits and call submit_patch soon."}

Patch

diff --git a/fastapi/exceptions.py b/fastapi/exceptions.py
index 0620428b..b3431e2d 100644
--- a/fastapi/exceptions.py
+++ b/fastapi/exceptions.py
@@ -155,30 +155,34 @@ class DependencyScopeError(FastAPIError):
 
 
 class ValidationException(Exception):
-    def __init__(self, errors: Sequence[Any]) -> None:
+    def __init__(self, errors: Sequence[Any], endpoint_context: str = "") -> None:
         self._errors = errors
+        self.endpoint_context = endpoint_context
 
     def errors(self) -> Sequence[Any]:
         return self._errors
 
 
 class RequestValidationError(ValidationException):
-    def __init__(self, errors: Sequence[Any], *, body: Any = None) -> None:
-        super().__init__(errors)
+    def __init__(self, errors: Sequence[Any], *, body: Any = None, endpoint_context: str = "") -> None:
+        super().__init__(errors, endpoint_context=endpoint_context)
         self.body = body
 
 
 class WebSocketRequestValidationError(ValidationException):
-    pass
+    def __init__(self, errors: Sequence[Any], *, endpoint_context: str = "") -> None:
+        super().__init__(errors, endpoint_context=endpoint_context)
 
 
 class ResponseValidationError(ValidationException):
-    def __init__(self, errors: Sequence[Any], *, body: Any = None) -> None:
-        super().__init__(errors)
+    def __init__(self, errors: Sequence[Any], *, body: Any = None, endpoint_context: str = "") -> None:
+        super().__init__(errors, endpoint_context=endpoint_context)
         self.body = body
 
     def __str__(self) -> str:
         message = f"{len(self._errors)} validation errors:\n"
         for err in self._errors:
             message += f"  {err}\n"
+        if self.endpoint_context:
+            message += f"\n{self.endpoint_context}"
         return message
diff --git a/fastapi/routing.py b/fastapi/routing.py
index c10175b1..b21bebf4 100644
--- a/fastapi/routing.py
+++ b/fastapi/routing.py
@@ -501,6 +501,28 @@ class APIWebSocketRoute(routing.WebSocketRoute):
         return match, child_scope
 
 
+
+def get_endpoint_context(endpoint: Any, method: str, path: str) -> str:
+    try:
+        while isinstance(endpoint, functools.partial):
+            endpoint = endpoint.func
+        endpoint = inspect.unwrap(endpoint)
+        try:
+            filename = inspect.getfile(endpoint)
+        except Exception:
+            filename = "unknown"
+        try:
+            lineno = inspect.getsourcelines(endpoint)[1]
+        except Exception:
+            try:
+                lineno = endpoint.__code__.co_firstlineno
+            except Exception:
+                lineno = 0
+        func_name = getattr(endpoint, "__name__", str(endpoint))
+        return f"\n\n  File "{filename}", line {lineno}, in {func_name}\n    {method} {path}"
+    except Exception:
+        return ""
+
 class APIRoute(routing.Route):
     def __init__(
         self,

Test output

show
==================================== ERRORS ====================================
___________ ERROR collecting tests/test_validation_error_context.py ____________
/Users/jp/repos/kaggle-gemini-coding-agent-post-training/.envs/fastapi/lib/python3.13/site-packages/_pytest/python.py:508: in importtestmodule
    mod = import_path(
/Users/jp/repos/kaggle-gemini-coding-agent-post-training/.envs/fastapi/lib/python3.13/site-packages/_pytest/pathlib.py:596: in import_path
    importlib.import_module(module_name)
/Users/jp/.local/share/uv/python/cpython-3.13.15-macos-aarch64-none/lib/python3.13/importlib/__init__.py:88: in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
<frozen importlib._bootstrap>:1395: in _gcd_import
    ???
<frozen importlib._bootstrap>:1360: in _find_and_load
    ???
<frozen importlib._bootstrap>:1331: in _find_and_load_unlocked
    ???
<frozen importlib._bootstrap>:935: in _load_unlocked
    ???
/Users/jp/repos/kaggle-gemini-coding-agent-post-training/.envs/fastapi/lib/python3.13/site-packages/_pytest/assertion/rewrite.py:188: in exec_module
    exec(co, module.__dict__)
tests/test_validation_error_context.py:1: in <module>
    from fastapi import FastAPI, Request, WebSocket
fastapi/__init__.py:7: in <module>
    from .applications import FastAPI as FastAPI
fastapi/applications.py:17: in <module>
    from fastapi import routing
E     File "/private/tmp/swe_work/pod_r5_v1h/fastapi_14306/b/workspace/fastapi/routing.py", line 522
E       return f"\n\n  File "{filename}", line {lineno}, in {func_name}\n    {method} {path}"
E                            ^
E   SyntaxError: invalid syntax
!!!!!!!!!!!!!!!!!!!!!!!!!! stopping after 1 failures !!!!!!!!!!!!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!
1 error in 0.22s