Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /ViperJuice_Code-Index-MCP /mcp_server /artifacts /semantic_profiles.py
| """Semantic profile registry and compatibility fingerprinting.""" | |
| from __future__ import annotations | |
| import copy | |
| import hashlib | |
| import json | |
| from dataclasses import dataclass, field | |
| from datetime import datetime, timezone | |
| from pathlib import Path | |
| from typing import Any, Dict, List, Mapping, Optional | |
| from ..interfaces.inference_contracts import ( | |
| COMPATIBILITY_CRITICAL_FIELDS, | |
| EmbeddingResponseV1, | |
| EmbeddingRole, | |
| ExpectedProfile, | |
| ProvenanceAuthority, | |
| ProvenanceField, | |
| validate_profile, | |
| ) | |
| from .semantic_namespace import SemanticNamespaceResolver | |
| class SemanticProfile: | |
| """Immutable semantic profile definition.""" | |
| profile_id: str | |
| provider: str | |
| model_name: str | |
| model_version: str | |
| vector_dimension: int | |
| distance_metric: str | |
| normalization_policy: str | |
| chunk_schema_version: str | |
| chunker_version: str | |
| compatibility_fingerprint: str | |
| reranker_defaults: Optional[Dict[str, Any]] = None | |
| build_metadata: Optional[Dict[str, Any]] = None | |
| def from_dict( | |
| cls, | |
| profile_id: str, | |
| payload: Mapping[str, Any], | |
| *, | |
| created_at: Optional[str] = None, | |
| tool_version: str = "unknown", | |
| ) -> "SemanticProfile": | |
| """Build profile from config payload and derive compatibility fingerprint.""" | |
| required = [ | |
| "provider", | |
| "model_name", | |
| "model_version", | |
| "vector_dimension", | |
| "distance_metric", | |
| "normalization_policy", | |
| "chunk_schema_version", | |
| "chunker_version", | |
| ] | |
| missing = [key for key in required if key not in payload] | |
| if missing: | |
| raise ValueError( | |
| f"Profile '{profile_id}' missing required fields: {', '.join(sorted(missing))}" | |
| ) | |
| vector_dimension = int(payload["vector_dimension"]) | |
| if vector_dimension <= 0: | |
| raise ValueError(f"Profile '{profile_id}' vector_dimension must be > 0") | |
| namespace_resolver = SemanticNamespaceResolver() | |
| build_metadata = dict(payload.get("build_metadata") or {}) | |
| supplemental = _supplement_enrichment_metadata(profile_id, payload) | |
| for key, value in supplemental.items(): | |
| build_metadata.setdefault(key, value) | |
| canonical: Dict[str, Any] = { | |
| "profile_id": profile_id, | |
| "provider": str(payload["provider"]), | |
| "model_name": str(payload["model_name"]), | |
| "model_version": str(payload["model_version"]), | |
| "vector_dimension": vector_dimension, | |
| "distance_metric": str(payload["distance_metric"]), | |
| "normalization_policy": str(payload["normalization_policy"]), | |
| "chunk_schema_version": str(payload["chunk_schema_version"]), | |
| "chunker_version": str(payload["chunker_version"]), | |
| "enrichment_model": _string_or_none( | |
| build_metadata.get("enrichment_model") or payload.get("enrichment_model") | |
| ), | |
| "enrichment_base_url_identity": namespace_resolver.normalize_endpoint_identity( | |
| build_metadata.get("enrichment_base_url") | |
| or payload.get("enrichment_base_url") | |
| or build_metadata.get("summarization_base_url") | |
| ), | |
| "prompt_template_hash": _prompt_template_hash( | |
| build_metadata.get("prompt_template") or payload.get("prompt_template") | |
| ), | |
| "collection_name": namespace_resolver.normalize_collection_name( | |
| build_metadata.get("collection_name") or payload.get("collection_name") | |
| ), | |
| } | |
| fingerprint = _compute_compatibility_fingerprint(canonical) | |
| metadata = build_metadata | |
| metadata.setdefault("created_at", created_at or datetime.now(timezone.utc).isoformat()) | |
| metadata.setdefault("tool_version", tool_version) | |
| metadata["compatibility_contract"] = { | |
| "enrichment_model": canonical["enrichment_model"], | |
| "enrichment_base_url_identity": canonical["enrichment_base_url_identity"], | |
| "prompt_template_hash": canonical["prompt_template_hash"], | |
| "collection_name": canonical["collection_name"], | |
| } | |
| return cls( | |
| profile_id=profile_id, | |
| provider=canonical["provider"], | |
| model_name=canonical["model_name"], | |
| model_version=canonical["model_version"], | |
| vector_dimension=canonical["vector_dimension"], | |
| distance_metric=canonical["distance_metric"], | |
| normalization_policy=canonical["normalization_policy"], | |
| chunk_schema_version=canonical["chunk_schema_version"], | |
| chunker_version=canonical["chunker_version"], | |
| compatibility_fingerprint=fingerprint, | |
| reranker_defaults=payload.get("reranker_defaults"), | |
| build_metadata=metadata, | |
| ) | |
| def to_dict(self) -> Dict[str, Any]: | |
| """Serialize profile for manifests and status endpoints.""" | |
| return { | |
| "profile_id": self.profile_id, | |
| "provider": self.provider, | |
| "model_name": self.model_name, | |
| "model_version": self.model_version, | |
| "vector_dimension": self.vector_dimension, | |
| "distance_metric": self.distance_metric, | |
| "normalization_policy": self.normalization_policy, | |
| "chunk_schema_version": self.chunk_schema_version, | |
| "chunker_version": self.chunker_version, | |
| "compatibility_fingerprint": self.compatibility_fingerprint, | |
| "reranker_defaults": self.reranker_defaults, | |
| "build_metadata": _redact_secret_fields(self.build_metadata), | |
| } | |
| class SemanticProfileRegistry: | |
| """Registry containing named semantic profiles and default selection.""" | |
| def __init__( | |
| self, | |
| profiles: Mapping[str, Mapping[str, Any]], | |
| default_profile: Optional[str] = None, | |
| *, | |
| created_at: Optional[str] = None, | |
| tool_version: str = "unknown", | |
| ) -> None: | |
| if not profiles: | |
| raise ValueError("Semantic profile registry requires at least one profile") | |
| self._profiles: Dict[str, SemanticProfile] = {} | |
| for profile_id, payload in profiles.items(): | |
| if profile_id in self._profiles: | |
| raise ValueError(f"Duplicate semantic profile ID: {profile_id}") | |
| self._profiles[profile_id] = SemanticProfile.from_dict( | |
| profile_id, | |
| payload, | |
| created_at=created_at, | |
| tool_version=tool_version, | |
| ) | |
| self.default_profile = default_profile or next(iter(self._profiles.keys())) | |
| if self.default_profile not in self._profiles: | |
| raise ValueError(f"Default semantic profile '{self.default_profile}' is not defined") | |
| def from_config_file( | |
| cls, | |
| config_path: Path, | |
| *, | |
| tool_version: str = "unknown", | |
| ) -> "SemanticProfileRegistry": | |
| """Load registry from .mcp-index.json style config file.""" | |
| payload = json.loads(config_path.read_text(encoding="utf-8")) | |
| profiles = payload.get("semantic_profiles") or {} | |
| default_profile = payload.get("semantic_default_profile") | |
| return cls(profiles, default_profile, tool_version=tool_version) | |
| def from_raw( | |
| cls, | |
| profiles: Mapping[str, Mapping[str, Any]], | |
| default_profile: Optional[str] = None, | |
| *, | |
| tool_version: str = "unknown", | |
| ) -> "SemanticProfileRegistry": | |
| """Build registry from in-memory profile payloads.""" | |
| return cls(profiles, default_profile, tool_version=tool_version) | |
| def get(self, profile_id: Optional[str] = None) -> SemanticProfile: | |
| """Get profile by ID, defaulting to configured default profile.""" | |
| resolved = profile_id or self.default_profile | |
| if resolved not in self._profiles: | |
| raise KeyError(f"Unknown semantic profile '{resolved}'") | |
| return self._profiles[resolved] | |
| def list(self) -> Dict[str, SemanticProfile]: | |
| """Return copy of profile map.""" | |
| return dict(self._profiles) | |
| def to_dict(self) -> Dict[str, Any]: | |
| """Serialize registry for diagnostics and manifests.""" | |
| return { | |
| "semantic_default_profile": self.default_profile, | |
| "semantic_profiles": { | |
| profile_id: profile.to_dict() for profile_id, profile in self._profiles.items() | |
| }, | |
| } | |
| # Substrings that mark a build_metadata key as holding a raw secret VALUE. | |
| _SECRET_KEY_MARKERS = ( | |
| "api_key", | |
| "apikey", | |
| "secret", | |
| "token", | |
| "password", | |
| "passwd", | |
| "bearer", | |
| "authorization", | |
| "credential", | |
| "access_key", | |
| "private_key", | |
| ) | |
| # Suffixes that mark a key as holding a secret REFERENCE (e.g. an env var name), | |
| # never the secret itself. These are preserved verbatim. | |
| _SECRET_REFERENCE_SUFFIXES = ( | |
| "_env", | |
| "_ref", | |
| "_name", | |
| "_var", | |
| "_reference", | |
| "_key_id", | |
| "_key_ref", | |
| ) | |
| _REDACTED_PLACEHOLDER = "***redacted***" | |
| def _looks_like_secret_reference(key: str) -> bool: | |
| """True when the key names a secret reference (env var name) not a value.""" | |
| return key.lower().endswith(_SECRET_REFERENCE_SUFFIXES) | |
| def _redact_secret_fields(metadata: Any) -> Any: | |
| """Redact any credential-bearing field from a metadata structure. | |
| Any key whose name looks like it holds a raw secret value | |
| (``*api_key*``, bearer/authorization/token/secret/password/credential) is | |
| replaced with a redaction placeholder. Secret-REFERENCE names (keys ending | |
| in ``_env``/``_ref``/``_name`` etc.) and any ``Bearer <token>`` string | |
| values are also handled. Nested mappings AND nested lists/tuples are redacted | |
| recursively (e.g. ``[{"api_key": "..."}]`` or | |
| ``[["Authorization", "Bearer ..."]]``) so no secret survives serialization | |
| via ``to_dict`` or artifact export. | |
| """ | |
| if isinstance(metadata, Mapping): | |
| redacted: Dict[str, Any] = {} | |
| for key, value in metadata.items(): | |
| key_str = str(key) | |
| lowered = key_str.lower() | |
| is_secret_key = any(marker in lowered for marker in _SECRET_KEY_MARKERS) | |
| if is_secret_key and not _looks_like_secret_reference(key_str): | |
| redacted[key] = _REDACTED_PLACEHOLDER | |
| else: | |
| # Recurse into the value so secrets nested in mappings, lists, | |
| # or tuples (or a bare ``Bearer <token>`` string) are redacted. | |
| redacted[key] = _redact_secret_fields(value) | |
| return redacted | |
| if isinstance(metadata, (list, tuple)): | |
| redacted_items = [_redact_secret_fields(item) for item in metadata] | |
| return tuple(redacted_items) if isinstance(metadata, tuple) else redacted_items | |
| if isinstance(metadata, str) and metadata.strip().lower().startswith("bearer "): | |
| return _REDACTED_PLACEHOLDER | |
| return metadata | |
| def _compute_compatibility_fingerprint(canonical_payload: Mapping[str, Any]) -> str: | |
| """Compute deterministic compatibility fingerprint for a profile.""" | |
| raw = json.dumps(canonical_payload, sort_keys=True, separators=(",", ":")) | |
| return hashlib.sha256(raw.encode("utf-8")).hexdigest()[:32] | |
| def _prompt_template_hash(prompt_template: Any) -> Optional[str]: | |
| if not isinstance(prompt_template, str): | |
| return None | |
| normalized = prompt_template.strip() | |
| if not normalized: | |
| return None | |
| return hashlib.sha256(normalized.encode("utf-8")).hexdigest()[:16] | |
| def _string_or_none(value: Any) -> Optional[str]: | |
| if not isinstance(value, str): | |
| return None | |
| normalized = value.strip() | |
| return normalized or None | |
| def _supplement_enrichment_metadata( | |
| profile_id: str, | |
| payload: Mapping[str, Any], | |
| ) -> Dict[str, Any]: | |
| build_metadata = payload.get("build_metadata") | |
| if isinstance(build_metadata, Mapping) and all( | |
| build_metadata.get(key) | |
| for key in ("enrichment_model", "enrichment_base_url", "prompt_template") | |
| ): | |
| return {} | |
| try: | |
| from mcp_server.config.settings import get_settings | |
| settings = get_settings() | |
| summarization = settings.get_profile_summarization_config(profile_id) | |
| except Exception: | |
| summarization = {} | |
| if not isinstance(summarization, Mapping): | |
| return {} | |
| supplemental: Dict[str, Any] = {} | |
| if summarization.get("model_name"): | |
| supplemental["enrichment_model"] = str(summarization["model_name"]) | |
| if summarization.get("base_url"): | |
| supplemental["enrichment_base_url"] = str(summarization["base_url"]) | |
| if summarization.get("prompt_template"): | |
| supplemental["prompt_template"] = str(summarization["prompt_template"]) | |
| return supplemental | |
| def extract_semantic_profile_metadata( | |
| metadata: Optional[Mapping[str, Any]], | |
| ) -> Dict[str, Dict[str, Any]]: | |
| """Extract normalized semantic profile metadata from multi or legacy payloads.""" | |
| if not metadata: | |
| return {} | |
| discovered: Dict[str, Dict[str, Any]] = {} | |
| semantic_profiles = metadata.get("semantic_profiles") | |
| if isinstance(semantic_profiles, Mapping): | |
| for raw_profile_id, payload in semantic_profiles.items(): | |
| if not isinstance(raw_profile_id, str) or not raw_profile_id: | |
| continue | |
| normalized: Dict[str, Any] = {"profile_id": raw_profile_id} | |
| if isinstance(payload, Mapping): | |
| normalized.update(dict(payload)) | |
| elif isinstance(payload, str): | |
| normalized["compatibility_fingerprint"] = payload | |
| discovered[raw_profile_id] = normalized | |
| legacy_profile = metadata.get("semantic_profile") | |
| if isinstance(legacy_profile, str) and legacy_profile and legacy_profile not in discovered: | |
| discovered[legacy_profile] = { | |
| "profile_id": legacy_profile, | |
| "compatibility_fingerprint": metadata.get("compatibility_fingerprint"), | |
| "compatibility_hash": metadata.get("compatibility_hash"), | |
| "embedding_provider": metadata.get("embedding_provider"), | |
| "embedding_model": metadata.get("embedding_model"), | |
| "model_version": metadata.get("model_version"), | |
| "model_dimension": metadata.get("model_dimension"), | |
| "distance_metric": metadata.get("distance_metric"), | |
| "normalization_policy": metadata.get("normalization_policy"), | |
| "chunk_schema_version": metadata.get("chunk_schema_version"), | |
| "collection_name": metadata.get("collection_name"), | |
| "qdrant_path": metadata.get("qdrant_path"), | |
| "created_at": metadata.get("created_at"), | |
| "updated_at": metadata.get("updated_at"), | |
| } | |
| return discovered | |
| def get_primary_semantic_profile_metadata( | |
| metadata: Optional[Mapping[str, Any]], | |
| ) -> tuple[Optional[str], Optional[Dict[str, Any]]]: | |
| """Return the primary semantic profile metadata entry, if present.""" | |
| profiles = extract_semantic_profile_metadata(metadata) | |
| if not profiles: | |
| return None, None | |
| requested = metadata.get("semantic_profile") if metadata else None | |
| if isinstance(requested, str) and requested in profiles: | |
| return requested, profiles[requested] | |
| profile_id = next(iter(profiles.keys())) | |
| return profile_id, profiles[profile_id] | |
| # ===================================================================== | |
| # Provenance attestation (IF-0-EMBEDPROV-1) | |
| # ===================================================================== | |
| # The reconciliation remediation, named verbatim in every fail-closed diagnostic | |
| # so an operator is always told exactly how to recover. | |
| REINDEX_REMEDIATION = ( | |
| "Run an operator-authorized reindex to rebuild the index under the attested " | |
| "provider profile (or probe-revalidate the live endpoint via " | |
| "SemanticIndexer.reconcile_existing_collection)." | |
| ) | |
| class ProfileAttestation: | |
| """Outcome of reconciling a provider response against a semantic profile. | |
| ``ok`` is fail-closed: any compatibility-critical field that is neither | |
| server-``reported`` nor operator-``declared`` (i.e. still ``unknown`` after the | |
| declared overlay), or whose server-reported value mismatches the profile, | |
| makes ``ok`` False. ``derived`` records, per compatibility-critical field, the | |
| value the index should be stamped with (server-reported values replace assumed | |
| ones) and the authority/source it came from. | |
| """ | |
| ok: bool | |
| failures: List[str] = field(default_factory=list) | |
| checked_fields: List[str] = field(default_factory=list) | |
| derived: Dict[str, Dict[str, Any]] = field(default_factory=dict) | |
| reported_fields: List[str] = field(default_factory=list) | |
| role: Optional[str] = None | |
| remediation: Optional[str] = None | |
| def to_dict(self) -> Dict[str, Any]: | |
| return { | |
| "ok": self.ok, | |
| "failures": list(self.failures), | |
| "checked_fields": list(self.checked_fields), | |
| "derived": {name: dict(entry) for name, entry in self.derived.items()}, | |
| "reported_fields": list(self.reported_fields), | |
| "role": self.role, | |
| "remediation": self.remediation, | |
| } | |
| def failure_reason(self, *, subject: str = "embedding profile") -> str: | |
| """Human-actionable diagnostic that always NAMES the remediation.""" | |
| detail = "; ".join(self.failures) or "provenance validation failed" | |
| remediation = self.remediation or REINDEX_REMEDIATION | |
| return ( | |
| f"Provenance attestation failed for {subject}: {detail}. " | |
| f"Refusing to write vectors under an unverified profile. {remediation}" | |
| ) | |
| def build_expected_profile(profile: Any, *, role: Optional[EmbeddingRole] = None) -> ExpectedProfile: | |
| """Build an :class:`ExpectedProfile` from a semantic profile's assumed values.""" | |
| return ExpectedProfile( | |
| served_model_id=getattr(profile, "model_name", None), | |
| model_revision=getattr(profile, "model_version", None), | |
| dimension=getattr(profile, "vector_dimension", None), | |
| normalization=getattr(profile, "normalization_policy", None), | |
| role=role, | |
| processor_id=None, | |
| ) | |
| def _overlay_declared( | |
| response: EmbeddingResponseV1, expected: ExpectedProfile | |
| ) -> EmbeddingResponseV1: | |
| """Return a copy of ``response`` with unknown critical fields declared. | |
| A compatibility-critical field the provider left ``unknown`` is explicitly | |
| upgraded to ``declared`` using the operator's profile value — never silently | |
| assumed and never fabricated as ``reported``. A field the profile also cannot | |
| supply stays ``unknown`` so it fails closed. The original response is not | |
| mutated. | |
| """ | |
| effective = copy.copy(response) | |
| for name in COMPATIBILITY_CRITICAL_FIELDS: | |
| pf = response.provenance_field(name) | |
| if pf.authority == ProvenanceAuthority.UNKNOWN: | |
| declared_value = expected.expected_value(name) | |
| if declared_value is not None: | |
| setattr(effective, name, ProvenanceField.declared(declared_value)) | |
| return effective | |
| def attest_embedding_response( | |
| profile: Any, | |
| response: EmbeddingResponseV1, | |
| *, | |
| role: Optional[EmbeddingRole] = None, | |
| remediation: str = REINDEX_REMEDIATION, | |
| ) -> ProfileAttestation: | |
| """Attest a provider ``embedding-response.v1`` against a semantic profile. | |
| Server-``reported`` values are the highest authority and are carried into the | |
| derived profile (replacing the assumed value). Fields the provider cannot | |
| report are explicitly ``declared`` from profile config. Any compatibility- | |
| critical field that remains ``unknown``, or whose reported value mismatches the | |
| profile, fails closed (``ok=False``) with a remediation-naming diagnostic. | |
| """ | |
| expected = build_expected_profile(profile, role=role) | |
| effective = _overlay_declared(response, expected) | |
| result = validate_profile(expected, effective) | |
| derived: Dict[str, Dict[str, Any]] = {} | |
| reported_fields: List[str] = [] | |
| for name in COMPATIBILITY_CRITICAL_FIELDS: | |
| pf = effective.provenance_field(name) | |
| if pf.authority == ProvenanceAuthority.REPORTED: | |
| source = "reported" | |
| reported_fields.append(name) | |
| elif pf.authority == ProvenanceAuthority.DECLARED: | |
| source = "declared" | |
| else: | |
| source = "unknown" | |
| derived[name] = { | |
| "value": pf.value, | |
| "authority": pf.authority.value, | |
| "source": source, | |
| } | |
| return ProfileAttestation( | |
| ok=result.ok, | |
| failures=result.failures, | |
| checked_fields=result.checked_fields, | |
| derived=derived, | |
| reported_fields=reported_fields, | |
| role=_resolve_role_string(role, response), | |
| remediation=None if result.ok else remediation, | |
| ) | |
| def _resolve_role_string( | |
| role: Optional[EmbeddingRole], response: EmbeddingResponseV1 | |
| ) -> Optional[str]: | |
| """Resolve the attestation's recorded role to an actual role STRING. | |
| Honors the explicit ``role=`` argument when supplied (never overriding the | |
| caller's intent with the response's own tag), and otherwise falls back to the | |
| response's ``role`` provenance value. In both cases the result is the plain | |
| role string (e.g. ``"document"``) — never an :class:`EmbeddingRole` repr like | |
| ``"EmbeddingRole.DOCUMENT"`` and never a raw :class:`ProvenanceField`. | |
| """ | |
| if role is not None: | |
| return role.value if isinstance(role, EmbeddingRole) else str(role) | |
| raw = response.role.value if isinstance(response.role, ProvenanceField) else response.role | |
| if isinstance(raw, EmbeddingRole): | |
| return raw.value | |
| if isinstance(raw, str): | |
| return raw | |
| return None | |
Xet Storage Details
- Size:
- 22 kB
- Xet hash:
- 961591bd749c3b20541e31adcdd8cae76e0478c23194fb70dd238c8c7e932936
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.