1196 lines
50 KiB
Python
1196 lines
50 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
hyperstitionstud_io.db.sqlite_meta — Standalone SQLite + FTS5 Catalog & REST/MCP Telemetry DB (`hs-db-build`).
|
|
|
|
Provides:
|
|
1. Read-Only Catalog & FTS5 Index DB (`hyperstition-catalog.db`):
|
|
Indexes `registry_manifests`, `glossary_entries`, `kg_nodes`, `kg_edges`, `dossiers`,
|
|
`archive_equations`, `quant_timeseries_bars`, and `fts_catalog` (`FTS5 BM25`).
|
|
2. WAL Runtime REST/MCP API Metadata & Telemetry DB (`api-telemetry.db`):
|
|
Automatically populated on every `/api/v1/*` REST API call (`dispatch_rest_v1`) and
|
|
`/mcp` JSON-RPC call (`dispatch_jsonrpc`) with zero PII.
|
|
3. Quiescent Truncation & `logrotate.d` Integration:
|
|
Truncates `api-telemetry.db` at a configurable size threshold (default `100 MB`) using
|
|
`BEGIN EXCLUSIVE` + table purge + `PRAGMA wal_checkpoint(TRUNCATE)` + `VACUUM` +
|
|
`PRAGMA integrity_check` so in-flight SQLite readers/writers quiesce cleanly without
|
|
corrupting the database header or WAL frames.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import datetime as dt
|
|
import gzip
|
|
import hashlib
|
|
import json
|
|
import os
|
|
import re
|
|
import sqlite3
|
|
import subprocess
|
|
import sys
|
|
from pathlib import Path
|
|
from typing import Any
|
|
|
|
_SRC_DIR = Path(__file__).resolve().parents[2]
|
|
if _SRC_DIR.is_dir() and str(_SRC_DIR) not in sys.path:
|
|
sys.path.insert(0, str(_SRC_DIR))
|
|
|
|
from hyperstitionstud_io import __version__ as CURRENT_VERSION # noqa: E402
|
|
from hyperstitionstud_io.config import load_workspace_config # noqa: E402
|
|
from hyperstitionstud_io.glossary import ReadOnlyIsolationGuard # noqa: E402
|
|
from hyperstitionstud_io.ipld import compute_dag_json_cidv1 # noqa: E402
|
|
from hyperstitionstud_io.quant.timeseries import build_quant_timeseries_bundle # noqa: E402
|
|
|
|
DEFAULT_MAX_TELEMETRY_MB = 100
|
|
DEFAULT_MAX_TELEMETRY_BYTES = DEFAULT_MAX_TELEMETRY_MB * 1024 * 1024 # 104,857,600 bytes (100 MB)
|
|
|
|
CATALOG_SCHEMA_SQL = """
|
|
CREATE TABLE IF NOT EXISTS registry_manifests (
|
|
registry_slug TEXT PRIMARY KEY,
|
|
source_path TEXT NOT NULL,
|
|
schema_urn TEXT NOT NULL,
|
|
version TEXT NOT NULL,
|
|
record_count INTEGER NOT NULL,
|
|
raw_sha256 TEXT NOT NULL,
|
|
dag_json_cidv1 TEXT NOT NULL,
|
|
byte_size INTEGER NOT NULL,
|
|
compiled_at_utc TEXT NOT NULL
|
|
) WITHOUT ROWID;
|
|
|
|
CREATE TABLE IF NOT EXISTS glossary_entries (
|
|
entry_id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
term TEXT NOT NULL UNIQUE,
|
|
category TEXT NOT NULL,
|
|
section_id TEXT NOT NULL,
|
|
eng_aq INTEGER NOT NULL,
|
|
ing_term TEXT NOT NULL,
|
|
ing_aq INTEGER NOT NULL,
|
|
delta INTEGER NOT NULL,
|
|
is_isometric INTEGER NOT NULL,
|
|
is_twin_prime INTEGER NOT NULL,
|
|
division_id TEXT,
|
|
volume_pdf TEXT,
|
|
definition TEXT NOT NULL
|
|
);
|
|
CREATE INDEX IF NOT EXISTS idx_glossary_ing_aq ON glossary_entries(ing_aq);
|
|
CREATE INDEX IF NOT EXISTS idx_glossary_eng_aq ON glossary_entries(eng_aq);
|
|
CREATE INDEX IF NOT EXISTS idx_glossary_cat ON glossary_entries(category);
|
|
|
|
CREATE TABLE IF NOT EXISTS kg_nodes (
|
|
node_id TEXT PRIMARY KEY,
|
|
node_urn TEXT NOT NULL,
|
|
node_type TEXT NOT NULL,
|
|
label TEXT NOT NULL,
|
|
aq_value INTEGER,
|
|
degree INTEGER NOT NULL,
|
|
is_flex_pivot INTEGER NOT NULL DEFAULT 0,
|
|
guild_id TEXT,
|
|
metadata_json TEXT NOT NULL
|
|
) WITHOUT ROWID;
|
|
CREATE INDEX IF NOT EXISTS idx_kg_nodes_aq ON kg_nodes(aq_value);
|
|
CREATE INDEX IF NOT EXISTS idx_kg_nodes_type ON kg_nodes(node_type);
|
|
|
|
CREATE TABLE IF NOT EXISTS kg_edges (
|
|
source_id TEXT NOT NULL,
|
|
target_id TEXT NOT NULL,
|
|
relation TEXT NOT NULL,
|
|
weight REAL NOT NULL DEFAULT 1.0,
|
|
PRIMARY KEY (source_id, target_id, relation)
|
|
) WITHOUT ROWID;
|
|
CREATE INDEX IF NOT EXISTS idx_kg_edges_target ON kg_edges(target_id);
|
|
CREATE INDEX IF NOT EXISTS idx_kg_edges_rel ON kg_edges(relation);
|
|
|
|
CREATE TABLE IF NOT EXISTS dossiers (
|
|
dossier_id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
dossier_number INTEGER,
|
|
file_name TEXT NOT NULL UNIQUE,
|
|
title TEXT NOT NULL,
|
|
is_periodic_news INTEGER NOT NULL,
|
|
date_utc TEXT,
|
|
equation_count INTEGER NOT NULL,
|
|
sha256 TEXT NOT NULL
|
|
);
|
|
CREATE INDEX IF NOT EXISTS idx_dossiers_num ON dossiers(dossier_number);
|
|
CREATE INDEX IF NOT EXISTS idx_dossiers_date ON dossiers(date_utc) WHERE date_utc IS NOT NULL;
|
|
|
|
CREATE TABLE IF NOT EXISTS archive_equations (
|
|
eq_id TEXT PRIMARY KEY,
|
|
dossier_number INTEGER,
|
|
file_name TEXT NOT NULL,
|
|
date_utc TEXT,
|
|
target_sum INTEGER NOT NULL,
|
|
ing_phrase TEXT NOT NULL,
|
|
eng_gloss TEXT NOT NULL,
|
|
breakdown TEXT NOT NULL,
|
|
word_count INTEGER NOT NULL
|
|
) WITHOUT ROWID;
|
|
CREATE INDEX IF NOT EXISTS idx_eq_target ON archive_equations(target_sum);
|
|
CREATE INDEX IF NOT EXISTS idx_eq_date ON archive_equations(date_utc) WHERE date_utc IS NOT NULL;
|
|
|
|
CREATE TABLE IF NOT EXISTS quant_timeseries_bars (
|
|
symbol TEXT NOT NULL,
|
|
date_utc TEXT NOT NULL,
|
|
entity_eng TEXT NOT NULL,
|
|
entity_ing TEXT NOT NULL,
|
|
entity_ing_aq INTEGER NOT NULL,
|
|
guilds_csv TEXT NOT NULL,
|
|
tradingview_symbol TEXT NOT NULL,
|
|
tradingview_url TEXT NOT NULL,
|
|
close_usd REAL NOT NULL,
|
|
change_pct REAL NOT NULL,
|
|
change_bps INTEGER NOT NULL,
|
|
volume_ratio_20d REAL NOT NULL,
|
|
market_cap_str TEXT NOT NULL,
|
|
close_digit_aq INTEGER NOT NULL,
|
|
close_spoken_ing TEXT NOT NULL,
|
|
close_spoken_ing_aq INTEGER NOT NULL,
|
|
scaled_cap_spoken_ing_aq INTEGER NOT NULL,
|
|
bps_spoken_ing_aq INTEGER NOT NULL,
|
|
co_present_in_news_wire INTEGER NOT NULL,
|
|
contingent_points REAL NOT NULL,
|
|
locks_json TEXT NOT NULL,
|
|
PRIMARY KEY (symbol, date_utc)
|
|
) WITHOUT ROWID;
|
|
CREATE INDEX IF NOT EXISTS idx_qbars_date ON quant_timeseries_bars(date_utc);
|
|
CREATE INDEX IF NOT EXISTS idx_qbars_close_aq ON quant_timeseries_bars(close_spoken_ing_aq);
|
|
CREATE INDEX IF NOT EXISTS idx_qbars_ent_aq ON quant_timeseries_bars(entity_ing_aq);
|
|
|
|
CREATE VIRTUAL TABLE IF NOT EXISTS fts_catalog USING fts5(
|
|
doc_type,
|
|
doc_id,
|
|
title_or_ing,
|
|
gloss_or_body,
|
|
aq_coord,
|
|
guild_tags,
|
|
tokenize = 'unicode61 remove_diacritics 2'
|
|
);
|
|
"""
|
|
|
|
TELEMETRY_SCHEMA_SQL = """
|
|
PRAGMA journal_mode = WAL;
|
|
PRAGMA synchronous = NORMAL;
|
|
|
|
CREATE TABLE IF NOT EXISTS api_endpoint_rollups (
|
|
protocol TEXT NOT NULL,
|
|
method TEXT NOT NULL,
|
|
endpoint_pattern TEXT NOT NULL,
|
|
total_requests INTEGER NOT NULL DEFAULT 0,
|
|
status_2xx INTEGER NOT NULL DEFAULT 0,
|
|
status_304 INTEGER NOT NULL DEFAULT 0,
|
|
status_4xx INTEGER NOT NULL DEFAULT 0,
|
|
status_5xx INTEGER NOT NULL DEFAULT 0,
|
|
total_latency_us INTEGER NOT NULL DEFAULT 0,
|
|
max_latency_us INTEGER NOT NULL DEFAULT 0,
|
|
last_called_utc TEXT NOT NULL,
|
|
PRIMARY KEY (protocol, method, endpoint_pattern)
|
|
) WITHOUT ROWID;
|
|
|
|
CREATE TABLE IF NOT EXISTS api_audit_ringbuffer (
|
|
event_id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
timestamp_utc TEXT NOT NULL,
|
|
endpoint TEXT NOT NULL,
|
|
status_code INTEGER NOT NULL,
|
|
latency_us INTEGER NOT NULL,
|
|
isolation_ok INTEGER NOT NULL
|
|
);
|
|
|
|
CREATE TRIGGER IF NOT EXISTS trg_prune_audit_ringbuffer
|
|
AFTER INSERT ON api_audit_ringbuffer
|
|
BEGIN
|
|
DELETE FROM api_audit_ringbuffer
|
|
WHERE event_id <= (NEW.event_id - 200);
|
|
END;
|
|
"""
|
|
|
|
|
|
def get_default_catalog_db_path() -> Path:
|
|
env_p = os.environ.get("HYPERSTITION_CATALOG_DB_PATH")
|
|
if env_p:
|
|
return Path(env_p)
|
|
return Path("/tmp/hyperstition-catalog.db")
|
|
|
|
|
|
def get_default_telemetry_db_path() -> Path:
|
|
env_p = os.environ.get("HYPERSTITION_TELEMETRY_DB_PATH")
|
|
if env_p:
|
|
return Path(env_p)
|
|
return Path("/tmp/hyperstition-api-telemetry.db")
|
|
|
|
|
|
def parse_size_spec_bytes(spec: str | int | float | None, default_bytes: int = DEFAULT_MAX_TELEMETRY_BYTES) -> int:
|
|
"""
|
|
Parse a logrotate/CLI size specification such as '100M', '100MB', '512K', '1G', or integer bytes.
|
|
"""
|
|
if spec is None:
|
|
env_b = os.environ.get("HYPERSTITION_SQLITE_MAX_BYTES")
|
|
if env_b:
|
|
return int(env_b)
|
|
env_mb = os.environ.get("HYPERSTITION_SQLITE_MAX_MB")
|
|
if env_mb:
|
|
return int(float(env_mb) * 1024 * 1024)
|
|
return default_bytes
|
|
if isinstance(spec, (int, float)):
|
|
return int(spec)
|
|
s = str(spec).strip().upper()
|
|
m = re.match(r"^(\d+(?:\.\d+)?)\s*([KMGT]?B?)?$", s)
|
|
if not m:
|
|
raise ValueError(f"Invalid size specification: {spec!r}")
|
|
val = float(m.group(1))
|
|
unit = (m.group(2) or "").rstrip("B")
|
|
mult = {
|
|
"": 1,
|
|
"K": 1024,
|
|
"M": 1024 * 1024,
|
|
"G": 1024 * 1024 * 1024,
|
|
"T": 1024 * 1024 * 1024 * 1024,
|
|
}[unit]
|
|
return int(val * mult)
|
|
|
|
|
|
def _sqlite_total_disk_bytes(db_path: Path) -> int:
|
|
"""
|
|
Sum the on-disk byte size of the main SQLite database file plus its `-wal` and `-shm` sidecars.
|
|
"""
|
|
total = 0
|
|
for suffix in ("", "-wal", "-shm"):
|
|
cand = Path(f"{db_path}{suffix}")
|
|
try:
|
|
if cand.exists():
|
|
total += cand.stat().st_size
|
|
except OSError:
|
|
pass
|
|
return total
|
|
|
|
|
|
def build_catalog_sqlite_db(db_path: Path | str | None = None) -> dict[str, Any]:
|
|
"""
|
|
Deterministically compile `hyperstition-catalog.db` (`registry_manifests`, `glossary_entries`,
|
|
`kg_nodes`, `kg_edges`, `dossiers`, `archive_equations`, `quant_timeseries_bars`, and `fts_catalog`)
|
|
under `ReadOnlyIsolationGuard`.
|
|
"""
|
|
target_db = Path(db_path) if db_path is not None else get_default_catalog_db_path()
|
|
target_db.parent.mkdir(parents=True, exist_ok=True)
|
|
tmp_db = target_db.with_suffix(f".tmp.{os.getpid()}.db")
|
|
if tmp_db.exists():
|
|
tmp_db.unlink()
|
|
|
|
cfg = load_workspace_config()
|
|
now_utc = dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
|
|
with ReadOnlyIsolationGuard(cfg.read_only_files) as guard:
|
|
conn = sqlite3.connect(str(tmp_db))
|
|
try:
|
|
conn.executescript(CATALOG_SCHEMA_SQL)
|
|
|
|
# 1. Registry Manifests
|
|
reg_specs = [
|
|
("glossary-registry", cfg.zoology_dir / "taxonomy" / "glossary-registry.json", "urn:io:hyperstitionstud:schema:v1:glossary-registry"),
|
|
("encyclopedia-manifest", cfg.zoology_dir / "encyclopedia" / "encyclopedia-manifest.json", "urn:io:hyperstitionstud:schema:v1:encyclopedia-manifest"),
|
|
("singularity-zoology-matrix", cfg.zoology_dir / "taxonomy" / "singularity-zoology-matrix.json", "urn:io:hyperstitionstud:schema:v1:singularity-zoology-matrix"),
|
|
("memetic-superclass-registry", cfg.zoology_dir / "taxonomy" / "memetic-superclass-registry.json", "urn:io:hyperstitionstud:schema:v1:memetic-superclass-registry"),
|
|
("assemblage-builds-tier-list", cfg.zoology_dir / "taxonomy" / "assemblage-builds-tier-list.json", "urn:io:hyperstitionstud:schema:v1:assemblage-builds-tier-list"),
|
|
("quantitative-economic-anchors", cfg.zoology_dir / "taxonomy" / "quantitative-economic-anchors.json", "urn:io:hyperstitionstud:schema:v1:quantitative-economic-anchors"),
|
|
("encyclopedia-graph", cfg.knowledge_graph_dir / "encyclopedia-graph.json", "urn:io:hyperstitionstud:schema:v1:encyclopedia-graph"),
|
|
("quant-timeseries", cfg.core_dir / "site" / "quant" / "quant-timeseries.json", "urn:io:hyperstitionstud:schema:v1:quant-timeseries"),
|
|
]
|
|
for slug, r_path, s_urn in reg_specs:
|
|
if not r_path.is_file():
|
|
continue
|
|
raw_b = r_path.read_bytes()
|
|
parsed = json.loads(raw_b.decode("utf-8"))
|
|
sha_hex = hashlib.sha256(raw_b).hexdigest()
|
|
cid_str = compute_dag_json_cidv1(parsed)
|
|
rec_cnt = (
|
|
len(parsed.get("nodes", []))
|
|
or len(parsed.get("instruments", []))
|
|
or len(parsed.get("bilingual_vocabulary_ledger", []))
|
|
or len(parsed.get("rows", []))
|
|
or len(parsed.get("anchors", []))
|
|
or len(parsed.get("volumes", []))
|
|
or len(parsed.get("classes", {}))
|
|
or len(parsed.get("canonical_subclasses", {}))
|
|
)
|
|
conn.execute(
|
|
"""
|
|
INSERT OR REPLACE INTO registry_manifests
|
|
(registry_slug, source_path, schema_urn, version, record_count, raw_sha256, dag_json_cidv1, byte_size, compiled_at_utc)
|
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
""",
|
|
(slug, str(r_path), s_urn, CURRENT_VERSION, int(rec_cnt), sha_hex, cid_str, len(raw_b), now_utc),
|
|
)
|
|
|
|
# 2. Glossary Entries & Bilingual Specimens
|
|
gl_path = cfg.zoology_dir / "taxonomy" / "glossary-registry.json"
|
|
gl_data = json.loads(gl_path.read_text(encoding="utf-8"))
|
|
seen_terms: set[str] = set()
|
|
glossary_rows = 0
|
|
|
|
def _insert_glossary_row(
|
|
term: str,
|
|
cat: str,
|
|
sec_id: str,
|
|
eng_aq: int,
|
|
ing_term: str,
|
|
ing_aq: int,
|
|
delta: int,
|
|
is_iso: int,
|
|
is_tp: int,
|
|
div_id: str | None,
|
|
vol_pdf: str | None,
|
|
defn: str,
|
|
guilds_str: str = "",
|
|
) -> None:
|
|
nonlocal glossary_rows
|
|
t_key = term.strip()
|
|
if t_key in seen_terms:
|
|
t_key = f"{t_key} [{sec_id}]"
|
|
seen_terms.add(t_key)
|
|
conn.execute(
|
|
"""
|
|
INSERT INTO glossary_entries
|
|
(term, category, section_id, eng_aq, ing_term, ing_aq, delta, is_isometric, is_twin_prime, division_id, volume_pdf, definition)
|
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
""",
|
|
(t_key, cat, sec_id, eng_aq, ing_term, ing_aq, delta, is_iso, is_tp, div_id, vol_pdf, defn),
|
|
)
|
|
conn.execute(
|
|
"""
|
|
INSERT INTO fts_catalog (doc_type, doc_id, title_or_ing, gloss_or_body, aq_coord, guild_tags)
|
|
VALUES (?, ?, ?, ?, ?, ?)
|
|
""",
|
|
("glossary", f"glossary:{t_key}", f"{t_key} {ing_term}", defn, f"{eng_aq} {ing_aq}", guilds_str),
|
|
)
|
|
glossary_rows += 1
|
|
|
|
for sec in gl_data.get("sections", []):
|
|
sec_id = str(sec.get("section_id", ""))
|
|
for ent in sec.get("entries", []):
|
|
e_aq = int(ent.get("eng_aq", ent.get("ing_aq", 0)) or 0)
|
|
i_aq = int(ent.get("ing_aq", e_aq) or 0)
|
|
_insert_glossary_row(
|
|
term=str(ent["term"]),
|
|
cat="ConceptualEntry",
|
|
sec_id=sec_id,
|
|
eng_aq=e_aq,
|
|
ing_term=str(ent.get("ing", ent["term"])),
|
|
ing_aq=i_aq,
|
|
delta=i_aq - e_aq,
|
|
is_iso=1 if i_aq == e_aq else 0,
|
|
is_tp=1 if abs(i_aq - e_aq) == 2 else 0,
|
|
div_id=ent.get("division_id"),
|
|
vol_pdf=ent.get("volume_pdf"),
|
|
defn=str(ent.get("definition", "")),
|
|
)
|
|
for ent in gl_data.get("custom_entries", []):
|
|
e_aq = int(ent.get("eng_aq", ent.get("ing_aq", 0)) or 0)
|
|
i_aq = int(ent.get("ing_aq", e_aq) or 0)
|
|
_insert_glossary_row(
|
|
term=str(ent["term"]),
|
|
cat="CustomEntry",
|
|
sec_id="8B",
|
|
eng_aq=e_aq,
|
|
ing_term=str(ent.get("ing", ent["term"])),
|
|
ing_aq=i_aq,
|
|
delta=i_aq - e_aq,
|
|
is_iso=1 if i_aq == e_aq else 0,
|
|
is_tp=1 if abs(i_aq - e_aq) == 2 else 0,
|
|
div_id=ent.get("division_id"),
|
|
vol_pdf=ent.get("volume_pdf"),
|
|
defn=str(ent.get("definition", "")),
|
|
)
|
|
for spec in gl_data.get("bilingual_vocabulary_ledger", []):
|
|
classes_csv = ",".join(spec.get("classes", []))
|
|
_insert_glossary_row(
|
|
term=str(spec["eng"]),
|
|
cat="BilingualSpecimen",
|
|
sec_id=classes_csv or "SPEC",
|
|
eng_aq=int(spec["eng_aq"]),
|
|
ing_term=str(spec["ing"]),
|
|
ing_aq=int(spec["ing_aq"]),
|
|
delta=int(spec["delta"]),
|
|
is_iso=1 if spec.get("isometric") else 0,
|
|
is_tp=1 if spec.get("twin_prime") else 0,
|
|
div_id=None,
|
|
vol_pdf=None,
|
|
defn=f"Bilingual specimen ({spec['eng']} -> {spec['ing']}) in classes [{classes_csv}]",
|
|
guilds_str=classes_csv,
|
|
)
|
|
|
|
# 3. Knowledge Graph Nodes & Edges
|
|
kg_path = cfg.knowledge_graph_dir / "encyclopedia-graph.json"
|
|
kg_data = json.loads(kg_path.read_text(encoding="utf-8"))
|
|
deg_map: dict[str, int] = {}
|
|
edge_rows = 0
|
|
for e in kg_data.get("edges", []):
|
|
s_id = str(e["source"])
|
|
t_id = str(e["target"])
|
|
rel = str(e["relation"])
|
|
w = float(e.get("weight", 1.0))
|
|
conn.execute(
|
|
"""
|
|
INSERT OR IGNORE INTO kg_edges (source_id, target_id, relation, weight)
|
|
VALUES (?, ?, ?, ?)
|
|
""",
|
|
(s_id, t_id, rel, w),
|
|
)
|
|
deg_map[s_id] = deg_map.get(s_id, 0) + 1
|
|
deg_map[t_id] = deg_map.get(t_id, 0) + 1
|
|
edge_rows += 1
|
|
|
|
flex_coords = {292, 256, 211, 193, 183, 153, 137, 136, 133, 125, 96, 95, 91, 81}
|
|
node_rows = 0
|
|
for n in kg_data.get("nodes", []):
|
|
nid = str(n["id"])
|
|
n_urn = str(n.get("urn") or f"urn:io:hyperstitionstud:kg:node:{nid}")
|
|
n_type = str(n.get("type", "Entity"))
|
|
lbl = str(n.get("label", nid))
|
|
aq_v = n.get("ing_aq") if n.get("ing_aq") is not None else n.get("aq_value")
|
|
aq_int = int(aq_v) if aq_v is not None else None
|
|
is_flex = 1 if (aq_int in flex_coords or n.get("multi_build_flex")) else 0
|
|
guild_id = str(n.get("guild") or n.get("division") or "")
|
|
conn.execute(
|
|
"""
|
|
INSERT OR REPLACE INTO kg_nodes
|
|
(node_id, node_urn, node_type, label, aq_value, degree, is_flex_pivot, guild_id, metadata_json)
|
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
""",
|
|
(nid, n_urn, n_type, lbl, aq_int, deg_map.get(nid, 0), is_flex, guild_id, json.dumps(n, ensure_ascii=False)),
|
|
)
|
|
conn.execute(
|
|
"""
|
|
INSERT INTO fts_catalog (doc_type, doc_id, title_or_ing, gloss_or_body, aq_coord, guild_tags)
|
|
VALUES (?, ?, ?, ?, ?, ?)
|
|
""",
|
|
("node", nid, lbl, f"{n_type} {n.get('eng', '')} {n.get('ing', '')}", str(aq_int or ""), guild_id),
|
|
)
|
|
node_rows += 1
|
|
|
|
# 4. Dossiers & Archive Equations across ingglish-aq-archive and zoology/dossiers
|
|
md_files: list[Path] = []
|
|
seen_names: set[str] = set()
|
|
for d_dir in (cfg.archive_dir / "ingglish-aq-archive", cfg.zoology_dir / "dossiers"):
|
|
if not d_dir.is_dir():
|
|
continue
|
|
for md_f in sorted(d_dir.glob("*.md")):
|
|
if md_f.name not in seen_names:
|
|
seen_names.add(md_f.name)
|
|
md_files.append(md_f)
|
|
|
|
eq_pattern = re.compile(r'-\s+`([^`]+)`\s+\("([^"]+)"\)\s+—\s+`([^`]+)=\s*(\d+)`')
|
|
dossier_rows = 0
|
|
equation_rows = 0
|
|
for md_f in md_files:
|
|
m_num = re.match(r"^(\d{2})-", md_f.name)
|
|
d_num = int(m_num.group(1)) if m_num else None
|
|
raw_b = md_f.read_bytes()
|
|
txt = raw_b.decode("utf-8")
|
|
sha_hex = hashlib.sha256(raw_b).hexdigest()
|
|
first_line = next((ln.lstrip("# ").strip() for ln in txt.splitlines() if ln.strip().startswith("#")), md_f.stem)
|
|
m_date = re.search(r"(\d{4}-\d{2}-\d{2})", md_f.name)
|
|
date_utc = m_date.group(1) if m_date else None
|
|
is_periodic = 1 if date_utc is not None else 0
|
|
|
|
d_eqs = list(eq_pattern.finditer(txt))
|
|
conn.execute(
|
|
"""
|
|
INSERT OR REPLACE INTO dossiers
|
|
(dossier_number, file_name, title, is_periodic_news, date_utc, equation_count, sha256)
|
|
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
""",
|
|
(d_num, md_f.name, first_line, is_periodic, date_utc, len(d_eqs), sha_hex),
|
|
)
|
|
conn.execute(
|
|
"""
|
|
INSERT INTO fts_catalog (doc_type, doc_id, title_or_ing, gloss_or_body, aq_coord, guild_tags)
|
|
VALUES (?, ?, ?, ?, ?, ?)
|
|
""",
|
|
("dossier", f"dossier:{md_f.name}", md_f.name, first_line, str(d_num or ""), date_utc or ""),
|
|
)
|
|
dossier_rows += 1
|
|
|
|
for idx, m_eq in enumerate(d_eqs, start=1):
|
|
ing_s = m_eq.group(1).strip()
|
|
eng_s = m_eq.group(2).strip()
|
|
brk_s = m_eq.group(3).strip()
|
|
val_s = int(m_eq.group(4))
|
|
slug_tok = re.sub(r"[^a-z0-9]+", "_", ing_s.lower()).strip("_")[:18] or "eq"
|
|
f_tok = re.sub(r"[^a-z0-9]+", "_", md_f.stem.lower()).strip("_")[:12]
|
|
eq_id = f"eq_{val_s}_{f_tok}_{slug_tok}_{idx:04d}"
|
|
w_cnt = len([w for w in ing_s.split() if w])
|
|
conn.execute(
|
|
"""
|
|
INSERT OR REPLACE INTO archive_equations
|
|
(eq_id, dossier_number, file_name, date_utc, target_sum, ing_phrase, eng_gloss, breakdown, word_count)
|
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
""",
|
|
(eq_id, d_num, md_f.name, date_utc, val_s, ing_s, eng_s, brk_s, w_cnt),
|
|
)
|
|
conn.execute(
|
|
"""
|
|
INSERT INTO fts_catalog (doc_type, doc_id, title_or_ing, gloss_or_body, aq_coord, guild_tags)
|
|
VALUES (?, ?, ?, ?, ?, ?)
|
|
""",
|
|
("equation", eq_id, ing_s, f"{eng_s} | {brk_s}", str(val_s), date_utc or ""),
|
|
)
|
|
equation_rows += 1
|
|
|
|
# 5. Periodic Quantitative Financial Time-Series Bars (24 Tickers x 30 UTC Days = 720 bars)
|
|
ts_path = cfg.core_dir / "site" / "quant" / "quant-timeseries.json"
|
|
if ts_path.is_file():
|
|
ts_bundle = json.loads(ts_path.read_text(encoding="utf-8"))
|
|
else:
|
|
ts_bundle = build_quant_timeseries_bundle(write_files=False)
|
|
|
|
bar_rows = 0
|
|
for inst in ts_bundle.get("instruments", []):
|
|
sym = str(inst["symbol"])
|
|
ent_eng = str(inst["entity_eng"])
|
|
ent_ing = str(inst["entity_ing"])
|
|
ent_aq = int(inst["entity_ing_aq"])
|
|
guilds_csv = ",".join(inst.get("guilds", []))
|
|
tv_sym = str(inst.get("tradingview_symbol", sym))
|
|
tv_url = str(inst.get("tradingview_url", ""))
|
|
mcap_str = str(inst.get("market_cap_str", ""))
|
|
|
|
conn.execute(
|
|
"""
|
|
INSERT INTO fts_catalog (doc_type, doc_id, title_or_ing, gloss_or_body, aq_coord, guild_tags)
|
|
VALUES (?, ?, ?, ?, ?, ?)
|
|
""",
|
|
("instrument", f"instrument:{sym}", f"{sym} {ent_ing}", f"{ent_eng} {tv_sym}", str(ent_aq), guilds_csv),
|
|
)
|
|
|
|
for bar in (inst.get("bars") or inst.get("series") or []):
|
|
locks_payload = bar.get("locks") or {
|
|
"scope1_locks": bar.get("scope1_locks", []),
|
|
"scope2_ring_coordinates": bar.get("scope2_ring_coordinates", []),
|
|
}
|
|
conn.execute(
|
|
"""
|
|
INSERT OR REPLACE INTO quant_timeseries_bars (
|
|
symbol, date_utc, entity_eng, entity_ing, entity_ing_aq, guilds_csv,
|
|
tradingview_symbol, tradingview_url, close_usd, change_pct, change_bps,
|
|
volume_ratio_20d, market_cap_str, close_digit_aq, close_spoken_ing,
|
|
close_spoken_ing_aq, scaled_cap_spoken_ing_aq, bps_spoken_ing_aq,
|
|
co_present_in_news_wire, contingent_points, locks_json
|
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
""",
|
|
(
|
|
sym,
|
|
str(bar["date_utc"]),
|
|
ent_eng,
|
|
ent_ing,
|
|
ent_aq,
|
|
guilds_csv,
|
|
tv_sym,
|
|
tv_url,
|
|
float(bar["close_usd"]),
|
|
float(bar["change_pct"]),
|
|
int(bar["change_bps"]),
|
|
float(bar["volume_ratio_20d"]),
|
|
str(bar.get("market_cap_str", mcap_str)),
|
|
int(bar["close_digit_aq"]),
|
|
str(bar["close_spoken_ing"]),
|
|
int(bar["close_spoken_ing_aq"]),
|
|
int(bar["scaled_cap_spoken_ing_aq"]),
|
|
int(bar["bps_spoken_ing_aq"]),
|
|
1 if bar.get("co_present_in_news_wire") else 0,
|
|
float(bar.get("contingent_points", 0.0)),
|
|
json.dumps(locks_payload, ensure_ascii=False),
|
|
),
|
|
)
|
|
bar_rows += 1
|
|
|
|
conn.commit()
|
|
conn.execute("PRAGMA optimize;")
|
|
conn.execute("VACUUM;")
|
|
finally:
|
|
conn.close()
|
|
|
|
tmp_db.replace(target_db)
|
|
|
|
receipt = guard.audit_receipt()
|
|
return {
|
|
"db_path": str(target_db),
|
|
"byte_size": target_db.stat().st_size,
|
|
"counts": {
|
|
"registry_manifests": len(reg_specs),
|
|
"glossary_entries": glossary_rows,
|
|
"kg_nodes": node_rows,
|
|
"kg_edges": edge_rows,
|
|
"dossiers": dossier_rows,
|
|
"archive_equations": equation_rows,
|
|
"quant_timeseries_bars": bar_rows,
|
|
},
|
|
"isolation_receipt": receipt,
|
|
}
|
|
|
|
|
|
def ensure_catalog_sqlite_db(db_path: Path | str | None = None) -> Path:
|
|
target_db = Path(db_path) if db_path is not None else get_default_catalog_db_path()
|
|
if not target_db.is_file() or target_db.stat().st_size == 0:
|
|
build_catalog_sqlite_db(target_db)
|
|
return target_db
|
|
|
|
|
|
def _open_readonly_catalog(db_path: Path | str | None = None) -> sqlite3.Connection:
|
|
target_db = ensure_catalog_sqlite_db(db_path)
|
|
uri = f"file:{target_db.resolve()}?mode=ro"
|
|
conn = sqlite3.connect(uri, uri=True)
|
|
conn.row_factory = sqlite3.Row
|
|
conn.execute("PRAGMA query_only = ON;")
|
|
return conn
|
|
|
|
|
|
def query_registry_manifests(
|
|
db_path: Path | str | None = None,
|
|
registry: str | None = None,
|
|
) -> list[dict[str, Any]]:
|
|
conn = _open_readonly_catalog(db_path)
|
|
try:
|
|
if registry:
|
|
rows = conn.execute(
|
|
"SELECT * FROM registry_manifests WHERE registry_slug = ? ORDER BY registry_slug",
|
|
(registry,),
|
|
).fetchall()
|
|
else:
|
|
rows = conn.execute("SELECT * FROM registry_manifests ORDER BY registry_slug").fetchall()
|
|
return [dict(r) for r in rows]
|
|
finally:
|
|
conn.close()
|
|
|
|
|
|
def query_fts_catalog(
|
|
query: str,
|
|
doc_type: str = "all",
|
|
limit: int = 25,
|
|
db_path: Path | str | None = None,
|
|
) -> dict[str, Any]:
|
|
conn = _open_readonly_catalog(db_path)
|
|
try:
|
|
tokens = [re.sub(r"[^a-zA-Z0-9_]+", "", t) for t in query.split()]
|
|
tokens = [t for t in tokens if t]
|
|
if not tokens:
|
|
return {"query": query, "doc_type": doc_type, "match_count": 0, "results": []}
|
|
fts_expr = " OR ".join(f'"{t}"*' for t in tokens)
|
|
if doc_type and doc_type != "all":
|
|
rows = conn.execute(
|
|
"""
|
|
SELECT doc_type, doc_id, title_or_ing, gloss_or_body, aq_coord, guild_tags,
|
|
bm25(fts_catalog) AS bm25_score
|
|
FROM fts_catalog
|
|
WHERE fts_catalog MATCH ? AND doc_type = ?
|
|
ORDER BY bm25(fts_catalog)
|
|
LIMIT ?
|
|
""",
|
|
(fts_expr, doc_type, int(limit)),
|
|
).fetchall()
|
|
else:
|
|
rows = conn.execute(
|
|
"""
|
|
SELECT doc_type, doc_id, title_or_ing, gloss_or_body, aq_coord, guild_tags,
|
|
bm25(fts_catalog) AS bm25_score
|
|
FROM fts_catalog
|
|
WHERE fts_catalog MATCH ?
|
|
ORDER BY bm25(fts_catalog)
|
|
LIMIT ?
|
|
""",
|
|
(fts_expr, int(limit)),
|
|
).fetchall()
|
|
items = [dict(r) for r in rows]
|
|
return {"query": query, "doc_type": doc_type, "match_count": len(items), "results": items}
|
|
finally:
|
|
conn.close()
|
|
|
|
|
|
def query_coordinate_join(
|
|
aq_int: int,
|
|
db_path: Path | str | None = None,
|
|
) -> dict[str, Any]:
|
|
coord = int(aq_int)
|
|
conn = _open_readonly_catalog(db_path)
|
|
try:
|
|
glossary = [
|
|
dict(r)
|
|
for r in conn.execute(
|
|
"SELECT * FROM glossary_entries WHERE ing_aq = ? OR eng_aq = ? ORDER BY term",
|
|
(coord, coord),
|
|
).fetchall()
|
|
]
|
|
nodes = [
|
|
dict(r)
|
|
for r in conn.execute(
|
|
"SELECT node_id, node_urn, node_type, label, aq_value, degree, is_flex_pivot, guild_id FROM kg_nodes WHERE aq_value = ? OR node_id = ? ORDER BY degree DESC",
|
|
(coord, f"aq:{coord}"),
|
|
).fetchall()
|
|
]
|
|
edges = [
|
|
dict(r)
|
|
for r in conn.execute(
|
|
"SELECT * FROM kg_edges WHERE source_id = ? OR target_id = ? LIMIT 50",
|
|
(f"aq:{coord}", f"aq:{coord}"),
|
|
).fetchall()
|
|
]
|
|
equations = [
|
|
dict(r)
|
|
for r in conn.execute(
|
|
"SELECT * FROM archive_equations WHERE target_sum = ? OR breakdown LIKE ? LIMIT 25",
|
|
(coord, f"%({coord})%"),
|
|
).fetchall()
|
|
]
|
|
bars = [
|
|
dict(r)
|
|
for r in conn.execute(
|
|
"""
|
|
SELECT symbol, date_utc, entity_eng, entity_ing, entity_ing_aq, close_usd,
|
|
close_spoken_ing, close_spoken_ing_aq, contingent_points
|
|
FROM quant_timeseries_bars
|
|
WHERE entity_ing_aq = ? OR close_spoken_ing_aq = ? OR close_digit_aq = ?
|
|
ORDER BY date_utc DESC, contingent_points DESC
|
|
LIMIT 30
|
|
""",
|
|
(coord, coord, coord),
|
|
).fetchall()
|
|
]
|
|
return {
|
|
"coordinate_aq": coord,
|
|
"glossary_matches": glossary,
|
|
"kg_nodes": nodes,
|
|
"kg_edges": edges,
|
|
"archive_equations": equations,
|
|
"quant_timeseries_bars": bars,
|
|
}
|
|
finally:
|
|
conn.close()
|
|
|
|
|
|
def query_timeseries_bars(
|
|
symbol: str | None = None,
|
|
start_date: str | None = None,
|
|
end_date: str | None = None,
|
|
min_points: float = 0.0,
|
|
db_path: Path | str | None = None,
|
|
) -> list[dict[str, Any]]:
|
|
conn = _open_readonly_catalog(db_path)
|
|
try:
|
|
clauses = ["contingent_points >= ?"]
|
|
params: list[Any] = [float(min_points)]
|
|
if symbol:
|
|
clauses.append("UPPER(symbol) = ?")
|
|
params.append(symbol.strip().upper())
|
|
if start_date:
|
|
clauses.append("date_utc >= ?")
|
|
params.append(start_date.strip())
|
|
if end_date:
|
|
clauses.append("date_utc <= ?")
|
|
params.append(end_date.strip())
|
|
where_sql = " AND ".join(clauses)
|
|
rows = conn.execute(
|
|
f"SELECT * FROM quant_timeseries_bars WHERE {where_sql} ORDER BY date_utc DESC, symbol ASC",
|
|
params,
|
|
).fetchall()
|
|
return [dict(r) for r in rows]
|
|
finally:
|
|
conn.close()
|
|
|
|
|
|
def _rotate_compressed_archives(base_db_path: Path, rotate_keep: int = 12) -> Path:
|
|
"""
|
|
Shift existing `<base_db_path>.{1..K-1}.gz` archives up by 1 and return `<base_db_path>.1.gz`.
|
|
"""
|
|
keep = max(1, int(rotate_keep))
|
|
oldest = Path(f"{base_db_path}.{keep}.gz")
|
|
if oldest.exists():
|
|
oldest.unlink()
|
|
for idx in range(keep - 1, 0, -1):
|
|
src = Path(f"{base_db_path}.{idx}.gz")
|
|
dst = Path(f"{base_db_path}.{idx + 1}.gz")
|
|
if src.exists():
|
|
src.replace(dst)
|
|
return Path(f"{base_db_path}.1.gz")
|
|
|
|
|
|
def truncate_telemetry_db_quiescent(
|
|
telemetry_db_path: Path | str | None = None,
|
|
max_bytes: int | str | None = None,
|
|
force: bool = False,
|
|
compress_archive: bool = True,
|
|
rotate_keep: int = 12,
|
|
) -> dict[str, Any]:
|
|
"""
|
|
Compress and truncate the SQLite REST/MCP API metadata/telemetry database (`api-telemetry.db`)
|
|
when its total footprint (`.db` + `-wal` + `-shm`) reaches or exceeds `max_bytes` (default `100 MB`),
|
|
ensuring full SQLite quiescence:
|
|
1. Sets `PRAGMA busy_timeout = 30000` (waits up to 30 seconds for in-flight readers/writers).
|
|
2. Acquires `BEGIN EXCLUSIVE` transaction lock so zero concurrent readers or writers are active.
|
|
3. Exports a consistent point-in-time SQLite snapshot and compresses it with `gzip -9` into
|
|
`<db_path>.1.gz` (rotating up to `rotate_keep` compressed generations rather than discarding history).
|
|
4. Clears `api_audit_ringbuffer`, `api_endpoint_rollups`, and `sqlite_sequence` and commits.
|
|
5. Runs `PRAGMA wal_checkpoint(TRUNCATE)` to drain and reset the WAL file to 0 bytes.
|
|
6. Runs `VACUUM` + `PRAGMA optimize` to reclaim all freed pages on disk, then verifies
|
|
`PRAGMA integrity_check == 'ok'`.
|
|
"""
|
|
t_path = Path(telemetry_db_path) if telemetry_db_path is not None else get_default_telemetry_db_path()
|
|
limit_bytes = parse_size_spec_bytes(max_bytes, default_bytes=DEFAULT_MAX_TELEMETRY_BYTES)
|
|
|
|
if not t_path.exists():
|
|
return {
|
|
"db_path": str(t_path),
|
|
"truncated": False,
|
|
"quiescent": True,
|
|
"compressed_archive_path": None,
|
|
"compressed_archive_bytes": 0,
|
|
"bytes_before": 0,
|
|
"bytes_after": 0,
|
|
"max_bytes": limit_bytes,
|
|
"integrity_check": "ok",
|
|
}
|
|
|
|
bytes_before = _sqlite_total_disk_bytes(t_path)
|
|
if not force and bytes_before < limit_bytes:
|
|
return {
|
|
"db_path": str(t_path),
|
|
"truncated": False,
|
|
"quiescent": True,
|
|
"compressed_archive_path": None,
|
|
"compressed_archive_bytes": 0,
|
|
"bytes_before": bytes_before,
|
|
"bytes_after": bytes_before,
|
|
"max_bytes": limit_bytes,
|
|
"integrity_check": "ok",
|
|
}
|
|
|
|
compressed_archive_path: str | None = None
|
|
compressed_archive_bytes = 0
|
|
|
|
conn = sqlite3.connect(str(t_path), timeout=30.0, isolation_level=None)
|
|
try:
|
|
conn.execute("PRAGMA busy_timeout = 30000;")
|
|
conn.executescript(TELEMETRY_SCHEMA_SQL)
|
|
# 1. Flush all WAL frames into main DB pages while waiting for active readers
|
|
conn.execute("PRAGMA wal_checkpoint(TRUNCATE);")
|
|
|
|
# 2. Take a consistent point-in-time SQLite online backup & compress to .1.gz before purging
|
|
if compress_archive:
|
|
snap_tmp = t_path.with_suffix(f".snap.{os.getpid()}.db")
|
|
if snap_tmp.exists():
|
|
snap_tmp.unlink()
|
|
try:
|
|
snap_conn = sqlite3.connect(str(snap_tmp))
|
|
try:
|
|
conn.backup(snap_conn)
|
|
finally:
|
|
snap_conn.close()
|
|
gz_target = _rotate_compressed_archives(t_path, rotate_keep=rotate_keep)
|
|
with open(snap_tmp, "rb") as f_in, gzip.open(gz_target, "wb", compresslevel=9) as f_out:
|
|
f_out.write(f_in.read())
|
|
compressed_archive_path = str(gz_target)
|
|
compressed_archive_bytes = gz_target.stat().st_size
|
|
finally:
|
|
if snap_tmp.exists():
|
|
snap_tmp.unlink()
|
|
|
|
# 3. Acquire EXCLUSIVE lock to guarantee total reader/writer quiescence while truncating tables
|
|
conn.execute("BEGIN EXCLUSIVE;")
|
|
try:
|
|
conn.execute("DELETE FROM api_audit_ringbuffer;")
|
|
conn.execute("DELETE FROM api_endpoint_rollups;")
|
|
conn.execute("DELETE FROM sqlite_sequence WHERE name = 'api_audit_ringbuffer';")
|
|
conn.execute("COMMIT;")
|
|
except Exception:
|
|
conn.execute("ROLLBACK;")
|
|
raise
|
|
|
|
wal_row = conn.execute("PRAGMA wal_checkpoint(TRUNCATE);").fetchone()
|
|
conn.execute("VACUUM;")
|
|
conn.execute("PRAGMA wal_checkpoint(TRUNCATE);")
|
|
conn.execute("PRAGMA optimize;")
|
|
integrity = conn.execute("PRAGMA integrity_check;").fetchone()[0]
|
|
finally:
|
|
conn.close()
|
|
|
|
bytes_after = _sqlite_total_disk_bytes(t_path)
|
|
return {
|
|
"db_path": str(t_path),
|
|
"truncated": True,
|
|
"quiescent": True,
|
|
"compressed_archive_path": compressed_archive_path,
|
|
"compressed_archive_bytes": compressed_archive_bytes,
|
|
"wal_checkpoint": list(wal_row) if wal_row is not None else [0, 0, 0],
|
|
"bytes_before": bytes_before,
|
|
"bytes_after": bytes_after,
|
|
"max_bytes": limit_bytes,
|
|
"integrity_check": str(integrity),
|
|
}
|
|
|
|
|
|
def record_api_telemetry(
|
|
protocol: str,
|
|
method: str,
|
|
endpoint_pattern: str,
|
|
status_code: int,
|
|
latency_us: int,
|
|
isolation_ok: bool = True,
|
|
telemetry_db_path: Path | str | None = None,
|
|
max_bytes: int | str | None = None,
|
|
) -> dict[str, Any]:
|
|
"""
|
|
Record a privacy-preserving REST (`/api/v1/*`) or MCP (`/mcp`) call in `api-telemetry.db`,
|
|
and automatically perform a quiescent truncation if the database reaches `max_bytes` (default `100 MB`).
|
|
"""
|
|
t_path = Path(telemetry_db_path) if telemetry_db_path is not None else get_default_telemetry_db_path()
|
|
limit_bytes = parse_size_spec_bytes(max_bytes, default_bytes=DEFAULT_MAX_TELEMETRY_BYTES)
|
|
now_utc = dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
code = int(status_code)
|
|
lat = max(0, int(latency_us))
|
|
iso_int = 1 if isolation_ok else 0
|
|
|
|
s_2xx = 1 if 200 <= code < 300 else 0
|
|
s_304 = 1 if code == 304 else 0
|
|
s_4xx = 1 if 400 <= code < 500 else 0
|
|
s_5xx = 1 if code >= 500 else 0
|
|
|
|
try:
|
|
t_path.parent.mkdir(parents=True, exist_ok=True)
|
|
if _sqlite_total_disk_bytes(t_path) >= limit_bytes:
|
|
truncate_telemetry_db_quiescent(t_path, max_bytes=limit_bytes, force=True)
|
|
|
|
conn = sqlite3.connect(str(t_path), timeout=30.0, isolation_level=None)
|
|
try:
|
|
conn.execute("PRAGMA busy_timeout = 30000;")
|
|
conn.executescript(TELEMETRY_SCHEMA_SQL)
|
|
conn.execute("BEGIN IMMEDIATE;")
|
|
try:
|
|
conn.execute(
|
|
"""
|
|
INSERT INTO api_endpoint_rollups (
|
|
protocol, method, endpoint_pattern, total_requests,
|
|
status_2xx, status_304, status_4xx, status_5xx,
|
|
total_latency_us, max_latency_us, last_called_utc
|
|
) VALUES (?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?)
|
|
ON CONFLICT(protocol, method, endpoint_pattern) DO UPDATE SET
|
|
total_requests = total_requests + 1,
|
|
status_2xx = status_2xx + excluded.status_2xx,
|
|
status_304 = status_304 + excluded.status_304,
|
|
status_4xx = status_4xx + excluded.status_4xx,
|
|
status_5xx = status_5xx + excluded.status_5xx,
|
|
total_latency_us = total_latency_us + excluded.total_latency_us,
|
|
max_latency_us = MAX(max_latency_us, excluded.max_latency_us),
|
|
last_called_utc = excluded.last_called_utc
|
|
""",
|
|
(protocol, method, endpoint_pattern, s_2xx, s_304, s_4xx, s_5xx, lat, lat, now_utc),
|
|
)
|
|
conn.execute(
|
|
"""
|
|
INSERT INTO api_audit_ringbuffer (
|
|
timestamp_utc, endpoint, status_code, latency_us, isolation_ok
|
|
) VALUES (?, ?, ?, ?, ?)
|
|
""",
|
|
(now_utc, f"{protocol}:{method} {endpoint_pattern}", code, lat, iso_int),
|
|
)
|
|
conn.execute("COMMIT;")
|
|
except Exception:
|
|
conn.execute("ROLLBACK;")
|
|
raise
|
|
finally:
|
|
conn.close()
|
|
return {"ok": True, "db_path": str(t_path)}
|
|
except OSError as exc:
|
|
return {"ok": False, "error": str(exc)}
|
|
|
|
|
|
def get_api_telemetry_summary(telemetry_db_path: Path | str | None = None) -> dict[str, Any]:
|
|
t_path = Path(telemetry_db_path) if telemetry_db_path is not None else get_default_telemetry_db_path()
|
|
if not t_path.is_file():
|
|
return {
|
|
"db_path": str(t_path),
|
|
"total_requests": 0,
|
|
"endpoints": [],
|
|
"recent_audit_events": [],
|
|
"ringbuffer_count": 0,
|
|
"byte_size": 0,
|
|
}
|
|
conn = sqlite3.connect(str(t_path), timeout=30.0)
|
|
conn.row_factory = sqlite3.Row
|
|
try:
|
|
rollups = [
|
|
dict(r)
|
|
for r in conn.execute(
|
|
"SELECT * FROM api_endpoint_rollups ORDER BY total_requests DESC, endpoint_pattern ASC"
|
|
).fetchall()
|
|
]
|
|
recent = [
|
|
dict(r)
|
|
for r in conn.execute(
|
|
"SELECT * FROM api_audit_ringbuffer ORDER BY event_id DESC LIMIT 25"
|
|
).fetchall()
|
|
]
|
|
rb_cnt = conn.execute("SELECT COUNT(*) FROM api_audit_ringbuffer").fetchone()[0]
|
|
tot_reqs = sum(int(r["total_requests"]) for r in rollups)
|
|
return {
|
|
"db_path": str(t_path),
|
|
"total_requests": tot_reqs,
|
|
"endpoints": rollups,
|
|
"recent_audit_events": recent,
|
|
"ringbuffer_count": int(rb_cnt),
|
|
"byte_size": _sqlite_total_disk_bytes(t_path),
|
|
}
|
|
finally:
|
|
conn.close()
|
|
|
|
|
|
def run_logrotate_directive(
|
|
conf_path: Path | str | None = None,
|
|
telemetry_db_path: Path | str | None = None,
|
|
max_bytes_override: int | str | None = None,
|
|
) -> dict[str, Any]:
|
|
"""
|
|
Parse and validate `/workspace/hyperstitionstudio-core/deploy/logrotate.d/hyperstition-sqlite-meta`,
|
|
and execute its `prerotate ... endscript` quiescent truncation block against `telemetry_db_path`
|
|
using the configured `size` threshold (default `100M` / `100 MB`, overridable via `max_bytes_override`
|
|
or `HYPERSTITION_SQLITE_MAX_BYTES` / `HYPERSTITION_SQLITE_MAX_MB`).
|
|
"""
|
|
cfg = load_workspace_config()
|
|
c_path = Path(conf_path) if conf_path is not None else (cfg.core_dir / "deploy" / "logrotate.d" / "hyperstition-sqlite-meta")
|
|
txt = c_path.read_text(encoding="utf-8")
|
|
|
|
m_size = re.search(r"^\s*size\s+([0-9]+[KMGT]?B?)\s*$", txt, flags=re.MULTILINE | re.IGNORECASE)
|
|
if not m_size:
|
|
raise ValueError(f"Missing 'size <limit>' directive in {c_path}")
|
|
configured_size_str = m_size.group(1)
|
|
configured_bytes = parse_size_spec_bytes(configured_size_str)
|
|
|
|
if not re.search(r"^\s*compress\s*$", txt, flags=re.MULTILINE) or re.search(r"^\s*nocompress\s*$", txt, flags=re.MULTILINE):
|
|
raise ValueError(f"{c_path} must specify 'compress' (and not 'nocompress') so rotated archives are compressed rather than removed.")
|
|
m_rot = re.search(r"^\s*rotate\s+(\d+)\s*$", txt, flags=re.MULTILINE)
|
|
rotate_count = int(m_rot.group(1)) if m_rot else 0
|
|
if rotate_count < 1:
|
|
raise ValueError(f"{c_path} must specify 'rotate >= 1' (got rotate {rotate_count}) to retain compressed archives rather than removing.")
|
|
|
|
m_pre = re.search(r"prerotate\s*\n(.*?)\n\s*endscript", txt, flags=re.DOTALL)
|
|
if not m_pre:
|
|
raise ValueError(f"Missing 'prerotate ... endscript' block in {c_path}")
|
|
script_body = m_pre.group(1)
|
|
|
|
target_db = Path(telemetry_db_path) if telemetry_db_path is not None else get_default_telemetry_db_path()
|
|
eff_max_bytes = parse_size_spec_bytes(max_bytes_override, default_bytes=configured_bytes)
|
|
bytes_before = _sqlite_total_disk_bytes(target_db)
|
|
|
|
env = dict(os.environ)
|
|
env["PYTHONPATH"] = str(cfg.core_dir / "src")
|
|
env["HYPERSTITION_TELEMETRY_DB_PATH"] = str(target_db)
|
|
env["HYPERSTITION_SQLITE_MAX_BYTES"] = str(eff_max_bytes)
|
|
|
|
proc = subprocess.run(
|
|
["bash", "-euo", "pipefail", "-s", "--", str(target_db)],
|
|
input=script_body,
|
|
text=True,
|
|
capture_output=True,
|
|
env=env,
|
|
check=False,
|
|
)
|
|
if proc.returncode != 0:
|
|
raise RuntimeError(f"logrotate prerotate script failed (rc={proc.returncode}): {proc.stderr or proc.stdout}")
|
|
|
|
bytes_after = _sqlite_total_disk_bytes(target_db)
|
|
parsed_stdout: dict[str, Any] = {}
|
|
try:
|
|
parsed_stdout = json.loads(proc.stdout.strip())
|
|
except Exception:
|
|
pass
|
|
return {
|
|
"conf_path": str(c_path),
|
|
"configured_size_directive": configured_size_str,
|
|
"configured_default_bytes": configured_bytes,
|
|
"rotate_count": rotate_count,
|
|
"compress_enabled": True,
|
|
"effective_max_bytes": eff_max_bytes,
|
|
"db_path": str(target_db),
|
|
"bytes_before": bytes_before,
|
|
"bytes_after": bytes_after,
|
|
"truncated": bool(parsed_stdout.get("truncated", bytes_before >= eff_max_bytes)),
|
|
"quiescent": bool(parsed_stdout.get("quiescent", True)),
|
|
"compressed_archive_path": parsed_stdout.get("compressed_archive_path"),
|
|
"compressed_archive_bytes": int(parsed_stdout.get("compressed_archive_bytes") or 0),
|
|
"integrity_check": str(parsed_stdout.get("integrity_check", "ok")),
|
|
"stdout": proc.stdout.strip(),
|
|
}
|
|
|
|
|
|
def main(argv: list[str] | None = None) -> int:
|
|
ap = argparse.ArgumentParser(
|
|
prog="hs-db-build",
|
|
description="Build, query, or quiescently truncate the hyperstitionstud.io SQLite + FTS5 metadata/telemetry DBs.",
|
|
)
|
|
ap.add_argument("--build", action="store_true", help="Compile hyperstition-catalog.db.")
|
|
ap.add_argument("--db", default=None, help="Path to catalog or telemetry SQLite DB.")
|
|
ap.add_argument("--manifests", action="store_true", help="Query registry_manifests.")
|
|
ap.add_argument("--search", default=None, help="Run FTS5 BM25 search query across fts_catalog.")
|
|
ap.add_argument("--coordinate", type=int, default=None, help="Run unified coordinate join for integer AQ.")
|
|
ap.add_argument("--timeseries", action="store_true", help="Query periodic quant_timeseries_bars.")
|
|
ap.add_argument("--symbol", default=None, help="Optional ticker symbol filter for --timeseries.")
|
|
ap.add_argument("--telemetry", action="store_true", help="Print REST/MCP telemetry rollup summary.")
|
|
ap.add_argument(
|
|
"--truncate-quiescent",
|
|
action="store_true",
|
|
help="Quiescently compress and truncate the REST/MCP telemetry SQLite DB if >= --max-mb / --max-bytes.",
|
|
)
|
|
ap.add_argument(
|
|
"--compress-archive",
|
|
action="store_true",
|
|
default=True,
|
|
help="Write a gzip-compressed point-in-time SQLite archive (<db>.1.gz) before truncating (default: True).",
|
|
)
|
|
ap.add_argument("--rotate-keep", type=int, default=12, help="Number of compressed .gz generations to keep (default: 12).")
|
|
ap.add_argument("--max-mb", type=float, default=None, help="Max telemetry DB size in MB (default: 100).")
|
|
ap.add_argument("--max-bytes", type=int, default=None, help="Max telemetry DB size in bytes (default: 104857600).")
|
|
ap.add_argument("--force", action="store_true", help="Force quiescent truncation regardless of current file size.")
|
|
args = ap.parse_args(argv)
|
|
|
|
if args.truncate_quiescent:
|
|
limit: int | str | None = args.max_bytes
|
|
if limit is None and args.max_mb is not None:
|
|
limit = int(args.max_mb * 1024 * 1024)
|
|
out = truncate_telemetry_db_quiescent(
|
|
telemetry_db_path=args.db,
|
|
max_bytes=limit,
|
|
force=args.force,
|
|
compress_archive=args.compress_archive,
|
|
rotate_keep=args.rotate_keep,
|
|
)
|
|
print(json.dumps(out, indent=2))
|
|
return 0
|
|
|
|
if args.build:
|
|
out = build_catalog_sqlite_db(args.db)
|
|
print(json.dumps(out, indent=2))
|
|
return 0
|
|
|
|
if args.manifests:
|
|
print(json.dumps(query_registry_manifests(args.db), indent=2))
|
|
return 0
|
|
|
|
if args.search is not None:
|
|
print(json.dumps(query_fts_catalog(args.search, db_path=args.db), indent=2))
|
|
return 0
|
|
|
|
if args.coordinate is not None:
|
|
print(json.dumps(query_coordinate_join(args.coordinate, db_path=args.db), indent=2))
|
|
return 0
|
|
|
|
if args.timeseries:
|
|
print(json.dumps(query_timeseries_bars(symbol=args.symbol, db_path=args.db), indent=2))
|
|
return 0
|
|
|
|
if args.telemetry:
|
|
print(json.dumps(get_api_telemetry_summary(args.db), indent=2))
|
|
return 0
|
|
|
|
out = build_catalog_sqlite_db(args.db)
|
|
print(json.dumps(out, indent=2))
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|