Skip to content

ConditionalRouter silently coerces string output to another type when output_type is str | None #12617

Open

Description

@Anishithavaram-4242

Describe the bug
ConditionalRouter.run() skips ast.literal_eval coercion when output_type is exactly str, but not when output_type is a Union that includes str (e.g. str | None, Optional[str]). This means a perfectly normal "optional string output" declaration silently has its string value mangled if the rendered value happens to parse as a Python literal.

Affected code
haystack/components/routers/conditional_router.py, inside run():

with contextlib.suppress(Exception):
    if not self._unsafe and output_type is not str:
        output_value = ast.literal_eval(output_value)

This check only special-cases the exact str type. Any Union including str still evaluates output_type is not str as True.

To Reproduce

from haystack.components.routers import ConditionalRouter

routes = [
    {
        "condition": "{{True}}",
        "output": "{{value}}",
        "output_name": "result",
        "output_type": str | None,
    }
]
router = ConditionalRouter(routes, validate_output_type=True)
result = router.run(value="42")
# Expected: {"result": "42"}
# Actual: raises ValueError (int 42 doesn't match str | None)

Without validate_output_type=True, this silently returns 42 (int) instead of "42" (str) to the next pipeline component.

Context
PR #12322 fixed this same class of bug for the exact output_type=str case (see test_string_output_type_preserved_over_literal_eval), but didn't generalize to Unions that include str, which is a very normal way to declare an optional string output.

Proposed fix
Add a helper that checks whether str is output_type itself or a member of a Union output_type, and use that instead of the direct is not str check. I have a fix and passing regression test ready — happy to open a PR.

Environment
Haystack main branch, Python 3.12.4


👋 Hello there! This issue will be handled internally and isn't open for external contributions. If you'd like to contribute, please take a look at issues labeled contributions welcome or good first issue. We'd really appreciate it!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

handled internallyHandled by the team, not open for external contributions

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions