Buckets:

download
raw
10.9 kB
"""
Message sending, receiving, and routing for EnhancedAgentBus.
Constitutional Hash: 608508a9bd224290
"""
from __future__ import annotations
import asyncio
from collections.abc import Awaitable, Callable
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, TypeAlias
if TYPE_CHECKING:
from enhanced_agent_bus._compat.types import JSONDict
else:
JSONDict: TypeAlias = dict[str, Any]
from enhanced_agent_bus.models import (
CONSTITUTIONAL_HASH,
AgentMessage,
MessageStatus,
)
from enhanced_agent_bus.observability.structured_logging import get_logger
from enhanced_agent_bus.validators import ValidationResult
from ..security_helpers import normalize_tenant_id
if TYPE_CHECKING:
from ..components import GovernanceValidator, MessageRouter, RegistryManager
from ..message_processor import MessageProcessor
from .validation import MessageValidator
logger = get_logger(__name__)
@dataclass(frozen=True)
class MessageGovernanceDecision:
"""Delivery-facing governance decision derived from validation results.
Constitutional Hash: 608508a9bd224290
"""
result: ValidationResult
allow_delivery: bool
class MessageHandler:
"""
Handles message sending, receiving, and routing operations.
Constitutional Hash: 608508a9bd224290
"""
def __init__(
self,
processor: MessageProcessor,
router_component: MessageRouter,
registry_manager: RegistryManager,
governance: GovernanceValidator,
validator: MessageValidator,
message_queue: asyncio.Queue[AgentMessage],
deliberation_queue: Any | None,
metering_manager: Any,
kafka_bus: Any | None,
metrics: JSONDict,
config: JSONDict,
) -> None:
"""
Initialize message handler.
Args:
processor: MessageProcessor for processing messages.
router_component: MessageRouter component.
registry_manager: RegistryManager for agent management.
governance: GovernanceValidator for governance checks.
validator: MessageValidator for validation.
message_queue: Queue for received messages.
deliberation_queue: Optional deliberation queue.
metering_manager: Metering manager.
kafka_bus: Optional Kafka bus.
metrics: Metrics dictionary reference.
config: Bus configuration.
"""
self._processor = processor
self._router_component = router_component
self._registry_manager = registry_manager
self._governance = governance
self._validator = validator
self._message_queue = message_queue
self._deliberation_queue = deliberation_queue
self._metering_manager = metering_manager
self._kafka_bus = kafka_bus
self._metrics = metrics
self._config = config
async def process_message_with_fallback(self, msg: AgentMessage) -> ValidationResult:
"""
Process message through processor with graceful degradation.
Attempts to process the message through the configured MessageProcessor.
If processing fails due to any exception, falls back to DEGRADED governance
mode where messages that already passed prior validation checks (constitutional
hash, tenant isolation, adaptive governance) are allowed through.
Args:
msg: The AgentMessage to process. Should have already passed
constitutional hash and tenant validation.
Returns:
ValidationResult: Processing result with one of:
- Normal validation result from processor (happy path)
- DEGRADED mode result with is_valid=True and metadata indicating
fallback was triggered (degraded path)
Degraded Mode Behavior:
When the processor fails, returns a ValidationResult with:
- is_valid=True (message was pre-validated)
- decision="ALLOW"
- status=MessageStatus.VALIDATED
- metadata containing governance_mode="DEGRADED" and fallback_reason
Performance:
- Normal path: Depends on processor complexity
- Degraded path: Near-instant return with minimal overhead
Constitutional Hash: 608508a9bd224290
Note:
This graceful degradation ensures system availability while
maintaining constitutional compliance through prior validation.
"""
return (await self.decide_message_governance(msg)).result
async def decide_message_governance(self, msg: AgentMessage) -> MessageGovernanceDecision:
"""Produce a delivery-facing governance decision for a message.
Separates the governance decision from subsequent routing/delivery while
preserving the existing ValidationResult contract for compatibility.
"""
try:
result = await self._processor.process(msg)
except Exception as e:
logger.warning(f"Processor fallback activated: {e}")
metadata = msg.metadata if isinstance(getattr(msg, "metadata", None), dict) else {}
has_explicit_prevalidation = bool(
metadata.get("prevalidated")
or metadata.get("prevalidated_result")
or metadata.get("validated_by_agent")
or metadata.get("independent_validator_id")
)
if not has_explicit_prevalidation:
result = ValidationResult(
is_valid=False,
errors=["Processor fallback denied: message lacks explicit prevalidation"],
metadata={"governance_mode": "DEGRADED", "fallback_reason": str(e)},
decision="DENY",
status=MessageStatus.FAILED,
constitutional_hash=CONSTITUTIONAL_HASH,
)
return self._build_governance_decision(result)
result = ValidationResult(
is_valid=True,
metadata={"governance_mode": "DEGRADED", "fallback_reason": str(e)},
decision="ALLOW",
status=MessageStatus.VALIDATED,
constitutional_hash=CONSTITUTIONAL_HASH,
)
return self._build_governance_decision(result)
@staticmethod
def _build_governance_decision(result: ValidationResult) -> MessageGovernanceDecision:
"""Convert a ValidationResult into a delivery-facing governance decision."""
return MessageGovernanceDecision(result=result, allow_delivery=bool(result.is_valid))
async def finalize_message_delivery(
self,
msg: AgentMessage,
result: ValidationResult | MessageGovernanceDecision,
) -> bool:
"""Handle routing and delivery of validated message."""
decision = (
result
if isinstance(result, MessageGovernanceDecision)
else self._build_governance_decision(result)
)
if decision.allow_delivery:
success = await self.route_and_deliver(msg)
if success:
self._validator.record_metrics_success()
else:
self._validator.record_metrics_failure()
return success
else:
self._validator.record_metrics_failure()
return False
async def route_and_deliver(self, msg: AgentMessage) -> bool:
"""Route and deliver message via router component."""
success = bool(
await self._router_component.route_and_deliver(msg, self._registry_manager._registry)
)
if success and not self._kafka_bus:
await self._message_queue.put(msg)
return success
async def broadcast_message(
self,
msg: AgentMessage,
send_message_func: Callable[[AgentMessage], Awaitable[ValidationResult]],
constitutional_hash: str,
) -> dict[str, ValidationResult]:
"""Broadcast message to all agents in same tenant.
Constitutional Hash: 608508a9bd224290
Performance: Uses O(1) tenant index lookup instead of O(n) iteration.
"""
normalized_tenant_id = normalize_tenant_id(msg.tenant_id)
if normalized_tenant_id is not None:
msg.tenant_id = normalized_tenant_id
targets = self._registry_manager.get_agents_by_tenant(msg.tenant_id)
results: dict[str, ValidationResult] = {}
for aid in targets:
if aid == msg.from_agent:
continue
content = msg.content if hasattr(msg, "content") else {}
m = AgentMessage(
from_agent=msg.from_agent, message_type=msg.message_type, content=content
)
m.to_agent = aid
m.tenant_id = msg.tenant_id
m.constitutional_hash = msg.constitutional_hash
res = await send_message_func(m)
if res.is_valid:
results[aid] = res
return results
async def receive_message(self, timeout: float = 1.0) -> AgentMessage | None:
"""Receive a message from the internal queue.
Args:
timeout: Maximum seconds to wait for a message.
Returns:
AgentMessage: Received message if available, None on timeout.
"""
try:
m = await asyncio.wait_for(self._message_queue.get(), timeout)
if m:
self._metrics["received"] += 1
self._metrics["messages_received"] += 1
return m
except TimeoutError:
return None
async def handle_deliberation(
self,
msg: AgentMessage,
routing: JSONDict | None = None,
start_time: float | None = None,
**kwargs: object,
) -> bool:
"""Handle deliberation for high-impact messages."""
if routing and hasattr(routing, "status"):
routing.status = MessageStatus.PENDING_DELIBERATION
if self._deliberation_queue:
enqueue_res = self._deliberation_queue.enqueue(msg, routing)
if asyncio.iscoroutine(enqueue_res):
await enqueue_res
if self._metering_manager and start_time is not None:
import time as _time
latency_ms = (_time.perf_counter() - start_time) * 1000
self._metering_manager.record_deliberation_request(msg, start_time, latency_ms)
return await self.route_and_deliver(msg)
def requires_deliberation(self, msg: AgentMessage) -> bool:
"""Check if message requires deliberation based on impact score."""
impact_score = getattr(msg, "impact_score", 0.0)
if not isinstance(impact_score, (int, float)):
return False
return float(impact_score) >= 0.8

Xet Storage Details

Size:
10.9 kB
·
Xet hash:
c54aa55c761ffb81c4006e287b6c203565d92c1fa901e24c6798a8a23d5c12c1

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.