feat: Placeholder Metadata V2 - Normative Implementation + ZIP Export Fix
Deploy Development / deploy (push) Successful in 54s
Build Test / lint-backend (push) Successful in 1s
Build Test / build-frontend (push) Successful in 15s

MAJOR CHANGES:
- Enhanced metadata schema with 7 QA fields
- Deterministic derivation logic (no guessing)
- Conservative inference (prefer unknown over wrong)
- Real source tracking (skip safe wrappers)
- Legacy mismatch detection
- Activity quality filter policies
- Completeness scoring (0-100)
- Unresolved fields tracking
- Fixed ZIP/JSON export auth (query param support)

FILES CHANGED:
- backend/placeholder_metadata.py (schema extended)
- backend/placeholder_metadata_enhanced.py (NEW, 418 lines)
- backend/generate_complete_metadata_v2.py (NEW, 334 lines)
- backend/tests/test_placeholder_metadata_v2.py (NEW, 302 lines)
- backend/routers/prompts.py (V2 integration + auth fix)
- docs/PLACEHOLDER_METADATA_VALIDATION.md (NEW, 541 lines)

PROBLEMS FIXED:
✓ value_raw extraction (type-aware, JSON parsing)
✓ Units for dimensionless values (scores, correlations)
✓ Safe wrappers as sources (now skipped)
✓ Time window guessing (confidence flags)
✓ Legacy inconsistencies (marked with flag)
✓ Missing quality filters (activity placeholders)
✓ No completeness metric (0-100 score)
✓ Orphaned placeholders (tracked)
✓ Unresolved fields (explicit list)
✓ ZIP/JSON export auth (query token support for downloads)

AUTH FIX:
- export-catalog-zip now accepts token via query param (?token=xxx)
- export-values-extended now accepts token via query param
- Allows browser downloads without custom headers

Konzept: docs/PLACEHOLDER_METADATA_REQUIREMENTS_V2_NORMATIVE.md

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
LarsandClaude Opus 4.6 committed 2026-03-29 21:23:37 +02:00
1 parent 087e8dd885
commit 650313347f
6 files changed
+1698 -31

No files matched your search

+92 -31
View File
@@ -267,22 +267,43 @@ def export_placeholder_values(session: dict = Depends(require_auth)):
@router.get("/placeholders/export-values-extended")
def export_placeholder_values_extended(session: dict = Depends(require_auth)):
def export_placeholder_values_extended(
token: Optional[str] = Query(None),
x_auth_token: Optional[str] = Header(default=None)
):
"""
Extended placeholder export with complete normative metadata.
Extended placeholder export with complete normative metadata V2.
Returns structured export with:
- Legacy format (for backward compatibility)
- Complete metadata per placeholder (normative standard)
- Complete metadata per placeholder (normative standard V2)
- Quality assurance metrics
- Summary statistics
- Gap report
- Validation results
This endpoint implements the PLACEHOLDER_METADATA_REQUIREMENTS_V2_NORMATIVE standard.
V2 implements strict quality controls:
- Correct value_raw extraction
- Accurate unit inference
- Precise time_window detection
- Real source provenance
- Quality filter policies for activity placeholders
Token can be passed via:
- Header: X-Auth-Token
- Query param: ?token=xxx (for direct access/downloads)
"""
from datetime import datetime
from placeholder_metadata_extractor import build_complete_metadata_registry
from generate_complete_metadata import apply_manual_corrections, generate_gap_report
from generate_complete_metadata_v2 import apply_enhanced_corrections
from auth import get_session
# Accept token from query param OR header
auth_token = token or x_auth_token
session = get_session(auth_token)
if not session:
raise HTTPException(401, "Nicht eingeloggt")
profile_id = session['profile_id']
@@ -294,10 +315,10 @@ def export_placeholder_values_extended(session: dict = Depends(require_auth)):
}
catalog = get_placeholder_catalog(profile_id)
# Build complete metadata registry
# Build complete metadata registry with V2 enhancements
try:
registry = build_complete_metadata_registry(profile_id)
registry = apply_manual_corrections(registry)
registry = apply_enhanced_corrections(registry) # V2: Enhanced quality controls
except Exception as e:
raise HTTPException(
status_code=500,
@@ -307,26 +328,26 @@ def export_placeholder_values_extended(session: dict = Depends(require_auth)):
# Get all metadata
all_metadata = registry.get_all()
# Populate runtime values (value_display, value_raw, available)
# Populate runtime values with V2 enhanced extraction
from placeholder_metadata_enhanced import extract_value_raw as extract_value_raw_v2
for key, metadata in all_metadata.items():
if key in cleaned_values:
value = cleaned_values[key]
metadata.value_display = str(value)
# Try to extract raw value
if isinstance(value, (int, float)):
metadata.value_raw = value
elif isinstance(value, str):
# Try to parse number from string (e.g., "85.8 kg" -> 85.8)
import re
match = re.search(r'([-+]?\d+\.?\d*)', value)
if match:
try:
metadata.value_raw = float(match.group(1))
except ValueError:
metadata.value_raw = value
else:
metadata.value_raw = value
# V2: Use enhanced extraction logic
raw_val, success = extract_value_raw_v2(
str(value),
metadata.output_type,
metadata.type
)
if success:
metadata.value_raw = raw_val
else:
metadata.value_raw = None
if 'value_raw' not in metadata.unresolved_fields:
metadata.unresolved_fields.append('value_raw')
# Check availability
if value in ['nicht verfügbar', 'nicht genug Daten', '[Fehler:', '[Nicht']:
@@ -336,8 +357,15 @@ def export_placeholder_values_extended(session: dict = Depends(require_auth)):
metadata.available = False
metadata.missing_reason = "Placeholder not in resolver output"
# Generate gap report
gaps = generate_gap_report(registry)
# Generate gap report (collect unresolved fields)
gaps = {
'unknown_time_window': [k for k, m in all_metadata.items() if m.time_window == TimeWindow.UNKNOWN],
'unknown_output_type': [k for k, m in all_metadata.items() if m.output_type == OutputType.UNKNOWN],
'legacy_unknown_type': [k for k, m in all_metadata.items() if m.type == PlaceholderType.LEGACY_UNKNOWN],
'unresolved_fields': {k: m.unresolved_fields for k, m in all_metadata.items() if m.unresolved_fields},
'legacy_mismatches': [k for k, m in all_metadata.items() if m.legacy_contract_mismatch],
'orphaned': [k for k, m in all_metadata.items() if m.orphaned_placeholder],
}
# Validation
validation_results = registry.validate_all()
@@ -394,28 +422,47 @@ def export_placeholder_values_extended(session: dict = Depends(require_auth)):
m.to_dict() for m in metadata_list
]
# Fill summary
# Fill summary with V2 QA metrics
total = len(all_metadata)
available = sum(1 for m in all_metadata.values() if m.available)
missing = total - available
by_type = {}
by_schema_status = {}
for metadata in all_metadata.values():
ptype = metadata.type.value
by_type[ptype] = by_type.get(ptype, 0) + 1
gap_count = sum(len(v) for v in gaps.values())
unresolved = len(gaps.get('validation_issues', []))
status = metadata.schema_status
by_schema_status[status] = by_schema_status.get(status, 0) + 1
# Calculate average completeness
avg_completeness = sum(m.metadata_completeness_score for m in all_metadata.values()) / total if total > 0 else 0
# Count QA metrics
legacy_mismatches = sum(1 for m in all_metadata.values() if m.legacy_contract_mismatch)
orphaned = sum(1 for m in all_metadata.values() if m.orphaned_placeholder)
has_quality_filter = sum(1 for m in all_metadata.values() if m.quality_filter_policy)
has_confidence = sum(1 for m in all_metadata.values() if m.confidence_logic)
export_data['metadata']['summary'] = {
"total_placeholders": total,
"available": available,
"missing": missing,
"by_type": by_type,
"by_schema_status": by_schema_status,
"quality_metrics": {
"average_completeness_score": round(avg_completeness, 1),
"legacy_mismatches": legacy_mismatches,
"orphaned": orphaned,
"with_quality_filter": has_quality_filter,
"with_confidence_logic": has_confidence
},
"coverage": {
"fully_resolved": total - gap_count,
"partially_resolved": gap_count - unresolved,
"unresolved": unresolved
"time_window_unknown": len(gaps.get('unknown_time_window', [])),
"output_type_unknown": len(gaps.get('unknown_output_type', [])),
"legacy_unknown_type": len(gaps.get('legacy_unknown_type', [])),
"with_unresolved_fields": len(gaps.get('unresolved_fields', {}))
}
}
@@ -440,7 +487,7 @@ def export_placeholder_values_extended(session: dict = Depends(require_auth)):
@router.get("/placeholders/export-catalog-zip")
def export_placeholder_catalog_zip(
token: Optional[str] = Query(None),
session: dict = Depends(require_admin)
x_auth_token: Optional[str] = Header(default=None)
):
"""
Export complete placeholder catalog as ZIP file.
@@ -453,6 +500,10 @@ def export_placeholder_catalog_zip(
This generates the files on-the-fly and returns as ZIP.
Admin only.
Token can be passed via:
- Header: X-Auth-Token
- Query param: ?token=xxx (for browser downloads)
"""
import io
import zipfile
@@ -465,6 +516,16 @@ def export_placeholder_catalog_zip(
)
from placeholder_metadata_extractor import build_complete_metadata_registry
from generate_complete_metadata import apply_manual_corrections, generate_gap_report
from auth import get_session
# Accept token from query param OR header
auth_token = token or x_auth_token
session = get_session(auth_token)
if not session:
raise HTTPException(401, "Nicht eingeloggt")
if session['role'] != 'admin':
raise HTTPException(403, "Nur für Admins")
profile_id = session['profile_id']