Implement WP-26 v1.3 (Phase 3): Enhance graph schema validation and edge handling
- Introduced a new function `load_graph_schema_full` to parse and cache both typical and prohibited edge types from the graph schema. - Updated `load_graph_schema` to utilize the full schema for improved edge type extraction. - Added `get_topology_info` to retrieve typical and prohibited edges for source/target pairs. - Implemented `validate_intra_note_edge` and `validate_edge_against_schema` for schema validation of intra-note edges. - Enhanced logging for schema validation outcomes and edge handling. - Updated documentation to reflect new validation features and testing procedures.
This commit is contained in:
1 parent
c5215e22e7
commit
509efc9393
5 files changed
+674
-23
No files matched your search
@@ -41,7 +41,7 @@ from app.services.llm_service import LLMService
|
||||
# Package-Interne Imports (Refactoring WP-14)
|
||||
from .ingestion_utils import load_type_registry, resolve_note_type, get_chunk_config_by_profile
|
||||
from .ingestion_db import fetch_note_payload, artifacts_missing, purge_artifacts, is_explicit_edge_present
|
||||
from .ingestion_validation import validate_edge_candidate
|
||||
from .ingestion_validation import validate_edge_candidate, validate_edge_against_schema
|
||||
from .ingestion_note_payload import make_note_payload
|
||||
from .ingestion_chunk_payload import make_chunk_payloads
|
||||
|
||||
@@ -621,6 +621,31 @@ class IngestionService:
|
||||
v_edge["target_section"] = target_section
|
||||
self.symmetry_buffer.append(v_edge)
|
||||
|
||||
# WP-26 v1.3: Schema-Validierung für Intra-Note-Edges (FA-12)
|
||||
# Prüfe is_internal Edges gegen graph_schema.md
|
||||
if explicit_edges:
|
||||
chunks_by_id = {c.get("chunk_id", c.get("id", "")): c for c in chunk_pls}
|
||||
schema_validated_edges = []
|
||||
schema_rejected_count = 0
|
||||
|
||||
for e in explicit_edges:
|
||||
is_valid, updated_edge = validate_edge_against_schema(
|
||||
edge=e,
|
||||
chunks_by_id=chunks_by_id,
|
||||
strict_mode=False # Im normalen Modus: atypische Edges erlaubt mit reduzierter Confidence
|
||||
)
|
||||
|
||||
if is_valid:
|
||||
schema_validated_edges.append(updated_edge)
|
||||
else:
|
||||
schema_rejected_count += 1
|
||||
logger.info(f"🚫 [SCHEMA-VALIDATION] Edge abgelehnt: {e.get('source_id')} -> {e.get('target_id')} ({e.get('kind')})")
|
||||
|
||||
if schema_rejected_count > 0:
|
||||
logger.info(f"📊 [SCHEMA-VALIDATION] {schema_rejected_count} Intra-Note-Edges aufgrund von Schema-Verletzungen abgelehnt")
|
||||
|
||||
explicit_edges = schema_validated_edges
|
||||
|
||||
# DB Upsert
|
||||
if purge_before and old_payload: purge_artifacts(self.client, self.prefix, note_id)
|
||||
|
||||
|
||||
@@ -3,24 +3,145 @@ FILE: app/core/ingestion/ingestion_validation.py
|
||||
DESCRIPTION: WP-15b semantische Validierung von Kanten gegen den LocalBatchCache.
|
||||
WP-24c: Erweiterung um automatische Symmetrie-Generierung (Inverse Kanten).
|
||||
WP-25b: Konsequente Lazy-Prompt-Orchestration (prompt_key + variables).
|
||||
VERSION: 3.0.0 (WP-24c: Symmetric Edge Management)
|
||||
WP-26 v1.3: Schema-Validierung für Intra-Note-Edges gegen graph_schema.md.
|
||||
VERSION: 3.1.0 (WP-26: Intra-Note-Edge Schema-Validation)
|
||||
STATUS: Active
|
||||
FIX:
|
||||
- WP-24c: Integration der EdgeRegistry zur dynamischen Inversions-Ermittlung.
|
||||
- WP-24c: Implementierung von validate_and_symmetrize für bidirektionale Graphen.
|
||||
- WP-25b: Beibehaltung der hierarchischen Prompt-Resolution und Modell-Spezi-Logik.
|
||||
- WP-26: FA-12 Schema-Validierung gegen effektiven Chunk-Typ.
|
||||
"""
|
||||
import logging
|
||||
from typing import Dict, Any, Optional, List
|
||||
from typing import Dict, Any, Optional, List, Tuple
|
||||
from app.core.parser import NoteContext
|
||||
|
||||
# Import der neutralen Bereinigungs-Logik zur Vermeidung von Circular Imports
|
||||
from app.core.registry import clean_llm_text
|
||||
# WP-24c: Zugriff auf das dynamische Vokabular
|
||||
from app.services.edge_registry import registry as edge_registry
|
||||
# WP-26 v1.3: Graph-Schema für Validierung
|
||||
from app.core.graph.graph_utils import get_topology_info
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
# WP-26 v1.3: Schema-Validierung für Intra-Note-Edges (FA-12)
|
||||
# ==============================================================================
|
||||
|
||||
def validate_intra_note_edge(
|
||||
edge: Dict[str, Any],
|
||||
source_chunk: Dict[str, Any],
|
||||
target_chunk: Dict[str, Any],
|
||||
strict_mode: bool = False
|
||||
) -> Tuple[bool, float, Optional[str]]:
|
||||
"""
|
||||
WP-26 v1.3 (FA-12): Validiert eine Intra-Note-Edge gegen das graph_schema.md.
|
||||
Verwendet den EFFEKTIVEN Typ (section_type || note_type) beider Chunks.
|
||||
|
||||
Args:
|
||||
edge: Das Edge-Dict mit "kind", "source_id", "target_id"
|
||||
source_chunk: Chunk-Payload der Quelle mit "type" (effektiver Typ)
|
||||
target_chunk: Chunk-Payload des Ziels mit "type" (effektiver Typ)
|
||||
strict_mode: Wenn True, werden atypische Edges abgelehnt (nicht nur gewarnt)
|
||||
|
||||
Returns:
|
||||
Tuple (is_valid, confidence, reason)
|
||||
- is_valid: True wenn die Edge erlaubt ist
|
||||
- confidence: Angepasste Confidence (0.7 für atypische, 0.0 für prohibited)
|
||||
- reason: Optional Begründung für Ablehnung/Warnung
|
||||
"""
|
||||
# Effektive Typen extrahieren (section_type hat Vorrang vor note_type)
|
||||
source_type = source_chunk.get("type") or source_chunk.get("note_type") or "default"
|
||||
target_type = target_chunk.get("type") or target_chunk.get("note_type") or "default"
|
||||
edge_kind = edge.get("kind", "related_to")
|
||||
|
||||
# Schema-Lookup
|
||||
topology = get_topology_info(source_type, target_type)
|
||||
typical_edges = topology.get("typical", [])
|
||||
prohibited_edges = topology.get("prohibited", [])
|
||||
|
||||
# 1. Prüfung: Ist die Edge verboten?
|
||||
if edge_kind in prohibited_edges:
|
||||
reason = f"Edge '{edge_kind}' von {source_type} → {target_type} ist verboten (prohibited)"
|
||||
logger.warning(f"🚫 [SCHEMA-VALIDATION] {reason}")
|
||||
return (False, 0.0, reason)
|
||||
|
||||
# 2. Prüfung: Ist die Edge typisch?
|
||||
if edge_kind in typical_edges:
|
||||
# Edge ist typisch → volle Confidence
|
||||
logger.debug(f"✅ [SCHEMA-VALIDATION] Edge '{edge_kind}' von {source_type} → {target_type} ist typisch")
|
||||
return (True, 1.0, None)
|
||||
|
||||
# 3. Edge ist atypisch (weder typical noch prohibited)
|
||||
reason = f"Edge '{edge_kind}' von {source_type} → {target_type} ist atypisch (nicht in typical: {typical_edges})"
|
||||
|
||||
if strict_mode:
|
||||
# Im Strict-Mode werden atypische Edges abgelehnt
|
||||
logger.warning(f"⚠️ [SCHEMA-VALIDATION] {reason} - ABGELEHNT (strict_mode)")
|
||||
return (False, 0.0, reason)
|
||||
else:
|
||||
# Im normalen Modus: Edge erlaubt, aber mit reduzierter Confidence (0.7)
|
||||
logger.info(f"ℹ️ [SCHEMA-VALIDATION] {reason} - erlaubt mit reduzierter Confidence")
|
||||
return (True, 0.7, reason)
|
||||
|
||||
|
||||
def validate_edge_against_schema(
|
||||
edge: Dict[str, Any],
|
||||
chunks_by_id: Dict[str, Dict[str, Any]],
|
||||
strict_mode: bool = False
|
||||
) -> Tuple[bool, Dict[str, Any]]:
|
||||
"""
|
||||
WP-26 v1.3: Wrapper für die Schema-Validierung mit Chunk-Lookup.
|
||||
|
||||
Args:
|
||||
edge: Das Edge-Dict
|
||||
chunks_by_id: Dictionary von chunk_id → chunk_payload
|
||||
strict_mode: Wenn True, werden atypische Edges abgelehnt
|
||||
|
||||
Returns:
|
||||
Tuple (is_valid, updated_edge)
|
||||
- is_valid: True wenn die Edge erlaubt ist
|
||||
- updated_edge: Edge mit ggf. angepasster Confidence
|
||||
"""
|
||||
source_id = edge.get("source_id", "")
|
||||
target_id = edge.get("target_id", "")
|
||||
is_internal = edge.get("is_internal", False)
|
||||
|
||||
# Nur Intra-Note-Edges validieren
|
||||
if not is_internal:
|
||||
return (True, edge)
|
||||
|
||||
# Chunks nachschlagen
|
||||
source_chunk = chunks_by_id.get(source_id, {})
|
||||
target_chunk = chunks_by_id.get(target_id, {})
|
||||
|
||||
# Wenn Chunks nicht gefunden → Edge erlauben (Integrität vor Präzision)
|
||||
if not source_chunk or not target_chunk:
|
||||
logger.debug(f"[SCHEMA-VALIDATION] Chunks nicht gefunden für {source_id} / {target_id} - Edge erlaubt")
|
||||
return (True, edge)
|
||||
|
||||
# Schema-Validierung durchführen
|
||||
is_valid, confidence, reason = validate_intra_note_edge(
|
||||
edge=edge,
|
||||
source_chunk=source_chunk,
|
||||
target_chunk=target_chunk,
|
||||
strict_mode=strict_mode
|
||||
)
|
||||
|
||||
if not is_valid:
|
||||
return (False, edge)
|
||||
|
||||
# Confidence anpassen wenn nötig
|
||||
updated_edge = edge.copy()
|
||||
if confidence < 1.0:
|
||||
original_confidence = edge.get("confidence", 1.0)
|
||||
updated_edge["confidence"] = min(original_confidence, confidence)
|
||||
updated_edge["schema_validation_note"] = reason
|
||||
|
||||
return (True, updated_edge)
|
||||
|
||||
async def validate_edge_candidate(
|
||||
chunk_text: str,
|
||||
edge: Dict,
|
||||
|
||||
Reference in new issue
Block a user