feat(lfx-serve): v2 workflow endpoints (sync + stream)
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, returnsWorkflowExecutionResponse(sync) or an SSE stream (langflow/aguiprotocols). flow_idresolves against the serve registry; per-requestdeepcopy+registry.stampmirrors 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 aggregatedRunOutputsshape. - stream drives the run with a token-stream
EventManagerwired intoexecute_graph_with_capture, feeding queue events through the sharedStreamAdapter; emits a terminalendso the adapter closes the run cleanly (lfxasync_startdoesn't emit one). backgroundandpublicmodes 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.
[!IMPORTANT]
Review skipped
Auto incremental reviews are disabled on this repository.
Please check the settings in the CodeRabbit UI or the
.coderabbit.yamlfile in this repository. To trigger a single review, invoke the@coderabbitai reviewcommand.⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID:
a6ede5e8-b575-45d7-9b77-a0c1770fe699You can disable this status message by setting the
reviews.review_statustofalsein 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_appinsrc/lfx/src/lfx/cli/serve_app.py, this PR adding V2 workflow route wiring while the other reworks serve startup around aFlowRegistry.
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.
Comment @coderabbitai help to get the list of available commands.
✅ Test Coverage Advisor
No source changes detected without accompanying tests. Thanks for keeping coverage up! 🎉
Advisory check only — never blocks merge.
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
@@ 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%> (ø) |
: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.
Frontend Unit Test Coverage Report
Coverage Summary
| Lines | Statements | Branches | Functions |
|---|---|---|---|
| 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: |
Thanks @erichare, all three addressed in 4eb9eb3.
globals: dropped the rejection and apply them as request-scoped variables viaapply_global_vars_to_graphon the per-request copy, same as the run/stream endpoints. The sync path activates the request scope aroundrun_graph_internaltoo (the stream path already had it throughexecute_graph_with_capture), and the response echoes them aseffective_globals.output_ids: added_validate_output_idsmirroring the backend, unknown ids now 422 (UNKNOWN_OUTPUT_IDS) against the flow's terminal nodes before anything runs.- stream overflow: ported the backend's
_WorkflowEventQueue, so a full queue emits an explicit error frame and ends the stream instead of dropping withput_nowait.
Added tests for each. Mind taking another look?
@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.
- 🔴 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.
- 🟠 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.
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}/runuses, which sub-depends on the api-key floor), so--identity-mode=jwt/headeris enforced identically, and the verifieduser_idis threaded into both the sync and stream paths (pinned onto the graph and Memory vertices viaapply_run_defaults). Added tests:/workflows401s on an invalid token before execution, and a valid token threadsuser_idinto 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
outputevent fromoutput_meta(_output_event).
Mind taking another look when you get a chance?
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.