Part 05 Scope & Analytical Objectives
- Diagnose why top-K passage RAG fails systematically on exhaustive aggregation, global summarization, and relational join queries.
- Design safe Semantic Layer / Read-Only Text-to-SQL routing architectures with schema linking, row-level security, and query cost AST validation.
- Implement bi-temporal versioning (`valid_time` vs. `transaction_time`) and entity-relationship Knowledge Graph traversal for multi-hop reasoning without look-ahead bias.
Executive & Technical Overview
Top-K vector/BM25 retrieval excels at pinpoint factual lookup (“What is the transformer thermal trip setting in Substation B?”)—and collapses completely when a user asks an **aggregative or relational question** (“How many interconnection requests exceeded 100 MW in ERCOT during Q2 2025, and what was their median study duration?”). Retrieving 8 text chunks out of 12,000 filings cannot compute a corpus-wide count or median!
Enterprise knowledge systems therefore route queries across three complementary retrieval modalities: **unstructured passage search**, **governed relational/semantic SQL execution**, and **entity-linked graph traversal**, unified under strict point-in-time temporal filtering.
5.1 Semantic Text-to-SQL Routing vs. Document Passage Retrieval
A. Query Intent Routing: Point Lookup vs. Global Aggregation
Before retrieving a single vector, classify query structure across three dimensions:
| Query Archetype | Example Question | Why Standard Passage RAG Fails | Correct Retrieval Modality |
|---|---|---|---|
| Local Clause Lookup | “What notice period applies to force majeure events under Tariff §14.3?” | Succeeds cleanly when §14.3 is chunked intact. | Hybrid BM25 + Dense Vector + Reranker |
| Quantitative Aggregation / Filtering | “Compute average P95 LMP across West Hub nodes during August 2025 heat hours.” | Top-K chunks sample an arbitrary subset; LLM tokens cannot average 50,000 rows. | Semantic Metric Layer or Read-Only SQL Tool |
| Multi-Hop Entity Chain | “Which suppliers provide cooling valves to facilities connected to constrained 230 kV buses?” | No single passage mentions both the Tier-2 valve vendor and the transmission bus ID. | Knowledge Graph Traversal / Iterative Hop Decomposition |
B. Safe Text-to-SQL & Governed Semantic Layers
Allowing an LLM to generate raw SQL directly against a normalized 400-table production warehouse introduces two major hazards: **metric drift** (inventing slightly wrong join predicates or forgetting soft-delete filters like is_cancelled = FALSE) and **database security risk** (resource exhaustion or unauthorized table joins).
- Prefer Curated Semantic Views / Metric APIs First: Expose pre-joined, business-verified views or parameterized analytical functions before falling back to arbitrary SQL generation.
- Read-Only AST Validation & Execution Sandboxing: Parse generated SQL into an Abstract Syntax Tree (AST) to confirm it contains a single `SELECT` statement, enforces mandatory tenant/row-level predicates, caps `LIMIT`, and runs under a read-only database credential with a strict statement timeout (e.g., `2,500 ms`).
5.2 Knowledge-Graph RAG, Multi-Hop Queries & Bi-Temporal Versioning
A. Knowledge-Graph RAG & Multi-Hop Decomposition
When reasoning spans heterogeneous entities—such as `(Compound A) -> [inhibits] -> (Protein Target X) -> [associated_with] -> (Pathway Y)` in biomedical discovery, or `(Generator G1) -> [injects_at] -> (Bus 402) -> [monitored_by] -> (Relay R9)` in power systems—representing explicit `(subject, predicate, object, provenance_chunk_id)` triples alongside text passages enables exact 1-to-2 hop neighborhood expansion. Crucially, every graph edge must retain its `provenance_chunk_id` so the generator still verifies the original prose qualification before answering.
B. Bi-Temporal Knowledge Versioning (Preventing Look-Ahead Contamination)
In financial backtesting, clinical retrospective audits, and regulatory compliance, every record carries **two distinct timestamps**:
- Valid Time (tvalid): The real-world operating interval to which the fact applies (e.g., Q3 2025 operating quarter).
- Transaction / Knowledge Time (tknown): The exact timestamp when that document or restatement entered the institutional record (e.g., restated filing published November 14, 2025).
Evaluating an AI forecasting or trading agent on historical dates τ without enforcing tknown ≤ τ leaks future earnings restatements, weather revisions, and post-event outage reports directly into historical decisions—invalidating the entire backtest.
Worked Engineering Lab & Reference Implementation
Below is an original Python reference implementation of a **Read-Only SQL Safety Gate** combined with a **Bi-Temporal Document & Graph Store** enforcing strict point-in-time (`as_of`) retrieval:
import re
from dataclasses import dataclass
from datetime import datetime
from typing import List, Optional
FORBIDDEN_SQL_TOKENS = re.compile(
r"\b(INSERT|UPDATE|DELETE|DROP|ALTER|TRUNCATE|GRANT|REVOKE|CREATE|ATTACH|COPY|PRAGMA)\b",
re.IGNORECASE,
)
def validate_readonly_sql(sql: str, max_limit: int = 500) -> str:
"""Enforces single-statement SELECT-only execution with bounded LIMIT."""
cleaned = sql.strip().rstrip(";")
if ";" in cleaned:
raise ValueError("Multi-statement SQL queries are prohibited.")
if not cleaned.upper().startswith(("SELECT", "WITH")):
raise ValueError("Only SELECT / WITH read-only queries are permitted.")
if FORBIDDEN_SQL_TOKENS.search(cleaned):
raise ValueError("Mutating or administrative SQL keyword detected.")
if re.search(r"\bLIMIT\s+\d+", cleaned, re.IGNORECASE) is None:
cleaned = f"{cleaned} LIMIT {max_limit}"
return cleaned
@dataclass(frozen=True)
class BiTemporalFact:
fact_id: str
subject: str
predicate: str
obj: str
valid_from: datetime
valid_to: Optional[datetime]
known_at: datetime # Transaction timestamp when recorded
def query_facts_as_of(
facts: List[BiTemporalFact], subject: str, as_of_decision_time: datetime
) -> List[BiTemporalFact]:
"""Returns only facts both valid and actually known on or before `as_of_decision_time`."""
results = []
for f in facts:
if f.subject != subject:
continue
if f.known_at > as_of_decision_time:
continue # Prevents future restatement / look-ahead leakage!
if f.valid_from <= as_of_decision_time and (f.valid_to is None or as_of_decision_time < f.valid_to):
results.append(f)
return results
Analytical Review & Self-Study Questions
Work through each analytical problem independently before expanding the reference derivation:
Problem 5.1 (Bi-Temporal Leakage): An analyst backtests an LLM market-commentary agent for July 15, 2025. A utility's Q2 outage summary covering June 2025 (`valid_time` = June 2025) was published on August 4, 2025 (`known_at` = Aug 4, 2025). Should a July 15, 2025 backtest query retrieve this document?
Problem 5.2 (Text-to-SQL Empty-Set Ambiguity): When an LLM-generated SQL query returns `0 rows` or `NULL`, what often goes wrong in naive pipelines and how do you prevent it?
Problem 5.3 (Graph RAG Cost Control): Why can unconstrained LLM triple-extraction over millions of documents become prohibitively expensive, and when is Graph RAG justified?
Public-Domain Standards & Open-Access References
All theoretical formulations, worked numerical examples, and Python implementations in this publication are originally authored by AhnLim Foundation and grounded exclusively in public-domain government standards and peer-reviewed open-access scientific literature:
- Snodgrass, R. T. (1999 / Public Open Archive). Developing Time-Oriented Database Applications in SQL — Bi-Temporal Valid vs. Transaction Time Foundations.
- Edge, D. et al. (2024). From Local to Global: A Graph RAG Approach to Query-Focused Summarization. Open-access preprint (arXiv:2404.16130).
- OWASP Application Security Verification Standard (ASVS) & OWASP Top 10 for LLM Applications — Parameterized & Least-Privilege Database Access.
ahnlim.org. Educators, researchers, practitioners, and independent readers may freely share, print, and adapt this publication under CC BY-NC 4.0 with attribution to AhnLim Foundation (Series I, Part 05).