Commit Graph

17637 Commits

Author SHA1 Message Date
aced13ef79 docs: clarify autosaving and versioned flow saving (#12794)
* add-clarification-to-1.9-and-next

* 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>
(cherry picked from commit 7fd8469917)
2026-04-23 17:49:52 -07:00
dbc87e7704 fix: db guards for deployments (#12339)
* checkout api handlers

* add missing table

* update to use "version" terminology for flows instead of outdated "history" verbage

* Fix provider account id mapping

* recover a little todo comment

* Add flow version migration and minor exception handling, etc

  1. deployments.py — Added AuthenticationError import + handling (401) in all 9 error handler blocks. Added update_deployment_db import + call to persist name changes to local DB after adapter update succeeds.
  2. flow_version/exceptions.py — Added FlowVersionDeployedError for blocking deletion of deployed versions.
  3. flow_version/crud.py —
    - Added has_deployment_attachments() helper that checks if a flow version has any deployment attachments
    - delete_flow_version_entry() now raises FlowVersionDeployedError if the version is attached to deployments
    - Pruning now excludes deployed versions via a NOT IN subquery on FlowVersionDeplottachment, preventing provider-side snapshot orphaning
  4. flow_version/__init__.py — Exports FlowVersionDeployedError
  5. flow_version.py (API route) — Imported FlowVersionDeployedError, added it to _translate_version_error as 409 Conflict
  6. models/__init__.py — Registered FlowVersionDeploymentAttachment for alembic/SQLModel metadata detection
  7. Migration c0d2ce43b315 — Creates flow_version_deployment_attachment table with all columns, FKs (CASCADE), and indexes. Single head, chains off fc7f696a57bf.

* [autofix.ci] apply automated fixes

* address bugs and inconsistencies

* rename column to "provider_snapshot_id"

* harden deployment API: fail loudly on invalid state instead of silently passing

Replace silent fallbacks, warning logs, and dropped values with hard
failures (422/500/502) across the deployment orchestration layer. Adds
logging to bare exception handlers and wraps materialize_snapshots in
the adapter error handler.

* [autofix.ci] apply automated fixes

* add materialize_snapshots to deployment service protocol

Promotes materialize_snapshots from duck-typed getattr usage to a
first-class method on DeploymentServiceProtocol, BaseDeploymentService,
and the no-op DeploymentService stub. Introduces MaterializeSnapshotsResult
schema for typed return values.

Updates deployments.py to call the method through the protocol instead of
getattr, giving static analysis coverage over the contract.

Documents the snapshot abstraction across BaseFlowArtifact, SnapshotItem,
MaterializeSnapshotsResult, and FlowVersionDeploymentAttachment.provider_snapshot_id
— explaining that snapshots are immutable, provider-owned copies of flow data
with opaque provider-assigned identifiers (e.g. wxO tool ID, K8s ConfigMap
name, S3 key).

* deployment sync: extract helpers, server-side type filter, orphan detection

- Extract _fetch_provider_resource_keys helper for provider validation
- Rename _sync_page_with_provider → _list_deployments_synced
- Match resource keys by provider ID only (not name)
- Restore server-side deployment_type filter with guard against
  false deletions (skip rows whose type doesn't match the filter
  instead of deleting them)
- Add orphan/divergence logging for post-create, post-update,
  post-duplicate DB write failures
- Return 422 on invalid UUID in update remove list (was silently ignored)
- Handle NotImplementedError → 501 from provider adapters
- Convert attachment IntegrityError to ValueError with descriptive message
- Add tests for sync helpers (15 cases)

* rebase on release-1.9.0 and align with lfx/services

* refactor(deployments): align provider mapper routing and WXO update payload mapping

Align deployment mapper resolution with adapter-type/provider-key routing and
refactor PATCH update handling to use mapper resolve/shape contracts end-to-end.
Map Langflow flow_version_id references at the API boundary into provider update
operations for Watsonx bind/unbind/remove paths, with expanded mapper tests.

* patch down-revision

* first pass with formalized boundary rules

* fix(deployments): harden watsonx payload boundary contracts

Enforce fail-fast payload slot parsing for required adapter results, split execution create/status slot contracts, and route execution-create mapping through deployment mappers.
Require watsonx flow artifact source_ref and move update reconciliation output to provider_result to keep mapper/adapter boundaries explicit and typed.

* refactor(deployments): modularize watsonx orchestrate create/update flow

Extract create/update logic into dedicated core modules with shared helpers to tighten deployment boundary contracts.
Align backend/lfx payload schema mapping and expand e2e/unit coverage for response mapping and update schema behavior.

* api impl for wxo-specific create payload

* further refactoring. add rollback of existing tools (undo new app bindings) in the create path

* add todo in execution.py

* refactor(deployments): replace snapshot_id/reference_id with source_ref-correlated tool refs
Introduce WatsonxToolRefBinding to correlate source_ref (flow version id)
with provider tool_id across all operation types. This replaces the prior
reference_id and snapshot_id fields with a unified structure that carries
provenance through create, bind, unbind, and remove_tool operations.
Key changes:
- Flatten API operation payloads: hoist flow_version_id onto operations,
  remove nested WatsonxApiUpdateToolReference wrapper
- Replace tools.existing_ids with inline tool_id_with_ref on bind operations
- Rename WatsonxCreateSnapshotBinding to WatsonxToolRefBinding (input) and
  WatsonxResultToolRefBinding (output, with created flag)
- Add created_app_ids to update results for connection tracking
- Raise HTTPException on contract violations in _to_api_tool_app_bindings
  instead of silently dropping unmappable bindings
- Add schema-level validation for conflicting source_ref on same tool_id
- E2E: cache tool_id→source_ref from create results, use helpers to build
  refs with distinct source_ref vs tool_id values

* Enforce DeploymentType enum and add description column

Make deployment_type a required column backed by a SQLAlchemy
TypeDecorator that validates on write (rejects None and invalid strings)
and coerces to DeploymentType on read. Add nullable description column
to the deployment model and surface it through the API.

Key changes:
- Add _DeploymentTypeColumn TypeDecorator for enum round-trip fidelity
- Make deployment_type non-optional in Deployment model, DeploymentRead,
  CRUD functions, and API layer
- Add description (Text, nullable) to Deployment model and fold its
  migration into the existing c0d2ce43b315 revision
- Remove _resolve_deployment_type helper — TypeDecorator handles coercion
- Remove DeploymentType fallbacks and backward-compat shims from API
  endpoints, base mapper, and watsonx orchestrate mapper
- Document cross-package coupling: DeploymentType is owned by lfx but
  persisted by langflow; member values must never be removed
- Fix pre-existing bug: provider_account_id → deployment_provider_account_id
  in get_deployment_status endpoint

Note: deployment_type is nullable=True at the DB level to satisfy the
EXPAND-phase migration validator; NOT NULL is enforced at the application
layer by the _DeploymentTypeColumn TypeDecorator.

* refactor(deployments): extract route helpers, harden sync and error handling
Move bulk of deployment route logic into mappers/helpers layer to slim
down deployments.py and enforce clearer boundary between routes, mappers,
and adapters (documented in DEPLOYMENT_BOUNDARY_RULES.md).
Key changes:
- Extract ~700 lines from deployments.py into helpers.py (pagination,
  adapter/mapper resolution, attachment management, snapshot sync,
  rollback, response shaping)
- Add read-path snapshot-level sync: get_deployment and
  list_deployments_synced verify provider_snapshot_ids against the
  provider and prune stale attachments, with graceful fallback on error
- Add compensating rollback for create (rollback_provider_create) and
  update (rollback_provider_update) when DB commit fails after provider
  mutation, using mapper-driven payload reconstruction
- Introduce handle_adapter_errors() context manager centralising
  DeploymentServiceError → HTTP status mapping via
  http_status_for_deployment_error; sanitise 500 detail to avoid
  leaking internals
- Add DeploymentNotConfiguredError → 503 mapping
- Add util_snapshot_ids_to_verify and resolve_rollback_update to base
  mapper with WxO overrides for provider-specific snapshot ID extraction
  and put_tools-based rollback payloads
- Add put_tools field to WatsonxDeploymentUpdatePayload for full tool
  list replacement; early-return in build_provider_update_plan and
  validate_operation_references when put_tools is set
- Extract verify_tools_by_ids into core/tools.py helper
- Harden resource_name_prefix with strip_whitespace + min_length=1
- Deduplicate snapshot_ids before provider calls
- Add deterministic order_by(created_at) to attachment CRUD queries
- Add exc_info=True to all best-effort rollback/compensate error logs
- Add session.rollback() in get_deployment snapshot sync error path
- Warn when list_snapshots receives both deployment_ids and snapshot_ids
- Add E2E scenarios for empty snapshot list, mixed snapshot IDs, tools
  endpoint, and deployment re-list after update
Tests:
- Add test_deployment_route_handlers.py covering stale-row delete +
  commit, non-404 adapter errors, handle_adapter_errors wiring,
  snapshot sync (happy path, skip, error fallback), project-scoped
  flow version validation for create and update
- Expand test_deployment_sync.py with snapshot-phase tests, rollback
  tests, pagination guard, and project-scoped validation
- Add deployment_type assertion to response mapping test
- Add DeploymentNotConfiguredError and bare DeploymentServiceError cases
  to exception mapping tests
- Add put_tools schema and update plan tests

* remove pompous performance commentary

* fix(deployments): remove upsert behavior and fail fast on duplicate name

The create_deployment endpoint previously performed a
get_deployment_by_resource_key lookup before inserting the DB row,
silently tolerating duplicates. Since the provider adapter returns a
fresh resource ID on every create, this lookup could never legitimately
match — and if it did, it would mask a data inconsistency bug.

Changes:
- Remove the get-or-create (upsert) pattern; go straight to
  create_deployment_db and let the unique constraint surface conflicts.
- Add deployment_name_exists CRUD function and an early 409 guard so
  duplicate names are rejected before any provider call, avoiding
  costly provider-side rollback for a locally-checkable condition.
- Update existing route-handler tests to reflect the removed lookup.
- Add tests for deployment_name_exists and the 409 duplicate-name path.

* feat: convert provider_key and deployment_type columns to DB-level enums
Replace plain string columns with SQLAlchemy Enum types backed by
Postgres/SQLite enum constraints, enforcing valid values at the DB
layer rather than only in application code.
Migration follows expand-contract pattern (add enum column, backfill,
drop old string column, rename) with index ops outside batch context
to avoid SQLite column-lookup issues. Upgrade and downgrade are fully
atomic.
- Add DeploymentProviderKey enum as single source of truth for
  provider identifiers; remove magic strings and _DeploymentTypeColumn
  TypeDecorator
- Make provider_key immutable after creation (remove from update
  request schema and API handler)
- Fix pre-existing test gap: add missing deployment_type argument to
  all TestDeploymentCRUD create_deployment() calls

* feat(flow-versions): add deployment awareness and sync-on-read

Add is_deployed field to flow version responses and provider-verified
sync to the list/get read paths, matching the existing deployment
endpoint sync pattern.

API changes:
- list_flow_versions returns is_deployed per entry and accepts optional
  deployment_ids filter to scope by specific deployments
- get_single_flow_version returns is_deployed on the full response
- Both endpoints now use write sessions and run best-effort
  snapshot-level sync before returning results

Sync-on-read (helpers.sync_flow_version_attachments):
- Queries all attachments for a flow's versions joined with deployment
  and provider account info in a single query
- Groups by provider, resolves adapter/mapper per group, verifies
  provider_snapshot_ids via list_snapshots, and prunes stale attachment
  rows through the existing sync_attachment_snapshot_ids helper
- Per-provider error handling so one provider outage doesn't block the
  response

New CRUD: list_attachments_for_flow_with_provider_info joins
FlowVersionDeploymentAttachment -> Deployment -> DeploymentProviderAccount
to avoid N+1 queries during sync grouping.

Tests: 50 passing (11 new) covering is_deployed indicator, deployment_ids
filtering, stale attachment pruning on list/get, and sync failure
resilience.

* Add user id authentication to a few missing endpoints

* [autofix.ci] apply automated fixes

* Update tests

Removes some mock tests that did nothing
Adds sqlite for true testing of db accessors
Reduces Mock objects usage

* refactor(deployments): enforce ownership boundaries on execution responses
Move provider-owned execution identifiers (execution_id, agent_id,
status, timestamps, errors) out of the top-level API response and into
provider_data, keeping only Langflow-owned fields (deployment_id) at the
top level.  This prevents future collisions if Langflow introduces its
own execution tracking.
Key changes:
- Remove execution_id from _ExecutionResponseBase; provider's opaque
  run identifier now lives exclusively inside provider_data
- Rename WatsonxExecutionResultData → WatsonxAgentExecutionResultData
  (adapter layer) and split the API-layer class into a private base
  (_WatsonxApiAgentExecutionResultBase) with dedicated
  WatsonxApiAgentExecutionCreateResultData and
  WatsonxApiAgentExecutionStatusResultData subclasses
- Translate WXO run_id → execution_id at the adapter boundary
  (create_agent_run_result / get_agent_run).
- Collapse util_execution_id + util_execution_deployment_resource_key
  into a single util_resource_key_from_execution that trusts the
  adapter-provided result.deployment_id directly
- Remove build_orchestrate_runs_query and extra payload fields
  (thread_id, llm_params, guardrails, etc.) unused in MVP
- Simplify WxOClient.post_run signature (drop query_suffix)
- Exclude provider_data from flow tool artifact to avoid unexpected
  top-level keys in the WxO tool runtime
- Document ownership boundary rules in DEPLOYMENT_BOUNDARY_RULES.md §14
- Add E2E polling for terminal execution status, input format variants,
  and missing-deployment negative test
- Expand unit tests for renamed schemas, field mapping, passthrough
  validation, and simplified payload builder

* feat: add name column to deployment_provider_account
Add a required, user-chosen display name to provider accounts
(e.g. "staging", "prod") that is unique within a given provider_key.
Includes model, CRUD, API schema/route, mapper, migration with
backfill, and tests.

* fix: replace hand-written migration with Alembic-generated revision
Replace the manually authored migration (b4e6f8a2c1d3) with an
Alembic-generated one (8255e9fc18d9) for the deployment_provider_account
name column.
Fix SQLite compatibility: sa.func.concat() generates a concat() function
call which does not exist in SQLite. Use sa.literal().concat() instead,
which produces the || operator and works on both PostgreSQL and SQLite.

* remove bogus unverified math from migration file

* feat: verify provider credentials before account creation
Add a verify_credentials step to the provider account creation flow
that validates API keys against the provider before persisting them.
This prevents storing invalid or revoked credentials and gives users
immediate feedback.
Key changes:
- Add verify_credentials to the deployment adapter interface (base,
  service, protocol) with WXO implementation that obtains a token
  via the IBM authenticator
- Add SSRF-hardened URL validation for provider_url (HTTPS-only,
  private IP blocklist, localhost rejection, normalization)
- Introduce ValidatedUrl/ValidatedUrlOptional annotated types in
  the API schema layer
- Refactor raise_for_status_and_detail to accept an optional cause
  parameter for explicit exception chain control
- Use ResourceNotFoundError (parent) instead of DeploymentNotFoundError
  in raise_for_status_and_detail for provider-agnostic 404 mapping
- Narrow get_authenticator return type to concrete union

* use whitelist only for valid urls

* feat: BREAKING: move credentials into provider_data and centralize update logic in mapper
- Replace top-level `api_key: SecretStr` with opaque `provider_data: dict` in API schemas;
  mapper extracts credentials via `resolve_credential_fields` for DB storage
- Add `resolve_provider_account_update` to base mapper so routes delegate
  full update-kwargs assembly (including cross-field logic) to the mapper
- WXO mapper override re-derives `provider_tenant_id` when `provider_url` changes
- Add tenant extraction utilities and `validate_tenant_url_consistency` in
  `deployment_provider_account/utils.py` as single source of truth
- Add `model_validator` on `DeploymentProviderAccount` for defense-in-depth
  tenant/URL consistency checks
- Rename `DEPLOYMENT_BOUNDARY_RULES.md` → `RULES.md`; document DB-direction
  mapper contract, credential flow, and update assembly
- Update all tests for new `provider_data` shape, mapper update methods,
  tenant extraction, and model-level consistency validation

* [autofix.ci] apply automated fixes

* [autofix.ci] apply automated fixes (attempt 2/3)

* fix(deployments): Harden provider account validation and WXO rollback

Use provider_url when resolving WXO credentials and scope provider account names per user within each provider. Re-verify provider account updates before persisting them and return 4xx responses for account conflicts instead of surfacing 500s.

Block deleting provider accounts that still own deployments and extend create rollback so failed WXO writes clean up provider-side resources. Add route, schema, mapper, sync, CRUD, and WXO tests to cover the new behavior.

* [autofix.ci] apply automated fixes

* update url validator docs; remove outdated reference to private url blacklist logic

* fix(deployments): Isolate snapshot sync writes

Use nested transactions around best-effort snapshot cleanup so provider sync failures cannot leak partial attachment deletes into the outer request transaction.

Persist explicit description clears during deployment PATCH requests, and add regression tests for both deployment sync paths and the route handler update flow.

* fix(deployments): Harden delete cleanup and wxO create tests

Treat missing provider agents as stale local cleanup so delete can
finish instead of leaving orphaned deployment rows behind.

Commit local delete operations eagerly, retry once on commit failure,
and move wxO create-path tests toward fake client objects so the real
service logic is exercised without external calls.

* new head

* fix(deployments): stop prefixing wxo raw connection app_ids
Preserve caller app_ids for newly created wxo connections while keeping lf_ prefixing for tool/deployment naming, centralize resource_name_prefix validation, and update mapper/service schema tests and docs to reflect the new behavior.

* fix(deployments): Harden provider account cleanup

Reconcile stale deployment rows before provider-account deletion so
out-of-band provider removals do not leave account cleanup blocked.

* fix: restore py310 compatibility and align payload slot tests
Import Self from typing_extensions in the deployment provider account model to keep backend imports working on Python 3.10, and update payload formalization tests to assert strict rejection of cross-model BaseModel inputs.

* fix(deployments): resolve mypy typing regressions across deployment flows
Normalize SQLModel query expressions for typed SQL operators, make deployment-related model IDs non-nullable where appropriate, and tighten provider mapper/update typing guards. Update deployment tests to align with stricter type contracts.

* fix(deployments): restore py310 test compatibility and migration idempotency
Replace Python 3.11-only UTC imports with timezone.utc in deployment-related tests and the watsonx e2e helper, and make the provider-account name migration safe to re-run when the column and unique constraint are created in separate steps.

* fix(deployments): restore provider account route ownership helpers
Reuse the shared provider-account lookup in update/delete routes so route tests keep the expected ownership path, and use the explicit-field helper when deciding whether to reverify credentials.

* [autofix.ci] apply automated fixes

* [autofix.ci] apply automated fixes (attempt 2/3)

* [autofix.ci] apply automated fixes (attempt 3/3)

* fix(deployments): enforce deployment guard constraints with clean API errors
Add DB trigger guards to block deleting deployed flow versions, deleting projects with deployments, and moving deployed flows across projects. Translate trigger violations to HTTP 409 with sanitized details, add best-effort pre-operation deployment/snapshot sync to reduce stale-state false positives, and cover guard parsing/delete flush behavior with tests.

* checkout latest crud and helpers files

* make helper for try catch sync logic

* add gaurd to prevent moving deployments across projects

* prevent moving deployments across provider accounts

* add live sqlite tests

* recover lost changes

* recover feature flag setup from release-1.9.0

* fix: address review findings for deployment guard branch
- Add comment in delete_user explaining why best-effort provider sync
  is intentionally skipped (too expensive; DB trigger is authoritative)
- Add docstring to _clean_guard_detail for maintainability
- Add happy-path trigger tests verifying operations succeed when no
  deployment conflicts exist (flow version delete, project delete,
  flow move, deployment rename)
- Fix list_attachments_for_flow_with_provider_info callers still using
  the old flow_id= parameter (now flow_ids=)
- Fix pre-existing broken test fixture (missing name in
  DeploymentProviderAccount)

* feat: add cross-project attachment guard and harden test suite
Add a new DB trigger (prevent_cross_project_attachment) that blocks
attaching a flow version to a deployment in a different project, for
both PostgreSQL and SQLite.
Refactor trigger tests into a unified dual-dialect test file
(test_deployment_guard_triggers.py) that runs against both SQLite
(always) and PostgreSQL (when TEST_DEPLOYMENT_GUARD_PG_URL is set).
Validated with both asyncpg and psycopg drivers.
Additional improvements:
- test_downgrade_removes_triggers now asserts the guard is active
  before downgrade, preventing false-positive passes
- Endpoint test uses statement inspection instead of fragile
  call-count gating
- Add exception parser coverage for CROSS_PROJECT_ATTACHMENT,
  implicit __context__ chains, and cyclic exception chains
- Add endpoint tests for cascade_delete_flow, update_flow,
  delete_multiple_flows, and global exception handler

* fix(deployments): make provider account identity immutable
Add DB deployment guard triggers to prevent updating provider account identity fields
(provider_key, provider_tenant_id, provider_url) once created, and preserve guard
error translation in the provider-account PATCH route. Extend trigger and route
tests to cover blocked updates and same-value no-op updates.

* refactor: extract sync logic into dedicated module and fix sync correctness issues
- Move deployment/attachment sync functions from helpers.py to new sync.py
  module, reducing helpers.py size and improving separation of concerns
- Fix fetch_provider_resource_keys to use deployment_ids instead of
  provider_params (pre-existing bug: wrong adapter parameter)
- Add empty-list guard to fetch_provider_resource_keys to avoid
  unnecessary provider calls
- Wrap snapshot sync in savepoint for proper fault isolation
- Update imports across flows.py, projects.py, flow_version.py,
  deployments.py to reference new sync module
- Update unit tests to target refactored module paths and add coverage
  for bug fixes

* refactor: implement binding-aware deployment sync and optimistic guard retries
Add provider binding contract and mapper extraction path:
- add ProviderSnapshotBinding in deployments/contracts.py
- add BaseDeploymentMapper.extract_snapshot_bindings() default no-op
- implement Watsonx mapper extract_snapshot_bindings() with strict provider_data parsing via PayloadSlot (snapshot_ids required)
Replace attachment snapshot verification loop with binding-aware set-based cleanup:
- add delete_unbound_attachments(user_id, deployment_ids, bindings) in flow_version_deployment_attachment/crud.py
  - uses CTE/anti-join to delete local attachments not present in provider bindings
  - when bindings are empty, delete all attachments for provided deployment_ids
- add count_attachments_by_deployment_ids() grouped recount helper
- update list_deployments_synced() in deployments/helpers.py to:
  - collect bindings from fetch_provider_resource_keys() provider_view during batch sync
  - run one savepoint-wrapped delete_unbound_attachments() for accepted deployments
  - run one grouped recount and patch attached_count from DB
  - remove list_attachments_by_deployment_ids + snapshot-provider phase
  - enforce two sync rounds max (initial pass + one refill)
Consolidate provider-side sync plumbing:
- change fetch_provider_resource_keys() in deployments/sync.py to return (known_resource_keys, provider_view)
- document tuple contents in function docstring
- remove now-unused sync_provider_attachment_snapshots() helper
- keep fetch_provider_snapshot_keys()/sync_attachment_snapshot_ids() for single-deployment read path
Scope read sync by provider account and conditionally expose deployment status:
- update deployment CRUD listing helpers to accept provider_account_id filter
- in flow_version API, add deployment_provider_account_id query param
- only perform deployment sync/is_deployed calculation when provider id is explicitly passed
- make FlowVersion.is_deployed optional (default None) so field can be omitted when not requested
Switch mutating APIs to optimistic catch-sync-retry pattern:
- add _retry_on_deployment_guard() in flows.py and projects.py
- replace pre-sync mutation flow with guarded retry on DeploymentGuardError
- for project create/update, retry only guarded flow-move DB operations
- preserve side-effect safety and improve stale-state recovery behavior
Tests:
- add unit tests for deployment guard retry helper (test_deployment_guard_retry.py)
- add unit tests for delete_unbound_attachments behavior, including empty bindings delete-all case (test_flow_version_deployment_attachment_crud.py)
- update deployment sync tests for tuple return, binding extraction, consolidated phase-2 cleanup/recount, and two-round refill behavior
- update flow_version tests for provider-scoped sync and conditional is_deployed field presence

* fix: extract tool_ids from provider data

* dont use stale rolled-back OORM Flow instance

* refactor(deployment): demote delete triggers and standardize guard handling
- Edit the existing deployment guard migration to remove DB delete triggers for flow version and project deletion in both PostgreSQL and SQLite.
- Keep core DB invariants (flow move, deployment project move, deployment provider account move, provider account identity immutability, and cross-project attachment).
- Add a new DB invariant trigger to enforce deployment.resource_key immutability.
- Rewrite trigger error text to technical/operator-focused language and remove ambiguous “detach” wording.
- Add migration comments documenting the current global provider identity guard and the future provider-specific migration path.
- Add app-level guard helpers in deployment/guards.py:
  - check_flow_has_deployed_versions
  - check_project_has_deployments
- Wire check_flow_has_deployed_versions into cascade_delete_flow before destructive deletes.
- Wire check_project_has_deployments into delete_project before deleting the folder row.
- Keep explicit DeploymentGuardError passthrough in cascade_delete_flow and retain parse fallback for non-guard exceptions.
- Refactor DeploymentGuardError to carry:
  - code
  - technical_detail
  - detail (API-friendly message)
- Add friendly guard-detail mapping by guard code.
- Update parse_deployment_guard_error to parse DEPLOYMENT_GUARD:<CODE>:<DETAIL> and preserve raw technical detail from chained exceptions.
- Simplify delete_user to DB-cascade delete + flush only.
- Remove deployment guard translation/parsing logic from delete_user.
- Keep an explicit endpoint comment documenting the intentional no-provider-teardown trade-off.
- Update flow_version deletion message to: “Remove its deployment attachment rows first.”
- Update tests to match the new guard contract and behavior:
  - Remove stale delete_user guard-translation endpoint test.
  - Update delete endpoint tests to assert app-level guard behavior and new friendly details.
  - Update trigger tests to reflect removed delete triggers and added resource_key trigger coverage.
  - Update trigger downgrade assertions for the revised trigger set.
  - Expand exception tests for code mapping, technical-detail preservation, unknown-code fallback, and new guard codes.
  - Add unit tests for deployment guard helper functions.

* surface better msg when project deletion attempted

* refactor(deployment): rename flow guard code and align guard messages
Rename FLOW_VERSION_DEPLOYED to FLOW_HAS_DEPLOYED_VERSIONS across deployment guard checks, project-level remapping, and tests.
Update friendly guard wording for flow/project/move/cross-project cases, and convert pytest match patterns to raw escaped regex strings to satisfy Ruff.

* add docs to migration file

* update docs in migration

* update docs

* refactor(flow-version): scope deployment status to list endpoint
Keep deployment status provider-scoped on version listing only, remove single-version sync/status behavior, and omit is_deployed from snapshot creation responses while aligning docs and tests.

* refactor(deployment): centralize guard retry helpers and align sync error handling
Move flow/project deployment-guard retry wrappers into deployment sync helpers while preserving upstream route logic, and align provider sync error mapping with deployment domain exceptions. Tighten wxo snapshot binding validation and update docs/tests for guard messaging and sync behavior.

* refactor(deployment): enforce snapshot ID invariants and improve delete error UX
- add shared non-empty string guard (`require_non_empty`) in database utils and use it in deployment attachment CRUD write paths
- enforce required `provider_snapshot_id` on attachment model and add Pydantic + SQLAlchemy validators as safety nets for non-CRUD writes
- introduce deployment attachment key schemas (`DeploymentAttachmentKey`, `DeploymentAttachmentKeyBatch`) with deduplication support
- add batch stale-row cleanup (`delete_deployment_attachments_by_keys`) using a VALUES CTE to delete exact deployment/flow-version pairs
- remove mapper-level `util_snapshot_ids_to_verify` hook from base + watsonx mapper and replace with sync utilities:
  - `extract_verified_snapshot_ids`
  - `extract_verified_provider_snapshot_ids`
- update sync and helper flows to use verified snapshot IDs, stricter provider ID validation, and safer corrected-count handling
- align provider ID handling so both deployment and snapshot sync paths reject blank provider IDs consistently
- tighten adapter/provider-key validation and enforce required snapshot binding during attach flow-version operations
- update deployment routes/helpers to new sync signatures and behavior
- remove legacy null/blank snapshot safety-net filters from attachment queries/delete-unbound reconciliation (intentional invariant enforcement)
- add broad backend test coverage for:
  - rejecting empty/blank snapshot IDs on create/update
  - exact-key batch deletion behavior
  - cartesian cross-delete regression prevention
  - updated route/sync expectations after helper refactor
- improve flow delete UX in the frontend list view by surfacing backend `detail` via `getAxiosErrorMessage` instead of a generic "Please try again"

* update logic and remove stale comment

* fix(deployment): handle orphaned deployment attachments and enforce SQLite FK constraints
Enable PRAGMA foreign_keys=ON for SQLite to enforce referential integrity
that was previously silently ignored, and add application-level cleanup for
orphaned FlowVersionDeploymentAttachment rows left behind by environments
where cascades never fired.
- Enable foreign_keys pragma in lfx SQLite settings
- Update deployment guards to detect and prune orphan attachments (missing
  deployment parent) before blocking on live ones, with structured logging
- Update flow_version and deployment CRUD queries to join on Deployment so
  is_deployed status and attachment counts reflect only live attachments
- Document has_deployment_attachments write side-effect (orphan pruning)
- Wrap pre-sync orphan cleanup in try/except so failures don't abort the
  sync process
- Explicitly delete spans and traces in cascade_delete_flow to avoid FK
  violations from the span.trace_id constraint (which lacks ON DELETE
  CASCADE in the DDL)
- Add in-memory SQLite integration tests covering guard pruning, orphan
  cleanup, version pruning, deployment counts, and is_deployed status
- Add unit tests for sync exception-handling paths

* refactor(deployment): replace DB trigger guards with ORM-layer preflight checks
Remove the unshipped trigger migration (97c9a98c9c01) and enforce
deployment invariants at the ORM/service layer instead:
- Add orm_guards.py with preflight checks for all six guard codes
  (FLOW_DEPLOYED_IN_PROJECT, DEPLOYMENT_PROJECT_MOVE, DEPLOYMENT_TYPE_UPDATE,
  DEPLOYMENT_RESOURCE_KEY_UPDATE, DEPLOYMENT_PROVIDER_ACCOUNT_MOVE,
  DEPLOYMENT_PROVIDER_ACCOUNT_IDENTITY_UPDATE, CROSS_PROJECT_ATTACHMENT)
- Wire guards as pure prefix blocks into deployment, provider-account,
  and attachment CRUD functions — existing write logic unchanged
- Add preflight validation before bulk update(Flow) statements in
  projects.py and folder/utils.py — existing statements unchanged
- Add ensure_flow_move_allowed to flows_helpers.py for ORM-instance
  update paths (_patch_flow, _update_existing_flow, _validate_and_assign_folder)
- Optimize batch flow-move guard to one query per source folder
- Simplify parse_deployment_guard_error to isinstance-only chain walk
  now that guards are raised explicitly as DeploymentGuardError
- Document retry helper contract: operations must enforce guards internally
- Replace trigger-centric tests with ORM/service-level guard tests
- Add project API guard integration tests for flow-move blocking

* fix(deployment): prune attachment rows before deployment deletes
Explicitly delete flow-version deployment attachments before deployment row deletes
to prevent orphaned attachments when FK cascades are disabled (e.g. SQLite
foreign_keys=OFF). Keep delete-by-resource-key and delete-by-id behavior intact
while documenting guard None-scope behavior and adding coverage for missing-row
and FK-disabled cleanup paths.

* recover lost tests

* misc

* remove deployment guard error extraction from lfx session scope

* extract re-raise logic into a helper

* fix: stabilize deployment guard retries and guard diagnostics
- scope WxO provider-client ContextVar state to each deployment provider scope via provider_clients_memoization_scope
- compose WxO scope lifecycle into deployment_provider_scope and document forward multi-adapter dispatch options
- add successful provider resource-key sync debug logging and remove stray print-based sync error debug
- log DeploymentGuardError details during flow cascade delete and in deployment guard exception re-raise helper
- fix folder defaulting guard precheck query to use Flow.folder_id.is_(None) so NULL-folder flows are included
- deduplicate require_non_empty by importing from langflow.services.database.utils in deployment mappers
- remove deprecated duplicate helper module at api/v1/mappers/deployments/util.py and keep package export wired to canonical helper
- add regression test for default-folder guard precheck covering NULL-folder flow handling

* add tests for provider scope context

* fix: improve deployment guard logging and async guard handling
Log DeploymentGuardError directly in flow/project endpoint guard catch blocks with operation context, and use the async guard helper for generic exception paths that need guard parsing. Add tests for async guard helper logging and raise behavior.

* less verbose name for scope

* harden delete_unbound_attachments by passing provider account id to it to scope deletion

* fix: return dense deployment attachment counts and simplify snapshot sync
Make `count_attachments_by_deployment_ids` return a dense mapping for all
requested deployment ids, including zero for ids with no countable attachments.
Update deployment listing code to rely on direct key access for corrected counts,
remove redundant `verified_snapshot_ids` plumbing from snapshot sync call sites,
keep local snapshot id integrity checks in sync logic, and align backend tests
plus log messaging with the new count contract.

* guard context scope

* test: expand deployment guard and sync regression coverage
Add comprehensive regression coverage for deployment guard and deployment-sync behavior across database and API test suites.
- verify deployment deletes remove linked attachment rows
- cover batched move guards and immutable deployment/provider fields
- validate cascade flow deletion and user-scoped orphan cleanup behavior
- exercise retry helper edge cases for flow/project guard retries
- align sync helper tests with stricter provider-id/error handling and dedupe/early-return paths
- add API 409 guard-path tests for deployed flow/project delete and move scenarios

* fix: align flow-version list semantics with provider-scoped deployment status
- remove `deployment_ids` handling from `GET /flows/{flow_id}/versions/` and keep plain list mode as versions-only
- enforce provider-account ownership for `deployment_provider_id` via `get_owned_provider_account_or_404` (404 on unknown/foreign ids)
- add explicit feature-flag guard for provider-scoped mode:
  `Cannot use deployment_provider_id: the wxo_deployments feature flag is disabled`
- remove `has_providers` / `count_provider_accounts` branching and drive behavior directly from request params
- replace `get_flow_version_list` with `get_flow_versions_with_provider_status` and scope `is_deployed` by:
  `Deployment.deployment_provider_account_id == provider_account_id`
- keep best-effort `sync_flow_version_attachments` before provider-scoped reads
- update API tests:
  - delete deployment_ids endpoint tests
  - add provider-scoped status regression coverage (true under provider A, false under provider B)
  - add provider-id feature-flag rejection test (400)
  - add unknown and foreign provider-id ownership tests (404)
  - simplify feature-disabled plain-list test to assert `is_deployed` remains omitted
- migrate CRUD/in-memory tests off removed `get_flow_version_list` to `get_flow_versions_with_provider_status`
- update stale flow export TODO comments referencing the removed function

* fix: batch stale deployment cleanup per provider sync group
Replace per-deployment stale deletes in deployment sync with a single batched delete per provider group.
Add a bulk deployment-delete CRUD helper and regression coverage for grouped stale-delete behavior plus multi-deployment attachment cleanup.

* test: expand deployment guard and provider account update coverage
Add direct ORM guard coverage for noop immutable updates and attachment project matching. Update in-memory deployment tests to cover provider account API key rotation and align stale fixtures with current model constraints.

* fix: make deployment GET sync binding-aware and harden guard/prune behavior
- Align SQLite defaults in `lfx/services/settings/base.py`:
  - remove forced `foreign_keys=ON` pragma from default sqlite pragmas
- Replace deployment GET snapshot-id verification with binding-aware reconciliation in `api/v1/deployments.py`:
  - resolve and use the concrete deployment mapper in GET
  - call mapper-provided `extract_snapshot_bindings_for_get(...)`
  - prune detached links via `delete_unbound_attachments(...)` inside `session.begin_nested()`
  - fall back safely to unverified attachment counts when sync is unsupported or fails
  - change provider_data response shaping to `mapper.shape_deployment_get_data(...)` to hide internal fields
- Extend mapper contracts in `api/v1/mappers/deployments/base.py`:
  - add `extract_snapshot_bindings_for_get(...)` (explicitly raises `NotImplementedError` by default)
  - add `shape_deployment_get_data(...)` (explicitly raises `NotImplementedError` by default)
  - make GET sync/shaping behavior explicit per provider instead of accidental passthrough
- Implement wxO-specific GET sync/shaping in `watsonx_orchestrate/mapper.py`:
  - parse/validate `provider_data.tool_ids` for binding extraction
  - emit `ProviderSnapshotBinding(resource_key, snapshot_id)` for each tool id
  - validate/shape GET `provider_data` to expose only `{"llm": ...}` to API clients
  - raise clear 500/value errors for malformed adapter payload contracts
- Update wxO adapter GET payload in `watsonx_orchestrate/service.py`:
  - always include `tool_ids` and derived `environment`
  - include `llm` when available
  - remove `or None` fallback so mapper receives consistent structure
- Harden flow-version pruning in `services/database/models/flow_version/crud.py`:
  - resolve concrete version IDs to prune first
  - delete `FlowVersionDeploymentAttachment` children before deleting `FlowVersion` rows
  - prevent stale doubly-orphan attachment rows when SQLite runs with foreign keys disabled
- Simplify guard exception semantics in `deployment/exceptions.py`:
  - stop walking chained exceptions; only treat explicit `DeploymentGuardError` instances as guard failures
  - add optional remap hook to `araise_if_deployment_guard_error_or_skip(...)`
  - add `remap_flow_guard_for_project_delete(...)` to convert flow guard code to project guard code where needed
- Remove duplicated per-route guard catch blocks and centralize behavior:
  - `api/utils/flow_utils.py`, `api/v1/flows.py`, and `api/v1/projects.py` now rely on shared async guard helper
  - project delete path now remaps `FLOW_HAS_DEPLOYED_VERSIONS` into `PROJECT_HAS_DEPLOYMENTS` via shared remap function
- Keep multi-delete flow route behavior consistent in `api/v1/flows.py`:
  - run guard remap/log helper in broad exception path before generic logging and 500 handling
- Update deployment exception tests in `test_exceptions.py`:
  - remove chain-parsing expectations
  - validate direct guard-raise semantics
  - add remap function coverage
- Expand flow version pruning tests:
  - `test_crud.py`: verify delete ordering (attachments first, versions second) and no-op behavior when nothing is pruned
  - `test_in_memory.py`: add broad regression class proving orphan attachment cleanup, live deployment preservation, cross-flow/user isolation, and repeated-cycle convergence
- Expand deployment API/mapper/sync test coverage:
  - `test_deployment_mapper_base.py`: assert new base mapper GET shaper raises until implemented
  - `test_deployment_route_handlers.py`: migrate assertions to binding-aware sync behavior, unsupported-provider fallback, sync-failure fallback, and provider_data sanitization
  - `test_deployment_sync.py`: add wxO mapper tests for `extract_snapshot_bindings_for_get(...)` and GET data shaping requirements
  - `test_watsonx_orchestrate.py`: validate wxO GET provider_data now includes `tool_ids`/`environment` defaults and feature-flag-scoped provider context behavior

* remove redunant description

* remove agent environment from payload for get()

* fix(deployment): prune orphan attachments before reading in flow guard

The cascade flow delete path called `check_flow_has_deployed_versions`,
which issued a SELECT before any write. On SQLite that left the
connection holding only a SHARED lock; the subsequent cascade DELETEs
then had to upgrade SHARED -> RESERVED, which doesn't busy-wait when
another connection already holds RESERVED, surfacing intermittently
in CI as `OperationalError: database is locked`.

Reorder the guard to issue a single DELETE-with-scalar-subquery for
orphan attachments first, so the connection acquires the writer lock
up front. The live-attachment SELECT runs afterwards on the same
session. As a side benefit, orphan pruning now also runs when live
attachments coexist (previously the early raise short-circuited it,
though SAVEPOINT rollback in the retry wrapper still discards the
prune in that failure path).

Log the raw driver-reported `rowcount` verbatim on every prune for
debuggability, and update guard tests for the new DELETE-then-SELECT
ordering.

* add log that pruning might be rolled back

* fix(deployment): set provider scope when reconciling before provider-account delete
The DELETE /api/v1/deployments/providers/{id} handler called
list_deployments_synced without entering deployment_provider_scope, so the
WxO adapter raised CredentialResolutionError ("Deployment account context is
not available for adapter resolution"). Reconciliation was silently dropped
and the stale local count blocked every delete with a 409.
Wrap the reconciliation call in deployment_provider_scope(provider_account.id)
to match every other adapter call site in this module, so stale local
deployment rows can actually be pruned and the provider account can be
removed when the provider no longer owns any resources.
Add three regression tests in TestProviderAccountRoutes:
- assert deployment_provider_scope is active (with the right provider id)
  during reconciliation, and that the context does not leak afterwards
- assert that a CredentialResolutionError from reconciliation falls back to
  the local count and returns 409 without deleting the provider row
- assert that reconciliation is skipped entirely when no local deployments
  exist for the provider

---------

Co-authored-by: Jordan Frazier <jordan.frazier@datastax.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
(cherry picked from commit 60bb53b44c)
2026-04-23 17:49:52 -07:00
b8fe970493 fix(mcp): close path traversal + cross-user disclosure (PVR0754098) (#12818)
* fix(mcp): close path traversal + cross-user disclosure in MCP endpoint (PVR0754098)

Path-containment on the storage service was only enforced in save_file;
get_file/get_file_stream/delete_file/get_file_size all resolved user-supplied
names directly, letting an authenticated user read arbitrary files via the
MCP resources/read handler. resources/list and tools/list additionally
returned every user's flows regardless of ownership.

- storage/local.py: extract path-containment into shared _validated_path()
  and call it from every read/write/delete entry point (langflow + lfx).
- mcp_utils.handle_read_resource: reject filenames containing ../, /, \ at
  the handler layer; require a current user and verify flow ownership
  (or self-owned user bucket) before dispatching to storage.
- mcp_utils.handle_read_resource: accept optional project_id so project
  servers can't read resources outside the project's flows.
- mcp_projects: pass project_id into handle_read_resource.
- mcp_utils.handle_list_resources / handle_list_tools: scope flow queries
  to the authenticated user on the global server.

Regression tests cover traversal rejection on every read path, cross-user
flow access denial, project-scope enforcement, and unauthenticated list
queries returning empty.

* fix(mcp): drop user-bucket files from project-scoped resources/list

Project-scoped handle_list_resources still appended every UserFile owned
by the caller, so a project MCP client could enumerate user-level files
unrelated to the project. User files have no project association, so
skip them entirely when project_id is set.

Adds a regression test proving that project-scoped resources/list returns
only files from flows in the project.

(cherry picked from commit f0fd436fe9)
2026-04-23 17:49:52 -07:00
dc2411cb18 fix(custom): honor asname in from X import Y as Z for custom components (#12813)
* fix(custom): honor asname in `from X import Y as Z` for custom components

`_handle_module_attributes` was keying `exec_globals` on `alias.name`, so
`from pkg import Foo as Bar` bound `Foo` instead of `Bar` in a custom
component's exec scope. Any reference to `Bar` then raised NameError and
the component failed to load.

Use `alias.asname or alias.name`, matching the `import X as Y` branch in
the same file and standard Python import semantics. Adds regression tests
against `prepare_global_scope` and end-to-end through `create_class`.

* fix: Make sdk env flag idempotent (release-1.9.1) (#12815)

fix: Make sdk env flag idempotent

Refactor pytest_addoption to register CLI options via a loop with
contextlib.suppress(ValueError), allowing langflow-sdk and lfx to
coexist without plugin registration conflicts.

Add test_pytest_addoption_is_idempotent to verify behavior.

(cherry picked from commit cae2bdfef6)
2026-04-23 17:49:52 -07:00
c77c473bb2 feat: e2e tests for deployments api (#12767)
* update e2e tests

* fix(watsonx): harden existing-resource create flow and rollback journaling
- move the direct Watsonx adapter E2E runner to `scripts/e2e_deployment_tests/watsonx_orchestrate/adapter.py` (rename-only) so deployment E2E assets are consolidated under one folder
- add `scripts/e2e_deployment_tests/watsonx_orchestrate/api.py` with a full `/api/v1/deployments` matrix covering create/update happy paths, validation rejections, attachment patching, rollback/error paths, concurrency races, large payload tiers, and failpoint scenarios with owned-resource cleanup
- clarify existing-resource create behavior in `src/backend/base/langflow/api/v1/deployments.py`: DB-only onboarding keeps `created_*` fields empty unless provider mutation operations are requested
- add `util_create_result_from_existing_resource` in `src/backend/base/langflow/api/v1/mappers/deployments/watsonx_orchestrate/mapper.py` to normalize non-mutating onboard responses into a create-style result with empty `app_ids` and `tools_with_refs`
- extend `src/backend/base/langflow/services/adapters/deployment/watsonx_orchestrate/core/config.py` to accept `created_app_ids_journal` and append app ids immediately after successful provider connection creation for rollback safety
- update shared connection orchestration in `src/backend/base/langflow/services/adapters/deployment/watsonx_orchestrate/core/shared.py` to normalize provider app ids via `RawConnectionCreatePlan.__post_init__`, propagate `created_app_ids_journal`, dedupe rollback ids, and wrap validation-stage failures as `ConnectionCreateBatchError` with rollback metadata
- wire journaling into create/update rollback flows in `src/backend/base/langflow/services/adapters/deployment/watsonx_orchestrate/core/create.py` and `src/backend/base/langflow/services/adapters/deployment/watsonx_orchestrate/core/update.py` so partial provider-side connection creation is always captured for cleanup
- add mapper coverage in `src/backend/tests/unit/api/v1/test_deployment_mapper_watsonx.py` for existing-resource create-result normalization
- expand `src/backend/tests/unit/services/deployment/test_watsonx_orchestrate.py` with coverage for provider app-id normalization, validation-failure rollback metadata, and create/update rollback when failures occur after provider connection creation; update mocks/monkeypatch targets to match the shared connection entrypoint signature

* simplify create result logic (improves error friendliness

(cherry picked from commit 9f42c9e707)
2026-04-23 17:49:51 -07:00
0a34421a0e feat(google): refresh Gemini model list and enable tool calling for Gemini 3 (#12797)
* feat(google): refresh Gemini model list and enable tool calling for Gemini 3

Updates the Google Generative AI model metadata to reflect the current Gemini
API lineup and langchain-google-genai 4.1.3 capabilities:

- Enable tool_calling for all Gemini 3 preview models (supported by
  langchain-google-genai 4.1.3, which handles Gemini 3 thought signatures)
- Remove gemini-3-pro-preview (shut down March 9, 2026; replaced by
  gemini-3.1-pro-preview which is already listed)
- Add gemini-3.1-flash-lite-preview (Gemini 3.1 Flash Lite)
- Add gemini-3.1-flash-image-preview (Nano Banana 2)
- Drop the stale TODO now that Gemini 3 tool calling is wired up

* [autofix.ci] apply automated fixes

* fix(models): flatten list-shaped AIMessage content so Gemini 3 works

Gemini 3 models (via langchain-google-genai >=4.1.0) return AIMessage.content
as a list of content blocks, e.g.

    [{"type": "text", "text": "...", "thought_signature": "..."}]

Message(text=...) only accepts strings/iterators, so building the Language
Model component with gemini-3.1-pro-preview (or any other Gemini 3 model)
raised a pydantic ValidationError with three "text.*" errors.

Add _normalize_message_content() which concatenates text blocks and drops
non-text blocks, and run every AIMessage through it in _get_chat_result and
_handle_stream before constructing the Message.

Includes unit tests covering the Gemini 3 shape, multiple text blocks,
mixed non-text blocks, and defensive cases (None, empty list, missing text).

* fix(models): hide and clear api_key for providers without one (e.g. Ollama)

handle_model_input_update unconditionally forced api_key.show=True at the end
of the update cycle. For providers whose metadata doesn't map a variable to
api_key (Ollama is the only one today), this left a stale cross-provider
credential like OPENAI_API_KEY sitting behind a field that should not be
visible at all.

apply_provider_variable_config_to_build_config already sets show=True for
providers whose metadata DOES map api_key, so the force-show was redundant
for every other provider. Drop it, and when api_key is hidden by the provider
config step, also clear its value and load_from_db flag so switching back to
an api_key provider triggers the normal auto-populate path via the stale
cross-provider variable detection.

Updates the existing default-state test (which encoded the bug) and adds two
new regression tests: one for Ollama (hidden + cleared) and one for OpenAI
(visible stays visible).

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
(cherry picked from commit 737279943b)
2026-04-23 17:49:51 -07:00
974c5abc5e feat(deployments): filter WXO agent list to drafts when load_from_provider=true (#12745)
* feat(deployments): filter WXO list to drafts and expose environments as a list

When `load_from_provider=true` on `GET /deployments`, restrict watsonx
Orchestrate results to draft agents only and surface their environment
metadata as `environments: list[str]` on both the list and status
responses.

- Add `BaseDeploymentMapper.resolve_load_from_provider_deployment_list_params`
  as an extension point; override in the WXO mapper to always inject
  `{"environment": "draft"}` when listing from the provider.
- In the WXO adapter's `list`, pop `environment` from `provider_params`
  before building the WXO query (it is not a native WXO query param) and
  apply it as a client-side membership filter.
- Skip forwarding `deployment_type` from the endpoint on the
  `load_from_provider` path; WXO only exposes agent deployments today and
  other list logic does not rely on it.
- Replace the single `environment` string with `environments: list[str]`
  in list and status `provider_data`. This is a breaking change to the
  provider-backed shape, accepted because the feature is still behind a
  flag.
- Introduce `get_agent_environments` with fail-fast access (no silent
  fallbacks/normalization) so WXO contract breaks surface immediately,
  and drop the now-unused `derive_agent_environment` categorizer.

Tests updated to cover the new filter, the list shape, the status shape,
and the fail-fast semantics of the helper.

* [autofix.ci] apply automated fixes

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
(cherry picked from commit ab70449427)
2026-04-23 17:49:51 -07:00
957ade8880 chore: upgrade wxo adk to 2.8.0 (#12707)
* chore: update wxo adk (2.8.0)

* make sure all sites use the helper

* revert tests

* remove thin helper and use adk directly

(cherry picked from commit b4f0870980)
2026-04-23 17:49:51 -07:00
b398f63a09 test: add missing test coverage for wxo deployments (#12689)
* test(deployments): add comprehensive test coverage for WXO deployment schemas, hooks, and components

Frontend (11 new/expanded test files, ~170 tests):
- use-connection-panel-state: tests for all handlers, ID sanitization, env var management
- step-review: tests for summary display, flows, connections, masking, edit mode
- global variable hooks: tests for useGetGlobalVariables auth guard and Zustand hydration
- use-patch-deployment: fix incorrect spec field assertion, test URL/body destructuring
- deployment-expanded-row, deployment-info-grid, deployment-flow-list: component tests
- flow-list-panel, version-panel, connection-search-list: panel component tests
- deployment-stepper-payload-builders: tests for buildConnectionPayloads,
  buildDeploymentUpdatePayload, buildDeploymentPayload, buildProviderAccountPayload

Backend (2 expanded test files, ~21 new tests):
- test_deployments_response_mapping: tests for update/list/execution/config response shapes
- test_deployment_schemas: tests for pagination constraints, execution schemas, snapshot schemas

* Fix nested button issue; remove more unnecessary tests

* update fe tests

* [autofix.ci] apply automated fixes

* [autofix.ci] apply automated fixes (attempt 2/3)

* [autofix.ci] apply automated fixes

* fix tests; filter sql warnings

* ruff

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Viktor Avelino <64113566+viktoravelino@users.noreply.github.com>
(cherry picked from commit 3fb40f3465)
2026-04-23 17:49:51 -07:00
7b06c2033c fix(frontend): filter duplicate draft/live connections in deploy modal (#12724)
* fix(frontend): filter duplicate draft/live connections in deploy modal

Connections with same app_id can exist as both draft and live, causing
both to appear selected simultaneously. Filter to draft-only and add
environment badge for clarity.

LFOSS-3373

* fix: remove connection environment badge

(cherry picked from commit 899f82de5b)
2026-04-23 17:49:51 -07:00
5307f400bf feat: filter out live connections from wxo adapter (#12744)
* filter out live configs

* remove test, trust adk and wxo api

* [autofix.ci] apply automated fixes

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
(cherry picked from commit ea57e9a57f)
2026-04-23 17:49:51 -07:00
6b0c95d192 refactor: Center truncate deployment provider URL (#12579)
* changed Deployment Provider URL to truncate in the center

* fix: center-truncate deployment provider URL using provider_data.url

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
Co-authored-by: Jordan Frazier <122494242+jordanrfrazier@users.noreply.github.com>
(cherry picked from commit 4f9bd2bcf4)
2026-04-23 17:49:51 -07:00
89d1c60bed feat: Enhance config loading by applying GUNICORN_CMD_ARGS before programmatic options (#12313)
* feat: Enhance config loading by applying GUNICORN_CMD_ARGS before programmatic options

* docs: Add Gunicorn configuration details to environment variables documentation

* Update src/backend/base/langflow/server.py

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Update src/backend/base/langflow/server.py

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* add unit test

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Gabriel Luiz Freitas Almeida <gabriel@logspace.ai>
Co-authored-by: Jordan Frazier <122494242+jordanrfrazier@users.noreply.github.com>
Co-authored-by: Jordan Frazier <jordan.frazier@datastax.com>
(cherry picked from commit 9d14d3b34e)
2026-04-23 17:49:51 -07:00
5d6a7a0f31 chore: address eric's comment 1
address eric's comment 1
2026-04-21 16:18:16 -04:00
88d95758b0 chore: add whitesource to ignore and scan all src
add whitesource to .gitignore and scan all of src
2026-04-21 16:18:16 -04:00
ce6507bee1 ci: add mend integration
add mend integration to OSS
2026-04-21 16:18:16 -04:00
9aae6de814 ci: increase backend test timeout 2026-04-15 08:41:09 -07:00
da516b7045 Merge release branch 2026-04-14 16:44:45 -07:00
14fe53e150 feat: add customOpenUrl utility for secure external link handling (#12705)
* feat: add customOpenUrl utility for secure external link handling

Extract window.open with noopener/noreferrer into a reusable customization
utility and use it in ProviderConfigurationForm. Also converts to type-only
imports where applicable.

* fix: use existing function

* fix: use custom open tab function
2026-04-14 22:07:49 +00:00
a47f2ad17e fix(frontend): add backdrop blur to test deployment modal (#12704)
Match the stepper modal's stronger backdrop overlay style.
2026-04-14 21:32:39 +00:00
38d142a723 fix: Upgrade cuga to 0.2.20 to resolve playwright dependency conflict (#12703)
* fix: upgrade playwright to 1.58.0 to address Chromium CVEs

- Add playwright>=1.58.0 to override-dependencies in pyproject.toml
- Update uv.lock: playwright 1.49.0 -> 1.58.0, pyee 12.0.0 -> 13.0.1
- Fixes CVE-2026-2313, CVE-2026-2314, CVE-2026-2315, CVE-2026-2319,
  CVE-2026-2321, CVE-2026-2441, CVE-2026-2648, CVE-2026-2649
- Ensures Docker builds download updated Chromium with security patches

* fix: update npm to latest version to address brace-expansion CVE-2026-33750

- Add npm update after Node.js installation in Dockerfile
- Fixes CVE-2026-33750 in system npm's brace-expansion dependency
- System npm had brace-expansion 2.0.2, update gets 5.0.5+
- Low risk change: npm is backward compatible, only affects CLI tool

* revert: remove npm update from Dockerfile

- npm update attempts were causing CI build failures
- Bundled npm has issues but updating it is proving problematic
- Focus on playwright CVE fix which is the primary concern
- brace-expansion CVE-2026-33750 is lower priority (DoS only)

* chore: sync uv.lock files

sync uv.lock files

* fix(mcp): dedupe edges in connect_components (#12701)

* fix(mcp): make add_connection idempotent to avoid duplicate edges

connect_components used to append a new edge unconditionally. Because
the edge id is deterministic from source/target/handles, calling it for
a pair the flow already had wired up (UI-then-MCP, batch retry, or just
a repeat call) produced a second edge with the same id, double-wiring
the flow at runtime.

Before appending, scan the existing edges for one with the same id and
return that instead. Different outputs/inputs between the same pair
still produce distinct ids and remain supported.

* test(mcp): cover dedupe against UI-saved edges, broaden match key

Older Langflow UIs saved edges with an `xy-edge__` id prefix instead of
the current `reactflow__edge-`, so an id-based dedup would miss the
UI-then-MCP case for any flow that came from an older version. Switch
the existence check to a structural one (source, target, sourceHandle
name, targetHandle fieldName) so the same logical connection dedupes
regardless of id format.

Add a fixture-driven test that loads MemoryChatbotNoLLM.json (an
xy-edge-prefixed flow) and replays each connection through
add_connection, asserting the edge count does not grow.

* fix(mcp): validate_flow fast-fails and reports partial errors (#12697)

* fix(mcp): validate_flow fast-fails and reports partial errors

validate_flow polled /monitor/builds for up to 30 seconds waiting for
every component to finish before reporting errors. When a component
fails early (for example a missing required field), downstream
components never run, so the loop waited out the full window and
returned just "Build timed out: N/M components completed" with no
actionable context.

- Short-circuit as soon as any completed build reports valid: false;
  return those errors immediately instead of polling on.
- On timeout, include the errors from the builds that did complete
  plus a component_count so the caller can see progress.
- Extract _collect_build_errors so the poll loop and timeout branch
  share the same error shape.

* fix(mcp): stream validate_flow build inline instead of polling

The previous implementation triggered an async build and polled
/monitor/builds, which depended on FastAPI BackgroundTasks firing the
log_vertex_build calls after the trigger request had returned. Under
ASGI test transport these tasks never run, so /monitor/builds stayed
empty and validate_flow timed out with component_count=0.

Switch to event_delivery=direct so the build streams its events back
inside the same request:

- Drive the build via client.stream_post and aggregate per-vertex
  results from end_vertex events.
- Fast-fail on the first vertex with valid=false, since downstream
  vertices depend on it and would not produce useful information.
- Surface top-level error events as a single flow-level error.
- Replace _collect_build_errors with _extract_vertex_error, which
  reads the structured error payload from the end_vertex outputs.

Update the lfx unit tests to use the streaming shape and tighten the
backend integration test to assert real success now that the build
actually runs end to end under ASGI.

* fix(graph): make end_all_traces_in_context Python 3.10 compatible

The implementation called asyncio.create_task(coro, context=context),
but the context= keyword was added to create_task in Python 3.11. On
3.10 it raised TypeError. The bug was latent because nothing in the
test suite previously consumed a streaming build response far enough
for Starlette to dispatch the post-response BackgroundTasks where this
code lives. The validate_flow streaming change exposes it.

On 3.10, route the create_task call through context.run so the new
Task copies the captured context as its current context, matching the
isolation the 3.11 path provides via the context= kwarg.

Add a regression test that asserts end_all_traces sees the value of a
contextvar set before the context was captured, even after the caller
mutates that var.

* fix: failing wxo list llm test (#12700)

patch service layer and update failing test

* [autofix.ci] apply automated fixes

* [autofix.ci] apply automated fixes (attempt 2/3)

* Try to fix the missing typer import

---------

Co-authored-by: Janardan S Kavia <janardanskavia@Janardans-MacBook-Pro.local>
Co-authored-by: Adam Aghili <Adam.Aghili@ibm.com>
Co-authored-by: Gabriel Luiz Freitas Almeida <gabriel@logspace.ai>
Co-authored-by: Hamza Rashid <74062092+HzaRashid@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>
2026-04-14 21:23:12 +00:00
07cb95a2c5 fix: add pydantic validation on component assistant (#12706) 2026-04-14 18:34:38 -03:00
449c26bb42 fix: failing wxo list llm test (#12700)
patch service layer and update failing test
2026-04-14 20:20:57 +00:00
0b58f1e532 fix(mcp): validate_flow fast-fails and reports partial errors (#12697)
* fix(mcp): validate_flow fast-fails and reports partial errors

validate_flow polled /monitor/builds for up to 30 seconds waiting for
every component to finish before reporting errors. When a component
fails early (for example a missing required field), downstream
components never run, so the loop waited out the full window and
returned just "Build timed out: N/M components completed" with no
actionable context.

- Short-circuit as soon as any completed build reports valid: false;
  return those errors immediately instead of polling on.
- On timeout, include the errors from the builds that did complete
  plus a component_count so the caller can see progress.
- Extract _collect_build_errors so the poll loop and timeout branch
  share the same error shape.

* fix(mcp): stream validate_flow build inline instead of polling

The previous implementation triggered an async build and polled
/monitor/builds, which depended on FastAPI BackgroundTasks firing the
log_vertex_build calls after the trigger request had returned. Under
ASGI test transport these tasks never run, so /monitor/builds stayed
empty and validate_flow timed out with component_count=0.

Switch to event_delivery=direct so the build streams its events back
inside the same request:

- Drive the build via client.stream_post and aggregate per-vertex
  results from end_vertex events.
- Fast-fail on the first vertex with valid=false, since downstream
  vertices depend on it and would not produce useful information.
- Surface top-level error events as a single flow-level error.
- Replace _collect_build_errors with _extract_vertex_error, which
  reads the structured error payload from the end_vertex outputs.

Update the lfx unit tests to use the streaming shape and tighten the
backend integration test to assert real success now that the build
actually runs end to end under ASGI.

* fix(graph): make end_all_traces_in_context Python 3.10 compatible

The implementation called asyncio.create_task(coro, context=context),
but the context= keyword was added to create_task in Python 3.11. On
3.10 it raised TypeError. The bug was latent because nothing in the
test suite previously consumed a streaming build response far enough
for Starlette to dispatch the post-response BackgroundTasks where this
code lives. The validate_flow streaming change exposes it.

On 3.10, route the create_task call through context.run so the new
Task copies the captured context as its current context, matching the
isolation the 3.11 path provides via the context= kwarg.

Add a regression test that asserts end_all_traces sees the value of a
contextvar set before the context was captured, even after the caller
mutates that var.
2026-04-14 19:52:34 +00:00
9a198b6953 fix(mcp): dedupe edges in connect_components (#12701)
* fix(mcp): make add_connection idempotent to avoid duplicate edges

connect_components used to append a new edge unconditionally. Because
the edge id is deterministic from source/target/handles, calling it for
a pair the flow already had wired up (UI-then-MCP, batch retry, or just
a repeat call) produced a second edge with the same id, double-wiring
the flow at runtime.

Before appending, scan the existing edges for one with the same id and
return that instead. Different outputs/inputs between the same pair
still produce distinct ids and remain supported.

* test(mcp): cover dedupe against UI-saved edges, broaden match key

Older Langflow UIs saved edges with an `xy-edge__` id prefix instead of
the current `reactflow__edge-`, so an id-based dedup would miss the
UI-then-MCP case for any flow that came from an older version. Switch
the existence check to a structural one (source, target, sourceHandle
name, targetHandle fieldName) so the same logical connection dedupes
regardless of id format.

Add a fixture-driven test that loads MemoryChatbotNoLLM.json (an
xy-edge-prefixed flow) and replays each connection through
add_connection, asserting the edge count does not grow.
2026-04-14 19:48:58 +00:00
67981c6e14 fix: retry on flow execution failure and surface friendly message for weak models (#12699)
* fix assistant retry

* agent suggestions fix
2026-04-14 19:33:23 +00:00
9f1402ed99 fix: remove fictional gpt-5.3 ids and surface helpful message on model_not_found (#12693)
* fix 5.3 model not working

* [autofix.ci] apply automated fixes

* fix ruff style and checker

* [autofix.ci] apply automated fixes

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
2026-04-14 19:29:39 +00:00
cecc4a6c28 fix(mcp): expose layout tool as layout_flow to match batch dispatch (#12698)
The Python function layout_flow_tool was advertised to MCP clients
under its raw function name (layout_flow_tool) while the batch tool
map dispatched it under layout_flow. A caller copying tool names from
the MCP tool list could not drive batch without translating the name.

Pass name="layout_flow" to the decorator so the external MCP name
matches the batch dispatch key. The Python symbol stays layout_flow_tool
to avoid a clash with the layout_flow helper imported from
lfx.graph.flow_builder.layout.

Added a test that asserts every batch tool_map key is an actual MCP
tool name, so future drift between the two surfaces gets caught.
2026-04-14 19:20:05 +00:00
9539996a81 feat(deployments): verify wxO credentials against instance API (#12449)
* feat(deployments): verify wxO credentials against instance API

- Probe GET /v1/orchestrate/models after IAM token to validate URL+key
- Add POST /deployments/providers/verify-credentials for connection tests
- Extend unit tests for models probe and WxO client stub

* fix(api): rename verify endpoint and redact 422 request input
Rename the deployment provider credential verification route to /deployments/providers/verify and sanitize RequestValidationError responses so raw request payloads are not echoed back in 422 errors. Update route/tests accordingly, including regression coverage for input redaction.

* revert(api): remove verification endpoint follow-up changes

Keep this PR focused on wxO adapter tenant validation via model-list fetch and drop API-layer validation endpoint and request-redaction changes.

* fix(wxo): resolve list_llms rebase conflict with adapter seam

Keep release default-model merge behavior while preserving fetch_models_adapter usage, and update list_llms expectations in tests.

* [autofix.ci] apply automated fixes

---------

Co-authored-by: Hamza Rashid <hzarashid@gmail.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Hamza Rashid <74062092+HzaRashid@users.noreply.github.com>
2026-04-14 19:11:00 +00:00
b96b17e1d0 fix(frontend): improve deployment stepper visibility in light mode (#12696)
* fix(frontend): improve deployment stepper visibility in light mode

Step labels were using text-muted-foreground which is nearly invisible
in light mode. Changed to text-foreground with font-medium for active
steps. Also added overlayClassName prop to DialogContent to allow
per-dialog backdrop customization, used to lighten the deployment
modal backdrop in light mode.

* fix(frontend): add backdrop blur to deployment stepper modal

---------

Co-authored-by: Hamza Rashid <74062092+HzaRashid@users.noreply.github.com>
2026-04-14 19:10:15 +00:00
b65515f351 fix: add uv sync step to SDK version determination job (#12695)
The determine-sdk-version job was missing the 'uv sync' step that creates
the cache, causing the 'Post Setup Environment' step to fail with:
'cache path does not exist on disk'

This matches the pattern used in determine-lfx-version job (line 247) and
the nightly build workflow (line 104-105).

Fixes the SDK build failure in release workflow dry run.
2026-04-14 18:14:51 +00:00
d93892a214 fix(mcp): preserve category when loading component registry (#12694)
load_registry iterated data.values(), discarding the category
group keys from /api/v1/all. Every component ended up with
category: "", which made the components(category=...) MCP tool
filter return empty results for every category.

Iterate data.items() instead and inject the category name onto
each component's entry so search_registry's category filter works.
2026-04-14 18:13:12 +00:00
acbeaf35ad feat: rename deployment /executions endpoint to /runs (#12685)
* refactor: rename deployment executions to runs at the API boundary
Rename the deployment sub-resource from "executions" to "runs" across
the API layer, frontend hooks, and tests. Internal adapter/service code
retains its own execution terminology — only the public-facing surface
changes.
- URL paths: /{deployment_id}/executions -> /{deployment_id}/runs
- Path param: execution_id -> run_id
- Route functions: create_deployment_execution -> create_deployment_run,
  get_deployment_execution -> get_deployment_run
- Schema classes: ExecutionCreateRequest -> RunCreateRequest,
  ExecutionCreateResponse -> RunCreateResponse,
  ExecutionStatusResponse -> RunStatusResponse
- provider_data field: execution_id -> id
- Frontend hooks: usePostDeploymentExecution -> usePostDeploymentRun,
  useGetDeploymentExecution -> useGetDeploymentRun
- Frontend types: DeploymentExecutionRequest -> DeploymentRunRequest,
  DeploymentExecutionResponse -> DeploymentRunResponse

* fix: rename remaining execution references to runs in FE and schema docs
Complete the executions→runs rename at the API layer by updating
local variables, user-facing error strings, test mock names, and
schema docstrings that still referenced "execution".

* make schema for runs to wxo

* harden validation

* clean up stale refs to old /executions endpoint
2026-04-14 17:53:09 +00:00
5486c9a160 chore: add default models to llm list result from wxo adapter (#12686)
* add default models to llm list response from adapter

* comment

* ensure can't duplicate hardcoded

* remove old commented call

---------

Co-authored-by: Jordan Frazier <jordan.frazier@datastax.com>
Co-authored-by: Jordan Frazier <122494242+jordanrfrazier@users.noreply.github.com>
2026-04-14 15:44:42 +00:00
7b856e7d22 fix(loop): iterate when only item is connected and render item as a table (#12669)
* fix(loop): drive iteration from item_output when done is not connected

Extract the loop body execution into an idempotent `_iterate` helper
that both `item_output` and `done_output` invoke. On release-1.9.0,
`_should_process_output` only runs outputs whose name is in the
vertex's outgoing edge source names, so `done_output` never ran when
nothing was connected to `done` and the subgraph iteration never
happened.

`_iterate` caches aggregated results and cached exceptions in ctx so
repeat calls (when both outputs are wired) run the subgraph exactly
once and surface the same failure on re-entry. `item_output` is now
async, calls `_iterate` before stopping the item branch, and returns
a Data payload listing the dispatched items so the inspector shows
real content instead of an empty string.

Add regression tests covering the item-only topology, the classic
both-outputs-connected topology, empty input, cached error re-raise,
and per-run ctx isolation.

* [autofix.ci] apply automated fixes

* [autofix.ci] apply automated fixes (attempt 2/3)

* fix(loop): emit item output as DataFrame so UI renders it as a table

Wrapping the iterated rows in a `Data` payload with `count` / `items`
keys caused the Item inspector to render as JSON instead of as a
tabular view. Return the rows as a DataFrame, mirroring the Mock Data
component pattern, so the inspector uses its table renderer.

* feat(loop): emit summary logs for each run

Add start, complete, skipped, and error log entries from `_iterate` so
the component's Logs tab shows a per-run summary with row counts and
total elapsed time. Failures include the elapsed duration and the
error message.

* [autofix.ci] apply automated fixes

* [autofix.ci] apply automated fixes (attempt 2/3)

* fix(loop): address review comments

- Refresh Research Translation Loop starter flow's saved item-output
  schema (JSON -> Table) to match item_output now returning a DataFrame.
- Clarify the test_ctx_isolation_across_runs docstring: production
  rebuilds the graph per request, so ctx is effectively per-run; reusing
  a single Graph instance across runs is intentionally not exercised.
- Update _iterate's docstring to describe the actual ctx scope rather
  than claiming graph-instance-level reset semantics that the framework
  does not provide.

* [autofix.ci] apply automated fixes

* [autofix.ci] apply automated fixes (attempt 2/3)

* fix(loop): stabilize chat output inspection test

* fix(loop): align starter project with item output contract

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
2026-04-14 15:35:38 +00:00
9029c4b61e fix: Updates the CI workflow to handle known dependency conflicts. (#12691)
* fix: upgrade playwright to 1.58.0 to address Chromium CVEs

- Add playwright>=1.58.0 to override-dependencies in pyproject.toml
- Update uv.lock: playwright 1.49.0 -> 1.58.0, pyee 12.0.0 -> 13.0.1
- Fixes CVE-2026-2313, CVE-2026-2314, CVE-2026-2315, CVE-2026-2319,
  CVE-2026-2321, CVE-2026-2441, CVE-2026-2648, CVE-2026-2649
- Ensures Docker builds download updated Chromium with security patches

* fix: update npm to latest version to address brace-expansion CVE-2026-33750

- Add npm update after Node.js installation in Dockerfile
- Fixes CVE-2026-33750 in system npm's brace-expansion dependency
- System npm had brace-expansion 2.0.2, update gets 5.0.5+
- Low risk change: npm is backward compatible, only affects CLI tool

* revert: remove npm update from Dockerfile

- npm update attempts were causing CI build failures
- Bundled npm has issues but updating it is proving problematic
- Focus on playwright CVE fix which is the primary concern
- brace-expansion CVE-2026-33750 is lower priority (DoS only)

* CI: Filter cuga/playwright dependency conflict in release workflow

- Filter cuga/playwright conflict (we override playwright>=1.58.0 for CVE fixes)
- Still fails CI if other genuine dependency issues are detected
- Applied to both base and main package build steps

---------

Co-authored-by: Janardan S Kavia <janardanskavia@Janardans-MacBook-Pro.local>
2026-04-14 15:29:28 +00:00
68a8990a1a feat: validate duplicate tool names at deployment review step (#12675)
* feat: validate duplicate tool names at deployment review step

Add early detection of duplicate WXO tool names before deployment,
preventing users from hitting a 409 error only at deploy time.

- Add `GET /snapshots/check-names` endpoint using SDK's
  `get_drafts_by_names()` for fast server-side lookup
- Add `check_tool_names_exist()` to WXO service adapter
- Show inline validation error with alert banner on the review step
  card when a tool name already exists in the provider
- Block deploy button while duplicate names exist
- Also detect batch duplicates (same name on multiple flows)
- Use `keepPreviousData` to prevent error flicker on re-validation

* fix: update duplicate tool name error message

* refactor: use snapshot list endpoint with name filter instead of dedicated check-names endpoint

Replace the dedicated `/snapshots/check-names` endpoint with a
`provider_snapshot_names` query parameter on the existing
`GET /deployments/snapshots` endpoint. This keeps the API surface
smaller and follows the existing list-with-filter pattern.

* test: add tests for snapshot name filter and duplicate tool name validation

- Add validation on provider_snapshot_names: min_length=1 on Query param,
  strip whitespace and reject empty entries in SnapshotListParams
- Backend unit tests: 5 validation tests + 3 adapter list_snapshots
  name-filter tests + 1 route handler test
- Frontend unit tests: 4 tests for useCheckToolNames hook
- Frontend E2E tests: 3 Playwright tests for duplicate tool name
  detection, unique name acceptance, and error clearing on edit
- Fix step-review unit test mock to include new context fields

* feat: standardize snapshot name filtering to names query param
Rename deployment snapshot filtering from provider_snapshot_names to names across backend and frontend callers.
Add trimmed non-empty + dedup validation, enforce deployment_id/name-filter mutual exclusivity, and normalize WXO snapshot names with expanded unit coverage.

* chore: restore package-lock.json from release-1.9.0

* fix(frontend): limit deployment creation retry to 1

Reduce usePostDeployment mutation retry from default 3 to 1 to avoid
excessive 409 requests when deploying.

* feat(frontend): check duplicate tool names on deployment update

When editing a deployment, pre-existing flows with renamed tool names
are now validated against the provider for duplicates. Previously only
new flows were checked, allowing renamed tools to collide silently.

Expose initialToolNameByFlow from stepper context so step-review can
detect name changes and include them in the provider duplicate check.

* fix(frontend): replace nested button with div role=button in flow list

Outer button element contained inner detach/undo buttons, causing
"button cannot be a descendant of button" console error.

---------

Co-authored-by: Hamza Rashid <hzarashid@gmail.com>
2026-04-14 14:49:55 +00:00
4ddb55b7e4 refactor: design sweep for 1.9.0 release (#12684)
* fix: agent icon color adjustment

* only show environment selector when more that one, adjust spacing

* adjustments to spacing

* fixed context shift

* added space between connections and scrollbar

* content & small updates

* fix: update test for connection panel

* [autofix.ci] apply automated fixes

* conditional padding change

* fix how visibleDeployments is filtered

* updated test

* fix: update deployments content

* updated content

* queryKey matches the API params

* updated approach to avoid extra API calls

* [autofix.ci] apply automated fixes

* add a small space between available connections

* fix: improve memo deps, simplify empty state, harden formatDate, fix test assertions

- Use providers array instead of providers.length in useMemo dep
- Collapse duplicate DeploymentsEmptyState branches
- Add explicit locale and invalid date guard to formatDate
- Fix add-provider-modal test for split text elements
- Add test asserting providerIdsToQuery is decoupled from selection

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Viktor Avelino <viktor.avelino@gmail.com>
Co-authored-by: Viktor Avelino <64113566+viktoravelino@users.noreply.github.com>
2026-04-14 14:26:45 +00:00
d274b7b32a docs: release note typo (#12690)
release-note-typo
2026-04-14 13:59:22 +00:00
f594412171 fix(frontend): auto-populate global variable key-value pairs (#12687)
fix(frontend): auto-populate global variable key-value pairs when creating a connection
updateDetectedEnvVars expected objects with key/global_variable_name
fields, but the backend detection endpoint returns a flat string array
of variable names. Simplified the function to accept string[] directly,
using each name as both the env var key and the global variable binding.
2026-04-14 11:26:19 +00:00
33cb6643f4 feat: enforce unique snapshot to flow version relationship (#12680)
* Enforce unique tool to flow version relationship

* fix: harden deployment snapshot attachment conflict handling
- add typed attachment conflict exceptions in attachment CRUD and map only those conflicts to HTTP 409 in deployment create/update routes
- update snapshot patch flow to bulk-update all attachment rows by provider_snapshot_id, commit inside the guarded block, and keep compensating provider rollback on DB failure
- document race-condition caveats around app-level snapshot/flow-version guards and add targeted warning/info logs for conflict and post-provider DB anomalies
- add/expand unit tests for attachment bulk update behavior, typed conflict exceptions, and snapshot route commit-failure compensation path
- align watsonx conflict-detail wording and corresponding mapper tests for tool/connection/agent duplicate-resource messages

---------

Co-authored-by: Hamza Rashid <hzarashid@gmail.com>
2026-04-14 10:59:46 +00:00
71fbf5ff00 docs: cut version 1.9.0 (#12681)
* version-1.9.0-docs

* [autofix.ci] apply automated fixes

* [autofix.ci] apply automated fixes (attempt 2/3)

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
2026-04-14 02:07:01 +00:00
2fa3d1c759 feat: add langflow-sdk support to release workflow (#12679)
* feat: add langflow-sdk build and publish support to release workflow

Add support for building and publishing the langflow-sdk package in the
release workflow, mirroring the nightly build support added in #12491.

Changes:
- Add `release_sdk` workflow input for controlling SDK release
- Add `determine-sdk-version` job with first-release PyPI handling
- Add `build-sdk` job with version verification and import testing
- Add `publish-sdk` job that publishes SDK to PyPI before LFX
- Update `build-lfx` to download SDK artifact and test both wheels together
- Update `build-base` and `build-main` to use SDK wheel as find-links
- Pass SDK artifact to cross-platform tests
- Add validation: releasing LFX requires releasing SDK
- Add pre-release version handling for SDK and LFX's SDK dependency

* Update release.yml

* Update release.yml

* Potential fix for pull request finding

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

* Potential fix for pull request finding

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

* Potential fix for pull request finding

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

* Potential fix for pull request finding

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

---------

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-04-14 01:43:25 +00:00
389b11b884 docs: update wxo signup link (#12683)
Update wxo signup link:
2026-04-13 22:04:24 -04:00
40c5973292 fix: Allow >= specifications in dependencies (#12682)
* fix: Allow >= specifications in dependencies

* [autofix.ci] apply automated fixes

* [autofix.ci] apply automated fixes (attempt 2/3)

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
2026-04-13 21:35:21 -04:00
19df4606ae chore: update deps (#12657)
* chore: update deps

update deps due to sec vuln

* chore: langchain-core>=1.2.28

langchain-core>=1.2.28

* chore: update pypdf

pypdf 6.10

* chore: pyarrow, openai, litellm, mem0ai, toolguard

picomatch, pyarrow, openai, litellm, mem0ai, toolguard

* chore: override litellm

* chore: match base uv.lock to root

* chore: update tool.uv position

update tool.uv position

* chore: langflow-base[complete]>=0.9.0

langflow-base[complete]>=0.9.0

* chore: revert pyarrow

revert pyarrow

* chore: revert "lfx~=0.4.0",

* chore: lfx white space

* chore: remove allow-direct-references = true

* chore: uv lock --upgrade after merge
2026-04-13 23:23:37 +00:00
26c415056c feat: add SHA-256 hash-based API key lookup (#12597)
* feat: add SHA-256 hash-based API key lookup

Replace the O(n) full table scan in check_key with an indexed
SHA-256 hash column for O(1) lookup. Legacy keys without a hash
fall back to decrypt-and-compare and get their hash backfilled
on first successful match.

- Add api_key_hash column to ApiKey model (nullable, indexed)
- Hash stored at key creation time
- Migration adds column and backfills hashes for existing keys
- Fail closed when multiple keys share the same hash
- Remove unused fernet_obj parameter from decrypt_api_key

* fix(migration): skip hashing duplicate-plaintext API keys

Two-pass backfill: decrypt all rows, group by plaintext, then hash only
unique-plaintext rows. Duplicate-plaintext groups are left with NULL
hash so the runtime fast-path lookup cannot return multiple matches and
fail closed. The runtime slow-path matches and backfills exactly one
row per group on first use; remaining NULL rows become harmless
orphans.

Logs counts only (no key IDs or plaintexts) to avoid leaking
operational info via deployment logs.

Extracts _backfill_hashes helper for testing; adds 9 unit tests.

---------

Co-authored-by: Eric Hare <ericrhare@gmail.com>
2026-04-13 23:06:44 +00:00
83acc4143d docs: mcp client and other changes (#12627)
* tools-component

* tools-partial-and-release-notes

* mcp-astra-changes

* tutorial-changes

* client-page-and-release-notes

* langflow-mcp-client-for-coding-agents

* fix-links

* Apply suggestions from code review

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

* include-explanation-for-step-4

---------

Co-authored-by: April I. Murphy <36110273+aimurphy@users.noreply.github.com>
2026-04-13 22:28:05 +00:00
a425540bdb docs: add flow versioning (#12634)
* add-flow-versioning-and-release-note

* add-flow-db-location
2026-04-13 22:20:05 +00:00
17ab88fca7 fix: fix base64 padding bug and empty Fernet error messages (#12595)
Extract shared `add_base64_padding` and `ensure_fernet_key` functions
to eliminate duplicated key derivation logic between AuthService and
auth/utils.py.

Fix `_add_padding` adding 4 `=` characters instead of 0 when key length
is a multiple of 4, which broke Fernet key derivation for 44-char keys.

Change `%s` to `%r` in decryption failure logs so InvalidToken exceptions
(which have no message string) render as `InvalidToken()` instead of
empty strings.
2026-04-13 21:18:29 +00:00