Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docker/sandbox.Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
FROM python:3.12-slim
RUN pip install --no-cache-dir pandas matplotlib
16 changes: 16 additions & 0 deletions tests/test_biblioteca_integracao.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,22 @@ def __init__(self, *args, **kwargs):
assert capturado["db_engine"] is db_engine
assert capturado["cache_dir"] == tmp_path

def test_engine_repassa_opcoes_docker_para_o_grafo(monkeypatch, tmp_path):
insight_engine_module = importlib.import_module("text_to_insight.InsightEngine")
capturado = {}

class _GraphEspiao(_FakeGraph):
def __init__(self, *args, **kwargs):
capturado.update(kwargs)
super().__init__(*args, **kwargs)

monkeypatch.setattr(insight_engine_module, "Graph", _GraphEspiao)
db_engine = _engine_em_memoria()
InsightEngine(api_key="k", model="gemini-2.5-flash", db_engine=db_engine, usar_docker = True, docker_runtime = "runsc")

assert capturado["usar_docker"] is True
assert capturado["docker_runtime"] == "runsc"


# --------------------------------------------------------------------------- #
# `run` — caminho feliz
Expand Down
131 changes: 131 additions & 0 deletions tests/test_exec_docker.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
import shutil, subprocess
import pytest
import os
from pathlib import Path
from text_to_insight.execucao_python import IMAGEM_DOCKER_PADRAO, executar_python_isolado

RUNTIME_TESTE = os.environ.get("T2I_DOCKER_RUNTIME")


def _docker_pronto(imagem=IMAGEM_DOCKER_PADRAO):
if shutil.which("docker") is None:
return False
if subprocess.run(["docker", "info"], capture_output=True).returncode != 0:
return False
return subprocess.run(["docker", "image", "inspect", imagem], capture_output=True).returncode == 0

pytestmark = pytest.mark.skipif(not _docker_pronto(), reason="Docker indisponível")

def test_docker_simples():
resultado = executar_python_isolado('print("ola")', usar_docker=True, docker_runtime=RUNTIME_TESTE)
assert resultado["ok"] is True
assert "ola" in resultado["saida_terminal"]

def test_timeout_docker():
resultado = executar_python_isolado('while True: pass', timeout_s=3, usar_docker=True, docker_runtime=RUNTIME_TESTE)
assert resultado["ok"] is False
assert "timeout" in resultado["erro_execucao"].lower()
assert subprocess.run(["docker", "ps", "-q", "--filter", "name=t2i_"],
capture_output=True, text=True).stdout.strip() == ""


def test_docker_script_errado():
resultado = executar_python_isolado('raise ValueError("deu ruim")', usar_docker=True, docker_runtime=RUNTIME_TESTE)
assert resultado["ok"] is False
assert "deu ruim" in resultado["erro_execucao"]


def test_docker_arquivo_chega_script(tmp_path):
origem = tmp_path / "dados dados.txt"
origem.write_text("conteudo de teste", encoding="utf-8")
script = 'print(open("entrada.txt", encoding="utf-8").read())'

resultado = executar_python_isolado(
script, arquivos_entrada={"entrada.txt": origem}, usar_docker=True, docker_runtime=RUNTIME_TESTE
)

assert resultado["ok"] is True, resultado["erro_execucao"]
assert "conteudo de teste" in resultado["saida_terminal"]


def test_docker_copiar_arquivo_de_saida(tmp_path):
script = 'open("saida.txt", "w", encoding="utf-8").write("resultado ok")'
destino = tmp_path / "resultado.txt"

resultado = executar_python_isolado(
script, arquivos_saida={"saida.txt": destino}, usar_docker=True, docker_runtime=RUNTIME_TESTE
)

assert resultado["ok"] is True, resultado["erro_execucao"]
assert destino.read_text(encoding="utf-8") == "resultado ok"


def test_docker_grafico_real_gera_png(tmp_path):
from text_to_insight.nodes import graph_generator as gg

csv = tmp_path / 'resultado "da" query.csv'
csv.write_text("x,y\n1,2\n2,4\n3,6\n", encoding="utf-8")
destino = tmp_path / "saida.png"
script = gg._construir_script("plt.plot(df['x'], df['y'])")

resultado = executar_python_isolado(
script,
arquivos_entrada={gg.NOME_CSV: csv},
arquivos_saida={gg.NOME_GRAFICO: destino},
timeout_s=60,
usar_docker=True,
docker_runtime=RUNTIME_TESTE,
)

assert resultado["ok"] is True, resultado["erro_execucao"]
assert destino.read_bytes().startswith(b"\x89PNG")

def test_docker_sem_rede():
script = (
"import socket\n"
'socket.create_connection(("1.1.1.1", 80), timeout=3)\n'
'print("CONECTOU")\n'
)
resultado = executar_python_isolado(script, usar_docker=True, docker_runtime=RUNTIME_TESTE)

assert resultado["ok"] is False
assert "CONECTOU" not in resultado["saida_terminal"]


def test_docker_nao_le_arquivo_da_maquina(tmp_path):
segredo = tmp_path / "segredo.env"
segredo.write_text("SENHA=abc123", encoding="utf-8")
script = f"print(open({str(segredo)!r}).read())"

resultado = executar_python_isolado(script, usar_docker=True, docker_runtime=RUNTIME_TESTE)

assert "abc123" not in resultado["saida_terminal"]
assert "abc123" not in resultado["erro_execucao"]


def test_docker_nao_ve_variaveis_do_host(monkeypatch):
monkeypatch.setenv("CHAVE_FALSA", "segredo123")
script = 'import os; print(os.environ.get("CHAVE_FALSA"))'

resultado = executar_python_isolado(script, usar_docker=True, docker_runtime=RUNTIME_TESTE)

assert resultado["ok"] is True, resultado["erro_execucao"]
assert "segredo123" not in resultado["saida_terminal"]


def test_docker_nao_escreve_fora_da_pasta():
resultado = executar_python_isolado('open("/etc/hack", "w").write("x")', usar_docker=True, docker_runtime=RUNTIME_TESTE)
assert resultado["ok"] is False


def test_docker_limite_de_memoria():
resultado = executar_python_isolado("x = bytearray(2 * 1024**3)", usar_docker=True, docker_runtime=RUNTIME_TESTE)
assert resultado["ok"] is False


def test_docker_runtime_inexistente():
resultado = executar_python_isolado(
'print("ola")', usar_docker=True, docker_runtime="runtime-que-nao-existe"
)
assert resultado["ok"] is False
assert resultado["erro_execucao"] != ""
10 changes: 10 additions & 0 deletions tests/test_exec_docker_ausente.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
from text_to_insight.execucao_python import executar_python_isolado

def test_docker_ausente(monkeypatch):
monkeypatch.setenv("PATH", "/caminho/nao/existente")
resultado = executar_python_isolado('print("rodou")', usar_docker=True)
assert resultado["ok"] is False
assert "docker" in resultado["erro_execucao"].lower()
assert "rodou" not in resultado["saida_terminal"]


4 changes: 2 additions & 2 deletions tests/test_integracao.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,10 +165,10 @@ def _fake_sandbox(estado, engine=None):
"saida_terminal": "ok",
}

def _fake_resposta(estado, llm=None):
def _fake_resposta(estado, llm=None, usar_docker=False, docker_runtime=None):
return {"resposta_natural": "ok"}

def _fake_gerador_grafico(estado, llm=None):
def _fake_gerador_grafico(estado, llm=None, usar_docker = False, docker_runtime = None):
graphs_dir = tmp_path / "graphs"
graphs_dir.mkdir(exist_ok=True)
output_path = graphs_dir / "grafico_teste.png"
Expand Down
14 changes: 14 additions & 0 deletions tests/test_nodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -467,3 +467,17 @@ def test_grafico_real_gera_png(tmp_path):
assert resultado["ok"] is True, resultado["erro_execucao"]
assert destino.exists()
assert destino.read_bytes().startswith(b"\x89PNG")

def test_gerador_repassa_cfg_docker(tmp_path, monkeypatch):
from text_to_insight.nodes import graph_generator as gg
csv = tmp_path / "resultado.csv"
csv.write_text("x, y\n1, 2\n, 4\n", encoding ="utf-8")
estado = {"caminho_csv_resultado": str(csv)}
recebidos = {}
def falso (script, **kwargs):
recebidos.update(kwargs)
return {"ok": False, "erro_execucao": "falso", "saida_terminal": ""}
monkeypatch.setattr(gg, "executar_python_isolado", falso)
gg.nos_nodo_gerador_grafico(estado, _FakeLLM("plt.plot([1, 2])"), usar_docker=True, docker_runtime="runsc")
assert recebidos["usar_docker"] is True
assert recebidos["docker_runtime"] == "runsc"
2 changes: 1 addition & 1 deletion tests/test_token_tracking.py
Original file line number Diff line number Diff line change
Expand Up @@ -441,7 +441,7 @@ def test_graph_generator_tokens(monkeypatch, tmp_path):
usage_metadata={"input_tokens": 60, "output_tokens": 30, "total_tokens": 90},
)

def fake_executar_python(script, *, arquivos_entrada, arquivos_saida, timeout_s):
def fake_executar_python(script, *, arquivos_entrada, arquivos_saida, timeout_s, usar_docker = False, docker_runtime = None):
for destino in arquivos_saida.values():
destino.write_bytes(b"png")
return {"ok": True, "erro_execucao": ""}
Expand Down
8 changes: 8 additions & 0 deletions text_to_insight/InsightEngine.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ def __init__(
inferir_fks_virtuais: bool = False,
model_kwargs: dict | None = None,
cache_dir: str | Path | None = None,
usar_docker: bool = False,
docker_runtime: str | None= None,
):
"""
`db_engine` é uma Engine do SQLAlchemy construída pelo chamador, que
Expand Down Expand Up @@ -61,6 +63,8 @@ def __init__(
self._db_engine = db_engine
self._cache_dir = cache_dir
self._model = model
self._usar_docker = usar_docker
self._docker_runtime = docker_runtime
# Parâmetros repassados ao construtor do LLM (ex.: temperature, max_tokens).
self._model_kwargs = dict(model_kwargs or {})
self._use_cot = use_cot
Expand All @@ -81,6 +85,8 @@ def __init__(
model_kwargs=self._model_kwargs,
db_engine=self._db_engine,
cache_dir=self._cache_dir,
usar_docker=self._usar_docker,
docker_runtime=self._docker_runtime,
)

print(f"[CONFIG] HITL: {'ATIVADO' if self._hitl_ativado else 'DESATIVADO'}")
Expand All @@ -94,6 +100,8 @@ def __init__(
print(f"[CONFIG] INFERIR-FKS-VIRTUAIS: {'ATIVADO' if self._inferir_fks_virtuais else 'DESATIVADO'}")
print(f"[CONFIG] BANCO: {self._db_engine.dialect.name}")
print(f"[CONFIG] MODEL_KWARGS: {self._model_kwargs or 'PADRÃO DO PROVEDOR'}")
print(f"[CONFIG] DOCKER: {'ATIVADO' if self._usar_docker else 'DESATIVADO'}")
print(f"[CONFIG] DOCKER_RUNTIME: {self._docker_runtime or 'PADRÃO'}")

def _config(self, thread_id: str) -> dict[str, Any]:
# O LangGraph usa esse bloco "configurable" para identificar a conversa.
Expand Down
46 changes: 42 additions & 4 deletions text_to_insight/execucao_python.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,13 @@
import sys
import tempfile
import shutil
import uuid
from pathlib import Path
from typing import Any

NOME_SCRIPT = "script.py"
IMAGEM_DOCKER_PADRAO = "text-to-insight-sandbox"
PASTA_CONTAINER = "/work"


def _resultado(ok: bool, erro: str, saida: str) -> dict[str, Any]:
Expand All @@ -38,11 +41,36 @@ def _ambiente_minimo(pasta: Path) -> dict[str, str]:
ambiente["SYSTEMROOT"] = os.environ.get("SYSTEMROOT", "")
return ambiente

def _comando_docker(pasta: Path, nome_container: str, imagem:str, runtime:str | None) -> list[str]:
comando = [
"docker", "run", "--rm",
"--name", nome_container,
"--network", "none",
"--read-only",
"--tmpfs", "/tmp",
"--memory", "512m", "--cpus", "1", "--pids-limit", "64",
"--cap-drop", "ALL", "--security-opt", "no-new-privileges",
"-e", "MPLCONFIGDIR=/tmp",
"-v", f"{pasta}:{PASTA_CONTAINER}",
"-w", PASTA_CONTAINER
]
if os.name != "nt":
comando += ["--user", f"{os.getuid()}:{os.getgid()}"]
if runtime != None:
comando += ["--runtime", runtime]
comando += [imagem, "python", NOME_SCRIPT]
return comando



def executar_python_isolado(
script: str,
arquivos_entrada: dict[str, Path] | None = None,
arquivos_saida: dict[str, Path] | None = None,
timeout_s: float = 30.0
timeout_s: float = 30.0,
usar_docker: bool = False,
docker_runtime: str | None = None,
docker_imagem: str = IMAGEM_DOCKER_PADRAO
) -> dict[str, Any]:
"""
Executa `script` num subprocesso, com uma pasta temporária como
Expand All @@ -57,18 +85,28 @@ def executar_python_isolado(
(pasta / NOME_SCRIPT).write_text(script, encoding="utf-8")
for nome, origem in arquivos_entrada.items():
shutil.copy(origem, pasta / nome)
nome_container = f"t2i_{uuid.uuid4().hex[:12]}"
if usar_docker:
comando = _comando_docker(pasta, nome_container, docker_imagem, docker_runtime)
env = None
else:
comando = [sys.executable, NOME_SCRIPT]
env = _ambiente_minimo(pasta)
try:
processo = subprocess.run(
[sys.executable, NOME_SCRIPT],
comando,
cwd=pasta,
env = _ambiente_minimo(pasta),
env = env,
capture_output=True,
text=True,
timeout=timeout_s,
)
except subprocess.TimeoutExpired:
if usar_docker == True:
subprocess.run(["docker", "rm", "-f", nome_container], capture_output=True)
return _resultado(False, f"Timeout: o script excedeu o limite de {timeout_s}s", "")

except FileNotFoundError:
return _resultado(False, "Docker não encontrado. Instale o Docker ou use o isolamento parcial", "")
stdout = processo.stdout.strip()
stderr = processo.stderr.strip()

Expand Down
6 changes: 4 additions & 2 deletions text_to_insight/graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ def nos_nodo_espera_humana(estado: EstadoTextToInsight):
return estado

class Graph:
def __init__(self, api_key: str, model: str, db_engine, hitl: bool = True, enable_graphs: bool = True, use_cot: bool = True, use_data_exploration: bool = True, use_exploration_selector: str = "off", use_rag: bool = True, enrich_rag: bool = False, model_kwargs: dict | None = None, cache_dir=None):
def __init__(self, api_key: str, model: str, db_engine, hitl: bool = True, enable_graphs: bool = True, use_cot: bool = True, use_data_exploration: bool = True, use_exploration_selector: str = "off", use_rag: bool = True, enrich_rag: bool = False, model_kwargs: dict | None = None, cache_dir=None, usar_docker: bool = False, docker_runtime: str | None = None):
self.llm = get_model(model, api_key, **(model_kwargs or {}))
self.memory = MemorySaver()
self.enable_graphs = enable_graphs
Expand All @@ -49,6 +49,8 @@ def __init__(self, api_key: str, model: str, db_engine, hitl: bool = True, enabl
self.use_exploration_selector = use_exploration_selector
self.use_rag = use_rag
self.enrich_rag = enrich_rag
self.usar_docker = usar_docker
self.docker_runtime = docker_runtime
# Engine SQLAlchemy injetada pelo chamador (dono do ciclo de vida da
# conexao). Nunca entra no estado do grafo: e passada via partial
# diretamente para os nos que precisam dela, então nunca e persistida
Expand Down Expand Up @@ -77,7 +79,7 @@ def _construir_grafo_text_to_insight(self, hitl: bool, enrich_rag: bool) -> Stat
construtor_grafo.add_node("agente_codigo", partial(nos_nodo_agente_codigo, llm=self.llm, use_cot=self.use_cot, engine=engine))
construtor_grafo.add_node("sandbox", partial(nos_nodo_sandbox, engine=engine))
construtor_grafo.add_node("salvar_csv", nos_nodo_salvar_csv)
construtor_grafo.add_node("gerador_grafico", partial(nos_nodo_gerador_grafico, llm=self.llm))
construtor_grafo.add_node("gerador_grafico", partial(nos_nodo_gerador_grafico, llm=self.llm, usar_docker = self.usar_docker, docker_runtime = self.docker_runtime))
construtor_grafo.add_node("resposta", partial(nos_nodo_resposta, llm=self.llm))

# 2. ARESTAS FIXAS
Expand Down
4 changes: 2 additions & 2 deletions text_to_insight/nodes/graph_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ def _construir_script(codigo_visualizacao: str) -> str:
'''


def nos_nodo_gerador_grafico(estado: EstadoTextToInsight, llm: ChatGoogleGenerativeAI) -> dict:
def nos_nodo_gerador_grafico(estado: EstadoTextToInsight, llm: ChatGoogleGenerativeAI, usar_docker: bool = False, docker_runtime: str | None = None) -> dict:
"""
Nó Gerador de Gráficos: usa o LLM para gerar código matplotlib e o executa.
"""
Expand Down Expand Up @@ -130,7 +130,7 @@ def nos_nodo_gerador_grafico(estado: EstadoTextToInsight, llm: ChatGoogleGenerat
print(script)
print(f"[GERADOR_GRAFICO] Executando script...")

resultado = executar_python_isolado(script, arquivos_entrada={NOME_CSV: Path(csv_path)}, arquivos_saida={NOME_GRAFICO: Path(output_path)}, timeout_s=30)
resultado = executar_python_isolado(script, arquivos_entrada={NOME_CSV: Path(csv_path)}, arquivos_saida={NOME_GRAFICO: Path(output_path)}, timeout_s=30, usar_docker = usar_docker, docker_runtime = docker_runtime)

token_update = build_token_usage_update("graph_generator", resposta)

Expand Down
Loading