{"record":{"id":"7cc860f6550e4cb8","repo":"zylon-ai/private-gpt","slug":"query-not-found-sql-query","errorCode":null,"errorMessage":"Query not found: {sql_query}","messagePattern":"Query not found: (.+?)","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"private_gpt/components/tabular/pandasai_sandbox.py","lineNumber":343,"sourceCode":"            except Exception as e:\n                custom_exception = e.__class__(clean_exception_text(str(e)))\n                exceptions.append(custom_exception)\n                logger.error(\"Failed to execute SQL query: %s\", custom_exception)\n\n        if not datasets_map and exceptions:\n            return \"\", exceptions\n\n        datasets_code = textwrap.dedent(\n            f\"\"\"\n            import os\n            import pandas as pd\n            _datasets_map = {datasets_map!r}\n            _temp_dir = {temp_dir!r}\n            def execute_sql_query(sql_query):\n                filename = _datasets_map.get(sql_query)\n                if filename:\n                    return pd.read_csv(os.path.join(_temp_dir, filename))\n                raise ValueError(f'Query not found: {{sql_query}}')\n        \"\"\"\n        ).strip()\n\n        return datasets_code, []\n\n    def _prepare_code_for_execution(self, code: str) -> str:\n        temp_dir = f\"/tmp/{self._user_id}\"\n\n        # Redirect any hardcoded .png paths into the sandbox temp dir\n        code = re.sub(\n            r\"\"\"(['\"])([^'\"]*\\.png)\\1\"\"\",\n            lambda m: (\n                f\"{m.group(1)}{temp_dir}/{os.path.basename(m.group(2))}{m.group(1)}\"\n            ),\n            code,\n        )\n\n        # Replace explicit color lists with CUSTOM_COLORS","sourceCodeStart":325,"sourceCodeEnd":361,"githubUrl":"https://github.com/zylon-ai/private-gpt/blob/4a030776a31a901ad80b1bf4d7faa2c1a367efbb/private_gpt/components/tabular/pandasai_sandbox.py#L325-L361","documentation":"Raised by the execute_sql_query helper that _process_sql_queries injects into the sandbox: every SQL query found in the generated code is pre-executed and its result written to a CSV keyed by the query string in _datasets_map. At runtime the generated code calls execute_sql_query(sql) and a lookup miss (exact string mismatch) raises this ValueError inside the sandbox. It almost always means the query string used at runtime differs from the one extracted at pre-processing time.","triggerScenarios":"The generated code builds the SQL string dynamically (f-string/concatenation) so the runtime string differs from the literal seen by _extract_sql_queries_from_code; string escaping differences between extraction and execution; whitespace/quoting differences between the extracted query and the map key.","commonSituations":"LLM writes parameterized or templated SQL; the extraction regex captures a slightly different span than what the code later passes; duplicate near-identical queries with subtle whitespace differences.","solutions":["Log both the map keys (_datasets_map) and the failing lookup string to see the exact mismatch.","Normalize map keys and lookups (strip/collapse whitespace) before comparison.","Prefer literal SQL strings in generated code — prompt the model not to construct SQL dynamically.","As a mitigation, fall back to executing the query directly when the lookup misses instead of raising."],"exampleFix":"# before\ndatasets_code = textwrap.dedent(\n    f\"\"\"\n    def execute_sql_query(sql_query):\n        filename = _datasets_map.get(sql_query)\n        if filename:\n            return pd.read_csv(os.path.join(_temp_dir, filename))\n        raise ValueError(f'Query not found: {{sql_query}}')\n    \"\"\"\n)\n\n# after (normalized lookup)\n_datasets_map_norm = {{k.strip(): v for k, v in _datasets_map.items()}}\ndef execute_sql_query(sql_query):\n    filename = _datasets_map_norm.get(sql_query.strip())\n    if filename:\n        return pd.read_csv(os.path.join(_temp_dir, filename))\n    raise ValueError(f'Query not found: {sql_query}')","handlingStrategy":"validation","validationCode":"# validate before execution: every SQL literal in generated code must be extractable\nimport re\nSQL_RE = re.compile(r'(['\"])(SELECT .*?FROM .*?)\\1', re.IGNORECASE | re.DOTALL)\n\ndef sql_literals_are_static(code: str) -> bool:\n    return not re.search(r'execute_sql_query\\s*\\(\\s*f?[\"\\'].*\\+', code)","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Prompt the model to pass SQL as exact string literals, never built dynamically","Normalize whitespace on both map keys and lookups","Log _datasets_map keys next to the failing lookup for fast diagnosis"],"tags":["sandbox","sql","string-matching","llm-output"],"backgroundTag":null,"analyzedSha":"4a030776a31a901ad80b1bf4d7faa2c1a367efbb","analyzedAt":"2026-08-15T03:51:26.951Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}