{"record":{"id":"1eff0c2c4472386c","repo":"xtekky/gpt4free","slug":"failed-to-load-workspace-module-name-source","errorCode":null,"errorMessage":"Failed to load workspace module '{name}' ({source_path}):\\n{traceback.format_exc()}","messagePattern":"Failed to load workspace module '(.+?)' \\((.+?)\\):\\\\n(.+?)","errorType":"exception","errorClass":"ImportError","httpStatus":null,"severity":"error","filePath":"g4f/mcp/pa_provider.py","lineNumber":368,"sourceCode":"    module_globals[\"__package__\"] = module.__package__\n    module.__dict__.update(module_globals)\n\n    try:\n        compiled = compile(code, str(source_path), \"exec\")\n    except SyntaxError:\n        raise ImportError(\n            f\"Syntax error in workspace module '{name}' \"\n            f\"({source_path}):\\n{traceback.format_exc()}\"\n        )\n\n    # Execute in the current thread (no timeout — module loading is expected\n    # to be fast and we need the module object synchronously).\n    prev_depth = sys.getrecursionlimit()\n    sys.setrecursionlimit(MAX_RECURSION_DEPTH)\n    try:\n        exec(compiled, module.__dict__, module.__dict__)  # noqa: S102\n    except Exception:\n        raise ImportError(\n            f\"Failed to load workspace module '{name}' \"\n            f\"({source_path}):\\n{traceback.format_exc()}\"\n        )\n    finally:\n        sys.setrecursionlimit(prev_depth)\n\n    sys.modules[name] = module\n    return module\n\n\n# ---------------------------------------------------------------------------\n# Restricted os shim\n# ---------------------------------------------------------------------------\n\n\ndef _make_restricted_os() -> types.ModuleType:\n    \"\"\"Return a restricted ``os`` module that only exposes safe, read-only\n    attributes (``urandom``, ``name``, ``sep``, ``linesep``, ``altsep``,","sourceCodeStart":350,"sourceCodeEnd":386,"githubUrl":"https://github.com/xtekky/gpt4free/blob/973504e1770928ed5fb82f43da528f441ad9ddc3/g4f/mcp/pa_provider.py#L350-L386","documentation":"Thrown by the .pa.py sandbox loader when compile() succeeded but exec() of the module body raised any exception — e.g. NameError, ImportError from a blocked module, ZeroDivisionError at import time, or a raised error inside a decorator. The whole traceback is embedded in the ImportError message. The loader deliberately raises rather than swallowing, so a half-initialized module never enters sys.modules.","triggerScenarios":"Module-level code that imports a blocklisted module (import requests inside the sandbox), references an undefined global, performs network/file work at import time that fails, or a subclass whose decorator executes immediately.","commonSituations":"Tool modules doing heavy work at top level instead of inside functions; imports of modules not in SAFE_MODULES; code assuming internet access during load in a restricted environment; a dependency on g4f internals not in _ALLOWED_G4F_SUBPATHS.","solutions":["Read the embedded traceback to find the failing line; move import-time logic into a function invoked later.","Replace blocked imports with allowed ones (only SAFE_MODULES and the allowed g4f subpaths can be imported).","Wrap risky module-level statements in try/except inside the sandbox module if failure is expected.","Re-test locally with the same restricted import policy to reproduce before re-uploading."],"exampleFix":"// before (module.pa.py)\nimport requests  # blocklisted -> exec fails -> ImportError\nDATA = requests.get('https://x').text\n\n// after\nALLOWED = True\ndef fetch():\n    raise NotImplementedError('use the provided tools instead')","handlingStrategy":"try-catch","validationCode":"def scan_for_blocked_imports(source: str, allowed: set) -> list:\n    import ast\n    tree = ast.parse(source)\n    blocked = []\n    for node in ast.walk(tree):\n        if isinstance(node, ast.Import):\n            blocked += [a.name for a in node.names if a.name.split('.')[0] not in allowed]\n        elif isinstance(node, ast.ImportFrom) and node.level == 0 and node.module:\n            if node.module.split('.')[0] not in allowed:\n                blocked.append(node.module)\n    return blocked","typeGuard":null,"tryCatchPattern":"try:\n    module = load_workspace_module(name, source_path)\nexcept ImportError as e:\n    if \"Failed to load workspace module\" in str(e):\n        logger.error(\"sandbox module crashed at exec:\\n%s\", e)\n        return None\n    raise","preventionTips":["Keep module-level code minimal; defer work into functions.","Only import modules on the sandbox allowlist; lint for blocked imports before upload.","Read the embedded traceback — it pinpoints the failing statement."],"tags":["sandbox","import-error","workspace","pa-provider"],"backgroundTag":null,"analyzedSha":"973504e1770928ed5fb82f43da528f441ad9ddc3","analyzedAt":"2026-08-14T23:45:32.408Z","schemaVersion":2},"datasetVersion":"2026-08-16T03:17:38.424Z"}