Files
hyperstitionstudio-core/src/hyperstitionstud_io/db/sqlite_meta.py
T

1633 lines
71 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,
data_available INTEGER NOT NULL DEFAULT 0,
status TEXT NOT NULL DEFAULT 'No data available',
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,
change_pct REAL,
change_bps INTEGER,
volume_ratio_20d REAL,
market_cap_str TEXT NOT NULL,
close_digit_aq INTEGER,
close_spoken_ing TEXT NOT NULL,
close_spoken_ing_aq INTEGER,
scaled_cap_spoken_ing_aq INTEGER,
bps_spoken_ing_aq INTEGER,
co_present_in_news_wire INTEGER NOT NULL,
contingent_points REAL,
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,
external_requests INTEGER NOT NULL DEFAULT 0,
internal_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,
traffic_source TEXT NOT NULL DEFAULT 'internal_test'
);
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;
CREATE TABLE IF NOT EXISTS api_parameter_rollups (
param_category TEXT NOT NULL,
param_value TEXT NOT NULL,
total_requests INTEGER NOT NULL DEFAULT 0,
external_requests INTEGER NOT NULL DEFAULT 0,
internal_requests INTEGER NOT NULL DEFAULT 0,
last_called_utc TEXT NOT NULL,
PRIMARY KEY (param_category, param_value)
) WITHOUT ROWID;
CREATE TABLE IF NOT EXISTS static_route_rollups (
route_prefix TEXT PRIMARY KEY,
total_hits INTEGER NOT NULL DEFAULT 0,
last_ingested_utc TEXT NOT NULL
) WITHOUT ROWID;
"""
ALLOWED_TELEMETRY_PARAM_ENUMS: dict[str, set[str]] = {
"symbol": {
"NVDA", "TSM", "ASML", "MSFT", "GOOGL", "META", "AMZN", "AAPL",
"PLTR", "AMD", "ARM", "AVGO", "ORCL", "TSLA", "COIN", "MSTR",
"IBIT", "BTC-USD", "ETH-USD", "SOL-USD", "SPY", "QQQ", "VIX", "ANTHR-PVT",
},
"lens": {
"tierzoo", "pokedex_scanner", "corporate_board",
"fund_manager", "fantasy_football", "schizoanalytic",
},
"lang": {"guile", "ts", "rust"},
"unit_filter": {"E0", "E1", "E2", "E3", "E4", "E5", "M0", "M1", "M2", "M3", "M4", "M5"},
"surface": {"home", "calc", "quant", "graph", "learn", "engineering", "math", "donate"},
"donate_from": {"home", "calc", "quant", "graph", "learn", "engineering", "math"},
"donate_copy": {"BTC", "XMR"},
"export_action": {
"learn_state_json", "quant_csv", "quant_json", "quant_tradingview", "graph_png",
},
}
CANONICAL_STATIC_ROUTE_PREFIXES: tuple[str, ...] = (
"/zoology/proposal-fund-manager-novel-investment-discovery.pdf",
"/zoology/proposal-corporate-board-technocapital-allocation.pdf",
"/zoology/proposal-fantasy-football-technocapital-roster-engine.pdf",
"/zoology/proposal-fund-manager-standard-english-aq.pdf",
"/zoology/proposal-corporate-board-standard-english-aq.pdf",
"/zoology/m7-emergent-subclass-bidirectional-aq-nucleation.pdf",
"/zoology/tier-list-technocapital-assemblage-builds.pdf",
"/zoology/tier-list-technocapital-assemblage-builds.png",
"/zoology/technocapital-singularity-zoology-comprehensive-glossary.pdf",
"/zoology/encyclopedia-of-technocapital-singularity-zoology-overview-and-manifest.pdf",
"/encyclopedia/",
"/calc/",
"/quant/",
"/graph/",
"/learn/",
"/engineering/",
"/math/",
"/donate/",
"/archive/",
"/ci/",
"/",
)
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)
state_dir = Path("/var/lib/hyperstitionstud.io")
if state_dir.is_dir() and os.access(state_dir, os.W_OK):
return state_dir / "api-telemetry.db"
if state_dir.parent.is_dir() and os.access(state_dir.parent, os.W_OK):
try:
state_dir.mkdir(parents=True, exist_ok=True)
if os.access(state_dir, os.W_OK):
return state_dir / "api-telemetry.db"
except OSError:
pass
try:
cache_dir = Path.home() / ".cache" / "hyperstitionstud.io"
cache_dir.mkdir(parents=True, exist_ok=True)
if os.access(cache_dir, os.W_OK):
return cache_dir / "api-telemetry.db"
except OSError:
pass
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, data_available, status, 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"]),
1 if bar.get("data_available") else 0,
str(bar.get("status") or ("ok" if bar.get("data_available") else "No data available")),
ent_eng,
ent_ing,
ent_aq,
guilds_csv,
tv_sym,
tv_url,
float(bar["close_usd"]) if bar.get("close_usd") is not None else None,
float(bar["change_pct"]) if bar.get("change_pct") is not None else None,
int(bar["change_bps"]) if bar.get("change_bps") is not None else None,
float(bar["volume_ratio_20d"]) if bar.get("volume_ratio_20d") is not None else None,
str(bar.get("market_cap_str") or "No data available"),
int(bar["close_digit_aq"]) if bar.get("close_digit_aq") is not None else None,
str(bar.get("close_spoken_ing") or "No data available"),
int(bar["close_spoken_ing_aq"]) if bar.get("close_spoken_ing_aq") is not None else None,
int(bar["scaled_cap_spoken_ing_aq"]) if bar.get("scaled_cap_spoken_ing_aq") is not None else None,
int(bar["bps_spoken_ing_aq"]) if bar.get("bps_spoken_ing_aq") is not None else None,
1 if bar.get("co_present_in_news_wire") else 0,
float(bar["contingent_points"]) if bar.get("contingent_points") is not None else None,
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;")
conn.execute("PRAGMA temp_store = MEMORY;")
conn.execute("PRAGMA cache_size = -8000;")
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 | None = None,
db_path: Path | str | None = None,
) -> list[dict[str, Any]]:
conn = _open_readonly_catalog(db_path)
try:
clauses: list[str] = []
params: list[Any] = []
if min_points is not None:
clauses.append("contingent_points IS NOT NULL AND contingent_points >= ?")
params.append(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 = (" WHERE " + " AND ".join(clauses)) if clauses else ""
rows = conn.execute(
f"SELECT * FROM quant_timeseries_bars{where_sql} ORDER BY date_utc DESC, symbol ASC",
params,
).fetchall()
return [dict(r) for r in rows]
finally:
conn.close()
def ensure_single_layer_gzip_file(gz_path: Path | str) -> dict[str, Any]:
"""
Inspect `gz_path` and ensure its decompressed stream is compressed strictly once (`1x`).
If the decompressed payload itself begins with a gzip (`\\x1f\\x8b`) or xz (`\\xfd7zXZ\\x00`)
magic header, iteratively peel outer compression layers in-place until the inner stream
is the raw uncompressed payload (e.g., `"SQLite format 3\\x00"` or POSIX `ustar`).
"""
p = Path(gz_path)
if not p.is_file():
return {"path": str(p), "peeled_layers": 0, "single_layer_verified": False}
peeled = 0
while True:
with gzip.open(p, "rb") as f_gz:
head = f_gz.read(6)
if head.startswith(b"\x1f\x8b"):
f_gz.seek(0)
inner_bytes = f_gz.read()
elif head.startswith(b"\xfd7zXZ\x00"):
import lzma
f_gz.seek(0)
raw_unwrapped = lzma.decompress(f_gz.read())
tmp_p = p.with_suffix(p.suffix + f".peel.{os.getpid()}")
with open(tmp_p, "wb") as f_raw:
with gzip.GzipFile(filename="", mode="wb", fileobj=f_raw, compresslevel=9, mtime=0) as gz_out:
gz_out.write(raw_unwrapped)
os.replace(tmp_p, p)
peeled += 1
continue
else:
break
tmp_p = p.with_suffix(p.suffix + f".peel.{os.getpid()}")
tmp_p.write_bytes(inner_bytes)
os.replace(tmp_p, p)
peeled += 1
return {"path": str(p), "peeled_layers": peeled, "single_layer_verified": True}
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():
ensure_single_layer_gzip_file(src)
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())
ensure_single_layer_gzip_file(gz_target)
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 api_parameter_rollups;")
conn.execute("DELETE FROM static_route_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 _ensure_telemetry_columns(conn: sqlite3.Connection) -> None:
"""
Idempotently migrate existing `api_endpoint_rollups` and `api_audit_ringbuffer` tables
so older databases gain `external_requests`, `internal_requests`, and `traffic_source`.
"""
rollup_cols = {r[1] for r in conn.execute("PRAGMA table_info(api_endpoint_rollups)").fetchall()}
if "external_requests" not in rollup_cols:
conn.execute("ALTER TABLE api_endpoint_rollups ADD COLUMN external_requests INTEGER NOT NULL DEFAULT 0;")
if "internal_requests" not in rollup_cols:
conn.execute("ALTER TABLE api_endpoint_rollups ADD COLUMN internal_requests INTEGER NOT NULL DEFAULT 0;")
conn.execute("UPDATE api_endpoint_rollups SET internal_requests = total_requests WHERE external_requests = 0 AND internal_requests = 0;")
rb_cols = {r[1] for r in conn.execute("PRAGMA table_info(api_audit_ringbuffer)").fetchall()}
if "traffic_source" not in rb_cols:
conn.execute("ALTER TABLE api_audit_ringbuffer ADD COLUMN traffic_source TEXT NOT NULL DEFAULT 'internal_test';")
_INITIALIZED_TELEMETRY_INODES: set[tuple[str, int, int]] = set()
def _ensure_telemetry_schema_initialized(conn: sqlite3.Connection, db_path: Path) -> None:
try:
st = db_path.stat()
inode_key = (str(db_path.resolve()), st.st_dev, st.st_ino)
except OSError:
inode_key = None
if inode_key is not None and inode_key in _INITIALIZED_TELEMETRY_INODES and st.st_size > 0:
return
conn.executescript(TELEMETRY_SCHEMA_SQL)
_ensure_telemetry_columns(conn)
if inode_key is not None:
try:
st_after = db_path.stat()
_INITIALIZED_TELEMETRY_INODES.add((str(db_path.resolve()), st_after.st_dev, st_after.st_ino))
except OSError:
pass
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,
traffic_source: str = "internal_test",
param_events: dict[str, str] | None = None,
) -> dict[str, Any]:
"""
Record a privacy-preserving REST (`/api/v1/*`) or MCP (`/mcp`) call in `api-telemetry.db`,
separating `external_production` traffic from `internal_test` probes, recording allowlisted
closed-set enum parameters in `api_parameter_rollups` (`Strategy 2B`), and automatically
performing 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
src_norm = "external_production" if traffic_source == "external_production" else "internal_test"
ext_inc = 1 if src_norm == "external_production" else 0
int_inc = 1 if src_norm == "internal_test" 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
valid_params: list[tuple[str, str]] = []
if param_events:
for raw_cat, raw_val in param_events.items():
if not raw_val:
continue
cat = str(raw_cat).strip()
allowed_set = ALLOWED_TELEMETRY_PARAM_ENUMS.get(cat)
if not allowed_set:
continue
val_cand = str(raw_val).strip()
if cat in ("symbol", "unit_filter", "donate_copy"):
val_cand = val_cand.upper()
else:
val_cand = val_cand.lower()
if val_cand in allowed_set:
valid_params.append((cat, val_cand))
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;")
_ensure_telemetry_schema_initialized(conn, t_path)
conn.execute("BEGIN IMMEDIATE;")
try:
conn.execute(
"""
INSERT INTO api_endpoint_rollups (
protocol, method, endpoint_pattern, total_requests,
external_requests, internal_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,
external_requests = external_requests + excluded.external_requests,
internal_requests = internal_requests + excluded.internal_requests,
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, ext_inc, int_inc, s_2xx, s_304, s_4xx, s_5xx, lat, lat, now_utc),
)
for p_cat, p_val in valid_params:
conn.execute(
"""
INSERT INTO api_parameter_rollups (
param_category, param_value, total_requests,
external_requests, internal_requests, last_called_utc
) VALUES (?, ?, 1, ?, ?, ?)
ON CONFLICT(param_category, param_value) DO UPDATE SET
total_requests = total_requests + 1,
external_requests = external_requests + excluded.external_requests,
internal_requests = internal_requests + excluded.internal_requests,
last_called_utc = excluded.last_called_utc
""",
(p_cat, p_val, ext_inc, int_inc, now_utc),
)
conn.execute(
"""
INSERT INTO api_audit_ringbuffer (
timestamp_utc, endpoint, status_code, latency_us, isolation_ok, traffic_source
) VALUES (?, ?, ?, ?, ?, ?)
""",
(now_utc, f"{protocol}:{method} {endpoint_pattern}", code, lat, iso_int, src_norm),
)
conn.execute("COMMIT;")
except Exception:
conn.execute("ROLLBACK;")
raise
finally:
conn.close()
for suf in ("", "-wal", "-shm"):
cand = Path(f"{t_path}{suf}")
if cand.exists():
try:
os.chmod(cand, 0o666)
except OSError:
pass
return {"ok": True, "db_path": str(t_path), "traffic_source": src_norm}
except Exception as exc:
return {"ok": False, "error": str(exc)}
MIN_EXTERNAL_REQUESTS_FOR_CONFIDENCE = 500
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,
"external_production_requests": 0,
"internal_test_requests": 0,
"market_demand_confidence": "No data available",
"endpoints": [],
"parameter_rollups": [],
"static_route_rollups": [],
"recent_audit_events": [],
"ringbuffer_count": 0,
"byte_size": 0,
}
conn = sqlite3.connect(str(t_path), timeout=30.0)
conn.row_factory = sqlite3.Row
try:
conn.executescript(TELEMETRY_SCHEMA_SQL)
_ensure_telemetry_columns(conn)
rollups = [
dict(r)
for r in conn.execute(
"SELECT * FROM api_endpoint_rollups ORDER BY total_requests DESC, endpoint_pattern ASC"
).fetchall()
]
param_rollups = [
dict(r)
for r in conn.execute(
"SELECT * FROM api_parameter_rollups ORDER BY total_requests DESC, param_category ASC, param_value ASC"
).fetchall()
]
static_rollups = [
dict(r)
for r in conn.execute(
"SELECT * FROM static_route_rollups ORDER BY total_hits DESC, route_prefix 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)
ext_reqs = sum(int(r.get("external_requests", 0)) for r in rollups)
int_reqs = sum(int(r.get("internal_requests", 0)) for r in rollups)
if ext_reqs < MIN_EXTERNAL_REQUESTS_FOR_CONFIDENCE:
confidence_status = "No data available"
else:
confidence_status = f"Sufficient external production sample (n={ext_reqs})"
return {
"db_path": str(t_path),
"total_requests": tot_reqs,
"external_production_requests": ext_reqs,
"internal_test_requests": int_reqs,
"market_demand_confidence": confidence_status,
"endpoints": rollups,
"parameter_rollups": param_rollups,
"static_route_rollups": static_rollups,
"recent_audit_events": recent,
"ringbuffer_count": int(rb_cnt),
"byte_size": _sqlite_total_disk_bytes(t_path),
}
finally:
conn.close()
def get_longitudinal_telemetry_summary(
telemetry_db_path: Path | str | None = None,
max_generations: int = 12,
) -> dict[str, Any]:
"""
Aggregate `api_endpoint_rollups`, `api_parameter_rollups`, and `static_route_rollups` across
both the active `api-telemetry.db` and up to `max_generations` rotated `.{1..K}.gz` snapshots
(`Strategy 2C`: `--telemetry-history`).
"""
import tempfile
t_path = Path(telemetry_db_path) if telemetry_db_path is not None else get_default_telemetry_db_path()
endpoint_totals: dict[tuple[str, str, str], dict[str, Any]] = {}
param_totals: dict[tuple[str, str], dict[str, Any]] = {}
static_totals: dict[str, dict[str, Any]] = {}
generations_scanned: list[str] = []
def _merge_summary(s: dict[str, Any], label: str) -> None:
generations_scanned.append(label)
for ep in s.get("endpoints", []):
key = (ep["protocol"], ep["method"], ep["endpoint_pattern"])
cur = endpoint_totals.get(key)
if cur is None:
endpoint_totals[key] = dict(ep)
else:
for k_num in ("total_requests", "external_requests", "internal_requests", "status_2xx", "status_304", "status_4xx", "status_5xx", "total_latency_us"):
cur[k_num] = int(cur.get(k_num, 0)) + int(ep.get(k_num, 0))
cur["max_latency_us"] = max(int(cur.get("max_latency_us", 0)), int(ep.get("max_latency_us", 0)))
if str(ep.get("last_called_utc", "")) > str(cur.get("last_called_utc", "")):
cur["last_called_utc"] = ep["last_called_utc"]
for pr in s.get("parameter_rollups", []):
pkey = (pr["param_category"], pr["param_value"])
cur_p = param_totals.get(pkey)
if cur_p is None:
param_totals[pkey] = dict(pr)
else:
for k_num in ("total_requests", "external_requests", "internal_requests"):
cur_p[k_num] = int(cur_p.get(k_num, 0)) + int(pr.get(k_num, 0))
if str(pr.get("last_called_utc", "")) > str(cur_p.get("last_called_utc", "")):
cur_p["last_called_utc"] = pr["last_called_utc"]
for sr in s.get("static_route_rollups", []):
rpref = sr["route_prefix"]
cur_s = static_totals.get(rpref)
if cur_s is None:
static_totals[rpref] = dict(sr)
else:
cur_s["total_hits"] = int(cur_s.get("total_hits", 0)) + int(sr.get("total_hits", 0))
if str(sr.get("last_ingested_utc", "")) > str(cur_s.get("last_ingested_utc", "")):
cur_s["last_ingested_utc"] = sr["last_ingested_utc"]
if t_path.is_file():
_merge_summary(get_api_telemetry_summary(t_path), str(t_path.name))
for idx in range(1, max_generations + 1):
gz_p = Path(f"{t_path}.{idx}.gz")
if not gz_p.is_file():
continue
try:
with tempfile.NamedTemporaryFile(suffix=".db", delete=True) as tmp_f:
with gzip.open(gz_p, "rb") as f_in:
tmp_f.write(f_in.read())
tmp_f.flush()
_merge_summary(get_api_telemetry_summary(tmp_f.name), gz_p.name)
except Exception:
continue
tot_reqs = sum(int(v.get("total_requests", 0)) for v in endpoint_totals.values())
ext_reqs = sum(int(v.get("external_requests", 0)) for v in endpoint_totals.values())
int_reqs = sum(int(v.get("internal_requests", 0)) for v in endpoint_totals.values())
confidence_status = (
"No data available"
if ext_reqs < MIN_EXTERNAL_REQUESTS_FOR_CONFIDENCE
else f"Sufficient external production sample (n={ext_reqs})"
)
return {
"base_db_path": str(t_path),
"generations_scanned": generations_scanned,
"generations_count": len(generations_scanned),
"total_requests": tot_reqs,
"external_production_requests": ext_reqs,
"internal_test_requests": int_reqs,
"market_demand_confidence": confidence_status,
"endpoints": sorted(endpoint_totals.values(), key=lambda x: (-int(x.get("total_requests", 0)), x["endpoint_pattern"])),
"parameter_rollups": sorted(param_totals.values(), key=lambda x: (-int(x.get("total_requests", 0)), x["param_category"], x["param_value"])),
"static_route_rollups": sorted(static_totals.values(), key=lambda x: (-int(x.get("total_hits", 0)), x["route_prefix"])),
}
def ingest_caddy_route_counts(
log_path: Path | str = "/var/log/caddy/hyperstition-access.json",
telemetry_db_path: Path | str | None = None,
truncate_log: bool = True,
) -> dict[str, Any]:
"""
Ingest zero-IP Caddy JSON access log entries (`Strategy 3A`: `--ingest-caddy-route-counts`)
into `static_route_rollups` inside `api-telemetry.db`, mapping URIs onto `CANONICAL_STATIC_ROUTE_PREFIXES`
and discarding all client identifiers.
"""
l_path = Path(log_path)
t_path = Path(telemetry_db_path) if telemetry_db_path is not None else get_default_telemetry_db_path()
now_utc = dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
if not l_path.is_file():
return {"ok": True, "log_path": str(l_path), "ingested_lines": 0, "matched_hits": 0, "status": "log_absent"}
counts_by_prefix: dict[str, int] = {}
lines_read = 0
for raw_ln in l_path.read_text(encoding="utf-8", errors="replace").splitlines():
ln = raw_ln.strip()
if not ln:
continue
lines_read += 1
try:
obj = json.loads(ln)
except Exception:
continue
status = int(obj.get("status", 0) or 0)
if status not in (200, 304):
continue
req_obj = obj.get("request") or {}
uri = str(req_obj.get("uri") or obj.get("uri") or "").split("?", 1)[0]
if not uri or uri.startswith("/api/v1") or uri.startswith("/mcp") or uri.startswith("/assets/"):
continue
for pref in CANONICAL_STATIC_ROUTE_PREFIXES:
if pref == "/":
if uri in ("/", "/index.html"):
counts_by_prefix["/"] = counts_by_prefix.get("/", 0) + 1
break
elif uri == pref or uri.startswith(pref):
counts_by_prefix[pref] = counts_by_prefix.get(pref, 0) + 1
break
if counts_by_prefix:
t_path.parent.mkdir(parents=True, exist_ok=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:
for pref, cnt in counts_by_prefix.items():
conn.execute(
"""
INSERT INTO static_route_rollups (route_prefix, total_hits, last_ingested_utc)
VALUES (?, ?, ?)
ON CONFLICT(route_prefix) DO UPDATE SET
total_hits = total_hits + excluded.total_hits,
last_ingested_utc = excluded.last_ingested_utc
""",
(pref, cnt, now_utc),
)
conn.execute("COMMIT;")
except Exception:
conn.execute("ROLLBACK;")
raise
finally:
conn.close()
if truncate_log:
try:
l_path.write_text("", encoding="utf-8")
except OSError:
pass
return {
"ok": True,
"log_path": str(l_path),
"db_path": str(t_path),
"ingested_lines": lines_read,
"matched_hits": sum(counts_by_prefix.values()),
"counts_by_prefix": counts_by_prefix,
}
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*nocompress\s*$", txt, flags=re.MULTILINE) or "--compress-archive" not in txt:
raise ValueError(
f"{c_path} must specify 'nocompress' in the outer logrotate block and '--compress-archive' in prerotate so sqlite_meta.py compresses rotated archives strictly once (1x)."
)
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("--telemetry-history", action="store_true", help="Print longitudinal REST/MCP telemetry aggregated across active DB and rotated .1.gz..12.gz snapshots (Strategy 2C).")
ap.add_argument("--ingest-caddy-route-counts", action="store_true", help="Ingest zero-IP Caddy JSON access log counts into static_route_rollups (Strategy 3A).")
ap.add_argument("--caddy-log", default="/var/log/caddy/hyperstition-access.json", help="Path to zero-IP Caddy access log.")
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_history:
print(json.dumps(get_longitudinal_telemetry_summary(args.db), indent=2))
return 0
if args.ingest_caddy_route_counts:
print(json.dumps(ingest_caddy_route_counts(args.caddy_log, telemetry_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())