Skip to content

fix: Load flows autologin false#9578

Merged
jordanrfrazier merged 5 commits into
release-1.6.0from
load_flows_autologin_false
Sep 17, 2025
Merged

fix: Load flows autologin false#9578
jordanrfrazier merged 5 commits into
release-1.6.0from
load_flows_autologin_false

Conversation

@phact
Copy link
Copy Markdown
Collaborator

@phact phact commented Aug 28, 2025

This pull request refactors the flow and bundle loading logic during startup to improve reliability and remove unnecessary dependencies on the AUTO_LOGIN setting. The main change is to always attempt to load flows and bundles for the superuser, regardless of the AUTO_LOGIN configuration, and to identify the superuser by role rather than username. This helps avoid issues when credentials are reset and ensures flows are loaded as expected.

Authentication and user lookup improvements:

  • Changed superuser lookup to use the is_superuser role instead of relying on the username, making the process more robust against credential changes (src/backend/base/langflow/initial_setup/setup.py) [1] [2].

Removal of unnecessary AUTO_LOGIN checks:

  • Removed checks for AUTO_LOGIN before loading flows and bundles, so these operations now run independently of the authentication setting (src/backend/base/langflow/initial_setup/setup.py) [1] [2] [3].

Summary by CodeRabbit

  • New Features

    • Flows in the local directory and bundles from URLs now load automatically during setup without requiring a special login setting.
    • A default folder is created for the admin user to store loaded items.
  • Bug Fixes

    • More reliable detection and loading of JSON flow files during initialization.
    • Clearer error messaging when no admin user is found, improving setup diagnostics.

mendonk and others added 3 commits August 27, 2025 18:40
* docs: update support documentation to reflect rebranding to IBM Elite Support for Langflow

* remove-info-tab

* Apply suggestions from code review

Co-authored-by: April I. Murphy <36110273+aimurphy@users.noreply.github.com>

---------

Co-authored-by: April I. Murphy <36110273+aimurphy@users.noreply.github.com>
@phact phact requested a review from ogabrielluiz August 28, 2025 03:50
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Aug 28, 2025

Important

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

Removes AUTO_LOGIN gating from flow and bundle loading, switches superuser retrieval to role-based lookup, updates error handling, ensures a default folder for the superuser, adjusts JSON path filtering, and moves user import locally within functions in src/backend/base/langflow/initial_setup/setup.py.

Changes

Cohort / File(s) Summary
AUTO_LOGIN gating removal
src/backend/base/langflow/initial_setup/setup.py
Removed AUTO_LOGIN checks from load_flows_from_directory and load_bundles_from_urls; both now execute based on path/URL presence.
Superuser lookup change
src/backend/base/langflow/initial_setup/setup.py
Replaced username-based lookup with role-based query: select(User).where(User.is_superuser == True).
Imports and error handling
src/backend/base/langflow/initial_setup/setup.py
Dropped get_user_by_username import; added local User import inside functions; updated NoResultFound message to “No superuser found in the database”.
Folder preparation
src/backend/base/langflow/initial_setup/setup.py
Ensures superuser’s default folder exists via get_or_create_default_folder(session, user.id) before loading flows.
JSON path filtering
src/backend/base/langflow/initial_setup/setup.py
Replaced AUTO_LOGIN-based filter with direct checks: path.is_relative_to(f"{dir_name}flows/") and path.suffix == ".json".
Docstring update
src/backend/base/langflow/initial_setup/setup.py
Removed note about AUTO_LOGIN gating in load_flows_from_directory docstring.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant App as App Startup
  participant Setup as setup.load_flows_from_directory
  participant DB as DB (SQLModel)
  participant FS as Filesystem
  participant Loader as Flow Loader

  App->>Setup: Invoke with session, dir_name
  Setup->>DB: select(User).where(is_superuser==True)
  alt Superuser found
    Setup->>DB: get_or_create_default_folder(user.id)
    Setup->>FS: Enumerate dir_name/flows/*.json
    Setup->>Loader: Load each JSON flow
    Loader-->>Setup: Success/Errors per file
    Setup-->>App: Completed
  else No superuser
    Setup-->>App: Raise NoResultFound("No superuser found in the database")
  end
Loading
sequenceDiagram
  autonumber
  participant App as App Startup
  participant Setup as setup.load_bundles_from_urls
  participant DB as DB (SQLModel)
  participant Net as Network
  participant Bundle as Bundle Processor

  App->>Setup: Invoke with session, bundle_urls
  Setup->>DB: select(User).where(is_superuser==True)
  alt Superuser found
    loop For each URL
      Setup->>Net: Fetch bundle
      Net-->>Setup: Bundle data
      Setup->>Bundle: Process bundle for user
      Bundle-->>Setup: Result
    end
    Setup-->>App: Completed
  else No superuser
    Setup-->>App: Raise NoResultFound("No superuser found in the database")
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Suggested labels

size:L, refactor

Suggested reviewers

  • jordanrfrazier
✨ Finishing touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch load_flows_autologin_false

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions github-actions Bot added the bug Something isn't working label Aug 28, 2025
@github-actions github-actions Bot added bug Something isn't working and removed bug Something isn't working labels Aug 28, 2025
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
src/backend/base/langflow/initial_setup/setup.py (2)

861-864: Fix: assigning FolderRead object to folder_id field (should be UUID).

get_or_create_default_folder returns FolderRead; existing.folder_id expects an ID. This currently sets a model into a UUID column and will break persistence.

-        if existing.folder_id is None:
-            folder_id = await get_or_create_default_folder(session, user_id)
-            existing.folder_id = folder_id
+        if existing.folder_id is None:
+            folder = await get_or_create_default_folder(session, user_id)
+            existing.folder_id = folder.id

749-756: Bug: to_thread on iterdir returns a generator, not the entries (still blocks the event loop).

Wrap the listing in list(...) inside the thread to avoid blocking I/O on the event loop.

-        for file_path in await asyncio.to_thread(Path(flows_path).iterdir):
+        files = await asyncio.to_thread(lambda: list(Path(flows_path).iterdir()))
+        for file_path in files:
🧹 Nitpick comments (3)
src/backend/base/langflow/initial_setup/setup.py (3)

798-804: DRY: factor superuser lookup into a helper.

The same query appears twice. Consider a small helper to centralize behavior and logging.

Add near this module (outside functions):

async def _get_superuser(session: AsyncSession):
    from langflow.services.database.models.user.model import User
    result = await session.exec(select(User).where(User.is_superuser == True))  # noqa: E712
    return result.first()

Then replace the duplicated blocks with:

user = await _get_superuser(session)

Also applies to: 736-741


1032-1034: Docstring mismatch: function returns FolderRead, not UUID.

Align the docstring with the actual return type and annotation.

-    Returns:
-        UUID: The ID of the default folder.
+    Returns:
+        FolderRead: The default folder object for the user.

789-833: Optional: avoid repeated extraction path accumulation issues.

When adding component paths, ensure you normalize and dedupe after extraction. Minor, but keeps paths tidy.

-                            component_paths.add(str(Path(temp_dir.name) / f"{dir_name}components"))
+                            component_paths.add(str((Path(temp_dir.name) / f"{dir_name}components").resolve()))
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 61a323d and fb4a946.

📒 Files selected for processing (1)
  • src/backend/base/langflow/initial_setup/setup.py (3 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
{src/backend/**/*.py,tests/**/*.py,Makefile}

📄 CodeRabbit inference engine (.cursor/rules/backend_development.mdc)

{src/backend/**/*.py,tests/**/*.py,Makefile}: Run make format_backend to format Python code before linting or committing changes
Run make lint to perform linting checks on backend Python code

Files:

  • src/backend/base/langflow/initial_setup/setup.py
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Optimize new Python code in this PR
🔇 Additional comments (2)
src/backend/base/langflow/initial_setup/setup.py (2)

725-733: Confirm intended lifecycle: superuser creation vs. flow/bundle loading order.

With AUTO_LOGIN no longer gating flow/bundle import, if AUTO_LOGIN is false and no superuser exists, imports will be skipped (as suggested above). Verify that this matches product expectations for fresh installs.

Would you like me to open a follow-up to optionally auto-create a disabled superuser (or defer imports until one exists) controlled by a setting?

Also applies to: 1004-1019


822-822: No compatibility issue with Path.is_relative_to usage
The project’s pyproject.toml specifies requires-python = ">=3.10,<3.14", so using Path.is_relative_to (introduced in 3.9) is safe and no changes are needed.

Comment on lines 731 to 735
flows_path = settings_service.settings.load_flows_path
if not flows_path:
return
if not settings_service.auth_settings.AUTO_LOGIN:
await logger.awarning("AUTO_LOGIN is disabled, not loading flows from directory")
return

async with session_scope() as session:
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Guard: check flows_path exists before iterating.

Path.iterdir will raise if the directory is missing. Return early with a warning.

     flows_path = settings_service.settings.load_flows_path
     if not flows_path:
         return
+    flows_dir = anyio.Path(flows_path)
+    if not await flows_dir.exists():
+        await logger.awarning(f"Flows path does not exist: {flows_path}")
+        return

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In src/backend/base/langflow/initial_setup/setup.py around lines 731 to 735,
guard against a missing flows_path before calling Path.iterdir by ensuring
flows_path is valid and exists; if flows_path may be a string, convert it to a
pathlib.Path, check .exists() (and optionally .is_dir()), log a warning
indicating the configured flows path was not found, and return early instead of
attempting to iterate the directory.

Comment on lines 742 to 745
if user is None:
msg = "Superuser not found in the database"
msg = "No superuser found in the database"
raise NoResultFound(msg)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Startup resilience: don’t crash if no superuser exists.

Raising here aborts startup in environments without a pre-created superuser (now that AUTO_LOGIN gating is removed). Prefer logging and skipping the import.

-        if user is None:
-            msg = "No superuser found in the database"
-            raise NoResultFound(msg)
+        if user is None:
+            await logger.awarning("No superuser found; skipping flows import.")
+            return

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In src/backend/base/langflow/initial_setup/setup.py around lines 742 to 745, the
code raises NoResultFound when no superuser exists which aborts startup; change
this to log a warning and skip the import instead of raising. Replace the raise
with a non-fatal path: log a clear message (use the module logger or Python
logging) indicating "No superuser found, skipping import" and then return or
otherwise skip the subsequent import logic so startup continues; add an import
for logging or use the existing logger if necessary.

Comment on lines +798 to 806
# Find superuser by role instead of username to avoid issues with credential reset
from langflow.services.database.models.user.model import User

stmt = select(User).where(User.is_superuser == True) # noqa: E712
result = await session.exec(stmt)
user = result.first()
if user is None:
msg = "Superuser not found in the database"
msg = "No superuser found in the database"
raise NoResultFound(msg)
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Same resilience for bundles: skip gracefully if no superuser.

Mirror the behavior in load_flows_from_directory to avoid aborting startup.

-        if user is None:
-            msg = "No superuser found in the database"
-            raise NoResultFound(msg)
+        if user is None:
+            await logger.awarning("No superuser found; skipping bundles import.")
+            return [], []
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
# Find superuser by role instead of username to avoid issues with credential reset
from langflow.services.database.models.user.model import User
stmt = select(User).where(User.is_superuser == True) # noqa: E712
result = await session.exec(stmt)
user = result.first()
if user is None:
msg = "Superuser not found in the database"
msg = "No superuser found in the database"
raise NoResultFound(msg)
# Find superuser by role instead of username to avoid issues with credential reset
from langflow.services.database.models.user.model import User
stmt = select(User).where(User.is_superuser == True) # noqa: E712
result = await session.exec(stmt)
user = result.first()
if user is None:
await logger.awarning("No superuser found; skipping bundles import.")
return [], []
🤖 Prompt for AI Agents
In src/backend/base/langflow/initial_setup/setup.py around lines 798 to 806, the
code currently raises NoResultFound if no superuser exists which aborts startup;
instead mirror load_flows_from_directory behavior by skipping gracefully:
replace the raise with a safe no-op path that logs or warns (use existing
logger) and returns/continues without error so startup proceeds, ensuring any
subsequent bundle-related logic checks for user being None before using it.

@jordanrfrazier jordanrfrazier changed the base branch from main to release-1.6.0 September 17, 2025 16:44
@github-actions github-actions Bot added bug Something isn't working and removed bug Something isn't working labels Sep 17, 2025
@github-actions github-actions Bot added bug Something isn't working and removed bug Something isn't working labels Sep 17, 2025
@sonarqubecloud
Copy link
Copy Markdown

@jordanrfrazier jordanrfrazier merged commit 63c2c28 into release-1.6.0 Sep 17, 2025
20 checks passed
@jordanrfrazier jordanrfrazier deleted the load_flows_autologin_false branch September 17, 2025 17:13
@github-actions github-actions Bot added the lgtm This PR has been approved by a maintainer label Sep 17, 2025
jordanrfrazier added a commit that referenced this pull request Sep 19, 2025
* docs: update support documentation to reflect support rebranding (#9538)

* docs: update support documentation to reflect rebranding to IBM Elite Support for Langflow

* remove-info-tab

* Apply suggestions from code review

Co-authored-by: April I. Murphy <36110273+aimurphy@users.noreply.github.com>

---------

Co-authored-by: April I. Murphy <36110273+aimurphy@users.noreply.github.com>

* setup.py disable autologin check for loading flows

* [autofix.ci] apply automated fixes

* New base branch, updated files for release

---------

Co-authored-by: Mendon Kissling <59585235+mendonk@users.noreply.github.com>
Co-authored-by: April I. Murphy <36110273+aimurphy@users.noreply.github.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Jordan Frazier <jordan.frazier@datastax.com>
github-merge-queue Bot pushed a commit that referenced this pull request Sep 19, 2025
* fix: Load flows autologin false (#9578)

* docs: update support documentation to reflect support rebranding (#9538)

* docs: update support documentation to reflect rebranding to IBM Elite Support for Langflow

* remove-info-tab

* Apply suggestions from code review

Co-authored-by: April I. Murphy <36110273+aimurphy@users.noreply.github.com>

---------

Co-authored-by: April I. Murphy <36110273+aimurphy@users.noreply.github.com>

* setup.py disable autologin check for loading flows

* [autofix.ci] apply automated fixes

* New base branch, updated files for release

---------

Co-authored-by: Mendon Kissling <59585235+mendonk@users.noreply.github.com>
Co-authored-by: April I. Murphy <36110273+aimurphy@users.noreply.github.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Jordan Frazier <jordan.frazier@datastax.com>

* fix: Move docling dependency into core dependencies instead of dev (#9906)

* fix: Make sure strings can be parsed in the python interpreter (#9908)

* fix: Execution of python interpreter

* Update test_python_repl_tool.py

* [autofix.ci] apply automated fixes

---------

Co-authored-by: Carlos Coelho <80289056+carlosrcoelho@users.noreply.github.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>

* Remove docling dep from optional group since its in main dep group

* fix: Correct the docling dependencies and Chroma in particular (#9925)

fix: Correct docling dependencies

---------

Co-authored-by: Sebastián Estévez <estevezsebastian@gmail.com>
Co-authored-by: Mendon Kissling <59585235+mendonk@users.noreply.github.com>
Co-authored-by: April I. Murphy <36110273+aimurphy@users.noreply.github.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Eric Hare <ericrhare@gmail.com>
Co-authored-by: Carlos Coelho <80289056+carlosrcoelho@users.noreply.github.com>
@phact phact restored the load_flows_autologin_false branch September 20, 2025 03:29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working lgtm This PR has been approved by a maintainer

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants