Skip to content

Performance regression in resolving variables #5644

Closed

Description

@d-biehl

RecommendationFinder is used in several places to produce "Did you mean...?" suggestions when variables or keywords are not found. It performs fuzzy string matching over all candidates, which is O(n×m) per lookup.

Affected locations

  1. robot.variables.notfound.variable_not_found() — iterates over all variable candidates
  2. robot.running.namespace.KeywordRecommendationFinder — iterates over all keywords from all libraries and resources (also affects --dryrun, since KeywordRunner passes recommend_on_failure=True by default)

(A third location in parsing.lexer.settings operates on a small fixed set of setting names, so it is not a performance concern.)

Note that there is already a TODO comment in

# TODO: Consider changing the default value of `recommend_on_failure` to False.

For tools that use Robot Framework's variable resolution programmatically (e.g., IDE language servers, static analysis tools, like RobotCode ), variable_not_found() may be triggered thousands of times during analysis. In large projects with many variables, this becomes a critical bottleneck.

Real-world impact: Analyzing 375 Robot Framework files took over 30 minutes, with the vast majority of time spent in RecommendationFinder. After monkey-patching variable_not_found to skip recommendations, the same analysis completes in under a minute. See: robotcodedev/robotcode#587

The KeywordRecommendationFinder in namespace.py has the same O(n×m) characteristic, though it primarily affects runtime execution and --dryrun rather than static analysis. RobotCode does not use RF's runtime namespace for keyword resolution, so this is not triggered in our case, but other tools or --dryrun with many missing keywords could be affected.

Current workaround

In RobotCode, we now monkey-patch variable_not_found across all modules that import it (robot.variables.notfound, finders, evaluation, store, robot.variables) to replace it with a version that simply raises VariableError without calling RecommendationFinder. This works, but it's fragile — it depends on internal module structure and could break with any refactoring of the robot.variables package.

Suggestion

A simple global flag like RECOMMENDATIONS_ENABLED (e.g., on RecommendationFinder or in robot.utils.recommendations) that can be set to False to skip all fuzzy matching would be sufficient and avoid the need for monkey-patching.

Activity

  1. pekkaklarck commented on Mar 31, 2026

    @pekkaklarck
    Member

    Let's at least change the default value of recommend_on_failure to False. We obviously need to turn it to True in certain cases during execution to get those helpful recommendations. If that affects also programmatic usage where recommendations aren't needed, we need to make it somehow configurable. An environment variable feels a bit icky, but it certainly is an option if there are no better alternatives.

  2. added this to the v7.5 milestone on Mar 31, 2026
  3. added theissue type on Mar 31, 2026
  4. MikeAckerschott commented on Apr 1, 2026

    @MikeAckerschott

    Hello, OOP here from the robotcode issue. Ive found that applying the monkeypatch before running robot like this:

    # Monkey-patch: suppress the slow "Did you mean ...?" RecommendationFinder
    # in robot.variables.notfound.variable_not_found.
    #
    # The original function builds fuzzy-match recommendations against all known
    # variables, which is expensive.  We replace it with a fast version that just
    # raises immediately.
    #
    # IMPORTANT: evaluation.py does `from .notfound import variable_not_found`,
    # so it holds a *direct reference* to the original function object.  We must
    # patch BOTH the module attribute AND every caller that already imported it.
    # ---------------------------------------------------------------------------
    from robot.errors import VariableError
    import robot.variables.notfound as _notfound_module
    import robot.variables.evaluation as _evaluation_module
    import robot.variables.finders as _finders_module
    import robot.variables.store as _store_module
    import robot.variables as _variables_pkg
    
    def _patched_variable_not_found(name, candidates, message=None, deco_braces=True):
        raise VariableError(message or f"Variable '{name}' not found.")
    
    # Patch every module that does `from .notfound import variable_not_found`
    _PATCH_TARGETS = [
        (_notfound_module, "robot.variables.notfound"),
        (_evaluation_module, "robot.variables.evaluation"),
        (_finders_module, "robot.variables.finders"),
        (_store_module, "robot.variables.store"),
        (_variables_pkg, "robot.variables.__init__"),
    ]
    for _mod, _name in _PATCH_TARGETS:
        _mod.variable_not_found = _patched_variable_not_found
        print(f"Monkey-patched variable_not_found in {_name}")
    
    from robot import run_cli
    
    run_cli()
    

    Does significantly speed up test execution time compared to running robot normally within the CLI. I also checked the performance with cProfile and found that for my test 187 / 196 seconds of runtime is spend within the variable_not_found function:

    
       Ordered by: cumulative time
       List reduced from 4319 to 30 due to restriction <30>
    
       ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        360/1    0.002    0.000  196.304  196.304 {built-in method builtins.exec}
            1    0.000    0.000  196.304  196.304 <frozen runpy>:201(run_module)
            1    0.000    0.000  195.988  195.988 <frozen runpy>:65(_run_code)
            1    0.000    0.000  195.988  195.988   C:\Development\venv\Lib\site-packages\robot\run.py:1(<module>)
            1    0.000    0.000  195.988  195.988   C:\Development\venv\Lib\site-packages\robot\run.py:509(run_cli)
            1    0.000    0.000  195.987  195.987   C:\Development\venv\Lib\site-packages\robot\utils\application.py:56(execute_cli)
            1    0.000    0.000  195.986  195.986   C:\Development\venv\Lib\site-packages\robot\utils\application.py:95(_execute)
            1    0.000    0.000  195.986  195.986   C:\Development\venv\Lib\site-packages\robot\run.py:451(main)
            1    0.000    0.000  195.912  195.912   C:\Development\venv\Lib\site-packages\robot\running\model.py:841(run)
        23/13    0.000    0.000  195.895   15.069   C:\Development\venv\Lib\site-packages\robot\model\testsuite.py:461(visit)
        21/16    0.000    0.000  195.895   12.243   C:\Development\venv\Lib\site-packages\robot\model\visitor.py:122(visit_suite)
            1    0.000    0.000  190.777  190.777   C:\Development\venv\Lib\site-packages\robot\running\suiterunner.py:52(start_suite)
            1    0.000    0.000  190.378  190.378   C:\Development\venv\Lib\site-packages\robot\variables\scopes.py:125(resolve_delayed)
            1    0.000    0.000  190.378  190.378   C:\Development\venv\Lib\site-packages\robot\variables\variables.py:51(resolve_delayed)
            1    0.001    0.001  190.378  190.378   C:\Development\venv\Lib\site-packages\robot\variables\store.py:32(resolve_delayed)
      571/559    0.002    0.000  190.375    0.341   C:\Development\venv\Lib\site-packages\robot\variables\store.py:42(_resolve_delayed)
      528/525    0.002    0.000  190.364    0.363   C:\Development\venv\Lib\site-packages\robot\variables\tablesetter.py:95(resolve)
    44727/16030    0.120    0.000  189.885    0.012 C:\Development\venv\Lib\site-packages\robot\variables\replacer.py:96(_replace)
    14341/14326    0.091    0.000  189.773    0.013 C:\Development\venv\Lib\site-packages\robot\variables\replacer.py:113(_get_variable_value)
           24    0.000    0.000  189.190    7.883 C:\Development\venv\Lib\site-packages\robot\variables\variables.py:54(replace_list)
            5    0.000    0.000  189.189   37.838 C:\Development\venv\Lib\site-packages\robot\variables\tablesetter.py:169(_replace_variables)
           24    0.000    0.000  189.189    7.883 C:\Development\venv\Lib\site-packages\robot\variables\replacer.py:32(replace_list)
           24    0.099    0.004  189.189    7.883 C:\Development\venv\Lib\site-packages\robot\variables\replacer.py:60(_replace_list)
    14346/14338    0.136    0.000  189.176    0.013 C:\Development\venv\Lib\site-packages\robot\variables\finders.py:43(find)
    14346/14343    0.034    0.000  188.618    0.013 C:\Development\venv\Lib\site-packages\robot\variables\finders.py:68(find)
    14350/14347    0.263    0.000  188.584    0.013 C:\Development\venv\Lib\site-packages\robot\variables\store.py:66(get)
    14350/14347    0.063    0.000  187.647    0.013 C:\Development\venv\Lib\site-packages\robot\variables\store.py:61(__getitem__)
        14328    0.208    0.000  187.439    0.013 C:\Development\venv\Lib\site-packages\robot\variables\notfound.py:22(variable_not_found)
        14328    0.553    0.000  121.259    0.008 C:\Development\venv\Lib\site-packages\robot\utils\recommendations.py:26(find_and_format)
        14328    0.174    0.000  120.706    0.008 C:\Development\venv\Lib\site-packages\robot\utils\recommendations.py:43(find)
    

    After finding out about this, i did migrate some of the variables to python variable files which did seem to reduce the variable_not_found cumulative time

  5. pekkaklarck commented on Apr 1, 2026

    @pekkaklarck
    Member

    @MikeAckerschott, do I get it right that RecommendationFinder causes performance issues for you also during normal execution, not only with RobotCode? That sounds a bit strange, because it should only be used in cases where keywords, variables, etc. aren't found and that shouldn't happen too often during normal execution. It's certainly possible that there's a bug in Robot's code that causes that to happen too often, though. We've had such bug earlier as #4659 and #5051 demonstrate.

    Could you create a simple example demonstrating the problem so that I can test it locally? That would massively help pinpointing where the problem is and hopefully fixing it.

  6. MikeAckerschott commented on Apr 1, 2026

    @MikeAckerschott

    Yes, RecommendationFinder seems to be causing performance issues during normal execution using robot in the commandline. Ill try to see if i can create a reproducible scenario without sharing any of the company's code base. This might take a bit as im not exactly sure what triggers the RecommendationFinder

  7. MikeAckerschott commented on Apr 1, 2026

    @MikeAckerschott

    Ive changed my variable_not_found function to the following to easily see when it triggers:

    def variable_not_found(name, candidates, message=None, deco_braces=True):
        """Raise DataError for missing variable name.
    
        Return recommendations for similar variable names if any are found.
        """
        # import logger and log
        from robot.api import logger
        logger.warn(f"Variable '{name}' not found. ")
    
        raise VariableError(message or f"Variable '{name}' not found.")
    

    A robotfile like this seems to trigger the added logging, but the test still passes, so the variables do get resolved when the VariableError is caught:

    *** Settings ***
    Documentation       mock test
    
    *** Variables ***
    ${variable1}                               ${1}
    ${variable2}                               ${variable1+1}
    ${variable3}                               ${variable1+2}
    
    *** Test Cases ***
    Test case 1
        Log    ${variable1}
        Log    ${variable2}
        Log    ${variable3}
    

    changing my variables section to this:

    *** Variables ***
    ${variable1: int}                               ${1}
    ${variable2: int}                               ${variable1+1}
    ${variable3: int}                               ${variable1+2}
    

    Has the same logging:

    robot -P ./ .\TestCases\robotdebugging\
    ==============================================================================
    Robotdebugging
    ==============================================================================
    [ WARN ] Variable '${1}' not found.
    [ WARN ] Variable '${variable1+1}' not found.
    [ WARN ] Variable '${variable1+2}' not found.
    Robotdebugging.Simpletest :: mock test
    ==============================================================================
    Test case 1                                                           | PASS |
    ------------------------------------------------------------------------------
    Robotdebugging.Simpletest :: mock test                                | PASS |
    1 test, 1 passed, 0 failed
    ==============================================================================
    Robotdebugging                                                        | PASS |
    1 test, 1 passed, 0 failed
    ==============================================================================
    

    Removing the brackets from the value of variable1 like this: ${variable1: int} 1, removes the [ WARN ] Variable '${1}' not found. warning.

    Then trying to change my variables like this:

    *** Variables ***
    ${variable1: int}                               1
    ${variable2: int}                               ${variable1} + 1
    ${variable3: int}                               ${variable1} + 2
    

    Causes the test to fail as it is interpreting the value as a string:

    robot -P ./ .\TestCases\robotdebugging\
    ==============================================================================
    Robotdebugging
    ==============================================================================
    [ ERROR ] Error in file 'C:\Development\simpletest.robot' on line 6: Setting variable '${variable2: int}' failed: Value '1 + 1' cannot be converted to integer.
    [ WARN ] Variable '${variable2}' not found.
    [ ERROR ] Error in file 'C:\Development\simpletest.robot' on line 7: Setting variable '${variable3: int}' failed: Value '1 + 2' cannot be converted to integer.
    [ WARN ] Variable '${variable3}' not found.
    Robotdebugging.Simpletest :: mock test
    ==============================================================================
    [ WARN ] Variable '${variable2}' not found.
    [ WARN ] Variable '${variable2}' not found.
    Test case 1                                                           | FAIL |
    Variable '${variable2}' not found.
    ------------------------------------------------------------------------------
    Robotdebugging.Simpletest :: mock test                                | FAIL |
    1 test, 0 passed, 1 failed
    ==============================================================================
    Robotdebugging                                                        | FAIL |
    1 test, 0 passed, 1 failed
    ==============================================================================
    

    Is there a defined best practice for declaring variables based on the value of other variables? im reading through the docs but cant find any information about that

  8. MikeAckerschott commented on Apr 1, 2026

    @MikeAckerschott

    If i follow the creating dictionaries example from chapter 2.6.3 , the ReccomendationFinder also gets triggered:

    *** Settings ***
    Documentation       mock test
    
    
    *** Variables ***
    &{USER 1}       name=Matti    address=xxx         phone=123
    &{USER 2}       name=Teppo    address=yyy         phone=456
    &{MANY}         first=1       second=${2}         ${3}=third
    &{EVEN MORE}    &{MANY}       first=override      empty=
    ...             =empty        key\=here=value
    
    *** Test Cases ***
    Test case 1
        Log  Hello world
    
    robot -P ./ .\TestCases\robotdebugging\
    ==============================================================================
    Robotdebugging
    ==============================================================================
    [ WARN ] Variable '${2}' not found.
    [ WARN ] Variable '${3}' not found.
    Robotdebugging.Simpletest :: mock test
    ==============================================================================
    Test case 1                                                           | PASS |
    ------------------------------------------------------------------------------
    Robotdebugging.Simpletest :: mock test                                | PASS |
    1 test, 1 passed, 0 failed
    ==============================================================================
    Robotdebugging                                                        | PASS |
    1 test, 1 passed, 0 failed
    ==============================================================================
    
  9. pekkaklarck commented on Apr 1, 2026

    @pekkaklarck
    Member

    Thanks for the examples! This seems to occur when variables are resolved and they aren't found directly. ${variable1+1} most likely triggers this because there's no variable with exactly that name, because this actually uses the extended variable syntax and there's only ${variable1}. ${1} most likely triggers this because there's no such pre-defined variable, but numbers are handled separately. I need to investigate this more closely, but I don't have time for that right now. My guess is that in these cases we just shouldn't look for recommendations. Instead of disabling them in these cases I believe we should disable them by default and only ask for them when we actually need them.

  10. MikeAckerschott commented on Apr 1, 2026

    @MikeAckerschott

    I agree. I do find the RecommendationFinder useful but practically it only presents the recommendation to the user if the VariableError is not resolved successfully and the test fails due to it. The many other calls to RecommendationFinder slow down tests drastically when a codebase has many variables, which the codebase i work in has.

  11. d-biehl commented on Apr 1, 2026

    @d-biehl
    ContributorAuthor

    I’d actually been thinking of using a global variable at module level to disable this, but I think the problem is actually a bit more complex than that...

  12. pekkaklarck commented on Apr 16, 2026

    @pekkaklarck
    Member

    I investigated variable related issues and my earlier guess why this occurs seems to be accurate. When Robot searches for any variable, it uses different variable finders to see is it

    • a normal variable,
    • a number variable (e.g. ${1}),
    • any variation of ${EMPTY},
    • inline Python code (e.g. ${{['a', 'b']}}),
    • an environment variable (e.g. %{HOME}), or
    • an extended variable (e.g. ${var + 1}).

    As you can see from the code, these are always attempted in the above order. That means that with each variable Robot first tries to see is the a variable with that name. If there isn't, the resulting error message contains recommendations, but in this particular case the whole error message is ignored. This makes no sense and needs to be changed.

    While investigating this, I noticed some other stupidity with the related code as well. I'll commit changes related to that shorty and will continue to investigate and fix the recommendation related issue later.

  13. pekkaklarck commented on Apr 16, 2026

    @pekkaklarck
    Member

    Fixing the variable finding related problem will help in normal usage as well as in programmatic usage. It may not be enough for the programmatic usage, though, and we can look at other alternatives as well. Adding an environment variable like ROBOT_NO_RECOMMENDATIONS that would disable all keyword and variable recommendations could be one solution. Let's anyway see what's the situation is once I got the issue discussed above fixed first.

  14. pekkaklarck commented on Apr 17, 2026

    @pekkaklarck
    Member

    The above commit ought to most of the problems with variable resolving performance. I tested that on my machine the following dummy test runs in ~1.25s with RF 7.4.2 but takes only ~0.75s with the latest code. That's a pathological example where variable resolving really dominates, but I noticed that Robot's own acceptance tests got a bit faster as well.

    *** Variables ***
    &{DICT}          \${i}=j
    ${VARIABLE}      ${0}
    ${VARIABLE1}     1
    ${VARIABLE2}     2
    ${VARIABLE3}     3
    
    *** Test Cases ***
    Example
        FOR    ${i}    IN RANGE    1000
            Should Be Equal    ${DICT['\${i}']}    j
            Should Be Equal    ${VARIABLE + 1}    ${1}
        END

    Can you @d-biehl and @MikeAckerschott test the latest code and report how it works? Based on your findings we can then decide should we do something else like adding that ROBOT_NO_RECOMMENDATIONS environment variable. I believe we should anyway concentrate on variable resolving performance in this issue and submit separate issues about other possible fixes/enhancements.

  15. self-assigned this
    on Apr 17, 2026
  16. changed the title [-]`RecommendationFinder` causes severe performance issues for programmatic use[/-] [+]Performance regression in resolving variables[/+] on Apr 17, 2026
  17. pekkaklarck commented on Apr 17, 2026

    @pekkaklarck
    Member

    I changed the title of this issue to cover only variable resolving. Unless more regressions are found, or the changes that are already don't have an effect, I think this issue can be closed. I'm open for making it possible to disable recommendations altogether with an environment variable, but that should then get its own issue.

  18. pekkaklarck commented on Apr 27, 2026

    @pekkaklarck
    Member

    There have been no comments lately and performance of resolving variables has been enhanced heavily. I consider this issue done, but it can be reopened if there's more to do variables. Other topics discussed as part of this issue nevertheless require their own issues if we want to address them.

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

Metadata

Metadata

Assignees

Type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions