File size: 13,812 Bytes
cc2ed2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
"""Π›ΠΎΠΊΠ°Π»ΡŒΠ½Ρ‹ΠΉ smoke-тСст работоспособности Ru2SQL.

ΠŸΡ€ΠΎΠ³ΠΎΠ½ΡΠ΅Ρ‚ ΠΊΠ»ΡŽΡ‡Π΅Π²Ρ‹Π΅ слои Π±Π΅Π· поднятия Streamlit/FastAPI ΠΊΠ°ΠΊ ΠΎΡ‚Π΄Π΅Π»ΡŒΠ½Ρ‹Ρ…
процСссов. ΠŸΠΎΠΊΡ€Ρ‹Π²Π°Π΅Ρ‚: ΠΈΠΌΠΏΠΎΡ€Ρ‚Ρ‹, demo-Π±Π°Π·Ρƒ, vocabulary, prompt,
постобработку, guardrail, Π½ΠΎΠ²Ρ‹ΠΉ API Ρ‡Π΅Ρ€Π΅Π· FastAPI TestClient ΠΈ
ΠΎΠΏΡ†ΠΈΠΎΠ½Π°Π»ΡŒΠ½ΠΎ β€” ΠΊΠΎΡ€ΠΎΡ‚ΠΊΠΈΠΉ инфСрСнс Ρ€Π΅Π°Π»ΡŒΠ½ΠΎΠΉ ΠΌΠΎΠ΄Π΅Π»ΠΈ.

Запуск:
    python scripts/smoke_local.py
    python scripts/smoke_local.py --with-model    # ΠΌΠ΅Π΄Π»Π΅Π½Π½ΠΎ, Π³Ρ€ΡƒΠ·ΠΈΡ‚ Qwen
"""

from __future__ import annotations

import argparse
import sys
import time
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))

GREEN = "\033[32m"
RED = "\033[31m"
YELLOW = "\033[33m"
RESET = "\033[0m"

results: list[tuple[str, str, str]] = []


def check(name: str):
    def decorator(fn):
        try:
            t0 = time.time()
            fn()
            dt = time.time() - t0
            results.append(("OK", name, f"{dt*1000:.0f} мс"))
        except Exception as e:
            results.append(("FAIL", name, f"{type(e).__name__}: {e}"))
        return fn
    return decorator


# ──────────────────────────────────────────────────────────────────────
# Π‘Π»ΠΎΠΉ 1 β€” ΠΈΠΌΠΏΠΎΡ€Ρ‚Ρ‹, ΠΊΠΎΠ½Ρ„ΠΈΠ³
# ──────────────────────────────────────────────────────────────────────
@check("Π˜ΠΌΠΏΠΎΡ€Ρ‚Ρ‹ ядра")
def _():
    from src.config import settings
    from src.api.schemas import GenerateRequest, QueryRequest, SchemaRequest
    from src.business.vocabulary import BusinessVocabulary
    from src.data.prompt import build_chat_messages, BASE_SYSTEM_PROMPT
    from src.data.schema_provider import (
        SpiderSchemaProvider, ConnectionSchemaProvider, TableSchema,
    )
    from src.db.connector import DbConnector
    from src.db.executor import SqlExecutor
    from src.models.postprocess import postprocess, is_select_only, is_valid_sql
    assert settings.base_model_name.startswith("Qwen")


# ──────────────────────────────────────────────────────────────────────
# Π‘Π»ΠΎΠΉ 2 β€” Π΄Π΅ΠΌΠΎ-Π±Π°Π·Π° ΠΈ read-only guardrail
# ──────────────────────────────────────────────────────────────────────
@check("Π”Π΅ΠΌΠΎ-Π±Π°Π·Π° sales.sqlite: ΠΏΠΎΠ΄ΠΊΠ»ΡŽΡ‡Π΅Π½ΠΈΠ΅ ΠΈ схСма")
def _():
    from src.db.connector import DbConnector
    db = ROOT / "data" / "demo" / "sales.sqlite"
    assert db.exists(), f"НС Π½Π°ΠΉΠ΄Π΅Π½ Ρ„Π°ΠΉΠ» {db} β€” запусти data/demo/create_demo_db.py"
    conn = DbConnector(str(db))
    tables = conn.list_tables()
    assert set(tables) == {"customers", "managers", "products", "orders", "order_items"}


@check("Π”Π΅ΠΌΠΎ-Π±Π°Π·Π°: Ρ€Π΅Π°Π»ΡŒΠ½Ρ‹ΠΉ SELECT Π²Ρ‹Ρ€ΡƒΡ‡ΠΊΠΈ")
def _():
    from src.db.executor import SqlExecutor
    ex = SqlExecutor(str(ROOT / "data" / "demo" / "sales.sqlite"))
    res = ex.run("SELECT SUM(amount) FROM orders WHERE status='paid'")
    assert res.success, res.error
    assert res.rows[0][0] > 0


@check("Read-only guardrail: DELETE отклоняСтся Π΄Ρ€Π°ΠΉΠ²Π΅Ρ€ΠΎΠΌ")
def _():
    from src.db.executor import SqlExecutor
    ex = SqlExecutor(str(ROOT / "data" / "demo" / "sales.sqlite"))
    res = ex.run("DELETE FROM orders")
    assert not res.success
    assert ex.run("SELECT COUNT(*) FROM orders").rows[0][0] == 120


# ──────────────────────────────────────────────────────────────────────
# Π‘Π»ΠΎΠΉ 3 β€” BusinessVocabulary ΠΈΠ· YAML
# ──────────────────────────────────────────────────────────────────────
@check("BusinessVocabulary ΠΈΠ· configs/example_vocabulary.yaml")
def _():
    from src.business.vocabulary import BusinessVocabulary
    vocab = BusinessVocabulary.from_yaml(ROOT / "configs" / "example_vocabulary.yaml")
    assert bool(vocab)
    assert "Π²Ρ‹Ρ€ΡƒΡ‡ΠΊΠ°" in vocab.terms
    assert "SUM(orders.amount)" in vocab.render_system_context()


# ──────────────────────────────────────────────────────────────────────
# Π‘Π»ΠΎΠΉ 4 β€” PromptBuilder с Ρ€Π΅Π°Π»ΡŒΠ½ΠΎΠΉ схСмой ΠΈ словарём
# ──────────────────────────────────────────────────────────────────────
@check("PromptBuilder: vocabulary ΡƒΡ…ΠΎΠ΄ΠΈΡ‚ Π² system, Π½Π΅ Π² user")
def _():
    from src.business.vocabulary import BusinessVocabulary
    from src.data.prompt import build_chat_messages
    from src.db.connector import DbConnector
    vocab = BusinessVocabulary.from_yaml(ROOT / "configs" / "example_vocabulary.yaml")
    schema = DbConnector(str(ROOT / "data" / "demo" / "sales.sqlite")).render_schema()
    msgs = build_chat_messages(schema, "Какая Π²Ρ‹Ρ€ΡƒΡ‡ΠΊΠ° Π·Π° 2026 Π³ΠΎΠ΄?", vocabulary=vocab)
    assert "SUM(orders.amount)" in msgs[0]["content"]
    assert "SUM(orders.amount)" not in msgs[1]["content"]


# ──────────────────────────────────────────────────────────────────────
# Π‘Π»ΠΎΠΉ 5 β€” постобработка ΠΈ guardrail
# ──────────────────────────────────────────────────────────────────────
@check("ΠŸΠΎΡΡ‚ΠΎΠ±Ρ€Π°Π±ΠΎΡ‚ΠΊΠ°: markdown, прСфиксы, truncated, мусор")
def _():
    from src.models.postprocess import postprocess, is_select_only
    cases = [
        ("```sql\nSELECT 1;\n```", lambda s: s.upper().startswith("SELECT")),
        ("ΠžΡ‚Π²Π΅Ρ‚: SELECT name FROM customers;", lambda s: s.startswith("SELECT name")),
        ("SELECT * FROM orders WHERE", lambda s: s == ""),
        ("просто тСкст Π±Π΅Π· SQL", lambda s: s == ""),
    ]
    for raw, ok in cases:
        assert ok(postprocess(raw)), f"Π‘Π±ΠΎΠΉ Π½Π°: {raw!r} β†’ {postprocess(raw)!r}"
    assert is_select_only("SELECT 1") is True
    assert is_select_only("DROP TABLE x") is False
    assert is_select_only("DELETE FROM x") is False


# ──────────────────────────────────────────────────────────────────────
# Π‘Π»ΠΎΠΉ 6 β€” FastAPI Ρ‡Π΅Ρ€Π΅Π· TestClient с Π·Π°ΠΌΠΎΠΊΠ°Π½Π½Ρ‹ΠΌ InferenceEngine
# ──────────────────────────────────────────────────────────────────────
@check("FastAPI: /health, /schema, /query с ΠΏΠΎΠ΄ΠΌΠ΅Π½Ρ‘Π½Π½Ρ‹ΠΌ engine")
def _():
    try:
        from fastapi.testclient import TestClient
    except ImportError:
        raise AssertionError("ΠŸΠΎΡΡ‚Π°Π²ΡŒ fastapi[all] ΠΈΠ»ΠΈ httpx β€” TestClient нСдоступСн")

    from src.api import dependencies as deps
    from src.api.main import app
    from src.models.inference import GenerationResult

    class FakeEngine:
        loaded = True
        base_model_name = "Qwen/Qwen2.5-Coder-3B-Instruct"
        def generate(self, schema, question, vocabulary=None, **kw):
            # Π­ΠΌΡƒΠ»ΠΈΡ€ΡƒΠ΅ΠΌ Π²Π°Π»ΠΈΠ΄Π½Ρ‹ΠΉ SQL β€” pipeline Π΄ΠΎΠ»ΠΆΠ΅Π½ ΠΏΡ€ΠΎΠΏΡƒΡΡ‚ΠΈΡ‚ΡŒ Ρ‡Π΅Ρ€Π΅Π· guardrail.
            sql = "SELECT SUM(amount) FROM orders WHERE status = 'paid'"
            return GenerationResult(sql=sql, raw_output=sql)

    app.dependency_overrides[deps.get_engine] = lambda: FakeEngine()
    try:
        with TestClient(app) as client:
            # /health
            r = client.get("/health")
            assert r.status_code == 200
            assert r.json()["model_loaded"] is True

            # /schema Π½Π° Ρ€Π΅Π°Π»ΡŒΠ½ΠΎΠΉ demo-Π±Π°Π·Π΅
            db_path = ROOT / "data" / "demo" / "sales.sqlite"
            r = client.post("/schema", json={
                "connection_string": str(db_path),
                "include_samples": True,
            })
            assert r.status_code == 200, r.text
            tables = r.json()["tables"]
            assert {t["name"] for t in tables} == {
                "customers", "managers", "products", "orders", "order_items"
            }

            # /query Π½Π° Ρ€Π΅Π°Π»ΡŒΠ½ΠΎΠΉ demo-Π±Π°Π·Π΅, FakeEngine отдаст Π²Π°Π»ΠΈΠ΄Π½Ρ‹ΠΉ SELECT
            r = client.post("/query", json={
                "question": "Какая Π²Ρ‹Ρ€ΡƒΡ‡ΠΊΠ° Π·Π° ΠΎΠΏΠ»Π°Ρ‡Π΅Π½Π½Ρ‹Π΅ Π·Π°ΠΊΠ°Π·Ρ‹?",
                "connection_string": str(db_path),
                "execute": True,
                "vocabulary": {
                    "company": "Π”Π΅ΠΌΠΎ",
                    "terms": {"Π²Ρ‹Ρ€ΡƒΡ‡ΠΊΠ°": "SUM(amount) WHERE status='paid'"},
                },
            })
            assert r.status_code == 200, r.text
            body = r.json()
            assert body["is_valid_sql"] is True
            assert body["execution"] is not None
            assert body["execution"]["rows"][0][0] > 0

            # /query с DELETE β€” Π΄ΠΎΠ»ΠΆΠ΅Π½ Π±Ρ‹Ρ‚ΡŒ ΠΎΡ‚Π±ΠΈΡ‚ guardrail'ΠΎΠΌ
            class DropEngine(FakeEngine):
                def generate(self, *a, **kw):
                    return GenerationResult(
                        sql="DELETE FROM orders WHERE id=1",
                        raw_output="DELETE FROM orders WHERE id=1",
                    )
            app.dependency_overrides[deps.get_engine] = lambda: DropEngine()
            r = client.post("/query", json={
                "question": "Π£Π΄Π°Π»ΠΈ Π·Π°ΠΊΠ°Π· 1",
                "connection_string": str(db_path),
                "execute": True,
            })
            assert r.status_code == 200, r.text
            body = r.json()
            assert body["execution"] is None
            assert body["error"] and "Π³Π²Π°Ρ€Π΄Π΅ΠΉΠ»" in body["error"].lower()
    finally:
        app.dependency_overrides.clear()


# ──────────────────────────────────────────────────────────────────────
# Π‘Π»ΠΎΠΉ 7 β€” ΠΎΠΏΡ†ΠΈΠΎΠ½Π°Π»ΡŒΠ½Ρ‹ΠΉ инфСрСнс Ρ€Π΅Π°Π»ΡŒΠ½ΠΎΠΉ ΠΌΠΎΠ΄Π΅Π»ΠΈ
# ──────────────────────────────────────────────────────────────────────
def run_model_smoke():
    @check("InferenceEngine: Π·Π°Π³Ρ€ΡƒΠ·ΠΊΠ° ΠΌΠΎΠ΄Π΅Π»ΠΈ ΠΈ ΠΎΠ΄Π½Π° гСнСрация")
    def _():
        from src.business.vocabulary import BusinessVocabulary
        from src.db.connector import DbConnector
        from src.models.inference import InferenceEngine

        engine = InferenceEngine()
        engine.load()
        assert engine.loaded
        schema = DbConnector(str(ROOT / "data" / "demo" / "sales.sqlite")).render_schema()
        vocab = BusinessVocabulary.from_yaml(ROOT / "configs" / "example_vocabulary.yaml")
        res = engine.generate(schema, "Какая суммарная Π²Ρ‹Ρ€ΡƒΡ‡ΠΊΠ° Π·Π° 2026 Π³ΠΎΠ΄?", vocab)
        assert res.sql and res.sql.upper().startswith("SELECT"), \
            f"МодСль Π²Π΅Ρ€Π½ΡƒΠ»Π°: {res.raw_output!r}"


# ──────────────────────────────────────────────────────────────────────
# main
# ──────────────────────────────────────────────────────────────────────
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--with-model", action="store_true",
        help="Π”ΠΎΠΏΠΎΠ»Π½ΠΈΡ‚Π΅Π»ΡŒΠ½ΠΎ ΠΏΡ€ΠΎΠ³Π½Π°Ρ‚ΡŒ Ρ€Π΅Π°Π»ΡŒΠ½Ρ‹ΠΉ инфСрСнс Qwen (ΠΌΠ΅Π΄Π»Π΅Π½Π½ΠΎ, ~30 сСк Π½Π° CPU)",
    )
    args = parser.parse_args()

    if args.with_model:
        run_model_smoke()

    print()
    print("=" * 64)
    print("Smoke-ΠΏΡ€ΠΎΠ²Π΅Ρ€ΠΊΠ° Ru2SQL")
    print("=" * 64)
    for status, name, info in results:
        color = GREEN if status == "OK" else RED
        mark = "βœ“" if status == "OK" else "βœ—"
        print(f"  {color}{mark}{RESET} {name}  {YELLOW}[{info}]{RESET}")
    ok = sum(1 for s, _, _ in results if s == "OK")
    print("=" * 64)
    summary_color = GREEN if ok == len(results) else RED
    print(f"  {summary_color}{ok} / {len(results)} ΠΏΡ€ΠΎΠ²Π΅Ρ€ΠΎΠΊ ΠΏΡ€ΠΎΠΉΠ΄Π΅Π½ΠΎ{RESET}")
    print("=" * 64)
    if ok < len(results):
        print()
        print("Подсказка: запусти 'pytest -v' для ΠΏΠΎΠ΄Ρ€ΠΎΠ±Π½Ρ‹Ρ… диагностик.")
    sys.exit(0 if ok == len(results) else 1)


if __name__ == "__main__":
    main()