[PR #20299] [CLOSED] fix: resolve infinite recursion and connection pool exhaustion in message retrieval #129208

Closed
opened 2026-05-21 12:20:37 -05:00 by GiteaMirror · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/open-webui/open-webui/pull/20299
Author: @silentoplayz
Created: 12/31/2025
Status: Closed

Base: devHead: fix/infinite-recursion-message-retrieval


📝 Commits (1)

  • 22571d6 fix: resolve infinite recursion and connection pool exhaustion in message retrieval

📊 Changes

1 file changed (+65 additions, -14 deletions)

View changed files

📝 backend/open_webui/models/messages.py (+65 -14)

📄 Description

Pull Request Checklist

Note to first-time contributors: Please open a discussion post in Discussions to discuss your idea/fix with the community before creating a pull request, and describe your changes before submitting a pull request.

This is to ensure large feature PRs are discussed with the community first, before starting work on it. If the community does not want this feature or it is not relevant for Open WebUI as a project, it can be identified in the discussion before working on the feature and submitting the PR.

Before submitting, make sure you've checked the following:

  • Target branch: Verify that the pull request targets the dev branch. Not targeting the dev branch will lead to immediate closure of the PR.
  • Description: Provide a concise description of the changes made in this pull request down below.
  • Changelog: Ensure a changelog entry following the format of Keep a Changelog is added at the bottom of the PR description.
  • Documentation: If necessary, update relevant documentation Open WebUI Docs like environment variables, the tutorials, or other documentation sources.
  • Dependencies: Are there any new dependencies? Have you updated the dependency versions in the documentation?
  • Testing: Perform manual tests to verify the implemented fix/feature works as intended AND does not break any other functionality. Take this as an opportunity to make screenshots of the feature/fix and include it in the PR description.
  • Agentic AI Code: Confirm this Pull Request is not written by any AI Agent or has at least gone through additional human review AND manual testing. If any AI Agent is the co-author of this PR, it may lead to immediate closure of the PR.
  • Code review: Have you performed a self-review of your code, addressing any coding standard issues and ensuring adherence to the project's coding standards?
  • Title Prefix: To clearly categorize this pull request, prefix the pull request title using one of the following:
    • BREAKING CHANGE: Significant changes that may affect compatibility
    • build: Changes that affect the build system or external dependencies
    • ci: Changes to our continuous integration processes or workflows
    • chore: Refactor, cleanup, or other non-functional code changes
    • docs: Documentation update or addition
    • feat: Introduces a new feature or enhancement to the codebase
    • fix: Bug fix or error correction
    • i18n: Internationalization or localization changes
    • perf: Performance improvement
    • refactor: Code restructuring for better maintainability, readability, or scalability
    • style: Changes that do not affect the meaning of the code (white space, formatting, missing semi-colons, etc.)
    • test: Adding missing tests or correcting existing tests
    • WIP: Work in progress, a temporary label for incomplete or ongoing work

Changelog Entry

Description

This PR fixes a RecursionError and potential connection pool exhaustion caused by a cyclic dependency in message retrieval methods.

The Issue:
The get_thread_replies_by_message_id method called get_message_by_id to hydrate the reply_to_message field. However, get_message_by_id recursively calls get_thread_replies_by_message_id to populate thread replies. This created an infinite recursion loop when fetching messages that were part of a reply chain or thread, leading to a stack overflow and rapid consumption of database connections.

The Fix:

  • Introduced get_message_by_id_slim: A new method that fetches a message and its user without recursively fetching thread replies or other nested relationships.
  • Refactored get_thread_replies_by_message_id, get_messages_by_channel_id, and get_messages_by_parent_id to use get_message_by_id_slim when populating the reply_to_message field. This effectively breaks the recursion cycle.

Added

  • get_message_by_id_slim method to MessageTable.

Changed

  • Updated get_thread_replies_by_message_id to use get_message_by_id_slim.
  • Updated get_messages_by_channel_id to use get_message_by_id_slim.
  • Updated get_messages_by_parent_id to use get_message_by_id_slim.

Fixed

  • RecursionError: maximum recursion depth exceeded while calling a Python object in message retrieval.
  • Resolved potential DB connection pool exhaustion due to deep recursion.

This PR solves the following error:

self.get_message_by_id(message.reply_to_id, db=db)
  File "/app/backend/open_webui/models/messages.py", line 186, in get_message_by_id
    thread_replies = self.get_thread_replies_by_message_id(id, db=db)
                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/app/backend/open_webui/models/messages.py", line 216, in get_thread_replies_by_message_id
    self.get_message_by_id(message.reply_to_id, db=db)
  File "/app/backend/open_webui/models/messages.py", line 186, in get_message_by_id
    thread_replies = self.get_thread_replies_by_message_id(id, db=db)
                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/app/backend/open_webui/models/messages.py", line 208, in get_thread_replies_by_message_id
    .filter_by(parent_id=id)
     ^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/sqlalchemy/orm/query.py", line 1991, in filter_by
    clauses = [
              ^
  File "/usr/local/lib/python3.11/site-packages/sqlalchemy/orm/query.py", line 1992, in <listcomp>
    _entity_namespace_key(from_entity, key) == value
  File "/usr/local/lib/python3.11/site-packages/sqlalchemy/sql/operators.py", line 584, in __eq__
    return self.operate(eq, other)
           ^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/sqlalchemy/orm/attributes.py", line 453, in operate
    return op(self.comparator, *other, **kwargs)  # type: ignore[no-any-return]  # noqa: E501
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/sqlalchemy/sql/operators.py", line 584, in __eq__
    return self.operate(eq, other)
           ^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/sqlalchemy/orm/properties.py", line 479, in operate
    return op(self.__clause_element__(), *other, **kwargs)  # type: ignore[no-any-return]  # noqa: E501
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/sqlalchemy/sql/annotation.py", line 371, in __eq__
    return self.__element.__class__.__eq__(self, other)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/sqlalchemy/sql/operators.py", line 584, in __eq__
    return self.operate(eq, other)
           ^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/sqlalchemy/sql/elements.py", line 1535, in operate
    return op(self.comparator, *other, **kwargs)  # type: ignore[no-any-return]  # noqa: E501
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/sqlalchemy/sql/operators.py", line 584, in __eq__
    return self.operate(eq, other)
           ^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/sqlalchemy/sql/type_api.py", line 210, in operate
    return op_fn(self.expr, op, *other, **addtl_kw)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/sqlalchemy/sql/default_comparator.py", line 120, in _boolean_compare
    obj = coercions.expect(
          ^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/sqlalchemy/sql/coercions.py", line 396, in expect
    resolved = impl._literal_coercion(
               ^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/sqlalchemy/sql/coercions.py", line 804, in _literal_coercion
    return expr._bind_param(operator, element, type_=bindparam_type)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/sqlalchemy/sql/elements.py", line 4669, in _bind_param
    return BindParameter(
           ^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/sqlalchemy/sql/elements.py", line 2000, in __init__
    self.key = _anonymous_label.safe_construct(
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/sqlalchemy/sql/elements.py", line 5545, in safe_construct
    body = re.sub(r"[%\(\) \$]+", "_", body)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/re/__init__.py", line 185, in sub
    return _compile(pattern, flags).sub(repl, string, count)
           ^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/re/__init__.py", line 274, in _compile
    if isinstance(flags, RegexFlag):
       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
RecursionError: maximum recursion depth exceeded while calling a Python object

Screenshots

Before

image

After

image

Additional Information

  • This issue was causing backend crashes when loading chat history with threaded replies.

Contributor License Agreement

By submitting this pull request, I confirm that I have read and fully agree to the Contributor License Agreement (CLA), and I am providing my contributions under its terms.

Note

Deleting the CLA section will lead to immediate closure of your PR and it will not be merged in.


🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.

## 📋 Pull Request Information **Original PR:** https://github.com/open-webui/open-webui/pull/20299 **Author:** [@silentoplayz](https://github.com/silentoplayz) **Created:** 12/31/2025 **Status:** ❌ Closed **Base:** `dev` ← **Head:** `fix/infinite-recursion-message-retrieval` --- ### 📝 Commits (1) - [`22571d6`](https://github.com/open-webui/open-webui/commit/22571d6640c69ab497d87b75ebd0cb004501b5cc) fix: resolve infinite recursion and connection pool exhaustion in message retrieval ### 📊 Changes **1 file changed** (+65 additions, -14 deletions) <details> <summary>View changed files</summary> 📝 `backend/open_webui/models/messages.py` (+65 -14) </details> ### 📄 Description # Pull Request Checklist ### Note to first-time contributors: Please open a discussion post in [Discussions](https://github.com/open-webui/open-webui/discussions) to discuss your idea/fix with the community before creating a pull request, and describe your changes before submitting a pull request. This is to ensure large feature PRs are discussed with the community first, before starting work on it. If the community does not want this feature or it is not relevant for Open WebUI as a project, it can be identified in the discussion before working on the feature and submitting the PR. **Before submitting, make sure you've checked the following:** - [x] **Target branch:** Verify that the pull request targets the `dev` branch. **Not targeting the `dev` branch will lead to immediate closure of the PR.** - [x] **Description:** Provide a concise description of the changes made in this pull request down below. - [x] **Changelog:** Ensure a changelog entry following the format of [Keep a Changelog](https://keepachangelog.com/) is added at the bottom of the PR description. - [x] **Documentation:** If necessary, update relevant documentation [Open WebUI Docs](https://github.com/open-webui/docs) like environment variables, the tutorials, or other documentation sources. - [x] **Dependencies:** Are there any new dependencies? Have you updated the dependency versions in the documentation? - [x] **Testing:** Perform manual tests to **verify the implemented fix/feature works as intended AND does not break any other functionality**. Take this as an opportunity to **make screenshots of the feature/fix and include it in the PR description**. - [x] **Agentic AI Code:** Confirm this Pull Request is **not written by any AI Agent** or has at least **gone through additional human review AND manual testing**. If any AI Agent is the co-author of this PR, it may lead to immediate closure of the PR. - [x] **Code review:** Have you performed a self-review of your code, addressing any coding standard issues and ensuring adherence to the project's coding standards? - [x] **Title Prefix:** To clearly categorize this pull request, prefix the pull request title using one of the following: - **BREAKING CHANGE**: Significant changes that may affect compatibility - **build**: Changes that affect the build system or external dependencies - **ci**: Changes to our continuous integration processes or workflows - **chore**: Refactor, cleanup, or other non-functional code changes - **docs**: Documentation update or addition - **feat**: Introduces a new feature or enhancement to the codebase - **fix**: Bug fix or error correction - **i18n**: Internationalization or localization changes - **perf**: Performance improvement - **refactor**: Code restructuring for better maintainability, readability, or scalability - **style**: Changes that do not affect the meaning of the code (white space, formatting, missing semi-colons, etc.) - **test**: Adding missing tests or correcting existing tests - **WIP**: Work in progress, a temporary label for incomplete or ongoing work # Changelog Entry ### Description This PR fixes a `RecursionError` and potential connection pool exhaustion caused by a cyclic dependency in message retrieval methods. **The Issue:** The `get_thread_replies_by_message_id` method called `get_message_by_id` to hydrate the `reply_to_message` field. However, `get_message_by_id` recursively calls `get_thread_replies_by_message_id` to populate thread replies. This created an infinite recursion loop when fetching messages that were part of a reply chain or thread, leading to a stack overflow and rapid consumption of database connections. **The Fix:** - Introduced `get_message_by_id_slim`: A new method that fetches a message and its user *without* recursively fetching thread replies or other nested relationships. - Refactored `get_thread_replies_by_message_id`, `get_messages_by_channel_id`, and `get_messages_by_parent_id` to use `get_message_by_id_slim` when populating the `reply_to_message` field. This effectively breaks the recursion cycle. ### Added - `get_message_by_id_slim` method to `MessageTable`. ### Changed - Updated `get_thread_replies_by_message_id` to use `get_message_by_id_slim`. - Updated `get_messages_by_channel_id` to use `get_message_by_id_slim`. - Updated `get_messages_by_parent_id` to use `get_message_by_id_slim`. ### Fixed - `RecursionError: maximum recursion depth exceeded while calling a Python object` in message retrieval. - Resolved potential DB connection pool exhaustion due to deep recursion. This PR solves the following error: ```js self.get_message_by_id(message.reply_to_id, db=db) File "/app/backend/open_webui/models/messages.py", line 186, in get_message_by_id thread_replies = self.get_thread_replies_by_message_id(id, db=db) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/app/backend/open_webui/models/messages.py", line 216, in get_thread_replies_by_message_id self.get_message_by_id(message.reply_to_id, db=db) File "/app/backend/open_webui/models/messages.py", line 186, in get_message_by_id thread_replies = self.get_thread_replies_by_message_id(id, db=db) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/app/backend/open_webui/models/messages.py", line 208, in get_thread_replies_by_message_id .filter_by(parent_id=id) ^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/sqlalchemy/orm/query.py", line 1991, in filter_by clauses = [ ^ File "/usr/local/lib/python3.11/site-packages/sqlalchemy/orm/query.py", line 1992, in <listcomp> _entity_namespace_key(from_entity, key) == value File "/usr/local/lib/python3.11/site-packages/sqlalchemy/sql/operators.py", line 584, in __eq__ return self.operate(eq, other) ^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/sqlalchemy/orm/attributes.py", line 453, in operate return op(self.comparator, *other, **kwargs) # type: ignore[no-any-return] # noqa: E501 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/sqlalchemy/sql/operators.py", line 584, in __eq__ return self.operate(eq, other) ^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/sqlalchemy/orm/properties.py", line 479, in operate return op(self.__clause_element__(), *other, **kwargs) # type: ignore[no-any-return] # noqa: E501 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/sqlalchemy/sql/annotation.py", line 371, in __eq__ return self.__element.__class__.__eq__(self, other) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/sqlalchemy/sql/operators.py", line 584, in __eq__ return self.operate(eq, other) ^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/sqlalchemy/sql/elements.py", line 1535, in operate return op(self.comparator, *other, **kwargs) # type: ignore[no-any-return] # noqa: E501 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/sqlalchemy/sql/operators.py", line 584, in __eq__ return self.operate(eq, other) ^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/sqlalchemy/sql/type_api.py", line 210, in operate return op_fn(self.expr, op, *other, **addtl_kw) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/sqlalchemy/sql/default_comparator.py", line 120, in _boolean_compare obj = coercions.expect( ^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/sqlalchemy/sql/coercions.py", line 396, in expect resolved = impl._literal_coercion( ^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/sqlalchemy/sql/coercions.py", line 804, in _literal_coercion return expr._bind_param(operator, element, type_=bindparam_type) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/sqlalchemy/sql/elements.py", line 4669, in _bind_param return BindParameter( ^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/sqlalchemy/sql/elements.py", line 2000, in __init__ self.key = _anonymous_label.safe_construct( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/sqlalchemy/sql/elements.py", line 5545, in safe_construct body = re.sub(r"[%\(\) \$]+", "_", body) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/re/__init__.py", line 185, in sub return _compile(pattern, flags).sub(repl, string, count) ^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/re/__init__.py", line 274, in _compile if isinstance(flags, RegexFlag): ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ RecursionError: maximum recursion depth exceeded while calling a Python object ``` --- ### Screenshots ### Before <img width="1339" height="1282" alt="image" src="https://github.com/user-attachments/assets/8e192981-0248-4aab-b5f2-7397438abe2d" /> ### After <img width="887" height="1273" alt="image" src="https://github.com/user-attachments/assets/7dfc364d-c14b-4b25-9d4d-48126316a748" /> ### Additional Information - This issue was causing backend crashes when loading chat history with threaded replies. ### Contributor License Agreement By submitting this pull request, I confirm that I have read and fully agree to the [Contributor License Agreement (CLA)](https://github.com/open-webui/open-webui/blob/main/CONTRIBUTOR_LICENSE_AGREEMENT), and I am providing my contributions under its terms. > [!NOTE] > Deleting the CLA section will lead to immediate closure of your PR and it will not be merged in. --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
GiteaMirror added the pull-request label 2026-05-21 12:20:37 -05:00
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: github-starred/open-webui#129208