512 lines
25 KiB
Python
512 lines
25 KiB
Python
"""
|
|
Pytest verification suite for hyperstitionstudio-core (hyperstitionstud_io.*).
|
|
Tests:
|
|
1. Zero-HTTPS offline namespace & HTML portability (urn:io:hyperstitionstud:*).
|
|
2. Base-36 AQ, Prime Rank, and G1-G6 vector parity across all 190 bilingual specimens.
|
|
3. Offline CMUdict phonetics fallback (zero --workdir dependency).
|
|
4. ReadOnlyIsolationGuard SHA-256 verification on glossary-registry.json & encyclopedia-manifest.json.
|
|
5. Local-config citation URL resolution ([citations.path_mounts]) and verify_draft() across all 5 proposals.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import re
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
_SRC_DIR = Path(__file__).resolve().parents[1] / "src"
|
|
if _SRC_DIR.is_dir() and str(_SRC_DIR) not in sys.path:
|
|
sys.path.insert(0, str(_SRC_DIR))
|
|
|
|
from hyperstitionstud_io.ciphers import (
|
|
assert_zero_d_filter,
|
|
compute_aq,
|
|
evaluate_bidirectional_lock,
|
|
is_repdigit_37,
|
|
prime_rank,
|
|
)
|
|
from hyperstitionstud_io.ci.citation_sources import (
|
|
load_ledger,
|
|
resolve_citation_target,
|
|
verify_draft,
|
|
)
|
|
from hyperstitionstud_io.ci.doctor import run_diagnostics
|
|
from hyperstitionstud_io.config import load_workspace_config
|
|
from hyperstitionstud_io.glossary import ReadOnlyIsolationGuard
|
|
from hyperstitionstud_io.graph import URN_GRAPH_NS, make_entity_urn
|
|
from hyperstitionstud_io.phonetics import translate_batch
|
|
|
|
|
|
def test_offline_urn_namespaces_and_no_external_https_fonts() -> None:
|
|
assert URN_GRAPH_NS == "urn:io:hyperstitionstud:ns:kg:1.0"
|
|
assert make_entity_urn("zoology", "build", "S1") == "urn:io:hyperstitionstud:zoology:build:S1"
|
|
|
|
cfg = load_workspace_config()
|
|
for html_p in (
|
|
cfg.core_dir / "site" / "index.html",
|
|
cfg.core_dir / "site" / "donate" / "index.html",
|
|
cfg.core_dir / "site" / "learn" / "index.html",
|
|
cfg.core_dir / "site" / "quant" / "index.html",
|
|
cfg.core_dir / "site" / "gallery" / "index.html",
|
|
cfg.knowledge_graph_dir / "index.html",
|
|
cfg.knowledge_graph_dir / "docs" / "cross-repo-dependency-and-audit-flow-diagram.html",
|
|
cfg.paths["gematria_js_dir"] / "index.html",
|
|
):
|
|
txt = html_p.read_text(encoding="utf-8")
|
|
assert "fonts.googleapis.com" not in txt
|
|
assert "https://hyperstitionstud.io" not in txt
|
|
assert "by Lemurs." in txt, f"Missing global Lemurs footer in {html_p}"
|
|
assert ("♥" in txt or "♥" in txt), f"Missing Unicode heart in {html_p}"
|
|
|
|
for nav_p in (
|
|
cfg.core_dir / "site" / "index.html",
|
|
cfg.core_dir / "site" / "learn" / "index.html",
|
|
cfg.core_dir / "site" / "quant" / "index.html",
|
|
):
|
|
nav_txt = nav_p.read_text(encoding="utf-8")
|
|
assert "btn-donate-pill" in nav_txt, f"Missing distinct stadium-pill Donate button in {nav_p}"
|
|
assert "donate-pill-emblem" in nav_txt, f"Missing circular 1:2 Donate emblem in {nav_p}"
|
|
assert "nav-donate-sep" in nav_txt, f"Missing vertical divider before Donate pill in {nav_p}"
|
|
assert "margin-left: auto" in nav_txt, f"Missing right-justification margin-left: auto in {nav_p}"
|
|
|
|
schemas_dir = cfg.core_dir / "schemas" / "v1"
|
|
for sp in schemas_dir.glob("*.schema.json"):
|
|
s_obj = json.loads(sp.read_text(encoding="utf-8"))
|
|
assert s_obj["$id"].startswith("urn:io:hyperstitionstud:schema:v1:")
|
|
assert "https://hyperstitionstud.io" not in sp.read_text(encoding="utf-8")
|
|
|
|
# Verify all visible site version numbers match hyperstitionstud_io.__version__
|
|
from hyperstitionstud_io import __version__ as cur_ver
|
|
from hyperstitionstud_io.version_sync import sync_workspace_version
|
|
|
|
v_sync = sync_workspace_version(cur_ver, check_only=True, ws_root=cfg.workspace_root)
|
|
assert v_sync["all_in_sync"] is True, f"Site version drift detected: {v_sync['mismatched_files']}"
|
|
|
|
|
|
def test_ciphers_and_bilingual_ledger_parity() -> None:
|
|
cfg = load_workspace_config()
|
|
gl_path = cfg.zoology_dir / "taxonomy" / "glossary-registry.json"
|
|
gl_data = json.loads(gl_path.read_text(encoding="utf-8"))
|
|
for item in gl_data["bilingual_vocabulary_ledger"]:
|
|
lock = evaluate_bidirectional_lock(item["eng"], item["ing"])
|
|
assert lock["eng_aq"] == item["eng_aq"]
|
|
assert lock["ing_aq"] == item["ing_aq"]
|
|
assert lock["delta"] == item["delta"]
|
|
assert lock["isometric"] == item["isometric"]
|
|
assert lock["twin_prime_mutation"] == item["twin_prime"]
|
|
assert compute_aq("Dario Amodei") == 193
|
|
assert prime_rank(193) == 44
|
|
assert is_repdigit_37(333) and is_repdigit_37(666) and is_repdigit_37(777)
|
|
assert_zero_d_filter("Pure Base-36 Alphanumeric Qabbala")
|
|
|
|
|
|
def test_offline_phonetics_fallback_zero_workdir() -> None:
|
|
res = translate_batch(
|
|
["schizoanalysis", "abstract machine", "synthetic data", "Anthropic", "flash crash", "Blackwell"],
|
|
workdir="/nonexistent/offline/path",
|
|
)
|
|
assert res["schizoanalysis"] == "shizohnalizis"
|
|
assert res["abstract machine"] == "abstrakt masheen"
|
|
assert res["synthetic data"] == "sinthetik dayta"
|
|
assert res["Anthropic"] == "anthropik"
|
|
assert res["flash crash"] == "flash krash"
|
|
assert res["Blackwell"] == "blakwel"
|
|
|
|
|
|
def test_read_only_isolation_guard() -> None:
|
|
cfg = load_workspace_config()
|
|
with ReadOnlyIsolationGuard(cfg.read_only_files) as guard:
|
|
_ = [p.stat().st_size for p in cfg.read_only_files]
|
|
receipt = guard.audit_receipt()
|
|
assert receipt["all_unchanged"] is True
|
|
|
|
|
|
def test_local_config_citation_resolution_and_proposals() -> None:
|
|
mounts = {
|
|
"/workspace/ingglish-hyperdope-gematria": "https://git.libre.audio/m00t/ingglish-hyperdope-gematria/src/branch/main"
|
|
}
|
|
# Mapped prefix resolves to configured remote URL
|
|
u1 = resolve_citation_target(
|
|
"/workspace/ingglish-hyperdope-gematria/ingglish-aq-archive/70-dossier-news-2026-11-28.md",
|
|
path_mounts=mounts,
|
|
)
|
|
assert u1 == "https://git.libre.audio/m00t/ingglish-hyperdope-gematria/src/branch/main/ingglish-aq-archive/70-dossier-news-2026-11-28.md"
|
|
|
|
# Unmapped prefix NEVER resolves to a global namespace URL; stays local filesystem path
|
|
u2 = resolve_citation_target(
|
|
"/workspace/technocapital-singularity-zoology/dossiers/65-dossier-technocapital-singularity-autoregressive-ai.md",
|
|
path_mounts=mounts,
|
|
)
|
|
assert u2 == "/workspace/technocapital-singularity-zoology/dossiers/65-dossier-technocapital-singularity-autoregressive-ai.md"
|
|
|
|
cfg = load_workspace_config()
|
|
common_sources = load_ledger(cfg.zoology_dir / "taxonomy" / "citations-ledger-common.json")["sources"]
|
|
for fname in (
|
|
"proposal-fantasy-football-technocapital-roster-engine.md",
|
|
"proposal-corporate-board-technocapital-allocation.md",
|
|
"proposal-fund-manager-novel-investment-discovery.md",
|
|
):
|
|
code, errors, _ = verify_draft(cfg.zoology_dir / fname, common_sources, require_evidence=True)
|
|
assert code == 0, f"{fname} failed: {errors}"
|
|
|
|
eng_sources = load_ledger(cfg.zoology_dir / "taxonomy" / "citations-ledger-english-aq.json")["sources"]
|
|
for fname in (
|
|
"proposal-corporate-board-standard-english-aq.md",
|
|
"proposal-fund-manager-standard-english-aq.md",
|
|
):
|
|
code, errors, _ = verify_draft(cfg.zoology_dir / fname, eng_sources, require_evidence=True)
|
|
assert code == 0, f"{fname} failed: {errors}"
|
|
|
|
|
|
def test_doctor_all_checks_pass() -> None:
|
|
diag = run_diagnostics()
|
|
assert diag["all_checks_passed"] is True
|
|
|
|
|
|
def test_ipld_quant_and_mcp_server() -> None:
|
|
from hyperstitionstud_io.ipld import compute_dag_json_cidv1, encode_dag_json
|
|
from hyperstitionstud_io.mcp.server import dispatch_jsonrpc
|
|
from hyperstitionstud_io.quant.collector import build_financial_quant_harvest
|
|
|
|
# 1. IPLD dag-json & CIDv1 deterministic parity
|
|
b1 = encode_dag_json({"b": 2, "a": 1})
|
|
b2 = encode_dag_json({"a": 1, "b": 2})
|
|
assert b1 == b2 == b'{"a":1,"b":2}'
|
|
cid = compute_dag_json_cidv1({"a": 1, "b": 2})
|
|
assert cid.startswith("baguqeera")
|
|
|
|
# 2. Quantitative Financial Telemetry Collector
|
|
q_harvest = build_financial_quant_harvest()
|
|
assert q_harvest["harvest_mode"] == "us-closing-bell"
|
|
assert q_harvest["regime_summary"]["instrument_count"] == 24
|
|
assert q_harvest["regime_summary"]["total_contingent_locks"] >= 20
|
|
assert q_harvest["isolation_receipt"]["all_unchanged"] is True
|
|
assert q_harvest["ipld_dag_json_cidv1"]["/"].startswith("baguqeera")
|
|
nvda_inst = next(x for x in q_harvest["instruments"] if x["symbol"] == "NVDA")
|
|
assert nvda_inst["quant_encodings"]["close_spoken_ing"] == "wuhn huhndrad therdee sevan"
|
|
assert nvda_inst["quant_encodings"]["scaled_cap_spoken_ing"] == "three point three faiv trilyan"
|
|
assert any(l["scope"] == "SCOPE1_INTRA_INSTRUMENT_SELF_LOCK" for l in nvda_inst["contingent_locks"])
|
|
|
|
q_rollover = build_financial_quant_harvest(harvest_mode="utc-rollover")
|
|
assert q_rollover["harvest_mode"] == "utc-rollover"
|
|
assert q_rollover["isolation_receipt"]["all_unchanged"] is True
|
|
|
|
# 3. MCP Server JSON-RPC 2.0 Dispatch (initialize, tools/list, tools/call, resources/read, prompts/get)
|
|
init_resp = dispatch_jsonrpc({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": "2025-03-26"}})
|
|
assert init_resp and init_resp["result"]["serverInfo"]["name"] == "hyperstitionstudio-mcp"
|
|
|
|
t_list = dispatch_jsonrpc({"jsonrpc": "2.0", "id": 2, "method": "tools/list"})
|
|
assert t_list and len(t_list["result"]["tools"]) == 12
|
|
|
|
t_call = dispatch_jsonrpc({
|
|
"jsonrpc": "2.0",
|
|
"id": 3,
|
|
"method": "tools/call",
|
|
"params": {"name": "hs_evaluate_aq_and_ingglish", "arguments": {"terms": ["schizoanalysis", "abstract machine", "synthetic data"]}},
|
|
})
|
|
assert t_call and t_call["result"]["isError"] is False
|
|
parsed_tool = json.loads(t_call["result"]["content"][0]["text"])
|
|
assert parsed_tool["exact_gen1_singularity"] is True
|
|
|
|
q_call = dispatch_jsonrpc({
|
|
"jsonrpc": "2.0",
|
|
"id": 4,
|
|
"method": "tools/call",
|
|
"params": {"name": "hs_scan_financial_quant_harvest", "arguments": {"symbol_filter": "NVDA"}},
|
|
})
|
|
assert q_call and q_call["result"]["isError"] is False
|
|
parsed_q = json.loads(q_call["result"]["content"][0]["text"])
|
|
assert len(parsed_q["instruments"]) == 1 and parsed_q["instruments"][0]["symbol"] == "NVDA"
|
|
|
|
r_read = dispatch_jsonrpc({
|
|
"jsonrpc": "2.0",
|
|
"id": 5,
|
|
"method": "resources/read",
|
|
"params": {"uri": "urn:io:hyperstitionstud:dossier:65"},
|
|
})
|
|
assert r_read and "292" in r_read["result"]["contents"][0]["text"]
|
|
|
|
p_get = dispatch_jsonrpc({
|
|
"jsonrpc": "2.0",
|
|
"id": 6,
|
|
"method": "prompts/get",
|
|
"params": {"name": "analyze_headline_zoology", "arguments": {"headline": "Nvidia Blackwell halts"}},
|
|
})
|
|
assert p_get and len(p_get["result"]["messages"]) == 1
|
|
|
|
# 4. Periodic Time-Series Bundle, LENS_REGISTRY Reversibility & REST API v1 (/api/v1/*)
|
|
from hyperstitionstud_io.mcp.rest import dispatch_rest_v1
|
|
from hyperstitionstud_io.quant.timeseries import build_quant_timeseries_bundle
|
|
|
|
ts_full = build_quant_timeseries_bundle(write_files=False)
|
|
assert ts_full["periodicity_gate"]["enforced"] is True
|
|
assert ts_full["periodicity_gate"]["non_periodic_records_ingested"] == 0
|
|
assert ts_full["periodicity_gate"]["dated_news_dossiers_ingested"] >= 20
|
|
assert len(ts_full["dates_utc"]) == 30
|
|
assert all(re.match(r"^\d{4}-\d{2}-\d{2}$", d) for d in ts_full["dates_utc"])
|
|
assert len(ts_full["instruments"]) == 24
|
|
nvda_ts = next(x for x in ts_full["instruments"] if x["symbol"] == "NVDA")
|
|
assert nvda_ts["tradingview_symbol"] == "NASDAQ:NVDA"
|
|
assert "tradingview.com/chart/?symbol=NASDAQ%3ANVDA" in nvda_ts["tradingview_url"]
|
|
assert "doc_references" in nvda_ts
|
|
assert "#page=" in nvda_ts["doc_references"]["encyclopedia_deep_link"]
|
|
assert "search=" in nvda_ts["doc_references"]["encyclopedia_deep_link"]
|
|
assert "?select=aq:137" in nvda_ts["doc_references"]["knowledge_graph_deep_link"]
|
|
assert "#:~:text=" in nvda_ts["doc_references"]["exemplar_dossier_deep_link"]
|
|
assert "struct_isometric_armor" in nvda_ts["structural_vector"]
|
|
assert "ts_duty_cycle_pct" in nvda_ts["timeseries_moments"]
|
|
assert "fund_manager" in nvda_ts["lens_projections"]
|
|
assert "pokedex_scanner" in nvda_ts["lens_projections"]
|
|
|
|
sample_wire_day = next(d for d in ts_full["daily_wire_series"] if d["sample_equations"])
|
|
sample_eq = sample_wire_day["sample_equations"][0]
|
|
assert "#:~:text=" in sample_eq["dossier_deep_link"]
|
|
assert "?highlight=" in sample_eq["api_highlight_link"]
|
|
assert any("?select=aq:" in gl for gl in sample_eq["graph_hub_links"])
|
|
|
|
# Verify 100% lens-removal invariance when pokedex_scanner, tierzoo_ecology, and fantasy_sabermetrics are disabled
|
|
ts_stripped = build_quant_timeseries_bundle(enabled_lenses=("neutral_math", "fund_manager"), write_files=False)
|
|
assert ts_stripped["enabled_lenses"] == ["neutral_math", "fund_manager"]
|
|
nvda_stripped = next(x for x in ts_stripped["instruments"] if x["symbol"] == "NVDA")
|
|
assert set(nvda_stripped["lens_projections"].keys()) == {"neutral_math", "fund_manager"}
|
|
assert "pokedex_profile" not in nvda_stripped
|
|
assert ts_stripped["isolation_receipt"]["all_unchanged"] is True
|
|
|
|
# Verify REST API v1 endpoints (/api/v1/*)
|
|
st_code, _, st_body = dispatch_rest_v1("GET", "/api/v1/status")
|
|
assert st_code == 200 and st_body["ok"] is True and st_body["isolation_verified"] is True
|
|
|
|
oa_code, _, oa_body = dispatch_rest_v1("GET", "/api/v1/openapi.json")
|
|
assert oa_code == 200 and oa_body["openapi"] == "3.1.0" and "/api/v1/ciphers/evaluate" in oa_body["paths"]
|
|
|
|
ev_code, _, ev_body = dispatch_rest_v1("GET", "/api/v1/ciphers/evaluate?terms=schizoanalysis,abstract%20machine,synthetic%20data")
|
|
assert ev_code == 200 and ev_body["data"]["exact_gen1_singularity"] is True
|
|
|
|
qi_code, _, qi_body = dispatch_rest_v1("GET", "/api/v1/quant/instruments/NVDA?raw=1")
|
|
assert qi_code == 200 and len(qi_body["instruments"]) == 1 and qi_body["instruments"][0]["symbol"] == "NVDA"
|
|
|
|
gn_code, _, gn_body = dispatch_rest_v1("GET", "/api/v1/graph/nodes/aq:125")
|
|
assert gn_code == 200 and gn_body["ok"] is True
|
|
|
|
pk_code, _, pk_body = dispatch_rest_v1("GET", "/api/v1/zoology/pokedex/NVDA")
|
|
assert pk_code == 200 and pk_body["data"]["instruments"][0]["pokedex_profile"]["dex_number"] == "DEX #137"
|
|
|
|
d_code, d_ctype, d_body = dispatch_rest_v1("GET", "/api/v1/dossiers/65?format=raw")
|
|
assert d_code == 200 and "text/markdown" in d_ctype and "292" in d_body
|
|
|
|
hl_code, _, hl_body = dispatch_rest_v1("GET", "/api/v1/dossiers/65?highlight=292")
|
|
assert hl_code == 200 and hl_body["data"]["match_count"] >= 1 and len(hl_body["data"]["matched_passages"]) >= 1
|
|
|
|
qts_code, _, qts_body = dispatch_rest_v1("GET", "/api/v1/quant/timeseries?symbol=NVDA")
|
|
assert qts_code == 200 and qts_body["ok"] is True and len(qts_body["data"]["instruments"]) == 1
|
|
|
|
# Verify every single link in quant-tutorials.js, doc_references, and OPERATORS-MANUAL-QUANT-TIMESERIES-WORKBENCH.md resolves cleanly
|
|
cfg = load_workspace_config()
|
|
tut_js_path = cfg.core_dir / "site" / "quant" / "quant-tutorials.js"
|
|
tut_js_txt = tut_js_path.read_text(encoding="utf-8")
|
|
assert "let speechEnabled = true;" in tut_js_txt, "Tutorial voice narration must be enabled by default"
|
|
assert "playWebAudioTelemetryChime" in tut_js_txt, "WebAudio fallback chime must be present when OS TTS voices are absent"
|
|
|
|
all_quant_links: set[str] = set(re.findall(r'href:\s*"([^"]+)"', tut_js_txt))
|
|
for inst in ts_full["instruments"]:
|
|
for v in (inst.get("doc_references") or {}).values():
|
|
if isinstance(v, str) and v.startswith("/"):
|
|
all_quant_links.add(v)
|
|
for b_item in ts_full["builds"]:
|
|
for v in (b_item.get("doc_references") or {}).values():
|
|
if isinstance(v, str) and v.startswith("/"):
|
|
all_quant_links.add(v)
|
|
|
|
route_prefix_map = {
|
|
"/encyclopedia/": cfg.zoology_dir / "encyclopedia",
|
|
"/zoology/": cfg.zoology_dir,
|
|
"/archive/": cfg.archive_dir / "ingglish-aq-archive",
|
|
"/graph/": cfg.knowledge_graph_dir,
|
|
"/learn/": cfg.core_dir / "site" / "learn",
|
|
"/quant/": cfg.core_dir / "site" / "quant",
|
|
"/donate/": cfg.core_dir / "site" / "donate",
|
|
"/schemas/": cfg.core_dir / "schemas",
|
|
}
|
|
for link in sorted(all_quant_links):
|
|
if link.startswith("https://"):
|
|
continue
|
|
no_frag = link.split("#")[0]
|
|
base_p = no_frag.split("?")[0]
|
|
if base_p.startswith("/api/v1"):
|
|
l_code, _, _ = dispatch_rest_v1("GET", no_frag)
|
|
assert l_code == 200, f"Broken tutorial/doc_references REST API link: {link} (status {l_code})"
|
|
else:
|
|
matched_fs = None
|
|
for pref, fs_dir in route_prefix_map.items():
|
|
if base_p.startswith(pref):
|
|
matched_fs = fs_dir / base_p[len(pref):]
|
|
break
|
|
assert matched_fs is not None and matched_fs.is_file(), f"Broken tutorial/doc_references static link: {link} -> {matched_fs}"
|
|
|
|
err_code, _, err_body = dispatch_rest_v1("GET", "/api/v1/ciphers/evaluate")
|
|
assert err_code == 422 and err_body["ok"] is False
|
|
|
|
# 5. SQLite + FTS5 Catalog, Automatic REST/MCP Telemetry Population, Inactive Plan Isolation & Quiescent Logrotate Truncation
|
|
import os
|
|
import sqlite3
|
|
import tempfile
|
|
|
|
from hyperstitionstud_io.db.sqlite_meta import (
|
|
DEFAULT_MAX_TELEMETRY_BYTES,
|
|
build_catalog_sqlite_db,
|
|
get_api_telemetry_summary,
|
|
get_default_telemetry_db_path,
|
|
parse_size_spec_bytes,
|
|
query_coordinate_join,
|
|
query_fts_catalog,
|
|
query_registry_manifests,
|
|
query_timeseries_bars,
|
|
run_logrotate_directive,
|
|
truncate_telemetry_db_quiescent,
|
|
)
|
|
|
|
assert DEFAULT_MAX_TELEMETRY_BYTES == 100 * 1024 * 1024
|
|
assert parse_size_spec_bytes("100M") == 100 * 1024 * 1024
|
|
assert parse_size_spec_bytes("100MB") == 100 * 1024 * 1024
|
|
|
|
prev_env_chk = os.environ.pop("HYPERSTITION_TELEMETRY_DB_PATH", None)
|
|
try:
|
|
def_tel_p = get_default_telemetry_db_path()
|
|
assert str(def_tel_p) == "/var/lib/hyperstitionstud.io/api-telemetry.db" or ".cache/hyperstitionstud.io" in str(def_tel_p)
|
|
finally:
|
|
if prev_env_chk is not None:
|
|
os.environ["HYPERSTITION_TELEMETRY_DB_PATH"] = prev_env_chk
|
|
|
|
with tempfile.TemporaryDirectory() as tmp_dir:
|
|
tmp_path = Path(tmp_dir)
|
|
cat_db = tmp_path / "test-catalog.db"
|
|
tel_db = tmp_path / "test-telemetry.db"
|
|
|
|
cat_res = build_catalog_sqlite_db(cat_db)
|
|
assert cat_res["isolation_receipt"]["all_unchanged"] is True
|
|
assert cat_res["counts"]["registry_manifests"] >= 7
|
|
assert cat_res["counts"]["glossary_entries"] >= 282
|
|
assert cat_res["counts"]["kg_nodes"] == 388
|
|
assert cat_res["counts"]["kg_edges"] == 1282
|
|
assert cat_res["counts"]["dossiers"] >= 71
|
|
assert cat_res["counts"]["quant_timeseries_bars"] == 720
|
|
|
|
manifests = query_registry_manifests(cat_db)
|
|
assert any(m["registry_slug"] == "encyclopedia-graph" and m["dag_json_cidv1"].startswith("baguqeera") for m in manifests)
|
|
|
|
fts_res = query_fts_catalog("envideea", db_path=cat_db)
|
|
assert fts_res["match_count"] >= 1
|
|
|
|
coord_137 = query_coordinate_join(137, db_path=cat_db)
|
|
assert coord_137["coordinate_aq"] == 137
|
|
assert len(coord_137["kg_nodes"]) >= 1
|
|
assert len(coord_137["quant_timeseries_bars"]) >= 1
|
|
|
|
nvda_bars = query_timeseries_bars(symbol="NVDA", min_points=1.0, db_path=cat_db)
|
|
assert len(nvda_bars) >= 1 and all(b["symbol"] == "NVDA" for b in nvda_bars)
|
|
|
|
# Verify MCP and REST API calls automatically populate the SQLite REST API metadata database
|
|
prev_tel_env = os.environ.get("HYPERSTITION_TELEMETRY_DB_PATH")
|
|
os.environ["HYPERSTITION_TELEMETRY_DB_PATH"] = str(tel_db)
|
|
try:
|
|
s1, _, _ = dispatch_rest_v1("GET", "/api/v1/status")
|
|
s2, _, _ = dispatch_rest_v1("GET", "/api/v1/quant/instruments/NVDA")
|
|
m1 = dispatch_jsonrpc({"jsonrpc": "2.0", "id": 99, "method": "tools/list"})
|
|
assert s1 == 200 and s2 == 200 and m1 is not None
|
|
|
|
# Verify inactive plan routes (/api/v1/meta/*, hs_query_sqlite_catalog) remain unexposed (404)
|
|
inact_meta_code, _, _ = dispatch_rest_v1("GET", "/api/v1/meta/manifests")
|
|
inact_tool_code, _, _ = dispatch_rest_v1("GET", "/api/v1/tools/hs_query_sqlite_catalog")
|
|
assert inact_meta_code == 404
|
|
assert inact_tool_code == 404
|
|
|
|
summary_before = get_api_telemetry_summary(tel_db)
|
|
assert summary_before["total_requests"] == 5
|
|
assert summary_before["ringbuffer_count"] == 5
|
|
protocols_seen = {ep["protocol"] for ep in summary_before["endpoints"]}
|
|
assert protocols_seen == {"rest_v1", "mcp_jsonrpc"}
|
|
patterns_seen = {ep["endpoint_pattern"] for ep in summary_before["endpoints"]}
|
|
assert "/api/v1/status" in patterns_seen
|
|
assert "/api/v1/quant/instruments/{symbol}" in patterns_seen
|
|
assert "tools/list" in patterns_seen
|
|
assert all(ev["isolation_ok"] == 1 for ev in summary_before["recent_audit_events"])
|
|
|
|
# Verify logrotate.d file configuration (default 100M = 100MB, compress enabled, rotate >= 12) & no-op when below limit
|
|
import gzip
|
|
|
|
lr_noop = run_logrotate_directive(telemetry_db_path=tel_db)
|
|
assert lr_noop["configured_size_directive"].upper() == "100M"
|
|
assert lr_noop["configured_default_bytes"] == 100 * 1024 * 1024
|
|
assert lr_noop["compress_enabled"] is True
|
|
assert lr_noop["rotate_count"] >= 12
|
|
assert lr_noop["truncated"] is False
|
|
assert get_api_telemetry_summary(tel_db)["total_requests"] == 5
|
|
|
|
# Verify logrotate.d quiescent compression + truncation when DB size >= configured limit
|
|
lr_trunc = run_logrotate_directive(telemetry_db_path=tel_db, max_bytes_override=1024)
|
|
assert lr_trunc["truncated"] is True
|
|
assert lr_trunc["quiescent"] is True
|
|
assert lr_trunc["integrity_check"] == "ok"
|
|
assert lr_trunc["compressed_archive_path"] == f"{tel_db}.1.gz"
|
|
assert lr_trunc["compressed_archive_bytes"] > 0
|
|
assert Path(lr_trunc["compressed_archive_path"]).is_file()
|
|
|
|
# Verify the compressed .1.gz archive preserved all 5 pre-truncation requests & passes SQLite integrity_check
|
|
restored_db = tmp_path / "restored-from-gz.db"
|
|
with gzip.open(lr_trunc["compressed_archive_path"], "rb") as f_gz:
|
|
restored_db.write_bytes(f_gz.read())
|
|
with sqlite3.connect(str(restored_db)) as r_conn:
|
|
assert r_conn.execute("PRAGMA integrity_check;").fetchone()[0] == "ok"
|
|
assert get_api_telemetry_summary(restored_db)["total_requests"] == 5
|
|
|
|
summary_after = get_api_telemetry_summary(tel_db)
|
|
assert summary_after["total_requests"] == 0
|
|
assert summary_after["ringbuffer_count"] == 0
|
|
|
|
# Verify SQLite integrity_check == 'ok' and continued automatic population after quiescent truncation
|
|
with sqlite3.connect(str(tel_db)) as check_conn:
|
|
assert check_conn.execute("PRAGMA integrity_check;").fetchone()[0] == "ok"
|
|
|
|
s_post, _, _ = dispatch_rest_v1("GET", "/api/v1/status")
|
|
assert s_post == 200
|
|
assert get_api_telemetry_summary(tel_db)["total_requests"] == 1
|
|
|
|
# Also verify second rotation shifts .1.gz -> .2.gz and writes new .1.gz
|
|
direct_trunc = truncate_telemetry_db_quiescent(tel_db, max_bytes=512, force=False)
|
|
assert direct_trunc["truncated"] is True
|
|
assert direct_trunc["quiescent"] is True
|
|
assert direct_trunc["integrity_check"] == "ok"
|
|
assert Path(f"{tel_db}.1.gz").is_file()
|
|
assert Path(f"{tel_db}.2.gz").is_file()
|
|
|
|
# Verify regression guard: read-only / unwritable SQLite path (sqlite3.OperationalError) never causes 502/crash
|
|
os.environ["HYPERSTITION_TELEMETRY_DB_PATH"] = "/sys/hyperstition-readonly-telemetry.db"
|
|
ro_code, _, ro_body = dispatch_rest_v1("GET", "/api/v1/quant/timeseries?symbol=NVDA")
|
|
assert ro_code == 200 and ro_body["ok"] is True
|
|
ro_mcp = dispatch_jsonrpc({"jsonrpc": "2.0", "id": 100, "method": "ping"})
|
|
assert ro_mcp is not None and "result" in ro_mcp
|
|
finally:
|
|
if prev_tel_env is None:
|
|
os.environ.pop("HYPERSTITION_TELEMETRY_DB_PATH", None)
|
|
else:
|
|
os.environ["HYPERSTITION_TELEMETRY_DB_PATH"] = prev_tel_env
|
|
|
|
|
|
if __name__ == "__main__":
|
|
test_offline_urn_namespaces_and_no_external_https_fonts()
|
|
print("[PASS] test_offline_urn_namespaces_and_no_external_https_fonts")
|
|
test_ciphers_and_bilingual_ledger_parity()
|
|
print("[PASS] test_ciphers_and_bilingual_ledger_parity")
|
|
test_offline_phonetics_fallback_zero_workdir()
|
|
print("[PASS] test_offline_phonetics_fallback_zero_workdir")
|
|
test_read_only_isolation_guard()
|
|
print("[PASS] test_read_only_isolation_guard")
|
|
test_local_config_citation_resolution_and_proposals()
|
|
print("[PASS] test_local_config_citation_resolution_and_proposals")
|
|
test_doctor_all_checks_pass()
|
|
print("[PASS] test_doctor_all_checks_pass")
|
|
test_ipld_quant_and_mcp_server()
|
|
print("[PASS] test_ipld_quant_and_mcp_server")
|
|
print("ALL 7 TEST SUITES PASSED.")
|