Spaces:
Build error
Build error
Download app/services/graph_validation.py from anwarkxc/trackademi: direct link, hf CLI and curl.
- Browser
- Download file 7.85 kB
-
https://huggingface.co/spaces/anwarkxc/trackademi/resolve/main/app/services/graph_validation.py
- Command line
-
hf download hf://spaces/anwarkxc/trackademi/app/services/graph_validation.py
-
curl -L -o graph_validation.py https://huggingface.co/spaces/anwarkxc/trackademi/resolve/main/app/services/graph_validation.py
7.85 kB
| """Two-tier graph validation, split around the expensive embeddings step so | |
| no embedding/LLM spend is wasted on structurally-broken data. | |
| light_validation runs right after graph_build, before embeddings: cheap | |
| structural checks only (every declared parent exists, element_type is | |
| recognized). A failure blocks progression to embeddings. | |
| heavy_validation runs last, after objectives_rollup: the full integrity | |
| sweep (orphans, dangling same_as targets, page-context mismatches). | |
| Non-blocking — findings are recorded, not fatal, so a document still | |
| finishes ingesting even if a corner case slips through. | |
| """ | |
| import logging | |
| from sqlalchemy import text as sql_text | |
| from sqlalchemy.ext.asyncio import AsyncSession | |
| from app.models.rag_db import RAG_ELEMENT_TYPES | |
| logger = logging.getLogger(__name__) | |
| async def run_light_validation(session: AsyncSession, *, document_id: str) -> bool: | |
| """FK/parent/element-type checks. Returns False (and logs) on failure — | |
| callers should NOT proceed to the embeddings stage when this fails.""" | |
| bad_types = (await session.execute( | |
| sql_text("SELECT COUNT(*) FROM rag_elements WHERE document_id = CAST(:doc AS uuid) " | |
| "AND element_type != ALL(:valid_types) AND deleted_at IS NULL"), | |
| {"doc": document_id, "valid_types": list(RAG_ELEMENT_TYPES)}, | |
| )).scalar() | |
| if bad_types: | |
| logger.error("light_validation: %d elements with unrecognized element_type in document %s", bad_types, document_id) | |
| return False | |
| dangling_chunk_refs = (await session.execute( | |
| sql_text(""" | |
| SELECT COUNT(*) FROM rag_elements e | |
| WHERE e.document_id = CAST(:doc AS uuid) AND e.element_type = 'paragraph' | |
| AND e.chunk_id IS NOT NULL AND e.deleted_at IS NULL | |
| AND NOT EXISTS (SELECT 1 FROM rag_chunks c WHERE c.id = e.chunk_id) | |
| """), | |
| {"doc": document_id}, | |
| )).scalar() | |
| if dangling_chunk_refs: | |
| logger.error("light_validation: %d paragraph elements reference a missing chunk in document %s", dangling_chunk_refs, document_id) | |
| return False | |
| dangling_relationship_endpoints = (await session.execute( | |
| sql_text(""" | |
| SELECT COUNT(*) FROM rag_element_relationships r | |
| WHERE (r.from_element_id IN (SELECT id FROM rag_elements WHERE document_id = CAST(:doc AS uuid)) | |
| OR r.to_element_id IN (SELECT id FROM rag_elements WHERE document_id = CAST(:doc AS uuid))) | |
| AND (NOT EXISTS (SELECT 1 FROM rag_elements e WHERE e.id = r.from_element_id) | |
| OR NOT EXISTS (SELECT 1 FROM rag_elements e WHERE e.id = r.to_element_id)) | |
| """), | |
| {"doc": document_id}, | |
| )).scalar() | |
| if dangling_relationship_endpoints: | |
| logger.error("light_validation: %d relationships with a dangling endpoint in document %s", dangling_relationship_endpoints, document_id) | |
| return False | |
| return True | |
| async def run_heavy_validation(session: AsyncSession, *, document_id: str, graph_version: int) -> dict: | |
| """Full integrity sweep + graph quality metrics. Non-blocking — populates | |
| RagDocument.graph_metrics and appends a graph_metrics_history row, and | |
| logs (but does not raise on) any structural anomalies found.""" | |
| orphan_elements = (await session.execute( | |
| sql_text(""" | |
| SELECT COUNT(*) FROM rag_elements e | |
| WHERE e.document_id = CAST(:doc AS uuid) AND e.element_type != 'paragraph' | |
| AND e.deleted_at IS NULL | |
| AND NOT EXISTS ( | |
| SELECT 1 FROM rag_element_relationships r | |
| WHERE r.relationship_type = 'belongs_to' AND r.from_element_id = e.id | |
| ) | |
| """), | |
| {"doc": document_id}, | |
| )).scalar() or 0 | |
| dangling_same_as = (await session.execute( | |
| sql_text(""" | |
| SELECT COUNT(*) FROM rag_element_relationships r | |
| WHERE r.relationship_type = 'same_as' | |
| AND (NOT EXISTS (SELECT 1 FROM rag_elements e WHERE e.id = r.from_element_id AND e.deleted_at IS NULL) | |
| OR NOT EXISTS (SELECT 1 FROM rag_elements e WHERE e.id = r.to_element_id AND e.deleted_at IS NULL)) | |
| """), | |
| )).scalar() or 0 | |
| counts = (await session.execute( | |
| sql_text(""" | |
| SELECT | |
| COUNT(*) FILTER (WHERE element_type != 'paragraph') AS non_paragraph_count, | |
| COUNT(*) FILTER (WHERE element_type = 'diagram') AS diagram_count, | |
| COUNT(DISTINCT page_number) AS page_count | |
| FROM rag_elements WHERE document_id = CAST(:doc AS uuid) AND deleted_at IS NULL | |
| """), | |
| {"doc": document_id}, | |
| )).mappings().first() | |
| rel_stats = (await session.execute( | |
| sql_text(""" | |
| SELECT COUNT(*) AS total, | |
| AVG(confidence) AS avg_confidence, | |
| AVG(normalized_confidence) AS avg_normalized_confidence, | |
| COUNT(*) FILTER (WHERE relationship_type = 'same_as')::float | |
| / GREATEST(COUNT(*), 1) AS same_as_ratio | |
| FROM rag_element_relationships r | |
| WHERE r.from_element_id IN (SELECT id FROM rag_elements WHERE document_id = CAST(:doc AS uuid)) | |
| """), | |
| {"doc": document_id}, | |
| )).mappings().first() | |
| page_count = counts["page_count"] or 1 | |
| metrics = { | |
| "relationships_per_page": (rel_stats["total"] or 0) / page_count, | |
| "diagrams_per_document": float(counts["diagram_count"] or 0), | |
| "orphan_element_pct": (orphan_elements / max(counts["non_paragraph_count"] or 1, 1)) * 100, | |
| "average_confidence": float(rel_stats["avg_confidence"]) if rel_stats["avg_confidence"] is not None else None, | |
| "average_normalized_confidence": float(rel_stats["avg_normalized_confidence"]) if rel_stats["avg_normalized_confidence"] is not None else None, | |
| "same_as_ratio": float(rel_stats["same_as_ratio"] or 0), | |
| } | |
| if orphan_elements: | |
| logger.warning("heavy_validation: %d orphan (parentless) elements in document %s", orphan_elements, document_id) | |
| if dangling_same_as: | |
| logger.warning("heavy_validation: %d dangling same_as relationships", dangling_same_as) | |
| import json as _json | |
| await session.execute( | |
| sql_text("UPDATE rag_documents SET graph_metrics = CAST(:m AS jsonb) WHERE id = CAST(:doc AS uuid)"), | |
| {"m": _json.dumps(metrics), "doc": document_id}, | |
| ) | |
| vision_model_row = (await session.execute( | |
| sql_text("SELECT vision_model, prompt_hash FROM rag_elements WHERE document_id = CAST(:doc AS uuid) " | |
| "AND vision_model IS NOT NULL ORDER BY created_at DESC LIMIT 1"), | |
| {"doc": document_id}, | |
| )).mappings().first() | |
| await session.execute( | |
| sql_text(""" | |
| INSERT INTO graph_metrics_history ( | |
| id, document_id, computed_at, vision_model, prompt_hash, | |
| relationships_per_page, diagrams_per_document, orphan_element_pct, | |
| average_confidence, average_normalized_confidence, same_as_ratio | |
| ) VALUES ( | |
| gen_random_uuid(), CAST(:doc AS uuid), NOW(), :model, :hash, | |
| :rpp, :dpd, :orphan_pct, :avg_conf, :avg_norm_conf, :same_as_ratio | |
| ) | |
| """), | |
| { | |
| "doc": document_id, | |
| "model": vision_model_row["vision_model"] if vision_model_row else None, | |
| "hash": vision_model_row["prompt_hash"] if vision_model_row else None, | |
| "rpp": metrics["relationships_per_page"], "dpd": metrics["diagrams_per_document"], | |
| "orphan_pct": metrics["orphan_element_pct"], "avg_conf": metrics["average_confidence"], | |
| "avg_norm_conf": metrics["average_normalized_confidence"], "same_as_ratio": metrics["same_as_ratio"], | |
| }, | |
| ) | |
| await session.commit() | |
| return metrics | |