Skip to content

Fix crash when argument conversion fails with other exception than ValueError - #5820

Merged
pekkaklarck merged 3 commits into
robotframework:masterfrom
d-biehl:argument-conversion-crashes
Oct 29, 2026
Merged

pekkaklarck merged 3 commits into
robotframework:masterfrom
d-biehl:argument-conversion-crashes

Conversation

@d-biehl

@d-biehl d-biehl commented Oct 22, 2026

Copy link
Copy Markdown
Contributor

Fixes #5819.

TypeConverter.convert now turns exceptions other than ValueError into a ValueError with the normal conversion error message. CustomConverter already does this for custom converters. Callers that handle ValueError therefore work also when a built-in converter fails with, for example, OverflowError (timedelta with 1e20) or TypeError (set with unhashable items). Callers include utils.Importer, typed command line variables, and the Variables section. TypeInfo.convert now raises only ValueError on conversion failures, as documented.

RecursionError is re-raised. Otherwise unions could silently fall back to another member type, such as str, with very deeply nested values of recursive type aliases.

For example, robot --listener Listener.py:1e20 with a timedelta argument used to crash with Unexpected error. It now reports the error and continues:

[ ERROR ] Taking listener 'Listener.py:1e20' into use failed: Importing listener '.../Listener.py' failed: Argument 'timeout' got value '1e20' that cannot be converted to timedelta: OverflowError: Python int too large to convert to C int

Library imports keep the context added in #5815. Their message now also names the argument:

Resolving arguments to library 'Lib' failed: ValueError: Argument 'timeout' got value '1e20' that cannot be converted to timedelta: OverflowError: Python int too large to convert to C int

Tests:

  • Unit tests TestTypeInfo.test_failing_conversion_with_other_exception_than_value_error and TestInstantiation.test_argument_conversion_failing_with_other_exception_than_value_error, which covers the utils.Importer path used by listeners, model modifiers and parsers.
  • Acceptance tests:
    • Invalid timedelta and Invalid set in keywords/type_conversion/annotations.robot.
    • A new Union with item failing with other exception than ValueError test in keywords/type_conversion/unions.robot.
    • Invalid value on CLI in variables/variable_types.robot.
  • The expected messages avoid texts that differ between Python versions. For example, the unhashable type message changed in Python 3.14, so it is matched with a pattern.

I ran the full unit and acceptance test suites with Python 3.13 on Linux. All 2444 unit tests pass. Of the 7144 acceptance tests, 7135 pass. The 9 failing ones are Screenshot library tests, and they fail the same way on unmodified master, because taking screenshots is not supported in my environment. All unit tests and the acceptance tests under keywords/type_conversion, variables, output/listener_interface, cli/model_modifiers and test_libraries/library_import_failing.robot also pass with Python 3.10, 3.14 (free-threaded) and 3.15. The changed files pass ruff, black and isort with the project configuration.


AI/tooling disclosure: This contribution was prepared with assistance from Claude Code. I reviewed the result manually, understand the changes, verified them locally, and confirm that I have the right to submit this contribution under the project license.

Copilot AI balanced review requested due to automatic review settings October 22, 2026 13:47

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟢 Approval recommended

The localized exception handling addresses the reported failures, preserves recursion error propagation, and has focused regression coverage with no unresolved findings.

No open issues 🎉

What changed in this PR

Fixes #5819 by normalizing built-in argument conversion failures to ValueError, allowing existing error handlers to report failures instead of aborting execution.

Changes:

  • Wraps unexpected conversion exceptions in the standard conversion error message while preserving RecursionError.
  • Adds regression coverage for importer and public API conversion failures.
  • Tests invalid keyword arguments, typed command-line variables, and union fallback behavior.
File Description
utest/​utils/​test_importer_util.py Tests importer error reporting for conversion overflow.
utest/​running/​test_typeinfo.py Tests normalization to ValueError through TypeInfo.
src/​robot/​running/​arguments/​typeconverters.py Normalizes conversion exceptions while re-raising RecursionError.
atest/​testdata/​keywords/​type_conversion/​unions.robot Adds union fallback cases after conversion overflow.
atest/​testdata/​keywords/​type_conversion/​unions.py Adds the timedelta-or-float test keyword.
atest/​testdata/​keywords/​type_conversion/​annotations.robot Covers timedelta overflow and unhashable set items.
atest/​robot/​variables/​variable_types.robot Checks typed command-line variable error reporting.
atest/​robot/​keywords/​type_conversion/​unions.robot Registers verification of the new union test.

Review effort: Balanced

@d-biehl

d-biehl commented Oct 22, 2026

Copy link
Copy Markdown
Contributor Author

The handling added to ClassLibrary.from_class in #5815 is still needed. It turns the ValueError into a DataError, which Namespace requires. This fix only makes sure that conversion fails with ValueError.

@pekkaklarck

Copy link
Copy Markdown
Member

This looks good in general (I didn't look at tests too closely), but there are some things to discuss:

  1. In general it would be better if each converter would make sure they only raise ValueErrors. That way they can also add more context information to errors they raise. Something can easily slip through, see below, so TypeConverter.convert having except Exception: is probably a good idea anyway.

  2. I was surprised that TypeInfo.from_type_hint(set).convert("[{}]") currently fails with TypeError. I though we handle that in the _literal_eval helper because TypeInfo.from_type_hint(set).convert("{[]}") fails as expected. After looking at the code, I realized that we nowadays accept any sequence in this case and then later do set(value) with the results. That means that "[{}]" can be evaluated, but the result cannot be converted to a set. We handle non-string values the same way, so also TypeInfo.from_type_hint(set).convert([{}]) currently fails for TypeError. This particular issue could be fixed by changing SetConverter._non_string_convert so that it passes the evaluated value to _string_conver and it then handles exceptions from calling set(value). I'm not sure is that too much better than handling these cases in TypeConverter.convert where, as discussed above, we probably anyway want to catch everything.

  3. TypeInfo.from_type_hint(timedelta).convert(1e20) failing could also be handled elsewhere, but in this time the right place would be inside the DateTime library that is used by the TimedeltaConverter. Basically we could there catch OverflowError and reraise it as ValueError with a message like "Value '{value}' is too large to be represented as a timedelta.".

  4. I don't think it's a good idea to let RecursionError slip through. It would mean that in those cases execution would crash and that's what we want to avoid.

  5. There seems to be some room for cleanup with the old code related to this.

What do you @d-biehl think about the above and how should we continue with this? One way is that I merge this PR in its current shape and the refactor the related code a bit. I'd remove the RecursionError handling and would also consider handling the [{}] case with sets in SetConverter.

@d-biehl

d-biehl commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks for the review! My thoughts:

  1. I only partly agree. I think the catch-all in TypeConverter.convert is the actual fix, not just a safety net. Built-in converters raise other exceptions than ValueError in more places than with timedelta and set, for example:

    • list[datetime] with [1e20] (OverflowError) or [1e18] (OSError on Linux), both from datetime.fromtimestamp
    • list[float] with 1 followed by 400 zeros (OverflowError: int too large to convert to float)
    • dict[list[int], int] with {(1, 2): 3} (TypeError: unhashable type: 'list')
    • a TypedDict with {1: 2, 'y': 3} (TypeError: '<' not supported between instances of 'str' and 'int')

    Making every converter handle all of these itself won't ever be complete, and Python also changes its messages. Handling errors in a converter is worth it when it gives a clearly better message, or when only the converter knows what an exception means (see 4.).

  2. I don't think special handling in SetConverter is worth it. With this PR, the string [{}] fails with Argument 'x' got value '[{}]' that cannot be converted to set: TypeError: unhashable type: 'dict', and an actual list [{}] gets the same error. That's already clear, and Python 3.14 makes it even more descriptive with cannot use 'dict' as a set element (unhashable type: 'dict'). Handling set(value) alone also wouldn't be enough. set[list[int]] with [(1, 2)] fails later, when the converted items are added to the set, and dict[list[int], int] with {(1, 2): 3} fails the same way with the converted keys. The catch-all handles all of these consistently. The only difference left is that {[]} fails with Evaluating expression failed: unhashable type: 'list', because there ast.literal_eval itself fails, but I don't think that matters much.

  3. This makes sense to me, because Python int too large to convert to C int is hard to understand. It would also help the DateTime keywords themselves, which currently fail with the same raw errors. For example, Convert Time 1e20 result_format=timedelta, Convert Date ${1e20} and Add Time To Date 2024-01-01 1e7 days all fail with an OverflowError. In the library, timedelta objects are created in Time._convert_to_timedelta and in the Time.timedelta property used in date calculations, and epoch seconds are converted to datetime in Date._epoch_seconds_to_datetime, which raises OverflowError or OSError depending on the value and the platform. Date calculations can also overflow themselves (date value out of range). One detail about the message: _convert_to_timedelta gets the time only in seconds, so a message with the value would show 86400000000000.0 for 1e9 days. Either the original value needs to be passed along, or it's better to leave it out. Argument conversion errors contain it anyway.

  4. Here I disagree. I'd keep letting RecursionError through TypeConverter.convert and fix the crashes where they actually come from.

    TypeConverter.convert is used also for nested values, so a RecursionError there doesn't necessarily mean that the value is invalid. It can also mean that the stack ran out while converting a deeply nested value. If the error is caught there, unions handle it like any other conversion error and try the next member type. For example, with this library and test:

    type JSON = dict[str, JSON] | list[JSON] | str | int | float | bool | None
    
    
    def nested_list(depth: int) -> list:
        value = [1]
        for _ in range(depth - 1):
            value = [value]
        return value
    
    
    def use_json(data: JSON):
        ...
    *** Settings ***
    Library    JsonLib.py
    
    *** Test Cases ***
    Example
        ${data} =    Nested List    150
        Use Json    ${data}  # here you will get a recursion error

    If RecursionError is caught, the test passes, but Use Json gets data where the list at level 96 has been replaced by its string representation. If the keyword is called via 20 nested user keywords, this happens already at level 75. On master and with this PR, the test fails with RecursionError. I think silently corrupted data is worse than a crash.

    You're right about the crashes, though. For example, --listener Listener.py:1+1+...+1 with a list argument and 10000 terms crashes with this PR (Python 3.13). These crashes come from ast.literal_eval. With too complex expressions it raises RecursionError, and with input like '-' * 6000 it raises MemoryError. MemoryError crashes the execution even with the catch-all, because get_error_message() re-raises it.

    Argument conversion calls ast.literal_eval only in the TypeConverter._literal_eval helper, which the list, tuple, dict, set, Sequence, Mapping and TypedDict converters use for parsing strings. The helper already handles the other exceptions that ast.literal_eval can raise with malformed input, so adding the two missing ones fixes these crashes:

             try:
                 value = literal_eval(value)
    -        except (ValueError, SyntaxError):
    +        except (ValueError, SyntaxError, MemoryError, RecursionError):
                 # Original errors aren't too informative in these cases.
                 raise ValueError("Invalid expression.")

    The try block contains only the ast.literal_eval call, and nested values are converted after it, so this doesn't affect the example above. I tested this in a prototype: the crashes are reported as normal errors, and the example still fails cleanly.

    After that, a crash is still possible if a RecursionError from nested conversion happens somewhere only ValueError is handled, for example with a listener argument that has a recursive alias type. To cover also that, RecursionError could be handled at the top level in TypeInfo.convert and ArgumentConverter._convert, where unions can't fall back anymore. That worked in a prototype as well.

  5. Sure. For example, CustomConverter._convert doesn't need its own except Exception anymore.

I can add the _literal_eval change with tests to this PR, or do it in a separate PR if you want to merge this first.

@d-biehl

d-biehl commented Oct 23, 2026

Copy link
Copy Markdown
Contributor Author

The _literal_eval change also fixes crashes in normal keyword calls. Currently this test crashes the whole execution with a MemoryError traceback. The second test is not run, and output.xml is left as invalid XML:

*** Settings ***
Library    Collections

*** Test Cases ***
Pathological string to list argument
    Log List    ${{'-' * 6000 + '1'}}

Next test
    No Operation

With the change, the first test fails normally with ValueError: Argument 'list_' got value '------...1' that cannot be converted to Sequence: Invalid expression., the same way as Log List foo, and the second test is run.

@pekkaklarck

pekkaklarck commented Oct 27, 2026 •

Copy link
Copy Markdown
Member

Replies to your replies:

  1. It seems we don't really disagree here. We both agree that catch-all in TypeConverter.convert is a good idea and that lower level converters in general should catch errors and report them cleanly.
  2. I'm fine with SetConverter not handling [{}] specially. It's very unlikely this error ever happens in practice and the error message Python emits is good enough (especially with Python 3.14+). That said, I don't think it would be wrong to handle it separately either.
  3. Let's fix DateTime library separately. I think it deserves its own issue. The fix may require adjusting these tests, but it should predominantly be tested with DateTime tests.
  4. First of all, its cool to see a recursive type alias in an example. Getting them parsed correctly and conversion working in RF 7.5 wasn't exactly trivial. The demonstrated problem certainly is pretty bad and I agree that failing for recursion is better. That said, I still don't like RecursionError in general going through. We can try to find a solution for that, but it's probably better to merge this PR first. Finally, your _literal_eval fixes look good. They can be part of this PR or done separately.
  5. That's true. Other things include using return self._handle_error(...) when that method always raises (I think earlier it could also return). It's best to concentrate on actual fixes as part of this PR and do larger cleanup separately.

How should we proceed? Are you planning to do some changes to this PR still? If not, I'll take a final look and merge it. We can do further adjustments still after that.

@pekkaklarck

Copy link
Copy Markdown
Member

Regarding to the point 4 discussed above, I got an idea how we could handle RecursionError and other such errors that we consider severe enough that we don't want to try other conversions. We could give TypeConverter.convert() a new parameter reraise_errors: bool = False that would control this behavior. By default, i.e. when the client code calls TypeConverter.convert(), all errors would be reported and no exception could slip through and crash the execution. Internally all converters that call convert() would then need to use rereise_errors=True and only catch ValueError if they want to handle other failures gracefully.

I tested the above so that I added

except RecursionError as error:
    if reraise_errors:
        raise
    return self._handle_error(value, name, kind, error)

to TypeConverter.convert() and reraise_errors=True to all internal calls to it. With these changes to recursive example fails like this:

ValueError: Argument 'data' got value '[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[1]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]' (list) that cannot be converted to dict[str, JSON], list[JSON], string, integer, float, boolean or None: maximum recursion depth exceeded

I think the above is pretty good. The only small nit is that I'd prefer the the final error message to be prefixed with RecursionError:, but that can be fixed by adjusting _handle_error so that it takes also other exceptions than ValueError into account.

@pekkaklarck

Copy link
Copy Markdown
Member

I reported the DateTime issue as #5834 and fixed it already. The fix probably requires updating tests added by this PR.

@pekkaklarck

Copy link
Copy Markdown
Member

Checks are failing because GitHub Actions doesn't anymore support Python 3.9 on ubuntu-latest which was just switched to mean ubuntu-26.04. I change configuration to use ubuntu-24.04 instead, but apparently PRs aren't automatically rebased. Running other checks fails because the aforementioned Python 3.9 run failed....

After robotframework#5834, too large `timedelta` values don't cause `OverflowError`
anymore. Use `float` with a huge integer and `set` with unhashable items
instead.
`ast.literal_eval` raises `MemoryError` if the expression is too complex
to parse. Report it as an invalid expression.

Part of robotframework#5819.
@d-biehl
d-biehl force-pushed the argument-conversion-crashes branch from d06bc72 to a0cb344 Compare October 28, 2026 21:09
Copilot AI balanced review requested due to automatic review settings October 28, 2026 21:09

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Changes recommended

The new unit test can fail on PyPy because parsing may raise a deliberately propagated RecursionError instead of the asserted ValueError; mocking literal_eval to raise MemoryError would make it deterministic.

1 open issue

Review effort: Balanced

Comment on lines +381 to +390
def test_failing_conversion_with_too_complex_expression(self):
expr = "-" * 6000 + "1"
assert_raises_with_msg(
ValueError,
f"Argument 'x' got value '{expr}' that cannot be converted "
f"to list[int]: Invalid expression.",
TypeInfo.from_type_hint("list[int]").convert,
expr,
"x",
)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

What do you think about the above @d-biehl? If we handle MemoryError in _literal_eval, patching ast.literal_eval to always raise MemoryError would probably be a good idea. This test likely fails on PyPy otherwise.

The reason I didn't commit the suggestion is that I'm not sure should we handle MemoryError in _literal_eval or should we handle it the same way as we handle RecursionError. If MemoryError is a symptom that the whole interpreter is running out of memory, handling it like RecursionError would make sense. If the error is local to ast.literal_eval parser, then it's better to handle it in _literal_eval.

@d-biehl

d-biehl commented Oct 28, 2026

Copy link
Copy Markdown
Contributor Author

I updated the PR:

  1. Rebased it to get the CI and DateTime fixes.

  2. Updated the tests in a separate commit. After DateTime: Conversion to timedelta fails with bad error message if values are too large #5834, too large timedelta values don't raise OverflowError anymore, so the tests using them didn't test the catch-all in TypeConverter.convert. They now use examples that still raise other exceptions than ValueError:

    • float with a huge integer like 10**400 fails with OverflowError: int too large to convert to float. Unlike the unhashable type message with sets, this message is the same with all Python versions.
    • Union[set, list] with [[1], [2]] gets [[1], [2]], because set fails with TypeError and list is tried next.

    timedelta conversion is now tested only by the DateTime tests.

  3. Added the _literal_eval change in its own commit, but only for MemoryError. I have to correct what I wrote earlier: catching RecursionError in _literal_eval isn't safe after all. Close to the recursion limit, ast.literal_eval fails with RecursionError even with a simple expression like [1]. _literal_eval would turn that into Invalid expression., and unions would try the next type. This example converts the same value at different stack depths and prints the first depth where each result occurs:

    import sys
    
    from robot.running import TypeInfo
    
    converter = TypeInfo.from_type_hint("dict[str, list[int]] | str").get_converter()
    
    
    def convert_at_depth(depth, value):
        if depth:
            return convert_at_depth(depth - 1, value)
        return converter.convert(value)
    
    
    first_seen = {}
    for depth in range(sys.getrecursionlimit()):
        try:
            result = repr(convert_at_depth(depth, {"a": "[1]"}))
        except RecursionError:
            result = "RecursionError"
        first_seen.setdefault(result, depth)
    for result, depth in first_seen.items():
        print(f"{depth:4}: {result}")

    With this PR and Python 3.14:

       0: {'a': [1]}
     985: RecursionError
    

    With RecursionError added to the except in _literal_eval:

       0: {'a': [1]}
     985: "{'a': '[1]'}"
     987: RecursionError
    

    At depths 985 and 986, the result is the string "{'a': '[1]'}" instead of the dict. Python 3.8, 3.13 and 3.15 also return the string, 3.9 and 3.11 don't. TypeInfo.convert() doesn't show the problem in this example, because it calls get_converter() first, and that already fails before depth 985. It happens when a converter is reused, as the get_converter() docs suggest.

    MemoryError is different. It comes from a fixed limit in the parser, so it depends only on the expression. I tested this with different stack depths and with Python 3.8-3.15. PyPy is an exception: with it, parsing '-' * 6000 + '1' fails with RecursionError depending on the stack depth, so I excluded the new acceptance test on PyPy. Expressions like 1+1+...+1 with thousands of terms still raise RecursionError with Python 3.11-3.13, which crashes the execution for example with listeners. I think that's better handled together with the other RecursionError cases (see below).

About #5834: Convert Time inf result_format=timedelta still fails with OverflowError: cannot convert float infinity to integer, and the same happens with -inf. The reason is that secs_to_timestr(inf) in the new except block raises OverflowError itself. Argument conversion handles this thanks to the catch-all, but the keyword doesn't. There are also other places in DateTime that still raise OverflowError, for example Add Time To Date 2024-01-01 1e20 (Time.timedelta) and Convert Date ${1e20} (datetime.fromtimestamp). Maybe these could be fixed in a separate issue.

The reraise_errors idea looks good to me, and the problem above is one more reason to handle RecursionError only where unions can't fall back anymore. It's basically handling RecursionError at the top level, but it works with all callers of TypeConverter.convert, also with external tools. The only risk I see is that if an internal call forgets to pass reraise_errors=True, unions silently fall back to other types again, so the recursive alias example would be a good regression test. The RecursionError: prefix could be added in the existing catch-all without changing _handle_error, because get_error_message() already returns RecursionError: maximum recursion depth exceeded. Doing this separately after this PR sounds good.

@pekkaklarck

Copy link
Copy Markdown
Member

Sounds good to me. Let's proceed like this:

  1. I'll review the PR once more and merge it unless I see something that needs further discussion.
  2. We add RecustionError handling afterwards. You can do that as a separate PR or I can do that myself.
  3. We consider DateTime problems and fixes separately. I think you could just add a comment about these cases to DateTime: Conversion to timedelta fails with bad error message if values are too large #5834 and we can then decide should they be fixed as part of that or should they get a separate issue.

@d-biehl

d-biehl commented Oct 29, 2026

Copy link
Copy Markdown
Contributor Author

OK, sounds good to me. Let me know if there's anything else I should do.

@pekkaklarck pekkaklarck left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Looks very good to me. The main reason I didn't merge this yet is that I'm not sure about handling MemoryError. I see two alternatives:

  1. We let it go through from _literal_eval and also let it go through on the higher level similarly as RecursionError.
  2. We handle it in _literal_eval, but use Too complex expression or something similar instead of Invalid expression.

The first approach would avoid the possibility that converting something fails for MemoryError and then we try alternative converter and that succeeds. That cannot happen if you have e.g. arg: list[str] | str, though, because if the argument is a list we use it as-is and non-list arguments don't go to _literal_eval. It could happen if you have arg: list[str] | CustomType, though. Possibly also other converters can fail for MemoryError and in those cases passing the error through like we pass RecursionError could make sense.

Run Should Fail
... -v "BAD_VALUE: int:bad" ${DATADIR}/misc/pass_and_fail.robot
... Command line variable '\${BAD_VALUE: int}' got value 'bad' that cannot be converted to integer.
VAR ${big} 1${{'0' * 400}}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This probably could be

VAR    ${big: int}    1e400

IntegerConverted uses Decimal for converting stuff that int cannot convert so it handles huge numbers in the scientific format correctly.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

It would be good to add this kind of test as well:

*** Variables ***
${BIG_INT: int}        1e400
${BIG_FLOAT: float}    ${BIG_INT}    # This fails for "int too large to convert to float"

Currently this crashes the whole execution and with these fixes it shouldn't.

List ${NO_CLASS} arg_type=NoClass

Too complex expression
[Documentation] The value is so long that the error message is cut.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Also in this case the exception could be specified here using FAIL GLOB: (or something similar).

# Converters should raise `ValueError`, but, for example, `set()` can
# raise `TypeError` and `float()` can raise `OverflowError`.
message = get_error_message()
return self._handle_error(value, name, kind, ValueError(message))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

It's a bit odd to first convert the error to a string, then to ValueError and then handle it in _handle_error. I think _handle_error should just handle all kind of errors. I can refactor this myself. There are also other things like using return with a method that always raises.

value = literal_eval(value)
except (ValueError, SyntaxError):
# Original errors aren't too informative in these cases.
except (ValueError, SyntaxError, MemoryError):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Wouldn't it be safer to let MemoryError go through? In higher level we could then handle it the same way as RecursionError? If we handle MemoryError here, perhaps it would be better to emit a different error like Too complex expression. instead of Invalid expression..

Comment on lines +381 to +390
def test_failing_conversion_with_too_complex_expression(self):
expr = "-" * 6000 + "1"
assert_raises_with_msg(
ValueError,
f"Argument 'x' got value '{expr}' that cannot be converted "
f"to list[int]: Invalid expression.",
TypeInfo.from_type_hint("list[int]").convert,
expr,
"x",
)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

What do you think about the above @d-biehl? If we handle MemoryError in _literal_eval, patching ast.literal_eval to always raise MemoryError would probably be a good idea. This test likely fails on PyPy otherwise.

The reason I didn't commit the suggestion is that I'm not sure should we handle MemoryError in _literal_eval or should we handle it the same way as we handle RecursionError. If MemoryError is a symptom that the whole interpreter is running out of memory, handling it like RecursionError would make sense. If the error is local to ast.literal_eval parser, then it's better to handle it in _literal_eval.

@d-biehl

d-biehl commented Oct 29, 2026

Copy link
Copy Markdown
Contributor Author

About 2: I can't do this right now, but I can take it later. I think it's an edge case that hardly anyone hits in practice, so it could also wait until after 7.5.1. I can open a separate issue for it with the cases discussed above, so they don't get lost. If you want to have it in 7.5.1, it's probably better if you do it yourself.

@pekkaklarck

Copy link
Copy Markdown
Member

We got so many lists that I'm not sure what you mean with 2. 😂

Anyway, this is what I plan to do next:

  • Merge this PR.
  • Handle RecursionError so that it cannot crash the execution.
  • Preserve the current MemoryError handling (except perhaps changing the message). We can reconsider this still before/after 7.5.1.
  • Refactor.

@pekkaklarck
pekkaklarck merged commit 79d56d9 into robotframework:master Oct 29, 2026
8 checks passed
@d-biehl

d-biehl commented Oct 29, 2026

Copy link
Copy Markdown
Contributor Author

yes exactly that recursion error and memory thing! 🤣

@pekkaklarck

Copy link
Copy Markdown
Member

I ought to now have everything discussed above done. In the end I decided to change handling MemoryError so that's it's not caught in _literal_eval and on higher level it's handled like RecursionError.

Earlier that I had prototyped handling RecursionErrors so that convert got new reraise_errors: bool = False argument that nested converters should use like reraise_errors=True. As you pointed out, that approach had a problem that it's very easy to forget using reraise_errors=True if we add more converters. Now I got this working so that TypeConverter.__init__ and TypeConverter.converter_for got new reraise_fatal argument that's then saved to self.rereise_fatal. Now nested converters automatically are initialized with reraise_fatal=True and we only need to remember to use it separately in few extra place.

I'll wait all tests to run locally with CPython and PyPy and then push my changes.

pekkaklarck added a commit that referenced this pull request Oct 30, 2026
Don't let RecursionError slip though so that it could crash the whole
execution. These errors are still considered more severe than normal
conversion failures and internally they stop further conversion
attempts.

Also handle MemoryError the same way as RecursionError and refactor
related code.

Part of issue #5819. See also PR #5820.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Argument conversion failing unexpectedly causes bad error messages with keywords and crashes elsewhere (e.g. with listeners)

3 participants