{"record":{"id":"1572792915c2a6a6","repo":"iflytek/astron-agent","slug":"21601-can-not-find-main-function","errorCode":"21601","errorMessage":"can not find main function","messagePattern":"can not find main function","errorType":"error_code","errorClass":"CustomException","httpStatus":null,"severity":"error","filePath":"core/workflow/engine/nodes/code/code_node.py","lineNumber":296,"sourceCode":"    :param python_code: Python code string containing function definitions\n    :return: List of parameter names from the main function\n    :raises CustomException: If main function is not found in the code\n    \"\"\"\n    # Remove comment lines to avoid parsing issues\n    python_code = \"\\n\".join(\n        line for line in python_code.splitlines() if not line.strip().startswith(\"#\")\n    )\n    # Regex pattern to match function definitions with optional type hints\n    re_pattern = r\"def\\s+(\\w+)\\s*\\(([^)]*)\\)\\s*(?:->\\s*[\\w\\[\\],\\s]*)?:\"\n    re_matches = re.findall(re_pattern, python_code, re.DOTALL)\n    re_parameter: str | None = None\n    # Find the main function specifically\n    for re_match in re_matches:\n        if re_match[0].strip() == \"main\":\n            re_parameter = re_match[1].strip()\n            break\n    if re_parameter is None:\n        raise CustomException(\n            CodeEnum.CODE_BUILD_ERROR,\n            err_msg=\"can not find main function\",\n            cause_error=\"can not find main function\",\n        )\n    # Split parameters and extract parameter names (remove type hints)\n    re_params = re_parameter.split(\",\")\n    variables = []\n    for re_param in re_params:\n        re_param = re_param.strip()\n        if re_param:\n            # Remove type hints if present (everything after colon)\n            re_param = re_param.split(\":\")[0].strip()\n            variables.append(re_param)\n    return variables\n\n\nclass CodeSandboxConfig(BaseModel):\n    model_config = ConfigDict(populate_by_name=True)","sourceCodeStart":278,"sourceCodeEnd":314,"githubUrl":"https://github.com/iflytek/astron-agent/blob/5e758547a83371a5a4b29dadf4ac03e8dd527635/core/workflow/engine/nodes/code/code_node.py#L278-L314","documentation":"_parser_code_parameter parses the node's Python source with regex to find function signatures and locate the entry point. The engine specifically requires a function named `main`; if none of the matched function definitions is named main (or the regex finds no functions at all), CODE_BUILD_ERROR is raised with 'can not find main function'. The code node contract mandates a main entry function.","triggerScenarios":"The code node's script defines only differently-named functions (e.g. `run`, `handler`, `execute`); main is nested inside a class or guarded in a way the regex doesn't match; the script is empty or contains only imports/comments; syntax variations (async def, decorators) break the regex match for the name group.","commonSituations":"Users pasting scripts from other platforms (which use different entry-point conventions); refactoring renamed main and forgot to update it; snippets with `if __name__ == '__main__'` blocks but no main def; templates using async def main which the parser may not recognize.","solutions":["Rename the entry function to exactly `def main(...):` at module top level.","Ensure main is a plain top-level def (not nested, not a method, no unusual formatting that breaks the regex).","Check that `async def main` is supported for your workflow version; otherwise make it synchronous.","Remove any syntax oddities (decorators on main, weird whitespace) and keep the signature simple.","Debug by running the script locally to confirm it parses, then re-save the node."],"exampleFix":"// before\ndef run(x):\n    return {\"out\": x}\n\n// after\ndef main(x):\n    return {\"out\": x}","handlingStrategy":"validation","validationCode":"import re\nsrc = code_node_source\nmatches = re.findall(r\"def\\s+(\\w+)\\s*\\(([^)]*)\\)\", src)\nif not any(name.strip() == \"main\" for name, _ in matches):\n    raise ValueError(\"code node must define a top-level 'def main(...)'\")","typeGuard":"def has_main_function(src: str) -> bool:\n    import re\n    return bool(re.search(r\"^\\s*def\\s+main\\s*\\(\", src, re.M))","tryCatchPattern":"try:\n    params = code_node._parser_code_parameter(code)\nexcept CustomException as e:\n    if e.err_code == CodeEnum.CODE_BUILD_ERROR:\n        log.error(\"code node missing main(): rename entry function to main\")\n    raise","preventionTips":["Always name the code node entry function exactly `main` at top level","Avoid renaming main during refactors without updating the node","Port scripts from other platforms by wrapping logic in def main(...)","Keep signatures simple (no decorators/nesting) so the parser matches"],"tags":["code-node","entry-point","parse-error","workflow"],"backgroundTag":"entity-not-found","analyzedSha":"5e758547a83371a5a4b29dadf4ac03e8dd527635","analyzedAt":"2026-09-12T08:03:51.356Z","contentChangedAt":"2026-09-12T08:03:51.356Z","schemaVersion":2},"datasetVersion":"2026-09-19T12:17:13.211Z"}