langflow icon indicating copy to clipboard operation
langflow copied to clipboard

feat(lfx-serve): v2 workflow endpoints (sync + stream)

Open ogabrielluiz opened this issue 5 months ago • 5 comments

Why

Our production story runs on lfx, but the v2 workflows API was built only on the langflow backend. This gives lfx serve the same contract so a client integrates identically against either runtime. Second step of the lfx production-parity effort; builds on the shared lfx.workflow layer extracted in #13782.

Stacked on #13782 (base feat/lfx-v2-shared-layer), so the diff here is just the new endpoint.

What

POST /workflows on the serve app, mirroring the backend POST /api/v2/workflows:

  • Body WorkflowRunRequest, returns WorkflowExecutionResponse (sync) or an SSE stream (langflow / agui protocols).
  • flow_id resolves against the serve registry; per-request deepcopy + registry.stamp mirrors the existing run/stream endpoints (never mutate the shared cached graph).
  • sync runs via run_graph_internal (the same primitive the backend sync path uses), so the shared converter sees the aggregated RunOutputs shape.
  • stream drives the run with a token-stream EventManager wired into execute_graph_with_capture, feeding queue events through the shared StreamAdapter; emits a terminal end so the adapter closes the run cleanly (lfx async_start doesn't emit one).
  • background and public modes return 422 (they need the DB / job queue / auth that stateless lfx serve doesn't have); tweaks/data/files/globals/partial-run boundaries are rejected too (no per-request graph rebuild yet).

execute_graph_with_capture gains an optional event_manager param (threaded into async_start), so streaming reuses the standard run path.

Tests

A real ChatInput -> ChatOutput flow (no mocks) exercises sync, both stream protocols, and the guard responses (unknown protocol, unsupported fields, background mode, unknown flow, missing key). 329 lfx serve + contract tests pass in the lfx-only env.

Note

WorkflowRunRequest requires a UUID flow_id, so a serve flow must be registered under a UUID id to be reachable here (exported langflow flows already are).

Summary by CodeRabbit

  • New Features

    • Added support for the new workflow execution endpoints, including both synchronous and streaming modes.
    • Streaming responses now emit clearer progress and completion events for compatible clients.
  • Bug Fixes

    • Improved validation for workflow requests to reject unsupported options earlier.
    • Added stronger handling for slow or overflowing streaming clients to surface an error instead of dropping updates.
    • Updated secret scan tracking to reflect the current source location.

ogabrielluiz avatar Jun 23 '26 17:06 ogabrielluiz

Review Change Stack

[!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.

⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: a6ede5e8-b575-45d7-9b77-a0c1770fe699

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

Use the checkbox below for a quick retry:

  • [ ] 🔍 Trigger review

Walkthrough

Adds an optional event_manager parameter to execute_graph_with_capture for streaming event emission, and introduces a new serve_workflow.py module implementing V2 workflow-shaped POST /workflows endpoints (sync and SSE streaming) with request validation, wired into create_multi_serve_app. Includes new tests and a secrets baseline line-number update.

Changes

V2 Workflow Endpoint Implementation

Layer / File(s) Summary
event_manager threading into graph execution
src/lfx/src/lfx/cli/common.py
execute_graph_with_capture accepts an optional event_manager parameter, documents its role, and passes it to get_default_coordinator().stream(...).
Workflow queue and validation helpers
src/lfx/src/lfx/cli/serve_workflow.py
New module defines constants, _WorkflowEventQueue with bounded overflow handling and explicit error events, plus _validate_output_ids, _reject_unsupported_fields, _build_inputs, and _terminal_node_ids helpers.
Sync and streaming execution paths
src/lfx/src/lfx/cli/serve_workflow.py
run_workflow_sync runs graphs to completion and converts results to WorkflowExecutionResponse; stream_workflow_frames formats SSE frames from captured token/message events with guaranteed error emission on failure.
Route registration and app wiring
src/lfx/src/lfx/cli/serve_workflow.py, src/lfx/src/lfx/cli/serve_app.py
add_v2_workflow_routes registers POST /workflows with API-key protection, validates protocol/mode, clones the cached graph, and dispatches to sync or streaming paths; serve_app.py imports and invokes it in create_multi_serve_app.
Tests and secrets baseline
src/lfx/tests/unit/cli/test_serve_workflow.py, .secrets.baseline
New test module covers sync/streaming responses, validation error codes, globals, output_ids, and queue overflow behavior; baseline line number updated for the relocated secret keyword.

Estimated code review effort: 4 (Complex) | ~60 minutes

Possibly related PRs

  • langflow-ai/langflow#13121: Both PRs modify create_multi_serve_app in src/lfx/src/lfx/cli/serve_app.py, this PR adding V2 workflow route wiring while the other reworks serve startup around a FlowRegistry.

Suggested reviewers: RamGopalSrikar


[!IMPORTANT]

Pre-merge checks failed

Please resolve all errors before merging. Addressing warnings is optional.

❌ Failed checks (1 error, 1 warning)

Check name Status Explanation Resolution
Test Coverage For New Implementations ❌ Error Tests were added, but key new behavior isn’t really asserted: test_globals_accepted only checks 200, and public mode has no regression test. Assert effective_globals in test_globals_accepted and add a 422 test for mode='public' (and any other unsupported workflow modes).
Test Quality And Coverage ⚠️ Warning The suite is broad, but key new behaviors are only smoke-tested: globals aren’t asserted via effective_globals, and public/stream output-id errors aren’t covered. Assert effective_globals in the sync test, add a public-mode 422 case, and cover stream-mode output_ids rejection plus any identity-dependent behavior.
✅ Passed checks (7 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely summarizes the main change: adding v2 workflow endpoints for sync and streaming in lfx-serve.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Test File Naming And Structure ✅ Passed PASS: test_serve_workflow.py follows backend pytest naming under unit/cli, uses a fixture and descriptive test names, and covers both positive and negative cases; async tests are supported by repo...
Excessive Mock Usage Warning ✅ Passed The new workflow tests use a real Graph/TestClient flow and no unittest.mock patching; only monkeypatch sets an env var, which is appropriate.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • [ ] Create PR with unit tests
  • [ ] Commit unit tests in branch feat/lfx-serve-v2

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.

coderabbitai[bot] avatar Jun 23 '26 17:06 coderabbitai[bot]

✅ Test Coverage Advisor

No source changes detected without accompanying tests. Thanks for keeping coverage up! 🎉

Advisory check only — never blocks merge.

github-actions[bot] avatar Jun 23 '26 17:06 github-actions[bot]

Codecov Report

:x: Patch coverage is 80.72289% with 32 lines in your changes missing coverage. Please review. :white_check_mark: Project coverage is 59.91%. Comparing base (ac97b04) to head (bc20b12). :warning: Report is 39 commits behind head on release-1.11.0.

Files with missing lines Patch % Lines
src/lfx/src/lfx/cli/serve_workflow.py 80.48% 22 Missing and 10 partials :warning:
Additional details and impacted files

Impacted file tree graph

@@                Coverage Diff                 @@
##           release-1.11.0   #13783      +/-   ##
==================================================
+ Coverage           59.43%   59.91%   +0.48%     
==================================================
  Files                2353     2313      -40     
  Lines              225309   225731     +422     
  Branches            31831    32676     +845     
==================================================
+ Hits               133909   135258    +1349     
+ Misses              89832    88886     -946     
- Partials             1568     1587      +19     
Flag Coverage Δ
backend 66.80% <ø> (+1.64%) :arrow_up:
frontend 58.79% <ø> (+0.27%) :arrow_up:
lfx 57.30% <80.72%> (+0.13%) :arrow_up:

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
src/lfx/src/lfx/cli/common.py 41.71% <ø> (ø)
src/lfx/src/lfx/cli/serve_app.py 96.39% <100.00%> (+0.01%) :arrow_up:
src/lfx/src/lfx/cli/serve_workflow.py 80.48% <80.48%> (ø)

... and 520 files with indirect coverage changes

:rocket: New features to boost your workflow:
  • :snowflake: Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • :package: JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

codecov[bot] avatar Jun 23 '26 17:06 codecov[bot]

Frontend Unit Test Coverage Report

Coverage Summary

Lines Statements Branches Functions
Coverage: 44%
44.79% (60951/136059) 69.59% (8343/11988) 43.19% (1381/3197)

Unit Test Results

Tests Skipped Failures Errors Time
5153 0 :zzz: 0 :x: 0 :fire: 18m 7s :stopwatch:

github-actions[bot] avatar Jun 23 '26 17:06 github-actions[bot]

Thanks @erichare, all three addressed in 4eb9eb3.

  1. globals: dropped the rejection and apply them as request-scoped variables via apply_global_vars_to_graph on the per-request copy, same as the run/stream endpoints. The sync path activates the request scope around run_graph_internal too (the stream path already had it through execute_graph_with_capture), and the response echoes them as effective_globals.
  2. output_ids: added _validate_output_ids mirroring the backend, unknown ids now 422 (UNKNOWN_OUTPUT_IDS) against the flow's terminal nodes before anything runs.
  3. stream overflow: ported the backend's _WorkflowEventQueue, so a full queue emits an explicit error frame and ends the stream instead of dropping with put_nowait.

Added tests for each. Mind taking another look?

ogabrielluiz avatar Jul 01 '26 18:07 ogabrielluiz

@ogabrielluiz I think the endpoints structure should look the same since it's going to be one router config, considering the follow-up PR #13816

Probably a better change to make on the other PR, but keeping the workflows available under /api/v2/workflows for consistency. That way, users always hit the same endpoint but a different domain/environment, keeping their testing setup consistent with their production setup.

dkaushik94 avatar Jul 06 '26 20:07 dkaushik94

  1. 🔴 Sync /workflows silently bypasses the no_env_fallback isolation policy — leaks os.environ credentials

src/lfx/src/lfx/cli/serve_workflow.py:223 (in run_workflow_sync)

run_workflow_sync runs via run_graph_internal and only calls activate_request_variables(...) — it never calls activate_no_env_fallback(disabled=bool(graph.context.get("no_env_fallback"))). That activation lives only in execute_graph_with_capture (common.py:367), which the stream path and the existing /flows/{id}/run path both use.

The _no_env_fallback contextvar is the enforcement mechanism: credentials.py (lines 66/122/161/199), instantiation.py:25, and variable/service.py all gate os.environ reads on is_env_fallback_disabled().

Failure scenario: operator runs lfx serve with LFX_SERVE_NO_ENV_FALLBACK=1 (→ registry._no_env_fallback=True → stamp() sets graph.context["no_env_fallback"]=True) to isolate served flows from process credentials. A POST /workflows in sync mode leaves is_env_fallback_disabled()==False, so a model-provider component resolves its API key from os.environ — exactly what the operator forbade. The same request in stream mode is correctly isolated.

  1. 🟠 Route mounts at /workflows, not /api/v2/workflows — the path-consistency concern you raised

src/lfx/src/lfx/cli/serve_workflow.py:337

The backend router is APIRouter(prefix="/workflows") under /api/v2 → /api/v2/workflows. add_v2_workflow_routes registers @app.post("/workflows") directly on the serve app root (the serve app has no /api/v2 prefix — all its routes are /flows, /health, etc.). The module + function docstrings claim a client "integrates identically," but the path differs, so switching runtimes requires changing the URL path, not just the host/domain — the opposite of your "same endpoint, different environment" goal.

/workflows is consistent with lfx-serve's own root-level convention, but not with the backend. The intent is one shared router config, this should mount under /api/v2/workflows.

dkaushik94 avatar Jul 07 '26 04:07 dkaushik94

Hey @erichare, thanks for the thorough pass. All five are addressed now:

  • Identity bypass (P1): the v2 route now depends on resolve_identity (the same dependency /flows/{id}/run uses, which sub-depends on the api-key floor), so --identity-mode=jwt/header is enforced identically, and the verified user_id is threaded into both the sync and stream paths (pinned onto the graph and Memory vertices via apply_run_defaults). Added tests: /workflows 401s on an invalid token before execution, and a valid token threads user_id into both sync and stream.
  • globals rejected: now accepted and applied as request-scoped variables (apply_global_vars_to_graph), with a test.
  • output_ids unvalidated: now rejected up front with 422 (_validate_output_ids), with tests.
  • stream queue dropping events: overflow now emits an explicit stream error instead of silently dropping, with a test.
  • langflow protocol output events: the adapter now builds the normalized output event from output_meta (_output_event).

Mind taking another look when you get a chance?

ogabrielluiz avatar Jul 07 '26 22:07 ogabrielluiz

Hey @dkaushik94, @erichare is OOO today and this is blocked on his changes-requested. I've addressed all five of his points (identity enforcement + user_id threading on the v2 route, globals accepted, output_ids validated, stream overflow emits an error, langflow output events), and it's got auto-merge queued. Could you take a look and approve if it looks good so it can go in? Thanks.

ogabrielluiz avatar Jul 07 '26 22:07 ogabrielluiz