diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f390d8d..46360b7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -35,3 +35,17 @@ jobs: run: pytest -q - name: MCP import smoke test run: python -c "from nlp_sql.mcp_server import build_server; from nlp_sql.engine import NlpSqlEngine; build_server(NlpSqlEngine())" + + startup: + runs-on: ${{ matrix.os }} + strategy: + matrix: + os: [ubuntu-latest, windows-latest, macos-latest] + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.11' + - run: python -m pip install pytest ruff + - run: python -m pytest tests/test_startup.py -q + - run: python -m ruff check start.py tests/test_startup.py diff --git a/README.md b/README.md index 9b43584..ef3d236 100644 --- a/README.md +++ b/README.md @@ -50,7 +50,59 @@ Natural-language query Retrieval and telemetry can inform explanations and future adaptive ranking, but they must not bypass validation. -## Installation +## One-command startup + +Prerequisites: Python 3.11+ with pip/venv support and internet access for the +first dependency installation and Kaggle dataset download. On systems where +`python` is unavailable, use `python3` in the commands below. Linux distributions +may require their `python3-venv` package. + +Clone once and enter the checkout: + +```bash +git clone https://github.com/rashidiff/NLP-SQL.git +cd NLP-SQL +``` + +Then, on Windows, macOS, or Linux, run this same command on every visit: + +```bash +python start.py +``` + +It creates/reuses `.venv`, installs the core package, prepares `data/housing.sqlite` +only if absent, and starts the HTTP API at `http://127.0.0.1:8000`. +No environment activation is needed. Send JSON POST requests to `/parse`, +`/explain`, or `/execute` (for example `{"query":"show top 5 properties by sale price"}`). +The root URL is not a browser UI. Stop with Ctrl+C. + +Existing databases and environment variables are preserved. A failed initial +build is discarded so the same command can retry safely. Dependency installation +is repeated when `pyproject.toml` or the selected extras change; use `--refresh` +to repair or reinstall dependencies explicitly. Repeat runs with unchanged setup +skip installation and dataset preparation. Run only one bootstrap process per checkout. + +Options (also available through `python start.py --help`): + +```bash +python start.py --port 8080 +python start.py --extras dev,mcp +python start.py --setup-only +python start.py --refresh +python start.py --db data/my-housing.sqlite +``` + +Relative database paths are resolved from the checkout, even when the script is +invoked from another directory. A supplied existing database must use the housing +schema. Optional `semantic` extras install sentence-transformers and may download +a model on first use; the default core setup uses local hash embeddings. +`--setup-only` prepares the same environment and database without starting a server. +For subsequent CLI work without activation, use `.venv/Scripts/python -m nlp_sql` +on Windows or `.venv/bin/python -m nlp_sql` on macOS/Linux, followed by a CLI command. +The launcher starts the HTTP API; the optional MCP server still uses its separate +entry point documented below. + +## Manual installation ```bash git clone https://github.com/rashidiff/NLP-SQL.git diff --git a/start.py b/start.py new file mode 100644 index 0000000..4a62e36 --- /dev/null +++ b/start.py @@ -0,0 +1,100 @@ +"""Bootstrap a checkout and serve NLP-SQL using only the Python standard library.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import subprocess +import sys +import tempfile +import venv +from pathlib import Path + +ROOT = Path(__file__).resolve().parent + + +def run(command: list[str]) -> None: + subprocess.run(command, cwd=ROOT, check=True) + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--host", default="127.0.0.1") + parser.add_argument("--port", type=int, default=8000) + parser.add_argument("--db", type=Path, default=Path("data/housing.sqlite")) + parser.add_argument("--extras", default="", help="Comma-separated extras: dev,semantic,mcp") + parser.add_argument("--refresh", action="store_true", help="Reinstall dependencies") + parser.add_argument( + "--setup-only", action="store_true", help="Prepare without starting the API" + ) + args = parser.parse_args(argv) + if sys.version_info < (3, 11): # noqa: UP036 - runs before package installation + parser.error("Python 3.11 or newer is required.") + extras = sorted(set(filter(None, (item.strip() for item in args.extras.split(","))))) + if set(extras) - {"dev", "semantic", "mcp"}: + parser.error("Supported extras are dev, semantic, and mcp.") + environment = ROOT / ".venv" + python = environment / ("Scripts/python.exe" if os.name == "nt" else "bin/python") + marker = environment / ".nlp-sql-setup.json" + try: + if not python.exists(): + print("Creating .venv...", flush=True) + venv.EnvBuilder(with_pip=True).create(environment) + signature = hashlib.sha256((ROOT / "pyproject.toml").read_bytes()).hexdigest() + state = {"project": signature, "extras": extras, "root": str(ROOT)} + try: + installed = json.loads(marker.read_text(encoding="utf-8")) + except (OSError, ValueError): + installed = None + if args.refresh or installed != state: + # An interrupted reinstall must be retried, even if an older marker exists. + marker.unlink(missing_ok=True) + package = "." + (f"[{','.join(extras)}]" if extras else "") + print("Installing dependencies...", flush=True) + run([str(python), "-m", "pip", "install", "-e", package]) + marker.write_text(json.dumps(state), encoding="utf-8") + database = args.db if args.db.is_absolute() else ROOT / args.db + if not database.exists(): + database.parent.mkdir(parents=True, exist_ok=True) + # Publish only a completed database; retries never reuse a partial build. + with tempfile.TemporaryDirectory(dir=database.parent) as staging: + prepared = Path(staging) / "housing.sqlite" + print("Preparing housing database...", flush=True) + run([str(python), "-m", "nlp_sql", "prepare-data", "--db", str(prepared)]) + prepared.replace(database) + if not args.setup_only: + print( + f"Starting NLP-SQL at http://{args.host}:{args.port} " + "(POST /parse, /explain, /execute). Ctrl+C stops the server.", + flush=True, + ) + run( + [ + str(python), + "-m", + "nlp_sql", + "serve", + "--db", + str(database), + "--host", + args.host, + "--port", + str(args.port), + ] + ) + return 0 + except KeyboardInterrupt: + return 130 + except (OSError, subprocess.CalledProcessError) as error: + print( + f"Startup failed: {error}\nFix the reported error and rerun the same command. " + "Dependency installation and the first dataset download require network access.", + file=sys.stderr, + ) + return 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/test_startup.py b/tests/test_startup.py new file mode 100644 index 0000000..525c41c --- /dev/null +++ b/tests/test_startup.py @@ -0,0 +1,113 @@ +"""Bootstrap orchestration checks without network access or a real server.""" + +import importlib.util +import subprocess +from pathlib import Path + +import pytest + +spec = importlib.util.spec_from_file_location("startup", Path(__file__).parents[1] / "start.py") +assert spec and spec.loader +startup = importlib.util.module_from_spec(spec) +spec.loader.exec_module(startup) + + +@pytest.fixture +def checkout(tmp_path, monkeypatch): + monkeypatch.setattr(startup, "ROOT", tmp_path) + (tmp_path / "pyproject.toml").write_text('[project]\nname="test"') + created = [] + + def create(builder, path): + created.append(path) + python = path / ("Scripts/python.exe" if startup.os.name == "nt" else "bin/python") + python.parent.mkdir(parents=True) + python.touch() + + monkeypatch.setattr(startup.venv.EnvBuilder, "create", create) + calls = [] + + def run(command): + calls.append(command) + if "prepare-data" in command: + Path(command[-1]).write_bytes(b"completed database") + + monkeypatch.setattr(startup, "run", run) + return tmp_path, calls, created + + +def test_first_and_repeat_start(checkout): + root, calls, created = checkout + assert startup.main([]) == 0 + assert len(created) == 1 + assert len(calls) == 3 + assert calls[0][-1] == "." + database = root / "data/housing.sqlite" + assert database.read_bytes() == b"completed database" + calls.clear() + assert startup.main([]) == 0 + assert len(calls) == 1 + assert "serve" in calls[0] + assert len(created) == 1 + assert database.read_bytes() == b"completed database" + + +def test_dependency_changes_and_options(checkout): + root, calls, _ = checkout + assert startup.main(["--setup-only", "--extras", "dev,mcp"]) == 0 + assert calls[0][-1] == ".[dev,mcp]" + calls.clear() + (root / "pyproject.toml").write_text("changed") + assert startup.main(["--extras", "mcp,dev", "--port", "8123", "--host", "localhost"]) == 0 + assert len(calls) == 2 + assert calls[-1][-4:] == ["--host", "localhost", "--port", "8123"] + calls.clear() + assert startup.main(["--refresh", "--setup-only"]) == 0 + assert len(calls) == 1 + + +def test_failed_data_build_can_retry(checkout, monkeypatch): + root, calls, _ = checkout + original = startup.run + + def fail(command): + if "prepare-data" in command: + Path(command[-1]).write_bytes(b"partial") + raise subprocess.CalledProcessError(1, command) + original(command) + + monkeypatch.setattr(startup, "run", fail) + assert startup.main([]) == 1 + assert not (root / "data/housing.sqlite").exists() + assert list((root / "data").iterdir()) == [] + monkeypatch.setattr(startup, "run", original) + assert startup.main(["--setup-only"]) == 0 + + +def test_failed_install_invalidates_marker(checkout, monkeypatch): + root, calls, _ = checkout + assert startup.main(["--setup-only"]) == 0 + + def fail(command): + raise subprocess.CalledProcessError(1, command) + + monkeypatch.setattr(startup, "run", fail) + assert startup.main(["--refresh"]) == 1 + assert not (root / ".venv/.nlp-sql-setup.json").exists() + + +def test_custom_existing_database_is_preserved(checkout): + root, calls, _ = checkout + database = root / "custom.sqlite" + database.write_bytes(b"user data") + assert startup.main(["--db", str(database)]) == 0 + assert len(calls) == 2 + assert database.read_bytes() == b"user data" + assert str(database) in calls[-1] + + +def test_invalid_extras_do_not_modify_checkout(checkout): + root, calls, created = checkout + with pytest.raises(SystemExit): + startup.main(["--extras", "unknown"]) + assert not calls and not created