DR-256-backup / tools /corpus_db.py
Shangy's picture
Add files using upload-large-folder tool
42bebde verified
Raw History Blame Contribute Delete
16.3 kB
"""SQLite storage and FTS5 retrieval for the local DeepResearch-9K corpus."""
from __future__ import annotations
import hashlib
import json
import re
import sqlite3
from pathlib import Path
from typing import Any
SCHEMA = """
PRAGMA journal_mode=WAL;
PRAGMA synchronous=NORMAL;
PRAGMA busy_timeout=5000;
CREATE TABLE IF NOT EXISTS documents (
url_id TEXT PRIMARY KEY,
canonical_url TEXT NOT NULL UNIQUE,
fetch_url TEXT NOT NULL,
domain TEXT NOT NULL,
title TEXT NOT NULL DEFAULT '',
text TEXT NOT NULL DEFAULT '',
source TEXT NOT NULL DEFAULT '',
status TEXT NOT NULL DEFAULT 'pending',
http_status INTEGER,
content_type TEXT NOT NULL DEFAULT '',
content_hash TEXT NOT NULL DEFAULT '',
error TEXT NOT NULL DEFAULT '',
fetched_at TEXT NOT NULL DEFAULT '',
visit_count INTEGER NOT NULL DEFAULT 0,
metadata_json TEXT NOT NULL DEFAULT '{}'
);
CREATE TABLE IF NOT EXISTS url_aliases (
alias_url TEXT PRIMARY KEY,
url_id TEXT NOT NULL REFERENCES documents(url_id)
);
CREATE INDEX IF NOT EXISTS url_aliases_url_id_idx ON url_aliases(url_id);
CREATE TABLE IF NOT EXISTS document_qids (
url_id TEXT NOT NULL REFERENCES documents(url_id),
qid TEXT NOT NULL,
PRIMARY KEY (url_id, qid)
);
CREATE INDEX IF NOT EXISTS document_qids_qid_idx ON document_qids(qid);
CREATE TABLE IF NOT EXISTS robots_decisions (
url_id TEXT PRIMARY KEY REFERENCES documents(url_id),
target_url TEXT NOT NULL,
origin TEXT NOT NULL,
robots_url TEXT NOT NULL,
user_agent TEXT NOT NULL,
allowed INTEGER NOT NULL CHECK(allowed IN (0, 1)),
reason TEXT NOT NULL,
policy_status TEXT NOT NULL,
robots_http_status INTEGER,
robots_content_sha256 TEXT NOT NULL DEFAULT '',
robots_fetched_at TEXT NOT NULL,
checked_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS robots_decisions_origin_idx ON robots_decisions(origin);
"""
def connect(path: Path, *, readonly: bool = False) -> sqlite3.Connection:
if readonly:
connection = sqlite3.connect(f"file:{path}?mode=ro", uri=True, check_same_thread=False)
else:
path.parent.mkdir(parents=True, exist_ok=True)
connection = sqlite3.connect(path, check_same_thread=False)
connection.executescript(SCHEMA)
connection.row_factory = sqlite3.Row
return connection
def ingest_manifest(connection: sqlite3.Connection, records: list[dict[str, Any]]) -> None:
"""Checkpoint manifest metadata without overwriting fetched content."""
with connection:
for record in records:
metadata = {
"difficulties": record.get("difficulties", []),
"dataset_rows": record.get("dataset_rows", []),
"goals": record.get("goals", []),
"has_jina_reader_url": bool(record.get("has_jina_reader_url")),
}
connection.execute(
"""
INSERT INTO documents (
url_id, canonical_url, fetch_url, domain, visit_count, metadata_json
) VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT(url_id) DO UPDATE SET
canonical_url=excluded.canonical_url,
fetch_url=excluded.fetch_url,
domain=excluded.domain,
visit_count=excluded.visit_count,
metadata_json=excluded.metadata_json
""",
(
record["url_id"],
record["canonical_url"],
record.get("fetch_url") or record["canonical_url"],
record.get("domain", ""),
int(record.get("visit_count", 0)),
json.dumps(metadata, ensure_ascii=False, sort_keys=True),
),
)
aliases = set(record.get("observed_urls", []))
aliases.add(record["canonical_url"])
aliases.add(record.get("fetch_url") or record["canonical_url"])
connection.executemany(
"INSERT OR REPLACE INTO url_aliases(alias_url, url_id) VALUES (?, ?)",
((alias, record["url_id"]) for alias in aliases if alias),
)
connection.executemany(
"INSERT OR IGNORE INTO document_qids(url_id, qid) VALUES (?, ?)",
((record["url_id"], qid) for qid in record.get("qids", [])),
)
def save_fetch_result(connection: sqlite3.Connection, url_id: str, result: dict[str, Any]) -> None:
text = result.get("text", "")
content_hash = hashlib.sha256(text.encode("utf-8")).hexdigest() if text else ""
with connection:
connection.execute(
"""
UPDATE documents SET
title=?, text=?, source=?, status=?, http_status=?, content_type=?,
content_hash=?, error=?, fetched_at=?
WHERE url_id=?
""",
(
result.get("title", ""),
text,
result.get("source", ""),
result["status"],
result.get("http_status"),
result.get("content_type", ""),
content_hash,
result.get("error", ""),
result.get("fetched_at", ""),
url_id,
),
)
decision = result.get("_robots_decision")
if decision is not None:
connection.execute(
"""
INSERT INTO robots_decisions (
url_id, target_url, origin, robots_url, user_agent, allowed,
reason, policy_status, robots_http_status,
robots_content_sha256, robots_fetched_at, checked_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(url_id) DO UPDATE SET
target_url=excluded.target_url,
origin=excluded.origin,
robots_url=excluded.robots_url,
user_agent=excluded.user_agent,
allowed=excluded.allowed,
reason=excluded.reason,
policy_status=excluded.policy_status,
robots_http_status=excluded.robots_http_status,
robots_content_sha256=excluded.robots_content_sha256,
robots_fetched_at=excluded.robots_fetched_at,
checked_at=excluded.checked_at
""",
(
url_id,
decision["target_url"],
decision["origin"],
decision["robots_url"],
decision["user_agent"],
int(bool(decision["allowed"])),
decision["reason"],
decision["policy_status"],
decision.get("robots_http_status"),
decision.get("robots_content_sha256", ""),
decision["robots_fetched_at"],
decision["checked_at"],
),
)
def chunk_text(text: str, *, max_words: int = 800, overlap_words: int = 100) -> list[str]:
"""Split a document into overlapping word-bounded chunks without rewriting text."""
if max_words < 1 or overlap_words < 0 or overlap_words >= max_words:
raise ValueError("require max_words >= 1 and 0 <= overlap_words < max_words")
words = list(re.finditer(r"\S+", text))
if not words:
return []
if len(words) <= max_words:
return [text.strip()]
chunks = []
stride = max_words - overlap_words
for start in range(0, len(words), stride):
end = min(start + max_words, len(words))
chunks.append(text[words[start].start() : words[end - 1].end()].strip())
if end == len(words):
break
return chunks
def rebuild_fts(connection: sqlite3.Connection, *, max_words: int = 800, overlap_words: int = 100) -> int:
"""Atomically rebuild a chunked, exact-document-deduplicated FTS index."""
# Rank each content hash once instead of running a full-table correlated
# duplicate scan for every successful document. The latter becomes
# quadratic on a full corpus and makes every recovery-stage FTS rebuild
# unnecessarily expensive.
document_query = """
WITH ranked_documents AS (
SELECT
d.rowid AS document_rowid,
d.url_id,
d.title,
d.text,
ROW_NUMBER() OVER (
PARTITION BY d.content_hash
ORDER BY d.visit_count DESC, d.rowid ASC
) AS content_rank
FROM documents AS d
WHERE d.status='success' AND length(trim(d.text)) > 0
)
SELECT url_id, title, text
FROM ranked_documents
WHERE content_rank=1
ORDER BY document_rowid
"""
document_count = 0
chunk_count = 0
with connection:
connection.execute("DROP TABLE IF EXISTS documents_fts")
connection.execute(
"""
CREATE VIRTUAL TABLE documents_fts USING fts5(
url_id UNINDEXED,
chunk_index UNINDEXED,
title,
text,
tokenize='unicode61 remove_diacritics 2'
)
"""
)
for document in connection.execute(document_query):
chunks = chunk_text(document["text"], max_words=max_words, overlap_words=overlap_words)
if not chunks:
continue
connection.executemany(
"INSERT INTO documents_fts(url_id, chunk_index, title, text) VALUES (?, ?, ?, ?)",
(
(document["url_id"], index, document["title"] if index == 0 else "", chunk)
for index, chunk in enumerate(chunks)
),
)
document_count += 1
chunk_count += len(chunks)
connection.execute(
"""
CREATE TABLE IF NOT EXISTS corpus_index_metadata (
key TEXT PRIMARY KEY,
value INTEGER NOT NULL
)
"""
)
connection.executemany(
"INSERT OR REPLACE INTO corpus_index_metadata(key, value) VALUES (?, ?)",
(
("documents", document_count),
("chunks", chunk_count),
("max_words", max_words),
("overlap_words", overlap_words),
),
)
return document_count
def fts_exists(connection: sqlite3.Connection) -> bool:
row = connection.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='documents_fts'").fetchone()
return row is not None
def fts_counts(connection: sqlite3.Connection) -> dict[str, int]:
if not fts_exists(connection):
return {"documents": 0, "chunks": 0}
metadata_exists = connection.execute(
"SELECT 1 FROM sqlite_master WHERE type='table' AND name='corpus_index_metadata'"
).fetchone()
if metadata_exists:
values = dict(connection.execute("SELECT key, value FROM corpus_index_metadata").fetchall())
if "documents" in values and "chunks" in values:
return {"documents": int(values["documents"]), "chunks": int(values["chunks"])}
chunks = int(connection.execute("SELECT count(*) FROM documents_fts").fetchone()[0])
columns = {row[1] for row in connection.execute("PRAGMA table_info(documents_fts)")}
documents = (
int(connection.execute("SELECT count(DISTINCT url_id) FROM documents_fts").fetchone()[0])
if "chunk_index" in columns
else chunks
)
return {"documents": documents, "chunks": chunks}
def make_fts_query(query: str, max_terms: int = 32) -> str:
terms = []
seen = set()
for term in re.findall(r"[^\W_]+", query.casefold(), flags=re.UNICODE):
if len(term) <= 1 or term in seen:
continue
seen.add(term)
terms.append(term.replace('"', '""'))
if len(terms) >= max_terms:
break
if not terms:
raise ValueError("query contains no searchable terms")
return " OR ".join(f'"{term}"' for term in terms)
def search(
connection: sqlite3.Connection,
query: str,
k: int = 20,
*,
excluded_docids: set[str] | frozenset[str] | None = None,
) -> list[dict[str, Any]]:
if not fts_exists(connection):
raise RuntimeError("FTS index is missing; run build_index.py first")
match = make_fts_query(query)
excluded_docids = excluded_docids or frozenset()
results = []
seen = set()
offset = 0
batch_size = max(100, k * 10)
while len(results) < k:
rows = connection.execute(
"""
SELECT
d.url_id AS docid,
d.canonical_url AS url,
d.title AS title,
snippet(documents_fts, 3, '', '', ' ... ', 80) AS text,
-bm25(documents_fts, 0.0, 0.0, 3.0, 1.0) AS score
FROM documents_fts
JOIN documents AS d USING(url_id)
WHERE documents_fts MATCH ?
ORDER BY bm25(documents_fts, 0.0, 0.0, 3.0, 1.0)
LIMIT ? OFFSET ?
""",
(match, batch_size, offset),
).fetchall()
if not rows:
break
for row in rows:
if row["docid"] in seen or row["docid"] in excluded_docids:
continue
seen.add(row["docid"])
result = dict(row)
title = result.pop("title", "").strip()
snippet = result.get("text", "").strip()
result["text"] = f"{title}\n{snippet}".strip()
results.append(result)
if len(results) == k:
break
offset += len(rows)
return results
def search_docids(
connection: sqlite3.Connection,
query: str,
k: int = 20,
*,
excluded_docids: set[str] | frozenset[str] | None = None,
) -> list[str]:
"""Fast search path for audits that do not need expensive FTS snippets."""
if not fts_exists(connection):
raise RuntimeError("FTS index is missing; run build_index.py first")
match = make_fts_query(query)
excluded_docids = excluded_docids or frozenset()
results = []
seen = set()
offset = 0
batch_size = max(100, k * 10)
while len(results) < k:
rows = connection.execute(
"""
SELECT url_id
FROM documents_fts
WHERE documents_fts MATCH ?
ORDER BY bm25(documents_fts, 0.0, 0.0, 3.0, 1.0)
LIMIT ? OFFSET ?
""",
(match, batch_size, offset),
).fetchall()
if not rows:
break
for row in rows:
docid = str(row["url_id"])
if docid in seen or docid in excluded_docids:
continue
seen.add(docid)
results.append(docid)
if len(results) == k:
break
offset += len(rows)
return results
def open_document(
connection: sqlite3.Connection, *, docid: str | None = None, url: str | None = None
) -> dict[str, Any] | None:
if docid:
row = connection.execute(
"SELECT url_id AS docid, canonical_url AS url, title, text FROM documents WHERE url_id=? AND status='success'",
(docid,),
).fetchone()
elif url:
row = connection.execute(
"""
SELECT d.url_id AS docid, d.canonical_url AS url, d.title, d.text
FROM url_aliases AS a JOIN documents AS d USING(url_id)
WHERE a.alias_url=? AND d.status='success'
""",
(url,),
).fetchone()
if row is None:
row = connection.execute(
"SELECT url_id AS docid, canonical_url AS url, title, text FROM documents WHERE canonical_url=? AND status='success'",
(url,),
).fetchone()
else:
return None
return dict(row) if row else None
def status_counts(connection: sqlite3.Connection) -> dict[str, int]:
return {
str(row["status"]): int(row["count"])
for row in connection.execute("SELECT status, count(*) AS count FROM documents GROUP BY status")
}