cribsheet 0.23.0.dev4__py3-none-any.whl → 0.23.1.dev2__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.
- crib/app.py +5 -2
- crib/cli.py +35 -0
- crib/generate.py +78 -0
- crib/server.py +12 -5
- crib/store_duckdb.py +201 -34
- crib/store_quack.py +29 -1
- {cribsheet-0.23.0.dev4.dist-info → cribsheet-0.23.1.dev2.dist-info}/METADATA +2 -2
- {cribsheet-0.23.0.dev4.dist-info → cribsheet-0.23.1.dev2.dist-info}/RECORD +10 -10
- {cribsheet-0.23.0.dev4.dist-info → cribsheet-0.23.1.dev2.dist-info}/WHEEL +0 -0
- {cribsheet-0.23.0.dev4.dist-info → cribsheet-0.23.1.dev2.dist-info}/entry_points.txt +0 -0
crib/app.py
CHANGED
|
@@ -1870,9 +1870,12 @@ class Crib:
|
|
|
1870
1870
|
[generate] mode is "on"."""
|
|
1871
1871
|
import functools
|
|
1872
1872
|
|
|
1873
|
+
# Never inline: a query must not wait on an LLM. Changed files are
|
|
1874
|
+
# re-indexed for structure now and queued for description (the daemon's
|
|
1875
|
+
# describe queue; without one, as in a one-shot CLI, inline).
|
|
1873
1876
|
self.code.revalidate(proj, functools.partial(
|
|
1874
1877
|
self._index_code_file_tracked,
|
|
1875
|
-
describe_mode=self._background_describe("
|
|
1878
|
+
describe_mode=self._background_describe("defer")))
|
|
1876
1879
|
|
|
1877
1880
|
def _may_generate(self, background: bool) -> bool:
|
|
1878
1881
|
"""[generate] mode: "on" generates anywhere, "explicit" only for a verb
|
|
@@ -6174,7 +6177,7 @@ def _build_shared_duckdb(
|
|
|
6174
6177
|
uri = quack_uri(c.host, c.port)
|
|
6175
6178
|
|
|
6176
6179
|
def probe() -> None:
|
|
6177
|
-
QuackStore.
|
|
6180
|
+
QuackStore.ping(uri, token, ext) # up and answering; no schema work
|
|
6178
6181
|
|
|
6179
6182
|
if not c.launch:
|
|
6180
6183
|
# Externally supervised: never start (or restart) it; just attach. A
|
crib/cli.py
CHANGED
|
@@ -398,6 +398,7 @@ def _emit_status(d: Any, as_json: bool) -> None:
|
|
|
398
398
|
print(f"{'sweep':10} {proj}: {sw.get('done', 0)}/{sw.get('total', 0)} files")
|
|
399
399
|
for proj, files in (d.get("indexing") or {}).items():
|
|
400
400
|
print(f"{'indexing':10} {proj}: {', '.join(files)}")
|
|
401
|
+
_emit_daemon(d)
|
|
401
402
|
projs = d.get("projects") or []
|
|
402
403
|
print(f"{'projects':10} {len(projs)}")
|
|
403
404
|
if projs:
|
|
@@ -2456,6 +2457,40 @@ def _E_apropos(d, a):
|
|
|
2456
2457
|
_emit_apropos(d, a.json)
|
|
2457
2458
|
|
|
2458
2459
|
|
|
2460
|
+
def _emit_daemon(d: dict[str, Any]) -> None:
|
|
2461
|
+
"""status's daemon and generation state, one line per thing that is going on."""
|
|
2462
|
+
dm = d.get("daemon") or {}
|
|
2463
|
+
if dm:
|
|
2464
|
+
log = f" log {dm['log_file']}" if dm.get("log_file") else ""
|
|
2465
|
+
print(f"{'daemon':10} up {_secs(dm.get('uptime_s', 0))}{log}")
|
|
2466
|
+
for j in dm.get("background") or []:
|
|
2467
|
+
detail = f" {j['detail']}" if j.get("detail") else ""
|
|
2468
|
+
print(f"{'running':10} {j['job']} for {_secs(j.get('running_s', 0))}{detail}")
|
|
2469
|
+
queued = {k: v for k, v in (dm.get("queues") or {}).items() if v}
|
|
2470
|
+
if queued:
|
|
2471
|
+
print(f"{'queued':10} " + ", ".join(f"{k.replace('_', ' ')} {v}"
|
|
2472
|
+
for k, v in queued.items()))
|
|
2473
|
+
notes = (dm.get("watchers") or {}).get("notes") or {}
|
|
2474
|
+
if notes.get("state") and notes["state"] != "healthy":
|
|
2475
|
+
lat = (f" ({notes['last_latency_s']}s)"
|
|
2476
|
+
if notes.get("last_latency_s") is not None else "")
|
|
2477
|
+
print(f"{'watching':10} {notes['state']}{lat}: reads still refresh; a "
|
|
2478
|
+
f"catch-up sweep runs while degraded")
|
|
2479
|
+
gen = d.get("generation") or {}
|
|
2480
|
+
if gen:
|
|
2481
|
+
pending = gen.get("pending_descriptions") or {}
|
|
2482
|
+
waiting = (": descriptions waiting in "
|
|
2483
|
+
+ ", ".join(f"{p} {n}" for p, n in pending.items())
|
|
2484
|
+
if pending else "")
|
|
2485
|
+
print(f"{'generate':10} {gen.get('mode', '?')}{waiting}")
|
|
2486
|
+
|
|
2487
|
+
|
|
2488
|
+
def _secs(s: float) -> str:
|
|
2489
|
+
s = int(s)
|
|
2490
|
+
return f"{s // 3600}h{s % 3600 // 60:02d}m" if s >= 3600 else (
|
|
2491
|
+
f"{s // 60}m{s % 60:02d}s" if s >= 60 else f"{s}s")
|
|
2492
|
+
|
|
2493
|
+
|
|
2459
2494
|
def _E_status(d, a):
|
|
2460
2495
|
_emit_status(d, a.json)
|
|
2461
2496
|
|
crib/generate.py
CHANGED
|
@@ -140,8 +140,72 @@ def _with_timeout(provider: Any, timeout: float | None) -> Any:
|
|
|
140
140
|
return dataclasses.replace(provider, timeout=float(timeout))
|
|
141
141
|
|
|
142
142
|
|
|
143
|
+
# Every generation call runs on ONE bounded pool of its own, under crib's own
|
|
144
|
+
# deadline: a provider call whose cancellation never unwinds (a CLI that never
|
|
145
|
+
# answers) can then hold a generation thread, never the threads tool calls and
|
|
146
|
+
# store work run on. Sized from [generate] concurrency on first use.
|
|
147
|
+
_POOL: Any = None
|
|
148
|
+
_POOL_LOCK = threading.Lock()
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _pool(cfg: GenerateConfig) -> Any:
|
|
152
|
+
global _POOL
|
|
153
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
154
|
+
|
|
155
|
+
with _POOL_LOCK:
|
|
156
|
+
if _POOL is None:
|
|
157
|
+
_POOL = ThreadPoolExecutor(
|
|
158
|
+
max_workers=max(2, int(getattr(cfg, "concurrency", 6) or 6)),
|
|
159
|
+
thread_name_prefix="crib-generate")
|
|
160
|
+
return _POOL
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def deadline_s(cfg: GenerateConfig) -> float:
|
|
164
|
+
"""How long a caller waits for one generation call: past the provider's own
|
|
165
|
+
timeout (llmkit's), so that one normally fires first, with room for its
|
|
166
|
+
retries; crib's backstop when it doesn't."""
|
|
167
|
+
return float(cfg.timeout or 90.0) * 1.5 + 30.0
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _bounded(cfg: GenerateConfig, purpose: str, fn: Any, *args: Any, **kw: Any) -> Any:
|
|
171
|
+
"""`fn(*args, **kw)` on the generation pool, waited on for at most
|
|
172
|
+
`deadline_s`. While it runs it is listed in `status` (a background job
|
|
173
|
+
named for its purpose), so a stuck call is visible; past the deadline the
|
|
174
|
+
caller gets a GenerationError and the call is left to finish (or not) on
|
|
175
|
+
its own thread."""
|
|
176
|
+
from concurrent.futures import TimeoutError as FutureTimeout
|
|
177
|
+
|
|
178
|
+
from .diag import DIAG
|
|
179
|
+
|
|
180
|
+
def run() -> Any:
|
|
181
|
+
token = DIAG.job(f"generation ({purpose})")
|
|
182
|
+
try:
|
|
183
|
+
return fn(*args, **kw)
|
|
184
|
+
finally:
|
|
185
|
+
DIAG.done(token)
|
|
186
|
+
|
|
187
|
+
fut = _pool(cfg).submit(run)
|
|
188
|
+
limit = deadline_s(cfg)
|
|
189
|
+
try:
|
|
190
|
+
return fut.result(timeout=limit)
|
|
191
|
+
except FutureTimeout:
|
|
192
|
+
fut.cancel() # still queued: never starts
|
|
193
|
+
raise GenerationError(
|
|
194
|
+
f"no reply from the {purpose!r} provider in {limit:.0f}s; the call was "
|
|
195
|
+
f"abandoned (the code's structure is saved, its description waits)"
|
|
196
|
+
) from None
|
|
197
|
+
|
|
198
|
+
|
|
143
199
|
def generate(
|
|
144
200
|
cfg: GenerateConfig, system: str, user: str, purpose: str = "distill"
|
|
201
|
+
) -> str:
|
|
202
|
+
"""Run one chat turn on the generation pool (see `_bounded`); return the
|
|
203
|
+
content stream as a stripped string."""
|
|
204
|
+
return _bounded(cfg, purpose, _generate, cfg, system, user, purpose)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def _generate(
|
|
208
|
+
cfg: GenerateConfig, system: str, user: str, purpose: str = "distill"
|
|
145
209
|
) -> str:
|
|
146
210
|
"""Run one chat turn; return the content stream as a stripped string.
|
|
147
211
|
|
|
@@ -193,6 +257,20 @@ def generate_structured(
|
|
|
193
257
|
purpose: str = "elaborate",
|
|
194
258
|
schema_name: str = "emit",
|
|
195
259
|
schema_description: str = "",
|
|
260
|
+
) -> object:
|
|
261
|
+
"""`_generate_structured` on the generation pool (see `_bounded`)."""
|
|
262
|
+
return _bounded(cfg, purpose, _generate_structured, cfg, system, user, schema,
|
|
263
|
+
purpose, schema_name, schema_description)
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def _generate_structured(
|
|
267
|
+
cfg: GenerateConfig,
|
|
268
|
+
system: str,
|
|
269
|
+
user: str,
|
|
270
|
+
schema: dict,
|
|
271
|
+
purpose: str = "elaborate",
|
|
272
|
+
schema_name: str = "emit",
|
|
273
|
+
schema_description: str = "",
|
|
196
274
|
) -> object:
|
|
197
275
|
"""Run one chat turn constrained to ``schema`` (JSON Schema); return the parsed
|
|
198
276
|
object. Adapters enforce the schema natively (anthropic forced tool-use,
|
crib/server.py
CHANGED
|
@@ -2430,13 +2430,20 @@ async def _serve_async(
|
|
|
2430
2430
|
) -> None:
|
|
2431
2431
|
from crib.diag import DIAG, install_log
|
|
2432
2432
|
|
|
2433
|
-
crib = Crib.open()
|
|
2434
2433
|
if transport != "stdio":
|
|
2435
|
-
# The daemon: sharedserver keeps no log of its stderr, so crib does
|
|
2436
|
-
|
|
2434
|
+
# The daemon: sharedserver keeps no log of its stderr, so crib does —
|
|
2435
|
+
# started BEFORE the store opens, so a hang there leaves a trace.
|
|
2436
|
+
from crib.config import Config
|
|
2437
|
+
from crib.paths import Paths
|
|
2438
|
+
|
|
2439
|
+
paths = Paths.resolve()
|
|
2440
|
+
daemon_cfg = Config.load(paths.config_file).daemon
|
|
2441
|
+
log = daemon_cfg.log_file
|
|
2437
2442
|
if log:
|
|
2438
|
-
path =
|
|
2439
|
-
install_log(path.expanduser(),
|
|
2443
|
+
path = paths.index_dir / "daemon.log" if log == "auto" else Path(log)
|
|
2444
|
+
install_log(path.expanduser(), daemon_cfg.log_max_mb * 1024 * 1024)
|
|
2445
|
+
DIAG.milestone("opening the store")
|
|
2446
|
+
crib = Crib.open()
|
|
2440
2447
|
from crib import __version__
|
|
2441
2448
|
|
|
2442
2449
|
DIAG.milestone("store ready", store=type(crib.store).__name__, version=__version__)
|
crib/store_duckdb.py
CHANGED
|
@@ -25,6 +25,7 @@ import contextlib
|
|
|
25
25
|
import json
|
|
26
26
|
import random
|
|
27
27
|
import re
|
|
28
|
+
import sys
|
|
28
29
|
import threading
|
|
29
30
|
import time
|
|
30
31
|
from collections.abc import Callable, Iterator, Sequence
|
|
@@ -52,6 +53,11 @@ EMBED_CACHE = "crib_embed_cache"
|
|
|
52
53
|
# when any table's layout changes; a mismatch drops every crib table, since all
|
|
53
54
|
# of them are rebuildable) and embed_model (which embedder wrote crib_chunks; see `Crib._maybe_recreate_for_dim`).
|
|
54
55
|
META = "crib_meta"
|
|
56
|
+
# Kept when the schema version changes: rows keyed by what they are (model and
|
|
57
|
+
# text; purpose and target), not by any layout of the other tables.
|
|
58
|
+
_KEPT_ACROSS_VERSIONS = (EMBED_CACHE, LEDGER, META)
|
|
59
|
+
# How long a conversion waits out other connections' conflicting writes.
|
|
60
|
+
MIGRATION_WAIT_S = 120.0
|
|
55
61
|
# 2: crib_chunks' `store` column is `kind`; 3: crib_items and the facet tables;
|
|
56
62
|
# 4: crib_chunks' `item_id` column (the item a chunk belongs to); 5: crib_edges;
|
|
57
63
|
# 6: crib_postings; 7: crib_files and crib_items.embed_text; 8: the symbol
|
|
@@ -137,6 +143,43 @@ def _lock_error(path: Path, exc: Exception) -> CribUserError:
|
|
|
137
143
|
)
|
|
138
144
|
|
|
139
145
|
|
|
146
|
+
# What DuckDB says about a file it cannot use AS a database (as opposed to one it
|
|
147
|
+
# can't reach: a lock, a permission), matched case-insensitively.
|
|
148
|
+
_UNREADABLE = ("corrupt", "checksum", "not a valid", "invalid database",
|
|
149
|
+
"serializ", "storage version", "magic bytes")
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _unreadable(exc: BaseException) -> bool:
|
|
153
|
+
"""Is `exc` DuckDB saying the file itself is unusable (so it can be set
|
|
154
|
+
aside and rebuilt), rather than that it is locked or not permitted?"""
|
|
155
|
+
import duckdb # lazy
|
|
156
|
+
|
|
157
|
+
if not isinstance(exc, duckdb.Error):
|
|
158
|
+
return False
|
|
159
|
+
msg = str(exc).lower()
|
|
160
|
+
if "lock" in msg or "permission" in msg:
|
|
161
|
+
return False
|
|
162
|
+
return isinstance(exc, (duckdb.SerializationException, duckdb.InternalException)) or any(
|
|
163
|
+
w in msg for w in _UNREADABLE)
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def set_aside(path: Path, why: BaseException) -> Path:
|
|
167
|
+
"""Move an unusable store file (and its WAL) out of the way, keeping it as
|
|
168
|
+
`<name>.broken-<stamp>`: the store is a cache rebuilt from the files, so a
|
|
169
|
+
fresh one costs a rebuild, and the old one stays for inspection."""
|
|
170
|
+
stamp = time.strftime("%Y%m%d-%H%M%S")
|
|
171
|
+
kept = path.with_name(f"{path.name}.broken-{stamp}")
|
|
172
|
+
for p, dest in ((path, kept),
|
|
173
|
+
(path.with_name(path.name + ".wal"),
|
|
174
|
+
path.with_name(f"{path.name}.wal.broken-{stamp}"))):
|
|
175
|
+
if p.exists():
|
|
176
|
+
p.rename(dest)
|
|
177
|
+
print(f"[crib] the DuckDB store {path} could not be opened ({why}); it was moved "
|
|
178
|
+
f"to {kept} and a fresh store is being built from your files",
|
|
179
|
+
file=sys.stderr)
|
|
180
|
+
return kept
|
|
181
|
+
|
|
182
|
+
|
|
140
183
|
def _json_path(key: str) -> str:
|
|
141
184
|
"""A JSON path naming `key` exactly, whatever characters it contains."""
|
|
142
185
|
return "$." + json.dumps(key)
|
|
@@ -475,6 +518,44 @@ def _set_meta_step(
|
|
|
475
518
|
return write
|
|
476
519
|
|
|
477
520
|
|
|
521
|
+
@contextlib.contextmanager
|
|
522
|
+
def _migration_lock(path: Path | None) -> Iterator[None]:
|
|
523
|
+
"""Exclusive, machine-wide: one crib process converts the store at a time
|
|
524
|
+
(every crib process on a machine shares the store's directory; the shared
|
|
525
|
+
server is loopback-only). No path (an in-memory store): no lock needed."""
|
|
526
|
+
if path is None:
|
|
527
|
+
yield
|
|
528
|
+
return
|
|
529
|
+
import fcntl
|
|
530
|
+
|
|
531
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
532
|
+
with open(path, "a") as f:
|
|
533
|
+
said = False
|
|
534
|
+
while True:
|
|
535
|
+
try:
|
|
536
|
+
fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
537
|
+
break
|
|
538
|
+
except BlockingIOError:
|
|
539
|
+
if not said:
|
|
540
|
+
print("[crib] waiting for another crib process to finish "
|
|
541
|
+
"converting the store", file=sys.stderr)
|
|
542
|
+
said = True
|
|
543
|
+
time.sleep(0.5)
|
|
544
|
+
try:
|
|
545
|
+
yield
|
|
546
|
+
finally:
|
|
547
|
+
fcntl.flock(f, fcntl.LOCK_UN)
|
|
548
|
+
|
|
549
|
+
|
|
550
|
+
def _backfill_pending(store: "DuckDBStore", ex: Any) -> bool:
|
|
551
|
+
if store._table_dim(ex) is None:
|
|
552
|
+
return False
|
|
553
|
+
# pi-lens-ignore: python-sql-injection
|
|
554
|
+
return bool(ex.run(
|
|
555
|
+
f"SELECT 1 FROM {TABLE} WHERE json_type(meta, '$.tags') = 'VARCHAR' "
|
|
556
|
+
"AND json_type(meta, '$.labels') IS NULL LIMIT 1"))
|
|
557
|
+
|
|
558
|
+
|
|
478
559
|
def _backfill_labels(store: "DuckDBStore", ex: Any) -> None:
|
|
479
560
|
"""Chunks written before 0.22.0 kept `tags` as a comma-joined string and had
|
|
480
561
|
no `labels` list, so a `tags=` lookup (which filters on `labels` in the
|
|
@@ -522,13 +603,30 @@ class DuckDBStore:
|
|
|
522
603
|
|
|
523
604
|
path = Path(path)
|
|
524
605
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
606
|
+
|
|
607
|
+
def connect() -> Any:
|
|
608
|
+
try:
|
|
609
|
+
return duckdb.connect(str(path), config=local_dirs(path.parent))
|
|
610
|
+
except duckdb.IOException as exc:
|
|
611
|
+
if "lock" in str(exc).lower():
|
|
612
|
+
raise _lock_error(path, exc) from exc
|
|
613
|
+
raise
|
|
614
|
+
|
|
615
|
+
try:
|
|
616
|
+
conn = connect()
|
|
617
|
+
except duckdb.Error as exc:
|
|
618
|
+
if not _unreadable(exc):
|
|
619
|
+
raise
|
|
620
|
+
set_aside(path, exc)
|
|
621
|
+
conn = connect()
|
|
525
622
|
try:
|
|
526
|
-
|
|
527
|
-
except duckdb.
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
623
|
+
return cls(conn, path)
|
|
624
|
+
except duckdb.Error as exc: # opened, but its contents can't be used
|
|
625
|
+
conn.close()
|
|
626
|
+
if not _unreadable(exc):
|
|
627
|
+
raise
|
|
628
|
+
set_aside(path, exc)
|
|
629
|
+
return cls(connect(), path)
|
|
532
630
|
|
|
533
631
|
def close(self) -> None:
|
|
534
632
|
with self._write: # never close under a writer mid-transaction
|
|
@@ -547,35 +645,104 @@ class DuckDBStore:
|
|
|
547
645
|
# ── schema ───────────────────────────────────────────────────────────────
|
|
548
646
|
|
|
549
647
|
def _prepare(self) -> None:
|
|
550
|
-
"""
|
|
551
|
-
|
|
552
|
-
A
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
648
|
+
"""Bring the file to this version's layout, once at open — safely.
|
|
649
|
+
|
|
650
|
+
A normal open WRITES NOTHING: `_schema_current` reads the version, the
|
|
651
|
+
tables and what is pending, and when nothing needs doing that is the
|
|
652
|
+
end of it, so an open can't conflict with the store's other users.
|
|
653
|
+
Only a real change (a new file, a version change, a retired table, a
|
|
654
|
+
backfill) writes, and then:
|
|
655
|
+
|
|
656
|
+
- under a machine-wide lock beside the store (`_migration_lock`), so
|
|
657
|
+
one crib process converts and the rest wait and find it done;
|
|
658
|
+
- as ONE transaction, with the version stamped in it, so a conversion
|
|
659
|
+
is all there or not at all, whatever kills the process;
|
|
660
|
+
- retried while another connection's writes conflict with it, for up
|
|
661
|
+
to MIGRATION_WAIT_S, then refused with what to do, rather than spun
|
|
662
|
+
on silently.
|
|
663
|
+
|
|
664
|
+
A different schema_version drops the rebuildable tables, but keeps the
|
|
665
|
+
embedding cache and the generation ledger: their rows are keyed by
|
|
666
|
+
model and text (by purpose and target), not by any layout, so a
|
|
667
|
+
conversion never costs re-embedding or re-generating everything. A
|
|
668
|
+
file from before crib_meta existed is adopted as version 1."""
|
|
669
|
+
if self._schema_current():
|
|
670
|
+
return
|
|
671
|
+
with _migration_lock(self._migration_lock_path()):
|
|
672
|
+
if self._schema_current():
|
|
673
|
+
return # another process converted it while we waited
|
|
674
|
+
self._converting(self._prepare_step)
|
|
675
|
+
|
|
676
|
+
def _prepare_step(self, ex: Any) -> None:
|
|
677
|
+
ex.run(
|
|
678
|
+
f"CREATE TABLE IF NOT EXISTS {META} (key VARCHAR PRIMARY KEY, value VARCHAR)"
|
|
679
|
+
)
|
|
680
|
+
meta = dict(ex.run(f"SELECT key, value FROM {META}"))
|
|
681
|
+
if meta.get("schema_version", SCHEMA_VERSION) != SCHEMA_VERSION:
|
|
682
|
+
for table in (TABLE, *_FIXED_TABLES):
|
|
683
|
+
if table not in _KEPT_ACROSS_VERSIONS:
|
|
564
684
|
ex.run(f"DROP TABLE IF EXISTS {table}")
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
685
|
+
ex.run(f"DELETE FROM {META}")
|
|
686
|
+
meta = {}
|
|
687
|
+
for table in _RETIRED_TABLES:
|
|
688
|
+
ex.run(f"DROP TABLE IF EXISTS {table}")
|
|
689
|
+
for key in _RETIRED_META:
|
|
690
|
+
if key in meta:
|
|
691
|
+
ex.run(f"DELETE FROM {META} WHERE key = ?", [key])
|
|
692
|
+
for table, columns in _FIXED_TABLES.items():
|
|
693
|
+
ex.run(f"CREATE TABLE IF NOT EXISTS {table} ({columns})")
|
|
694
|
+
if meta.get("schema_version") != SCHEMA_VERSION:
|
|
695
|
+
_put_meta(ex, "schema_version", SCHEMA_VERSION)
|
|
696
|
+
_backfill_labels(self, ex)
|
|
697
|
+
|
|
698
|
+
def _schema_current(self) -> bool:
|
|
699
|
+
"""Read-only: is the file already this version's layout, with nothing
|
|
700
|
+
to retire or backfill? (A file that can't even be read is not.)"""
|
|
701
|
+
try:
|
|
702
|
+
with self._reading() as ex:
|
|
703
|
+
tables = {t for (t,) in ex.run(
|
|
704
|
+
"SELECT table_name FROM duckdb_tables() WHERE schema_name = 'main'")}
|
|
705
|
+
if META not in tables:
|
|
706
|
+
return False
|
|
707
|
+
meta = dict(ex.run(f"SELECT key, value FROM {META}"))
|
|
708
|
+
if (meta.get("schema_version") != SCHEMA_VERSION
|
|
709
|
+
or any(t not in tables for t in _FIXED_TABLES)
|
|
710
|
+
or any(t in tables for t in _RETIRED_TABLES)
|
|
711
|
+
or any(k in meta for k in _RETIRED_META)):
|
|
712
|
+
return False
|
|
713
|
+
return not _backfill_pending(self, ex)
|
|
714
|
+
except Exception: # noqa: BLE001 — anything odd: take the careful path
|
|
715
|
+
return False
|
|
716
|
+
|
|
717
|
+
def _migration_lock_path(self) -> Path | None:
|
|
718
|
+
return self._path.with_name(self._path.name + ".migrate.lock") if self._path else None
|
|
719
|
+
|
|
720
|
+
def _converting(self, body: Callable[[Any], None]) -> None:
|
|
721
|
+
"""`_transaction(body)`, kept trying while other connections' writes
|
|
722
|
+
conflict with it (they are the store's users finishing their work),
|
|
723
|
+
up to MIGRATION_WAIT_S; then a clear refusal."""
|
|
724
|
+
import duckdb # lazy
|
|
725
|
+
|
|
726
|
+
deadline = time.monotonic() + MIGRATION_WAIT_S
|
|
727
|
+
said = False
|
|
728
|
+
while True:
|
|
729
|
+
try:
|
|
730
|
+
self._transaction(body)
|
|
731
|
+
return
|
|
732
|
+
except duckdb.TransactionException as e:
|
|
733
|
+
if time.monotonic() >= deadline:
|
|
734
|
+
raise CribUserError(
|
|
735
|
+
"crib could not convert its DuckDB store to this version: "
|
|
736
|
+
f"another connection kept writing for {MIGRATION_WAIT_S:.0f}s "
|
|
737
|
+
f"({e}). Stop every crib process (and the crib DuckDB server), "
|
|
738
|
+
"then start one; the store is a cache, so moving its file "
|
|
739
|
+
"aside is also safe (it is rebuilt from your notes)"
|
|
740
|
+
) from e
|
|
741
|
+
if not said:
|
|
742
|
+
print("[crib] store conversion is waiting for another connection's "
|
|
743
|
+
"writes to finish", file=sys.stderr)
|
|
744
|
+
said = True
|
|
745
|
+
time.sleep(1.0)
|
|
579
746
|
|
|
580
747
|
def checkpoint(self) -> None:
|
|
581
748
|
"""Write the WAL into the database file (DuckDB's CHECKPOINT)."""
|
crib/store_quack.py
CHANGED
|
@@ -267,6 +267,26 @@ class QuackStore(DuckDBStore):
|
|
|
267
267
|
conn, remote = _open_session(uri, token, extension_directory)
|
|
268
268
|
return cls(conn, remote, uri, token, extension_directory, relaunch)
|
|
269
269
|
|
|
270
|
+
@staticmethod
|
|
271
|
+
def ping(uri: str, token: str, extension_directory: Path | str | None = None) -> None:
|
|
272
|
+
"""Is the server up and accepting this token? One session and a
|
|
273
|
+
`SELECT 1`, nothing else: readiness must never wait on the schema
|
|
274
|
+
work a real `connect` does (a busy store is still a ready server)."""
|
|
275
|
+
conn, remote = _open_session(uri, token, extension_directory)
|
|
276
|
+
try:
|
|
277
|
+
remote.execute("SELECT 1").fetchall()
|
|
278
|
+
finally:
|
|
279
|
+
conn.close()
|
|
280
|
+
|
|
281
|
+
def _migration_lock_path(self) -> Path | None:
|
|
282
|
+
# The server is loopback-only, so every client is on this machine and
|
|
283
|
+
# shares crib's DuckDB directory: lock beside the store file there.
|
|
284
|
+
from .paths import Paths
|
|
285
|
+
|
|
286
|
+
base = (Path(self._ext).parent if self._ext
|
|
287
|
+
else Paths.resolve().duckdb_extension_dir.parent)
|
|
288
|
+
return base / "crib.duckdb.migrate.lock"
|
|
289
|
+
|
|
270
290
|
@contextlib.contextmanager
|
|
271
291
|
def _reading(self) -> Iterator[Any]:
|
|
272
292
|
with self._session:
|
|
@@ -513,9 +533,17 @@ def serve(
|
|
|
513
533
|
import duckdb # lazy
|
|
514
534
|
|
|
515
535
|
check_shared_bind(host)
|
|
536
|
+
from .store_duckdb import _unreadable, set_aside
|
|
537
|
+
|
|
516
538
|
db_path = Path(db_path)
|
|
517
539
|
db_path.parent.mkdir(parents=True, exist_ok=True)
|
|
518
|
-
|
|
540
|
+
try:
|
|
541
|
+
conn = duckdb.connect(str(db_path), config=_connect_config(extension_directory))
|
|
542
|
+
except duckdb.Error as exc:
|
|
543
|
+
if not _unreadable(exc):
|
|
544
|
+
raise
|
|
545
|
+
set_aside(db_path, exc) # a cache: rebuilt by the clients, old file kept
|
|
546
|
+
conn = duckdb.connect(str(db_path), config=_connect_config(extension_directory))
|
|
519
547
|
_install_quack(conn)
|
|
520
548
|
uri = quack_uri(host, port)
|
|
521
549
|
conn.execute(f"CALL quack_serve({to_literal(uri)}, token = {to_literal(token)})")
|
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: cribsheet
|
|
3
|
-
Version: 0.23.
|
|
3
|
+
Version: 0.23.1-dev2
|
|
4
4
|
Summary: Local MCP server: markdown memory with a DuckDB embedding index
|
|
5
5
|
Requires-Python: >=3.13
|
|
6
6
|
Requires-Dist: duckdb<3,>=2.0
|
|
7
7
|
Requires-Dist: fastembed>=0.3
|
|
8
8
|
Requires-Dist: fastmcp<5,>=4.1.5
|
|
9
9
|
Requires-Dist: numpy>=2
|
|
10
|
-
Requires-Dist: polyllmkit[all,md]>=0.2.
|
|
10
|
+
Requires-Dist: polyllmkit[all,md]>=0.2.3
|
|
11
11
|
Requires-Dist: pyyaml>=6.0
|
|
12
12
|
Requires-Dist: watchdog>=4.0
|
|
13
13
|
Provides-Extra: st
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
crib/__init__.py,sha256=KzW14Xf3xyTCrmhsSbcFleJVCU6u6-WFidcrLB4YZSw,1001
|
|
2
2
|
crib/__main__.py,sha256=umIc03A2oA7s2oiL80Ts_QnS-0zj9fjV3IQ103AmNXg,232
|
|
3
|
-
crib/app.py,sha256=
|
|
3
|
+
crib/app.py,sha256=60qpOv41aT46B-VSlYmwXEfFmNJZnLQkYxkld-l345w,286429
|
|
4
4
|
crib/chunk.py,sha256=ICh4fmpxViXAIKDVNTbbO9-5bT6wWNPTsPUUNs8uwtg,15129
|
|
5
5
|
crib/claudemem.py,sha256=Xf4mVgTFbXHdhhqteTIRz2zirc4irf0wim8AeMybudI,4804
|
|
6
|
-
crib/cli.py,sha256=
|
|
6
|
+
crib/cli.py,sha256=heJBqbqX_qCjssEioANlU0i_xdxc068lBMtqlCCEF0Q,150548
|
|
7
7
|
crib/client.py,sha256=-PRVFFLjbI-D-libZ_wMdDFdcXkyHmc9AYikzxd9PmI,6605
|
|
8
8
|
crib/codeindex.py,sha256=HYavhLOEieD62iNQasC__kAaMEN6ld1uP2oHmoJjyEI,89916
|
|
9
9
|
crib/codeindexer.py,sha256=-eocU6ThZdNJar-cGaNJUgB5b6fd21QsjIRx56UFy-I,36737
|
|
@@ -19,7 +19,7 @@ crib/embedcache.py,sha256=x-4lV90Sw9jzbJWQ6NuxLULixKhFNr34owy9U8jLBXs,4896
|
|
|
19
19
|
crib/enrichments.py,sha256=R99rCJxGsiCVx2YgJuzogo80ZgjKTJnyjkO2TBNxq1A,6142
|
|
20
20
|
crib/errors.py,sha256=OBCUWM1vH1zbZUPB7DhAkOydBQFYYfSWsCC83XRbDeo,1363
|
|
21
21
|
crib/filesync.py,sha256=H8n2gf3HqSBf5ezW7oQWG7RrwchqLmL0kWzomVw91MY,3739
|
|
22
|
-
crib/generate.py,sha256=
|
|
22
|
+
crib/generate.py,sha256=lDvqbUOkEoPm2nAR5UxDqq38hLG9FNZGvqbM5GgOiZ0,15448
|
|
23
23
|
crib/genledger.py,sha256=cgHo3ucf1gFU8b42PApfEI2Rhh5oo-66AciTr0zuI6U,7450
|
|
24
24
|
crib/gensetup.py,sha256=rXOVBMrvr-TlHsjOXRhXKHH0Xd5DaPzAeAQGJT23mbY,17572
|
|
25
25
|
crib/gitbacking.py,sha256=soVFzumWDQ7QMhn_qBZeP5wtzdofTLrNdmz8Zh4tQMU,25249
|
|
@@ -38,20 +38,20 @@ crib/refs.py,sha256=Rp-1WSs7tTYY0jvdkIfpZVCN7gJVVOrceyB77vZ46vg,13341
|
|
|
38
38
|
crib/related.py,sha256=KH3MwE-CiISq3Ro5MfklG88anylPBEtLdypsA885Pvc,3907
|
|
39
39
|
crib/retrieve.py,sha256=S8b8lEOthfprCRTfSetTZFbDH0B65Iv0nKzcFG-U83c,27140
|
|
40
40
|
crib/section_index.py,sha256=nhFEZQBjlfV9y5fpB39Rp5RPFHLnp2nhZbAG8S7fUNg,8846
|
|
41
|
-
crib/server.py,sha256=
|
|
41
|
+
crib/server.py,sha256=E8wRNN9zKBRi9Z80-CqIVeKuZy1Rt6bZfjaqTiuJd78,126219
|
|
42
42
|
crib/session.py,sha256=HMF_6n6ZIPY3p8mRJfMJ75iByKOoPIUvUJST1r8sSOQ,13631
|
|
43
43
|
crib/sharedserver.py,sha256=KtCBTQaw_LhaY93ICY5ILI5t3fj5kzXAROb7cI_4-8k,2135
|
|
44
44
|
crib/sources.py,sha256=ZMCKYixRyV_MSrcFkYq5WUt-haEwWBxCMtDZBgKigBI,2918
|
|
45
45
|
crib/store.py,sha256=mqOqkiba4ZayOe-eVXM-6KYy80Xm7fTan3GupTwtCj4,20659
|
|
46
|
-
crib/store_duckdb.py,sha256=
|
|
47
|
-
crib/store_quack.py,sha256=
|
|
46
|
+
crib/store_duckdb.py,sha256=Dk0ajqpb4grHbhnad5J0Yo3VkwID04ST_sl_7SMXe60,60482
|
|
47
|
+
crib/store_quack.py,sha256=5Ve_kjNUbau1cKYiMkPcNQLyoT05yXqwMWr2dpRKk5g,26711
|
|
48
48
|
crib/symbols.py,sha256=A3sRq1tdPtBhNUGLX9RfQQx2bEnUnC8IBtn4YLIKqzE,27427
|
|
49
49
|
crib/symconvert.py,sha256=StCH_0SrS9ZaHUZEsSKPq3-lV4-kH5Lk01SzY627VPs,3149
|
|
50
50
|
crib/tomlrec.py,sha256=ptDbYNhTLmXQeN1BrQGcy2E4wNv0hpKM7aayQ7WvkxE,3796
|
|
51
51
|
crib/util.py,sha256=EmDszxT0SIjIkgcppD6pDJxbkp3eU-7blYRwri5b_m4,3282
|
|
52
52
|
crib/versions.py,sha256=P517DveKCh2jKb3o5IOxkzki8ddwmc-QeuiYMvsBb88,3646
|
|
53
53
|
crib/watch.py,sha256=29Vt-QxheleVT8RuQHsz-ptILHZKurc9zz7fqV99htw,33826
|
|
54
|
-
cribsheet-0.23.
|
|
55
|
-
cribsheet-0.23.
|
|
56
|
-
cribsheet-0.23.
|
|
57
|
-
cribsheet-0.23.
|
|
54
|
+
cribsheet-0.23.1.dev2.dist-info/METADATA,sha256=nmlhAcMIOhmEQIWGCFv5RQOPblRlcYZdRrZzOBVtayk,20614
|
|
55
|
+
cribsheet-0.23.1.dev2.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
56
|
+
cribsheet-0.23.1.dev2.dist-info/entry_points.txt,sha256=CjLxgcZdPGI6U4VRZmrwQ2kL1gUkNykYNkLzT8EQkfQ,39
|
|
57
|
+
cribsheet-0.23.1.dev2.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|