File size: 16,184 Bytes
6f9ef2b
 
 
 
 
 
 
 
0a6db2f
 
 
 
6f9ef2b
 
0a6db2f
6f9ef2b
0a6db2f
 
 
0a2cb86
 
f1d0266
0a6db2f
 
 
 
6f9ef2b
 
 
 
 
 
 
 
 
0a6db2f
6f9ef2b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a6db2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
af99bc6
0a6db2f
 
 
6f9ef2b
0a6db2f
6f9ef2b
 
 
0a6db2f
6f9ef2b
f1d0266
 
0a6db2f
 
 
 
f1d0266
 
0a6db2f
 
 
af99bc6
0a6db2f
6f9ef2b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a6db2f
af99bc6
 
 
 
 
 
 
 
 
 
0a6db2f
 
 
 
 
 
 
 
 
6f9ef2b
 
 
0a6db2f
 
 
 
 
 
 
 
 
 
6f9ef2b
 
0a6db2f
 
 
 
 
 
 
 
 
 
 
 
 
 
6f9ef2b
 
 
 
0a6db2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
af99bc6
0a6db2f
 
 
af99bc6
0a6db2f
6f9ef2b
0a6db2f
 
 
 
 
 
e339cad
af99bc6
7f551ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
af99bc6
 
 
 
f1d0266
 
0a2cb86
 
af99bc6
0a2cb86
 
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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
"""Journal des cycles (SQLAlchemy 2.0, SQLite) + export JSONL pour fine-tuning.

SQLite ne travaille JAMAIS directement sur le stockage persistant /data (volume réseau : verrous et WAL non
fiables -> base corrompue au redémarrage, constaté le 2026-11-02). La base de travail est sur le disque local ;
après chaque écriture, une copie cohérente (API backup) est écrite dans /data puis renommée atomiquement.
Au démarrage, la copie /data est vérifiée (integrity_check) ; si elle est corrompue, elle est mise de côté
(.corrupt-<date>) et les lignes lisibles sont récupérées.
"""
from __future__ import annotations

import json
import os
import shutil
import sqlite3
import tempfile
import threading
from datetime import datetime, timezone
from typing import Optional

from sqlalchemy import (Boolean, DateTime, Float, Integer, String, Text, and_, case, cast, create_engine, desc, event,
                        func, select)
from sqlalchemy.pool import NullPool
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, sessionmaker


def default_db_path() -> str:
    """Base de TRAVAIL : toujours sur le disque local."""
    return os.environ.get("SKY_DB") or os.path.expanduser("~/.cache/sky/cycle_logs.db")


def default_persist_path():
    """Copie persistante : SKY_DB_PERSIST ('' = aucune), sinon /data/cycle_logs.db si /data est inscriptible."""
    if "SKY_DB_PERSIST" in os.environ:
        return os.environ["SKY_DB_PERSIST"] or None
    if os.path.isdir("/data") and os.access("/data", os.W_OK):
        return "/data/cycle_logs.db"
    return None


def _healthy(path: str) -> bool:
    try:
        con = sqlite3.connect(path)
        try:
            row = con.execute("PRAGMA integrity_check").fetchone()
        finally:
            con.close()
        return bool(row) and row[0] == "ok"
    except sqlite3.Error:
        return False


def _salvage(path: str) -> dict:
    """Lignes lisibles d'une base corrompue : parcours croissant puis décroissant (contourne la page abîmée)."""
    out = {}
    try:
        con = sqlite3.connect(f"file:{path}?mode=ro", uri=True)
    except sqlite3.Error:
        return out
    try:
        for table in ("cycle_logs", "bench_results"):
            try:
                cols = [r[1] for r in con.execute(f"PRAGMA table_info({table})")]
            except sqlite3.Error:
                continue
            if "id" not in cols:
                continue
            rows = {}
            for order in ("ASC", "DESC"):
                try:
                    for r in con.execute(f"SELECT {', '.join(cols)} FROM {table} ORDER BY id {order}"):
                        rows.setdefault(r[cols.index("id")], dict(zip(cols, r)))
                except sqlite3.Error:
                    pass
            out[table] = list(rows.values())
    finally:
        con.close()
    return out


def _now() -> datetime:
    return datetime.now(timezone.utc).replace(tzinfo=None)


class Base(DeclarativeBase):
    pass


class CycleLog(Base):
    __tablename__ = "cycle_logs"
    id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
    timestamp: Mapped[datetime] = mapped_column(DateTime, default=_now, index=True)
    task: Mapped[str] = mapped_column(Text)
    plan: Mapped[str] = mapped_column(Text, default="")
    attempts: Mapped[int] = mapped_column(Integer, default=0)
    pytest_passed: Mapped[bool] = mapped_column(Boolean, default=False, index=True)
    user_feedback: Mapped[int] = mapped_column(Integer, default=0)  # 1 / -1 / 0
    stop_reason: Mapped[str] = mapped_column(String(40), default="")
    duration_s: Mapped[float] = mapped_column(Float, default=0.0)
    tokens_in: Mapped[int] = mapped_column(Integer, default=0)
    tokens_out: Mapped[int] = mapped_column(Integer, default=0)
    diff: Mapped[str] = mapped_column(Text, default="")
    trajectory: Mapped[str] = mapped_column(Text, default="[]")


class BenchRow(Base):
    __tablename__ = "bench_results"
    id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
    run_id: Mapped[str] = mapped_column(String(32), index=True)
    timestamp: Mapped[datetime] = mapped_column(DateTime, default=_now)
    task_id: Mapped[str] = mapped_column(String(64))
    hidden_passed: Mapped[bool] = mapped_column(Boolean, default=False)
    agent_claimed: Mapped[bool] = mapped_column(Boolean, default=False)
    attempts: Mapped[int] = mapped_column(Integer, default=0)
    duration_s: Mapped[float] = mapped_column(Float, default=0.0)
    detail: Mapped[str] = mapped_column(Text, default="")
    config: Mapped[str] = mapped_column(String(200), default="")


class Database:
    def __init__(self, path: Optional[str] = None, persist_path=...) -> None:
        self.path = path or default_db_path()
        self.persist_path = default_persist_path() if persist_path is ... else persist_path
        self.notice = ""  # message affiché dans l'UI (ex. base corrompue restaurée)
        self._persist_lock = threading.Lock()
        os.makedirs(os.path.dirname(self.path) or ".", exist_ok=True)
        salvaged = self._restore_from_persist() if self.persist_path else None
        self.engine = create_engine(f"sqlite:///{self.path}", poolclass=NullPool,
                                    connect_args={"check_same_thread": False, "timeout": 30})

        @event.listens_for(self.engine, "connect")
        def _pragmas(conn, _):  # noqa: ANN001
            cur = conn.cursor()
            cur.execute("PRAGMA journal_mode=DELETE")
            cur.execute("PRAGMA synchronous=FULL")
            cur.close()

        Base.metadata.create_all(self.engine)
        self._migrate()
        self.Session = sessionmaker(self.engine, expire_on_commit=False)
        if salvaged:
            self._reinsert(salvaged)
        self._persist()

    # ---- persistance : copie atomique vers /data -------------------------------------
    def _restore_from_persist(self):
        """Copie /data -> disque local. Retourne les lignes récupérées si la copie persistante est corrompue."""
        src = self.persist_path
        if not os.path.exists(src):
            return None
        tmp = self.path + ".restore"
        for suffix in ("", "-wal"):  # un -wal de l'ancien mode WAL est rejoué s'il est valide
            if os.path.exists(src + suffix):
                shutil.copyfile(src + suffix, tmp + suffix)
            elif os.path.exists(tmp + suffix):
                os.remove(tmp + suffix)
        healthy = _healthy(tmp)
        salvaged = None if healthy else _salvage(tmp)
        stamp = datetime.now().strftime("%Y%m%d-%H%M%S")
        for suffix in ("-wal", "-shm"):  # restes de l'ancien mode WAL : jamais réutilisés tels quels
            if os.path.exists(src + suffix):
                os.replace(src + suffix, f"{src}{suffix}.old-{stamp}")
        if healthy:
            con = sqlite3.connect(tmp)
            con.execute("PRAGMA journal_mode=DELETE")  # intègre le -wal éventuel dans le fichier principal
            con.close()
            os.replace(tmp, self.path)
        else:
            os.replace(src, f"{src}.corrupt-{stamp}")
            n = sum(len(v) for v in salvaged.values())
            self.notice = (f"Base persistante corrompue mise de côté ({os.path.basename(src)}.corrupt-{stamp}) ; "
                           f"{n} ligne(s) récupérée(s).")
            print(f"[DB] {self.notice}", flush=True)
            if os.path.exists(self.path):
                os.remove(self.path)
        for suffix in ("", "-wal", "-shm", "-journal"):
            if os.path.exists(tmp + suffix):
                os.remove(tmp + suffix)
        return salvaged

    def _reinsert(self, salvaged: dict) -> None:
        with self.engine.begin() as conn:
            for table, rows in salvaged.items():
                cols_now = {r[1] for r in conn.exec_driver_sql(f"PRAGMA table_info({table})")}
                for row in rows:
                    cols = [c for c in row if c in cols_now]
                    conn.exec_driver_sql(
                        f"INSERT OR IGNORE INTO {table} ({', '.join(cols)}) VALUES ({', '.join('?' * len(cols))})",
                        tuple(row[c] for c in cols))

    def _persist(self) -> None:
        """Copie cohérente (API backup) vers un .tmp puis renommage atomique. Un échec n'interrompt jamais l'app."""
        if not self.persist_path:
            return
        with self._persist_lock:
            tmp = self.persist_path + ".tmp"
            try:
                os.makedirs(os.path.dirname(self.persist_path) or ".", exist_ok=True)
                src, dst = sqlite3.connect(self.path), sqlite3.connect(tmp)
                try:
                    src.backup(dst)
                finally:
                    dst.close()
                    src.close()
                os.replace(tmp, self.persist_path)
            except (OSError, sqlite3.Error) as e:
                print(f"[DB] persistance impossible : {e}", flush=True)

    # Colonnes ajoutées après coup : create_all ne modifie pas une table existante (base persistante /data).
    _MIGRATIONS = (("bench_results", "config", "VARCHAR(200) DEFAULT ''"),)

    def _migrate(self) -> None:
        with self.engine.begin() as conn:
            for table, col, ddl in self._MIGRATIONS:
                cols = {r[1] for r in conn.exec_driver_sql(f"PRAGMA table_info({table})")}
                if col not in cols:
                    conn.exec_driver_sql(f"ALTER TABLE {table} ADD COLUMN {col} {ddl}")

    # ---- cycles --------------------------------------------------------------------
    def add_cycle(self, task: str, result) -> int:
        row = CycleLog(task=task, plan=result.plan, attempts=result.attempts, pytest_passed=bool(result.success),
                       stop_reason=result.stop_reason, duration_s=result.duration_s, diff=result.diff,
                       tokens_in=result.tokens_in, tokens_out=result.tokens_out,
                       trajectory=json.dumps(result.trajectory, ensure_ascii=False))
        with self.Session() as s:
            s.add(row)
            s.commit()
            rid = row.id
        self._persist()
        return rid

    def set_feedback(self, cycle_id: int, value: int) -> bool:
        if value not in (-1, 0, 1):
            raise ValueError("feedback doit valoir -1, 0 ou 1")
        with self.Session() as s:
            row = s.get(CycleLog, int(cycle_id))
            if row is None:
                return False
            row.user_feedback = value
            s.commit()
        self._persist()
        return True

    def recent(self, limit: int = 50) -> list:
        with self.Session() as s:
            rows = s.scalars(select(CycleLog).order_by(desc(CycleLog.id)).limit(limit)).all()
            return [[r.id, r.timestamp.strftime("%Y-%m-%d %H:%M"), r.task[:70], r.attempts,
                     "✅" if r.pytest_passed else "❌", {1: "👍", -1: "👎"}.get(r.user_feedback, "—"),
                     r.tokens_out, r.stop_reason] for r in rows]

    def stats(self) -> dict:
        with self.Session() as s:
            total = s.scalar(select(func.count(CycleLog.id))) or 0
            passed = s.scalar(select(func.count(CycleLog.id)).where(CycleLog.pytest_passed.is_(True))) or 0
            up = s.scalar(select(func.count(CycleLog.id)).where(CycleLog.user_feedback == 1)) or 0
            down = s.scalar(select(func.count(CycleLog.id)).where(CycleLog.user_feedback == -1)) or 0
        d = {"cycles": total, "pytest_ok": passed, "👍": up, "👎": down, "db": self.persist_path or self.path}
        if self.notice:
            d["avertissement"] = self.notice
        return d

    def export_jsonl(self, min_feedback: int = 0, out_path: Optional[str] = None) -> tuple:
        """Export des cycles dont pytest a réussi et dont le feedback est >= min_feedback (0 exclut les 👎).

        Une ligne par étape ACCEPTÉE (plan retenu + dernière étape Codeur/Debugger qui a fait passer
        pytest) : les tentatives échouées intermédiaires ne sont jamais exportées.
        """
        out_path = out_path or os.path.join(tempfile.mkdtemp(), f"sky_dataset_{datetime.now():%Y%m%d_%H%M}.jsonl")
        n = 0
        with self.Session() as s, open(out_path, "w", encoding="utf-8") as f:
            q = (select(CycleLog).where(CycleLog.pytest_passed.is_(True), CycleLog.user_feedback >= min_feedback)
                 .order_by(CycleLog.id))
            for row in s.scalars(q):
                for step in json.loads(row.trajectory):
                    if step.get("accepted"):
                        f.write(json.dumps({"messages": step["messages"],
                                            "metadata": {"cycle_id": row.id, "role": step["role"],
                                                         "feedback": row.user_feedback,
                                                         "attempts": row.attempts}}, ensure_ascii=False) + "\n")
                        n += 1
        return out_path, n

    # ---- benchmark -----------------------------------------------------------------
    def add_bench(self, run_id: str, r, config: str = "") -> None:
        with self.Session() as s:
            s.add(BenchRow(run_id=run_id, task_id=r.task_id, hidden_passed=r.hidden_passed,
                           agent_claimed=r.agent_claimed, attempts=r.attempts, duration_s=r.duration_s,
                           detail=r.detail[:2000], config=config))
            s.commit()
        self._persist()

    def recent_bench(self, limit: int = 40) -> list:
        with self.Session() as s:
            rows = s.scalars(select(BenchRow).order_by(desc(BenchRow.id)).limit(limit)).all()
            return [[r.run_id, r.timestamp.strftime("%Y-%m-%d %H:%M"), r.task_id,
                     "✅" if r.hidden_passed else "❌", "✅" if r.agent_claimed else "❌",
                     r.attempts, r.duration_s, (r.detail or "")[:300], r.config or ""] for r in rows]

    def bench_by_config(self, limit: int = 8) -> list:
        """Une ligne par configuration, tous runs confondus : un seul run est trop bruité pour comparer des versions."""
        fp = func.sum(case((and_(BenchRow.agent_claimed.is_(True), BenchRow.hidden_passed.is_(False)), 1), else_=0))
        with self.Session() as s:
            q = (select(BenchRow.config, func.count(func.distinct(BenchRow.run_id)), func.count(BenchRow.id),
                        func.sum(cast(BenchRow.hidden_passed, Integer)), fp, func.avg(BenchRow.attempts),
                        func.avg(BenchRow.duration_s), func.max(BenchRow.timestamp))
                 .group_by(BenchRow.config).order_by(desc(func.max(BenchRow.timestamp))).limit(limit))
            out = []
            for cfg, runs, n, h, f, it, dur, _ in s.execute(q):
                h = int(h or 0)
                out.append([cfg or "(avant v3.2)", runs, f"{h}/{n} ({h / n:.0%})" if n else "0/0", int(f or 0),
                            f"{(f or 0) / n:.0%}" if n else "-", round(float(it or 0), 2), round(float(dur or 0), 1)])
            return out

    def bench_runs(self, limit: int = 10) -> list:
        """Une ligne par run : taux de réussite caché, auto-validation, itérations — pour comparer les versions."""
        with self.Session() as s:
            q = (select(BenchRow.run_id, func.min(BenchRow.timestamp), func.count(BenchRow.id),
                        # cast : sans lui, SQLAlchemy type la somme en Boolean et 5 devient True (affiché 1)
                        func.sum(cast(BenchRow.hidden_passed, Integer)), func.sum(cast(BenchRow.agent_claimed, Integer)),
                        func.avg(BenchRow.attempts), func.max(BenchRow.config),
                        func.sum(case((and_(BenchRow.agent_claimed.is_(True), BenchRow.hidden_passed.is_(False)), 1), else_=0)))
                 .group_by(BenchRow.run_id).order_by(desc(func.min(BenchRow.timestamp))).limit(limit))
            return [[rid, ts.strftime("%Y-%m-%d %H:%M"), f"{int(h or 0)}/{n}", f"{int(a or 0)}/{n}", int(fp or 0),
                     round(float(it or 0), 2), cfg or "(avant v3.2)"] for rid, ts, n, h, a, it, cfg, fp in s.execute(q)]