compactlab 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- compactlab/__init__.py +3 -0
- compactlab/adapters/__init__.py +2 -0
- compactlab/adapters/base.py +212 -0
- compactlab/adapters/cache.py +396 -0
- compactlab/adapters/claude_code.py +226 -0
- compactlab/adapters/codex.py +298 -0
- compactlab/adapters/dsh.py +287 -0
- compactlab/adapters/gemini_cli.py +259 -0
- compactlab/adapters/opencode.py +375 -0
- compactlab/apply/__init__.py +582 -0
- compactlab/cli/__init__.py +5 -0
- compactlab/cli/main.py +2436 -0
- compactlab/data/config_knobs.json +158 -0
- compactlab/data/harness_defaults.json +72 -0
- compactlab/data/harness_formats.json +300 -0
- compactlab/data/pricing.json +51 -0
- compactlab/engine/__init__.py +138 -0
- compactlab/engine/live.py +306 -0
- compactlab/engine/settings.py +175 -0
- compactlab/engine/watch.py +82 -0
- compactlab/eval/__init__.py +1 -0
- compactlab/eval/deep.py +390 -0
- compactlab/eval/executors.py +84 -0
- compactlab/eval/factcheck.py +75 -0
- compactlab/lens.py +80 -0
- compactlab/model/__init__.py +285 -0
- compactlab/pricing/__init__.py +211 -0
- compactlab/pricing/auto.py +118 -0
- compactlab/pricing/ids.py +148 -0
- compactlab/pricing/refresh.py +299 -0
- compactlab/publish.py +125 -0
- compactlab/py.typed +0 -0
- compactlab/recommend/__init__.py +201 -0
- compactlab/recommend/claude_code.py +172 -0
- compactlab/recommend/codex.py +104 -0
- compactlab/recommend/dsh.py +89 -0
- compactlab/recommend/gemini_cli.py +85 -0
- compactlab/recommend/opencode.py +117 -0
- compactlab/recommend/units.py +63 -0
- compactlab/report/__init__.py +3 -0
- compactlab/report/html.py +27 -0
- compactlab/report/template.html +1189 -0
- compactlab/service/__init__.py +1 -0
- compactlab/service/core.py +220 -0
- compactlab/service/http.py +133 -0
- compactlab/service/lock.py +92 -0
- compactlab/service/policy.py +258 -0
- compactlab/service/schedule.py +212 -0
- compactlab/share.py +553 -0
- compactlab/sim/__init__.py +1 -0
- compactlab/sim/baseline.py +214 -0
- compactlab/sim/calibrate.py +108 -0
- compactlab/sim/engine.py +1130 -0
- compactlab/sim/select.py +238 -0
- compactlab/sim/timing.py +134 -0
- compactlab/synth.py +416 -0
- compactlab/term/__init__.py +0 -0
- compactlab/term/style.py +134 -0
- compactlab/term/top.py +531 -0
- compactlab/term/views.py +598 -0
- compactlab/term/widgets.py +238 -0
- compactlab/verify.py +462 -0
- compactlab-0.2.0.dist-info/METADATA +243 -0
- compactlab-0.2.0.dist-info/RECORD +67 -0
- compactlab-0.2.0.dist-info/WHEEL +4 -0
- compactlab-0.2.0.dist-info/entry_points.txt +2 -0
- compactlab-0.2.0.dist-info/licenses/LICENSE +21 -0
compactlab/__init__.py
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
"""Adapter interface and registry.
|
|
2
|
+
|
|
3
|
+
A harness adapter knows where its transcripts live and how to turn one JSONL file into a
|
|
4
|
+
normalized `Session`. Parsing is done by an incremental `Parser` so the scan cache can resume
|
|
5
|
+
an append-only file from the last byte offset instead of re-reading it.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import abc
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import time
|
|
14
|
+
from collections.abc import Iterator, Sequence
|
|
15
|
+
from datetime import datetime
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Any, ClassVar
|
|
18
|
+
|
|
19
|
+
from ..model import Session
|
|
20
|
+
|
|
21
|
+
_REGISTRY: dict[str, type[Adapter]] = {}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class Parser(abc.ABC):
|
|
25
|
+
"""Stateful, resumable line parser.
|
|
26
|
+
|
|
27
|
+
`dump()` must return JSON-serializable state with the session under "session" (as `session_to_dict`). The scan
|
|
28
|
+
cache stores that session apart from the rest of the state and rebuilds an unchanged file with
|
|
29
|
+
`load({"path": ..., "session": ...}).finish()`, so `finish()` must depend only on the session.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
version: ClassVar[int] = 1
|
|
33
|
+
# records at the top of a file a reader of only the file's end must feed first (e.g. Codex's session_meta)
|
|
34
|
+
head_records: ClassVar[int] = 0
|
|
35
|
+
# the session's working directory as last logged; shown only by the live view, never stored or cached
|
|
36
|
+
cwd: str | None = None
|
|
37
|
+
# whether the harness appends copies of earlier messages (original times) that the full parse drops as seen, so
|
|
38
|
+
# a reader of only the file's end has to look further back when the newest record is well after the last request
|
|
39
|
+
rewrites_history: ClassVar[bool] = False
|
|
40
|
+
|
|
41
|
+
@abc.abstractmethod
|
|
42
|
+
def feed(self, record: dict[str, Any]) -> None: ...
|
|
43
|
+
|
|
44
|
+
@abc.abstractmethod
|
|
45
|
+
def finish(self) -> Session:
|
|
46
|
+
"""Return the session parsed so far without consuming parser state."""
|
|
47
|
+
|
|
48
|
+
@abc.abstractmethod
|
|
49
|
+
def dump(self) -> dict[str, Any]: ...
|
|
50
|
+
|
|
51
|
+
@classmethod
|
|
52
|
+
@abc.abstractmethod
|
|
53
|
+
def load(cls, state: dict[str, Any]) -> Parser: ...
|
|
54
|
+
|
|
55
|
+
def note_unknown(self, session: Session, kind: str) -> None:
|
|
56
|
+
session.unknown_events[kind] = session.unknown_events.get(kind, 0) + 1
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class Adapter(abc.ABC):
|
|
60
|
+
name: ClassVar[str] = ""
|
|
61
|
+
parser_cls: ClassVar[type[Parser]]
|
|
62
|
+
# False when a file cannot be resumed from a byte offset (e.g. compressed logs): the scan cache then
|
|
63
|
+
# reuses an unchanged file and re-parses a changed one from the start.
|
|
64
|
+
resumable: ClassVar[bool] = True
|
|
65
|
+
|
|
66
|
+
def __init__(self, roots: Sequence[str | os.PathLike[str]] | str | os.PathLike[str] | None = None):
|
|
67
|
+
if roots is None:
|
|
68
|
+
self.roots = self.default_roots()
|
|
69
|
+
elif isinstance(roots, (str, os.PathLike)):
|
|
70
|
+
self.roots = [Path(os.path.expanduser(str(roots)))]
|
|
71
|
+
else:
|
|
72
|
+
self.roots = [Path(os.path.expanduser(str(r))) for r in roots]
|
|
73
|
+
|
|
74
|
+
@classmethod
|
|
75
|
+
@abc.abstractmethod
|
|
76
|
+
def default_roots(cls) -> list[Path]:
|
|
77
|
+
"""Where this harness keeps transcripts on this machine (may not exist)."""
|
|
78
|
+
|
|
79
|
+
@classmethod
|
|
80
|
+
def config_paths(cls) -> list[Path]:
|
|
81
|
+
"""Config files `apply` may target (for `doctor`)."""
|
|
82
|
+
return []
|
|
83
|
+
|
|
84
|
+
def find_files(self) -> Iterator[Path]:
|
|
85
|
+
for r in self.roots:
|
|
86
|
+
if r.exists():
|
|
87
|
+
yield from sorted(r.rglob("*.jsonl"))
|
|
88
|
+
|
|
89
|
+
def new_parser(self, path: Path) -> Parser:
|
|
90
|
+
return self.parser_cls.load({"path": str(path)})
|
|
91
|
+
|
|
92
|
+
def read_records(self, path: Path, parser: Parser | None = None) -> Iterator[dict[str, Any]]:
|
|
93
|
+
"""Records of one log file; override for logs that are not plain JSONL."""
|
|
94
|
+
return iter_jsonl(path, parser)
|
|
95
|
+
|
|
96
|
+
def parse_file(self, path: Path) -> Session:
|
|
97
|
+
p = self.new_parser(path)
|
|
98
|
+
for rec in self.read_records(path, p):
|
|
99
|
+
p.feed(rec)
|
|
100
|
+
return p.finish()
|
|
101
|
+
|
|
102
|
+
def load(self, path: Path, cache: Any = None, since: float | None = None) -> list[Session]:
|
|
103
|
+
"""Sessions in one file found by `find_files()`, skipping a file not modified since `since` (epoch s).
|
|
104
|
+
Most harnesses keep one session per file; a harness with one database for every session (OpenCode)
|
|
105
|
+
overrides this, filters by each session's own update time and returns many."""
|
|
106
|
+
if since and path.stat().st_mtime < since:
|
|
107
|
+
return []
|
|
108
|
+
return [cache.parse(self, path) if cache is not None else self.parse_file(path)]
|
|
109
|
+
|
|
110
|
+
def fingerprint(self, path: Path, since: float | None = None) -> list[Any] | None:
|
|
111
|
+
"""Identity of what `load(path, cache, since)` would read, taken before reading it: part of the key a saved
|
|
112
|
+
analysis result is reused under, so it must change whenever the sessions `load` returns could. None when
|
|
113
|
+
`load` would return nothing. A harness that overrides `load` overrides this too."""
|
|
114
|
+
import hashlib
|
|
115
|
+
|
|
116
|
+
st = path.stat()
|
|
117
|
+
if since and st.st_mtime < since:
|
|
118
|
+
return None
|
|
119
|
+
with open(path, "rb") as f:
|
|
120
|
+
head = hashlib.sha1(f.read(4096)).hexdigest()
|
|
121
|
+
return [str(path), self.parser_cls.version, st.st_size, st.st_mtime_ns, head]
|
|
122
|
+
|
|
123
|
+
def doctor_checks(self) -> list[dict[str, Any]]:
|
|
124
|
+
"""Extra `doctor` lines for this harness: [{"ok": bool, "label": str, "text": str}]."""
|
|
125
|
+
return []
|
|
126
|
+
|
|
127
|
+
def sessions(self, since_days: float | None = None, cache: Any = None) -> Iterator[Session]:
|
|
128
|
+
cut = time.time() - since_days * 86400 if since_days else None
|
|
129
|
+
for path in self.find_files():
|
|
130
|
+
try:
|
|
131
|
+
found = self.load(path, cache, cut)
|
|
132
|
+
except OSError:
|
|
133
|
+
continue
|
|
134
|
+
yield from (s for s in found if s.turns)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def register(cls: type[Adapter]) -> type[Adapter]:
|
|
138
|
+
if not cls.name:
|
|
139
|
+
raise ValueError("adapter needs a name")
|
|
140
|
+
_REGISTRY[cls.name] = cls
|
|
141
|
+
return cls
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def get_adapter(name: str) -> type[Adapter]:
|
|
145
|
+
return _REGISTRY[name]
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def adapter_names() -> list[str]:
|
|
149
|
+
return sorted(_REGISTRY)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def parse_lines(lines: Iterator[bytes], parser: Parser | None = None) -> Iterator[dict[str, Any]]:
|
|
153
|
+
for raw in lines:
|
|
154
|
+
line = raw.strip()
|
|
155
|
+
if not line:
|
|
156
|
+
continue
|
|
157
|
+
try:
|
|
158
|
+
d = json.loads(line)
|
|
159
|
+
except (ValueError, UnicodeDecodeError):
|
|
160
|
+
_bump_error(parser)
|
|
161
|
+
continue
|
|
162
|
+
if isinstance(d, dict):
|
|
163
|
+
yield d
|
|
164
|
+
else:
|
|
165
|
+
_bump_error(parser)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _bump_error(parser: Parser | None) -> None:
|
|
169
|
+
s = getattr(parser, "session", None)
|
|
170
|
+
if s is not None:
|
|
171
|
+
s.parse_errors += 1
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
class BadRecord(ValueError):
|
|
175
|
+
"""A recognized record whose fields are unusable; the parser skips it and counts a parse error."""
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def count(v: Any) -> int:
|
|
179
|
+
"""A non-negative integer token count; absent/null is 0. Strings, bools, NaN and negatives are bad."""
|
|
180
|
+
if v is None:
|
|
181
|
+
return 0
|
|
182
|
+
if isinstance(v, bool) or not isinstance(v, (int, float)):
|
|
183
|
+
raise BadRecord(f"not a number: {v!r}")
|
|
184
|
+
if isinstance(v, float) and (v != v or v in (float("inf"), float("-inf"))):
|
|
185
|
+
raise BadRecord(f"not finite: {v!r}")
|
|
186
|
+
if v < 0:
|
|
187
|
+
raise BadRecord(f"negative: {v!r}")
|
|
188
|
+
return int(v)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def iter_jsonl(path: Path, parser: Parser | None = None) -> Iterator[dict[str, Any]]:
|
|
192
|
+
with open(path, "rb") as f:
|
|
193
|
+
yield from parse_lines(iter(f), parser)
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def parse_ts(v: Any) -> float | None:
|
|
197
|
+
if v is None:
|
|
198
|
+
return None
|
|
199
|
+
if isinstance(v, (int, float)):
|
|
200
|
+
return float(v) / 1000 if v > 1e11 else float(v)
|
|
201
|
+
try:
|
|
202
|
+
return datetime.fromisoformat(str(v).replace("Z", "+00:00")).timestamp()
|
|
203
|
+
except ValueError:
|
|
204
|
+
return None
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def env_roots(var: str, sub: str, fallbacks: list[str]) -> list[Path]:
|
|
208
|
+
"""Roots from an env var (comma-separated base dirs) or the given fallbacks."""
|
|
209
|
+
val = os.environ.get(var)
|
|
210
|
+
if val:
|
|
211
|
+
return [Path(os.path.expanduser(x.strip())) / sub for x in val.split(",") if x.strip()]
|
|
212
|
+
return [Path(os.path.expanduser(x)) for x in fallbacks]
|
|
@@ -0,0 +1,396 @@
|
|
|
1
|
+
"""Incremental on-disk scan cache.
|
|
2
|
+
|
|
3
|
+
One SQLite row per log file: size, mtime_ns, SHA-1 of the first 4 KiB, byte offset of the last complete line,
|
|
4
|
+
parser version and parser state. Unchanged file -> rebuild its session from the row. Appended file with the same
|
|
5
|
+
head -> resume the parser from the saved offset. Anything else -> full parse. A run reads and writes only the rows
|
|
6
|
+
of the files it scans, one row per transaction, so a change rewrites one row, not the whole cache.
|
|
7
|
+
|
|
8
|
+
The parser state is stored in two parts: the session, which is all an unchanged file needs, and the rest (seen
|
|
9
|
+
message ids, pending tool calls), which is read only to resume an appended file.
|
|
10
|
+
|
|
11
|
+
The same database keeps the last few lite analysis results, each under a key of the files it was made from and of
|
|
12
|
+
every other input (see `cli/main.py`), so a run whose files and inputs are unchanged reuses one without decoding a
|
|
13
|
+
session.
|
|
14
|
+
|
|
15
|
+
Sessions are stored lean (`model.lean`): token counts and timings, a flag for user messages that correct the agent,
|
|
16
|
+
hashed tool keys and summary lengths, but no prompt text, tool arguments, output snippets or summaries. The resume
|
|
17
|
+
part may still hold the text of a log's last user message while its turn is unfinished. The cache is kept in a 0700
|
|
18
|
+
directory (`~/.compactlab/cache`) with 0600 files. Rows of files that no longer exist are pruned after each scan, the
|
|
19
|
+
first scan with a new cache version deletes the files of older versions (never newer ones), `--no-cache` bypasses it
|
|
20
|
+
and `compactlab cache clear` removes every version.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import contextlib
|
|
26
|
+
import hashlib
|
|
27
|
+
import json
|
|
28
|
+
import os
|
|
29
|
+
import re
|
|
30
|
+
import sqlite3
|
|
31
|
+
from collections.abc import Callable, Iterator
|
|
32
|
+
from pathlib import Path
|
|
33
|
+
from typing import TYPE_CHECKING, Any, BinaryIO, NamedTuple
|
|
34
|
+
|
|
35
|
+
from ..model import lean, lean_dict, lean_state
|
|
36
|
+
from .base import parse_lines
|
|
37
|
+
|
|
38
|
+
if TYPE_CHECKING:
|
|
39
|
+
from ..model import Session
|
|
40
|
+
from .base import Adapter, Parser
|
|
41
|
+
|
|
42
|
+
# 5: lean rows, no transcript text (the first scan deletes version 4's, which had it); 6: nor in the resume state (5's
|
|
43
|
+
# kept a user message, tool command and tool output that no turn had yet)
|
|
44
|
+
CACHE_VERSION = 6
|
|
45
|
+
HEAD = 4096
|
|
46
|
+
BUSY_TIMEOUT_S = 10.0 # wait this long for another run's write; then go on without caching that file
|
|
47
|
+
ERASE_TIMEOUT_S = 1.0 # wait this long for other runs' reads to end before erasing pruned rows from the files
|
|
48
|
+
RESULTS_KEPT = 4 # analysis results kept (one per set of inputs: the service's, a `simulate` with other options)
|
|
49
|
+
# Files this cache (any version) may leave in its directory: the database and its journals, the JSON files of
|
|
50
|
+
# versions 1-3, and their temporary files. Nothing else in the directory is touched.
|
|
51
|
+
_OURS = re.compile(r"scan-v(\d+)\.(?:json|sqlite3(?:-wal|-shm|-journal)?)|\.scan\.[a-z0-9_]{8}")
|
|
52
|
+
_SCHEMA = """
|
|
53
|
+
CREATE TABLE IF NOT EXISTS entries (
|
|
54
|
+
adapter TEXT NOT NULL,
|
|
55
|
+
path TEXT NOT NULL,
|
|
56
|
+
parser INTEGER NOT NULL,
|
|
57
|
+
head TEXT NOT NULL,
|
|
58
|
+
size INTEGER NOT NULL,
|
|
59
|
+
mtime_ns INTEGER NOT NULL,
|
|
60
|
+
offset INTEGER NOT NULL,
|
|
61
|
+
session TEXT NOT NULL,
|
|
62
|
+
resume TEXT NOT NULL,
|
|
63
|
+
PRIMARY KEY (adapter, path)
|
|
64
|
+
);
|
|
65
|
+
CREATE TABLE IF NOT EXISTS results (
|
|
66
|
+
files TEXT NOT NULL,
|
|
67
|
+
inputs TEXT NOT NULL,
|
|
68
|
+
facts TEXT NOT NULL,
|
|
69
|
+
result TEXT NOT NULL,
|
|
70
|
+
made REAL NOT NULL,
|
|
71
|
+
PRIMARY KEY (files, inputs)
|
|
72
|
+
);
|
|
73
|
+
"""
|
|
74
|
+
_META = "parser, head, size, mtime_ns, offset"
|
|
75
|
+
_JSON = json.JSONEncoder(separators=(",", ":"))
|
|
76
|
+
_UNUSABLE = {sqlite3.SQLITE_CORRUPT, sqlite3.SQLITE_NOTADB}
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class Pruned(NamedTuple):
|
|
80
|
+
"""What `prune()` did: rows of deleted logs found, whether they were deleted, and whether their bytes are gone
|
|
81
|
+
from the cache files too (not while another run still reads a snapshot that holds them)."""
|
|
82
|
+
|
|
83
|
+
stale: int
|
|
84
|
+
deleted: bool
|
|
85
|
+
erased: bool
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class ScanCache:
|
|
89
|
+
def __init__(self, directory: str | os.PathLike[str]):
|
|
90
|
+
self.dir = Path(os.path.expanduser(str(directory)))
|
|
91
|
+
self.file = self.dir / f"scan-v{CACHE_VERSION}.sqlite3"
|
|
92
|
+
self.stats = {"hit": 0, "resumed": 0, "parsed": 0}
|
|
93
|
+
self._db: sqlite3.Connection | None = None
|
|
94
|
+
self._broken = False # the database could not be opened: scan without it
|
|
95
|
+
|
|
96
|
+
# ---------- scanning ----------
|
|
97
|
+
|
|
98
|
+
def parse(self, adapter: Adapter, path: Path) -> Session:
|
|
99
|
+
st = path.stat()
|
|
100
|
+
ver = adapter.parser_cls.version
|
|
101
|
+
with open(path, "rb") as f:
|
|
102
|
+
head = hashlib.sha1(f.read(HEAD)).hexdigest()
|
|
103
|
+
rows = self._exec(f"SELECT {_META} FROM entries WHERE adapter=? AND path=?", (adapter.name, str(path)))
|
|
104
|
+
row = rows[0] if rows else None
|
|
105
|
+
if row and row[0] == ver and row[1] == head:
|
|
106
|
+
_, _, size, mtime_ns, offset = row
|
|
107
|
+
if size == st.st_size and mtime_ns == st.st_mtime_ns:
|
|
108
|
+
state = self._state(adapter, path, row, resume=False)
|
|
109
|
+
session = _rebuild(adapter, state) if state is not None else None
|
|
110
|
+
if session is not None:
|
|
111
|
+
self.stats["hit"] += 1
|
|
112
|
+
return lean(session)
|
|
113
|
+
elif adapter.resumable and st.st_size > offset and size <= st.st_size:
|
|
114
|
+
state = self._state(adapter, path, row, resume=True)
|
|
115
|
+
resumed = _resume(adapter, state, f, offset) if state is not None else None
|
|
116
|
+
if resumed is not None:
|
|
117
|
+
self.stats["resumed"] += 1
|
|
118
|
+
return self._store(adapter, path, head, st, resumed[1], resumed[0])
|
|
119
|
+
parser = adapter.new_parser(path)
|
|
120
|
+
if adapter.resumable:
|
|
121
|
+
offset = _consume(f, 0, parser)
|
|
122
|
+
else:
|
|
123
|
+
for rec in adapter.read_records(path, parser):
|
|
124
|
+
parser.feed(rec)
|
|
125
|
+
offset = st.st_size
|
|
126
|
+
self.stats["parsed"] += 1
|
|
127
|
+
return self._store(adapter, path, head, st, offset, parser)
|
|
128
|
+
|
|
129
|
+
def _state(self, adapter: Adapter, path: Path, meta: tuple[Any, ...], resume: bool) -> dict[str, Any] | None:
|
|
130
|
+
"""Parser state of the row `meta` was read from; None if another run has replaced that row since."""
|
|
131
|
+
cols = "session, resume" if resume else "session"
|
|
132
|
+
same = " AND ".join(f"{c}=?" for c in _META.split(", "))
|
|
133
|
+
rows = self._exec(
|
|
134
|
+
f"SELECT {cols} FROM entries WHERE adapter=? AND path=? AND {same}", (adapter.name, str(path), *meta)
|
|
135
|
+
)
|
|
136
|
+
if not rows:
|
|
137
|
+
return None
|
|
138
|
+
try:
|
|
139
|
+
session = json.loads(rows[0][0])
|
|
140
|
+
rest = json.loads(rows[0][1]) if resume else {}
|
|
141
|
+
except ValueError:
|
|
142
|
+
return None # unreadable row: parse the file again, which replaces it
|
|
143
|
+
if not isinstance(session, dict) or not isinstance(rest, dict):
|
|
144
|
+
return None # valid JSON of the wrong shape (e.g. `null`): the same
|
|
145
|
+
return {"path": str(path), "session": session, **rest}
|
|
146
|
+
|
|
147
|
+
def _store(
|
|
148
|
+
self, adapter: Adapter, path: Path, head: str, st: os.stat_result, offset: int, parser: Parser
|
|
149
|
+
) -> Session:
|
|
150
|
+
# lean first: the finished session shares its turns with the parser's, so the dump below is lean already and
|
|
151
|
+
# each user message is checked for a correction once
|
|
152
|
+
finished = lean(parser.finish())
|
|
153
|
+
db = self._open(create=True)
|
|
154
|
+
if db is not None:
|
|
155
|
+
state = parser.dump()
|
|
156
|
+
session = lean_dict(state.pop("session")) # no transcript text on disk (compactions; anything not shared)
|
|
157
|
+
state.pop("path", None)
|
|
158
|
+
state = lean_state(state) if adapter.resumable else {} # only resuming reads it
|
|
159
|
+
self._exec(
|
|
160
|
+
"INSERT OR REPLACE INTO entries VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
|
161
|
+
(
|
|
162
|
+
adapter.name,
|
|
163
|
+
str(path),
|
|
164
|
+
adapter.parser_cls.version,
|
|
165
|
+
head,
|
|
166
|
+
st.st_size,
|
|
167
|
+
st.st_mtime_ns,
|
|
168
|
+
offset,
|
|
169
|
+
_JSON.encode(session),
|
|
170
|
+
_JSON.encode(state),
|
|
171
|
+
),
|
|
172
|
+
)
|
|
173
|
+
return finished
|
|
174
|
+
|
|
175
|
+
def prune(self) -> Pruned:
|
|
176
|
+
"""Delete the rows of files that no longer exist, in one transaction, and erase them from the cache files.
|
|
177
|
+
|
|
178
|
+
`secure_delete` zeroes the deleted rows in the pages SQLite writes, but those pages go to the write-ahead log
|
|
179
|
+
first and the old ones stay in the database file until a checkpoint copies the new ones over them. A
|
|
180
|
+
checkpoint cannot do that while another run is reading a snapshot that still holds the rows, so erasing waits
|
|
181
|
+
up to `ERASE_TIMEOUT_S` for such reads to end; when they have not, the rows are erased by the checkpoint SQLite
|
|
182
|
+
runs when the last run using the cache closes it."""
|
|
183
|
+
rows = self._exec("SELECT adapter, path FROM entries", create=False) or []
|
|
184
|
+
gone = [(a, p) for a, p in rows if not os.path.exists(p)]
|
|
185
|
+
if not gone:
|
|
186
|
+
return Pruned(0, True, True)
|
|
187
|
+
db = self._open(create=False)
|
|
188
|
+
if db is None:
|
|
189
|
+
return Pruned(len(gone), False, False)
|
|
190
|
+
try:
|
|
191
|
+
db.execute("BEGIN IMMEDIATE") # all or none: a half-done prune would look done
|
|
192
|
+
db.executemany("DELETE FROM entries WHERE adapter=? AND path=?", gone)
|
|
193
|
+
db.execute("COMMIT")
|
|
194
|
+
except sqlite3.Error:
|
|
195
|
+
if db.in_transaction:
|
|
196
|
+
with contextlib.suppress(sqlite3.Error):
|
|
197
|
+
db.execute("ROLLBACK")
|
|
198
|
+
return Pruned(len(gone), False, False)
|
|
199
|
+
return Pruned(len(gone), True, self._erase())
|
|
200
|
+
|
|
201
|
+
def _erase(self) -> bool:
|
|
202
|
+
"""Checkpoint the write-ahead log into the database and truncate it. False when another run's read kept
|
|
203
|
+
part of it from being copied."""
|
|
204
|
+
db = self._db
|
|
205
|
+
if db is None:
|
|
206
|
+
return False
|
|
207
|
+
try:
|
|
208
|
+
db.execute(f"PRAGMA busy_timeout={int(ERASE_TIMEOUT_S * 1000)}")
|
|
209
|
+
try:
|
|
210
|
+
busy = db.execute("PRAGMA wal_checkpoint(TRUNCATE)").fetchone()[0]
|
|
211
|
+
finally:
|
|
212
|
+
db.execute(f"PRAGMA busy_timeout={int(BUSY_TIMEOUT_S * 1000)}")
|
|
213
|
+
except sqlite3.Error:
|
|
214
|
+
return False
|
|
215
|
+
return busy == 0
|
|
216
|
+
|
|
217
|
+
# ---------- analysis results ----------
|
|
218
|
+
|
|
219
|
+
def facts(self, files: str) -> dict[str, Any] | None:
|
|
220
|
+
"""What the analysis saved about the sessions of these files (see `save_result`), or None."""
|
|
221
|
+
rows = self._exec("SELECT facts FROM results WHERE files=? ORDER BY made DESC LIMIT 1", (files,), create=False)
|
|
222
|
+
try:
|
|
223
|
+
return json.loads(rows[0][0]) if rows else None
|
|
224
|
+
except ValueError:
|
|
225
|
+
return None
|
|
226
|
+
|
|
227
|
+
def result(self, files: str, inputs: str) -> dict[str, Any] | None:
|
|
228
|
+
"""The analysis result saved for exactly these files and inputs, or None."""
|
|
229
|
+
rows = self._exec("SELECT result FROM results WHERE files=? AND inputs=?", (files, inputs), create=False)
|
|
230
|
+
try:
|
|
231
|
+
res = json.loads(rows[0][0]) if rows else None
|
|
232
|
+
except ValueError:
|
|
233
|
+
return None
|
|
234
|
+
return res if isinstance(res, dict) else None
|
|
235
|
+
|
|
236
|
+
def save_result(self, files: str, inputs: str, facts: dict[str, Any], result: str, now: float) -> None:
|
|
237
|
+
"""Keep `result` (JSON text) for these keys; `facts` are the session-derived values the next run needs to
|
|
238
|
+
rebuild `inputs` without decoding a session (models seen, harness and model pairs). Only the newest
|
|
239
|
+
`RESULTS_KEPT` results are kept."""
|
|
240
|
+
self._exec(
|
|
241
|
+
"INSERT OR REPLACE INTO results VALUES (?, ?, ?, ?, ?)", (files, inputs, _JSON.encode(facts), result, now)
|
|
242
|
+
)
|
|
243
|
+
self._exec(
|
|
244
|
+
"DELETE FROM results WHERE rowid NOT IN (SELECT rowid FROM results ORDER BY made DESC LIMIT ?)",
|
|
245
|
+
(RESULTS_KEPT,),
|
|
246
|
+
)
|
|
247
|
+
|
|
248
|
+
def close(self) -> None:
|
|
249
|
+
if self._db is not None:
|
|
250
|
+
self._db.close()
|
|
251
|
+
self._db = None
|
|
252
|
+
|
|
253
|
+
# ---------- inspection and cleanup ----------
|
|
254
|
+
|
|
255
|
+
def info(self) -> dict[str, Any]:
|
|
256
|
+
"""What is on disk: rows (and how many are of deleted logs), saved results, bytes of this version, of older
|
|
257
|
+
versions (deleted by the next scan) and of newer ones (a newer compactlab's, left alone). Creates nothing."""
|
|
258
|
+
paths = [p for (p,) in self._exec("SELECT path FROM entries", create=False) or []]
|
|
259
|
+
results = self._exec("SELECT count(*) FROM results", create=False)
|
|
260
|
+
sizes = [(_age(ver), p.stat().st_size) for p, ver in self._ours()]
|
|
261
|
+
return {
|
|
262
|
+
"path": str(self.file),
|
|
263
|
+
"exists": self.file.exists(),
|
|
264
|
+
"files": len(paths),
|
|
265
|
+
"stale": sum(not os.path.exists(p) for p in paths),
|
|
266
|
+
"results": results[0][0] if results else 0,
|
|
267
|
+
"bytes": sum(n for age, n in sizes if age == 0),
|
|
268
|
+
"old_bytes": sum(n for age, n in sizes if age < 0),
|
|
269
|
+
"newer_bytes": sum(n for age, n in sizes if age > 0),
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
def clear(self) -> list[Path]:
|
|
273
|
+
"""Delete the cache files of every version. Returns the paths removed."""
|
|
274
|
+
self.close()
|
|
275
|
+
return self._remove(lambda _ver: True)
|
|
276
|
+
|
|
277
|
+
def _ours(self) -> Iterator[tuple[Path, int | None]]:
|
|
278
|
+
if not self.dir.is_dir():
|
|
279
|
+
return
|
|
280
|
+
for p in sorted(self.dir.iterdir()):
|
|
281
|
+
m = _OURS.fullmatch(p.name)
|
|
282
|
+
if m and p.is_file():
|
|
283
|
+
yield p, int(m.group(1)) if m.group(1) else None
|
|
284
|
+
|
|
285
|
+
def _remove(self, which: Callable[[int | None], bool]) -> list[Path]:
|
|
286
|
+
removed = []
|
|
287
|
+
for p, ver in self._ours():
|
|
288
|
+
if which(ver):
|
|
289
|
+
with contextlib.suppress(FileNotFoundError):
|
|
290
|
+
p.unlink()
|
|
291
|
+
removed.append(p)
|
|
292
|
+
return removed
|
|
293
|
+
|
|
294
|
+
# ---------- database ----------
|
|
295
|
+
|
|
296
|
+
def _open(self, create: bool) -> sqlite3.Connection | None:
|
|
297
|
+
if self._db is not None or self._broken:
|
|
298
|
+
return self._db
|
|
299
|
+
if not create and not self.file.exists():
|
|
300
|
+
return None
|
|
301
|
+
try:
|
|
302
|
+
if create:
|
|
303
|
+
self._prepare()
|
|
304
|
+
try:
|
|
305
|
+
self._db = _connect(self.file)
|
|
306
|
+
except sqlite3.DatabaseError as e:
|
|
307
|
+
if not create or getattr(e, "sqlite_errorcode", None) not in _UNUSABLE:
|
|
308
|
+
raise
|
|
309
|
+
self._remove(lambda ver: ver == CACHE_VERSION) # corrupt or not a database: start over
|
|
310
|
+
self._prepare()
|
|
311
|
+
self._db = _connect(self.file)
|
|
312
|
+
except (OSError, sqlite3.Error):
|
|
313
|
+
self._broken = True
|
|
314
|
+
return self._db
|
|
315
|
+
|
|
316
|
+
def _prepare(self) -> None:
|
|
317
|
+
self.dir.mkdir(parents=True, exist_ok=True)
|
|
318
|
+
os.chmod(self.dir, 0o700)
|
|
319
|
+
# Older versions' files. Never a newer version's: a newer compactlab may share this directory. Leftover
|
|
320
|
+
# temporary files of the JSON versions carry no version; they are left alone too while a newer one is here.
|
|
321
|
+
newer = any(_age(ver) > 0 for _, ver in self._ours())
|
|
322
|
+
self._remove(lambda ver: _age(ver) < 0 and not (ver is None and newer))
|
|
323
|
+
os.close(os.open(self.file, os.O_RDWR | os.O_CREAT, 0o600))
|
|
324
|
+
os.chmod(self.file, 0o600) # the WAL and shared-memory files take the database's mode
|
|
325
|
+
|
|
326
|
+
def _exec(self, sql: str, args: Any = (), create: bool = True, many: bool = False) -> list[Any] | None:
|
|
327
|
+
"""Rows of one statement, or None if the cache is unavailable or the statement failed. A failure never stops
|
|
328
|
+
a scan: a lock held by another run skips this statement, and a database found corrupt is deleted (with
|
|
329
|
+
`create`) so that this run's next write starts a new one."""
|
|
330
|
+
db = self._open(create)
|
|
331
|
+
if db is None:
|
|
332
|
+
return None
|
|
333
|
+
try:
|
|
334
|
+
return (db.executemany if many else db.execute)(sql, args).fetchall()
|
|
335
|
+
except sqlite3.Error as e:
|
|
336
|
+
if create and getattr(e, "sqlite_errorcode", None) in _UNUSABLE:
|
|
337
|
+
self.close()
|
|
338
|
+
self._remove(lambda ver: ver == CACHE_VERSION)
|
|
339
|
+
return None
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def _age(ver: int | None) -> int:
|
|
343
|
+
"""-1 for an older cache version's file (a JSON version's temporary file has no version), 0 for this one's,
|
|
344
|
+
1 for a newer one's."""
|
|
345
|
+
if ver is None or ver < CACHE_VERSION:
|
|
346
|
+
return -1
|
|
347
|
+
return 1 if ver > CACHE_VERSION else 0
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
def _rebuild(adapter: Adapter, state: dict[str, Any]) -> Session | None:
|
|
351
|
+
"""The session of an unchanged file from its row; None when the row does not fit the parser (wrong shape)."""
|
|
352
|
+
try:
|
|
353
|
+
return adapter.parser_cls.load(state).finish()
|
|
354
|
+
except Exception: # a damaged or foreign row: parse the file again, which replaces it
|
|
355
|
+
return None
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
def _resume(adapter: Adapter, state: dict[str, Any], f: BinaryIO, offset: int) -> tuple[Parser, int] | None:
|
|
359
|
+
"""The parser resumed from its row and fed the appended lines, with the new offset; None when the row does not
|
|
360
|
+
fit the parser."""
|
|
361
|
+
try:
|
|
362
|
+
parser = adapter.parser_cls.load(state)
|
|
363
|
+
return parser, _consume(f, offset, parser)
|
|
364
|
+
except Exception: # a damaged or foreign row: parse the file again from the start, which replaces it
|
|
365
|
+
return None
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
def _connect(file: Path) -> sqlite3.Connection:
|
|
369
|
+
db = sqlite3.connect(file, timeout=BUSY_TIMEOUT_S, isolation_level=None) # autocommit: one row, one transaction
|
|
370
|
+
try:
|
|
371
|
+
db.execute("PRAGMA journal_mode=WAL") # concurrent runs read while another writes
|
|
372
|
+
db.execute("PRAGMA synchronous=NORMAL")
|
|
373
|
+
db.execute("PRAGMA secure_delete=ON") # zero pruned and replaced rows: no excerpts of deleted logs linger
|
|
374
|
+
db.executescript(_SCHEMA)
|
|
375
|
+
except BaseException:
|
|
376
|
+
db.close()
|
|
377
|
+
raise
|
|
378
|
+
return db
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
def _consume(f: BinaryIO, start: int, parser: Parser) -> int:
|
|
382
|
+
"""Feed complete lines from `start`; return the offset after the last one. A torn last line is left unread."""
|
|
383
|
+
f.seek(start)
|
|
384
|
+
end = start
|
|
385
|
+
|
|
386
|
+
def lines() -> Iterator[bytes]:
|
|
387
|
+
nonlocal end
|
|
388
|
+
for raw in f:
|
|
389
|
+
if not raw.endswith(b"\n"):
|
|
390
|
+
return # partially written; read it next time
|
|
391
|
+
end += len(raw)
|
|
392
|
+
yield raw
|
|
393
|
+
|
|
394
|
+
for rec in parse_lines(lines(), parser):
|
|
395
|
+
parser.feed(rec)
|
|
396
|
+
return end
|