File size: 22,217 Bytes
9abace2 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 | """
DSL Validator for HyperKittyConstraintDSL.
Validates:
1. BooleanKernel (NAND truthtable, derived gates)
2. Entropy constraint (H ≤ 0.20 nats)
3. Trust axiom (active ⇒ trusted)
4. GlyphType constraints (injective mapping)
5. DAG validation (acyclic, reachable)
Pure Python stdlib: hashlib (Blake2b), math (log), collections, enum, dataclasses.
"""
import hashlib
import math
from dataclasses import dataclass
from enum import Enum
from typing import Dict, List, Tuple, Set, Optional
from collections import defaultdict, deque
class PROOF_STATUS(Enum):
"""Proof status for constraint validation results."""
PROOF_TRUE = "PROOF_TRUE"
PROOF_FALSE = "PROOF_FALSE"
PROOF_INCOMPLETE = "PROOF_INCOMPLETE"
@dataclass
class ValidationResult:
"""Result of a single constraint validation."""
passed: bool
constraint: str
detail: str
proof_status: PROOF_STATUS = PROOF_STATUS.PROOF_INCOMPLETE
class DSLValidator:
"""Validator for HyperKittyConstraintDSL constraints."""
def __init__(self):
"""Initialize validator with empty results list."""
self.results: List[ValidationResult] = []
# ========== BOOLEAN KERNEL VALIDATION ==========
@staticmethod
def nand(a: int, b: int) -> int:
"""
NAND truthtable: NOT(a AND b).
NAND(0,0) = 1
NAND(0,1) = 1
NAND(1,0) = 1
NAND(1,1) = 0
"""
return int(not (a and b))
@staticmethod
def not_gate(a: int) -> int:
"""
NOT derived from NAND: NOT(A) = NAND(A,A).
"""
return DSLValidator.nand(a, a)
@staticmethod
def and_gate(a: int, b: int) -> int:
"""
AND derived: AND(A,B) = NOT(NAND(A,B)).
"""
return DSLValidator.not_gate(DSLValidator.nand(a, b))
@staticmethod
def or_gate(a: int, b: int) -> int:
"""
OR derived: OR(A,B) = NAND(NOT(A),NOT(B)).
"""
return DSLValidator.nand(
DSLValidator.not_gate(a),
DSLValidator.not_gate(b)
)
@staticmethod
def implies_gate(a: int, b: int) -> int:
"""
IMPLIES derived: IMPLIES(A,B) = NAND(A,NOT(B)).
False only when A=1 and B=0.
"""
return DSLValidator.nand(a, DSLValidator.not_gate(b))
@staticmethod
def equal_gate(a: int, b: int) -> int:
"""
EQUAL derived: EQUAL(A,B) = AND(IMPLIES(A,B),IMPLIES(B,A)).
True when A and B have same truth value.
"""
return DSLValidator.and_gate(
DSLValidator.implies_gate(a, b),
DSLValidator.implies_gate(b, a)
)
def validate_nand_truthtable(self) -> ValidationResult:
"""
Validate NAND truth table exhaustively.
Expected:
- NAND(0,0) = 1
- NAND(0,1) = 1
- NAND(1,0) = 1
- NAND(1,1) = 0
"""
expected = {
(0, 0): 1,
(0, 1): 1,
(1, 0): 1,
(1, 1): 0,
}
for (a, b), expected_result in expected.items():
actual = self.nand(a, b)
if actual != expected_result:
return ValidationResult(
passed=False,
constraint="NAND_TRUTHTABLE",
detail=f"NAND({a},{b}) = {actual}, expected {expected_result}",
proof_status=PROOF_STATUS.PROOF_FALSE
)
return ValidationResult(
passed=True,
constraint="NAND_TRUTHTABLE",
detail="NAND truth table: 4/4 entries correct",
proof_status=PROOF_STATUS.PROOF_TRUE
)
def validate_not_derivation(self) -> ValidationResult:
"""
Validate NOT derived from NAND: NOT(A) = NAND(A,A).
"""
for a in [0, 1]:
derived = self.not_gate(a)
expected = int(not a)
if derived != expected:
return ValidationResult(
passed=False,
constraint="NOT_DERIVATION",
detail=f"NOT({a}) = {derived}, expected {expected}",
proof_status=PROOF_STATUS.PROOF_FALSE
)
return ValidationResult(
passed=True,
constraint="NOT_DERIVATION",
detail="NOT gate: 2/2 truth values verified",
proof_status=PROOF_STATUS.PROOF_TRUE
)
def validate_and_derivation(self) -> ValidationResult:
"""
Validate AND derived from NAND: AND(A,B) = NOT(NAND(A,B)).
"""
for a in [0, 1]:
for b in [0, 1]:
derived = self.and_gate(a, b)
expected = int(a and b)
if derived != expected:
return ValidationResult(
passed=False,
constraint="AND_DERIVATION",
detail=f"AND({a},{b}) = {derived}, expected {expected}",
proof_status=PROOF_STATUS.PROOF_FALSE
)
return ValidationResult(
passed=True,
constraint="AND_DERIVATION",
detail="AND gate: 4/4 truth values verified",
proof_status=PROOF_STATUS.PROOF_TRUE
)
def validate_or_derivation(self) -> ValidationResult:
"""
Validate OR derived from NAND: OR(A,B) = NAND(NOT(A),NOT(B)).
"""
for a in [0, 1]:
for b in [0, 1]:
derived = self.or_gate(a, b)
expected = int(a or b)
if derived != expected:
return ValidationResult(
passed=False,
constraint="OR_DERIVATION",
detail=f"OR({a},{b}) = {derived}, expected {expected}",
proof_status=PROOF_STATUS.PROOF_FALSE
)
return ValidationResult(
passed=True,
constraint="OR_DERIVATION",
detail="OR gate: 4/4 truth values verified",
proof_status=PROOF_STATUS.PROOF_TRUE
)
def validate_implies_derivation(self) -> ValidationResult:
"""
Validate IMPLIES derived from NAND: IMPLIES(A,B) = NAND(A,NOT(B)).
False only when A=1 and B=0.
"""
for a in [0, 1]:
for b in [0, 1]:
derived = self.implies_gate(a, b)
expected = int(not a or b)
if derived != expected:
return ValidationResult(
passed=False,
constraint="IMPLIES_DERIVATION",
detail=f"IMPLIES({a},{b}) = {derived}, expected {expected}",
proof_status=PROOF_STATUS.PROOF_FALSE
)
return ValidationResult(
passed=True,
constraint="IMPLIES_DERIVATION",
detail="IMPLIES gate: 4/4 truth values verified",
proof_status=PROOF_STATUS.PROOF_TRUE
)
def validate_equal_derivation(self) -> ValidationResult:
"""
Validate EQUAL derived from NAND: EQUAL(A,B) = AND(IMPLIES(A,B),IMPLIES(B,A)).
True when A and B have same truth value.
"""
for a in [0, 1]:
for b in [0, 1]:
derived = self.equal_gate(a, b)
expected = int(a == b)
if derived != expected:
return ValidationResult(
passed=False,
constraint="EQUAL_DERIVATION",
detail=f"EQUAL({a},{b}) = {derived}, expected {expected}",
proof_status=PROOF_STATUS.PROOF_FALSE
)
return ValidationResult(
passed=True,
constraint="EQUAL_DERIVATION",
detail="EQUAL gate: 4/4 truth values verified",
proof_status=PROOF_STATUS.PROOF_TRUE
)
def validate_boolean_kernel(self) -> bool:
"""
Validate entire boolean kernel: all 6 gate derivations.
Returns True if all gates pass their truth tables.
"""
checks = [
self.validate_nand_truthtable(),
self.validate_not_derivation(),
self.validate_and_derivation(),
self.validate_or_derivation(),
self.validate_implies_derivation(),
self.validate_equal_derivation(),
]
all_passed = all(check.passed for check in checks)
self.results.extend(checks)
return all_passed
# ========== ENTROPY CONSTRAINT VALIDATION ==========
def validate_entropy(self, distribution: Dict[str, float], max_entropy: float = 0.20) -> bool:
"""
Validate entropy constraint: H ≤ max_entropy nats.
Shannon entropy: H = -Σ pᵢ log(pᵢ)
Args:
distribution: dict mapping route/state names to probabilities
max_entropy: maximum allowed entropy (default 0.20 nats)
Returns:
True if entropy satisfies constraint.
"""
# Check for empty distribution
if not distribution:
result = ValidationResult(
passed=False,
constraint="ENTROPY",
detail="Distribution is empty",
proof_status=PROOF_STATUS.PROOF_FALSE
)
self.results.append(result)
return False
# Normalize distribution
total = sum(distribution.values())
if total <= 0:
result = ValidationResult(
passed=False,
constraint="ENTROPY",
detail="Distribution total is <= 0",
proof_status=PROOF_STATUS.PROOF_FALSE
)
self.results.append(result)
return False
normalized = {k: v / total for k, v in distribution.items()}
# Calculate Shannon entropy: H = -Σ pᵢ log(pᵢ)
entropy = 0.0
for prob in normalized.values():
if prob > 0:
entropy -= prob * math.log(prob)
passed = entropy <= max_entropy
result = ValidationResult(
passed=passed,
constraint="ENTROPY",
detail=f"H = {entropy:.6f} nats (limit: {max_entropy})",
proof_status=PROOF_STATUS.PROOF_TRUE if passed else PROOF_STATUS.PROOF_FALSE
)
self.results.append(result)
return passed
# ========== TRUST AXIOM VALIDATION ==========
def validate_trust(self, active_set: Set[str], trusted_set: Set[str]) -> bool:
"""
Validate trust axiom: active(I) ⇒ trusted(I).
Constraint: every agent instance in active_set must be in trusted_set.
Args:
active_set: set of currently active agent IDs
trusted_set: set of trusted agent IDs
Returns:
True if all active agents are trusted.
"""
untrusted_active = active_set - trusted_set
passed = len(untrusted_active) == 0
detail = "All active agents are trusted"
if untrusted_active:
detail = f"Untrusted active agents: {sorted(untrusted_active)}"
result = ValidationResult(
passed=passed,
constraint="TRUST_AXIOM",
detail=detail,
proof_status=PROOF_STATUS.PROOF_TRUE if passed else PROOF_STATUS.PROOF_FALSE
)
self.results.append(result)
return passed
# ========== GLYPH TYPE VALIDATION ==========
def validate_glyph_types(self, mapping: Dict[str, str]) -> bool:
"""
Validate GlyphType constraint.
Constraints:
1. Each glyph maps to exactly one semantic type (by construction)
2. No two glyphs map to same type (injective)
3. All types in universe covered (surjective within declared types)
Args:
mapping: dict from glyph name to semantic type name
Returns:
True if mapping is injective.
"""
if not mapping:
result = ValidationResult(
passed=False,
constraint="GLYPH_TYPES",
detail="Mapping is empty",
proof_status=PROOF_STATUS.PROOF_FALSE
)
self.results.append(result)
return False
# Check injectivity: no two glyphs map to same type
type_to_glyphs: Dict[str, List[str]] = defaultdict(list)
for glyph, glyph_type in mapping.items():
type_to_glyphs[glyph_type].append(glyph)
# Find violations of injectivity
duplicates = {t: glyphs for t, glyphs in type_to_glyphs.items() if len(glyphs) > 1}
if duplicates:
detail = f"Non-injective: {dict(duplicates)}"
result = ValidationResult(
passed=False,
constraint="GLYPH_TYPES",
detail=detail,
proof_status=PROOF_STATUS.PROOF_FALSE
)
self.results.append(result)
return False
result = ValidationResult(
passed=True,
constraint="GLYPH_TYPES",
detail=f"Injective mapping verified: {len(mapping)} glyphs → {len(type_to_glyphs)} types",
proof_status=PROOF_STATUS.PROOF_TRUE
)
self.results.append(result)
return True
# ========== DAG VALIDATION ==========
def validate_dag(self, adjacency: Dict[str, List[str]]) -> bool:
"""
Validate DAG (directed acyclic graph) constraint.
Constraints:
1. Graph must be acyclic (no cycles)
2. Topological sort must succeed
3. No orphan nodes (all nodes reachable from at least one root)
Args:
adjacency: dict mapping node names to list of neighbor nodes
Returns:
True if graph is a valid DAG with no orphans.
"""
if not adjacency:
result = ValidationResult(
passed=True,
constraint="DAG_VALIDATION",
detail="Empty graph is acyclic",
proof_status=PROOF_STATUS.PROOF_TRUE
)
self.results.append(result)
return True
# Get all nodes in graph
all_nodes = set(adjacency.keys())
for neighbors in adjacency.values():
all_nodes.update(neighbors)
# Check for cycles using DFS with recursion stack
visited: Set[str] = set()
rec_stack: Set[str] = set()
def has_cycle(node: str) -> bool:
"""DFS cycle detection using recursion stack."""
visited.add(node)
rec_stack.add(node)
for neighbor in adjacency.get(node, []):
if neighbor not in visited:
if has_cycle(neighbor):
return True
elif neighbor in rec_stack:
return True
rec_stack.remove(node)
return False
# Check all nodes for cycles
for node in all_nodes:
if node not in visited:
if has_cycle(node):
result = ValidationResult(
passed=False,
constraint="DAG_VALIDATION",
detail="Cycle detected in routing graph",
proof_status=PROOF_STATUS.PROOF_FALSE
)
self.results.append(result)
return False
# Calculate in-degree for each node
in_degree = defaultdict(int)
for node in all_nodes:
if node not in in_degree:
in_degree[node] = 0
for neighbors in adjacency.values():
for neighbor in neighbors:
in_degree[neighbor] += 1
# Find root nodes (in-degree = 0)
roots = {node for node in all_nodes if in_degree[node] == 0}
if not roots:
result = ValidationResult(
passed=False,
constraint="DAG_VALIDATION",
detail="No root nodes: all nodes have incoming edges",
proof_status=PROOF_STATUS.PROOF_FALSE
)
self.results.append(result)
return False
# BFS from all roots to find reachable nodes
reachable = set()
queue = deque(roots)
reachable.update(roots)
while queue:
node = queue.popleft()
for neighbor in adjacency.get(node, []):
if neighbor not in reachable:
reachable.add(neighbor)
queue.append(neighbor)
# Check for orphan nodes (unreachable from roots)
orphans = all_nodes - reachable
if orphans:
result = ValidationResult(
passed=False,
constraint="DAG_VALIDATION",
detail=f"Orphan nodes (unreachable): {sorted(orphans)}",
proof_status=PROOF_STATUS.PROOF_FALSE
)
self.results.append(result)
return False
result = ValidationResult(
passed=True,
constraint="DAG_VALIDATION",
detail=f"DAG valid: {len(all_nodes)} nodes, {len(roots)} roots, acyclic, fully reachable",
proof_status=PROOF_STATUS.PROOF_TRUE
)
self.results.append(result)
return True
# ========== COMPOSITE VALIDATION ==========
def validate_all(self) -> Tuple[bool, List[ValidationResult]]:
"""
Run all validations and return combined result.
Currently runs boolean kernel validation.
Other validations (entropy, trust, glyph, dag) must be called explicitly.
Returns:
(all_passed, results_list)
"""
self.results = []
boolean_valid = self.validate_boolean_kernel()
return boolean_valid, self.results
def generate_proof_hash(results: List[ValidationResult]) -> str:
"""
Generate Blake2b hash over all constraint validation results.
Encodes each result as canonical string:
constraint:passed:proof_status:detail
Sorts results for deterministic ordering, then computes Blake2b-256 hash.
Args:
results: list of ValidationResult objects
Returns:
Hex digest of Blake2b-256 hash (64 characters).
"""
result_strings = []
for result in results:
# Canonical encoding: constraint:passed:proof_status:detail
encoded = f"{result.constraint}:{result.passed}:{result.proof_status.value}:{result.detail}"
result_strings.append(encoded)
# Sort for deterministic ordering
result_strings.sort()
# Concatenate with newlines
combined = "\n".join(result_strings)
# Compute Blake2b-256 hash
hasher = hashlib.blake2b(digest_size=32)
hasher.update(combined.encode('utf-8'))
return hasher.hexdigest()
# ========== EXAMPLE USAGE AND TESTS ==========
if __name__ == "__main__":
print("=" * 70)
print("DSL Validator - HyperKittyConstraintDSL")
print("=" * 70)
validator = DSLValidator()
# Test 1: Boolean Kernel
print("\n[1] Boolean Kernel Validation")
print("-" * 70)
bool_valid, bool_results = validator.validate_all()
for result in bool_results:
status = "✓ PASS" if result.passed else "✗ FAIL"
print(f" {status:8} {result.constraint:25} {result.detail}")
print(f"\n Overall: {'✓ VALID' if bool_valid else '✗ INVALID'}")
# Test 2: Entropy
print("\n[2] Entropy Constraint Validation")
print("-" * 70)
validator.results = []
dist = {"route_a": 0.3, "route_b": 0.5, "route_c": 0.2}
entropy_valid = validator.validate_entropy(dist, max_entropy=0.20)
for result in validator.results:
status = "✓ PASS" if result.passed else "✗ FAIL"
print(f" {status:8} {result.constraint:25} {result.detail}")
# Test 3: Trust Axiom
print("\n[3] Trust Axiom Validation")
print("-" * 70)
validator.results = []
active = {"agent_1", "agent_2", "agent_3"}
trusted = {"agent_1", "agent_2", "agent_3", "agent_4"}
trust_valid = validator.validate_trust(active, trusted)
for result in validator.results:
status = "✓ PASS" if result.passed else "✗ FAIL"
print(f" {status:8} {result.constraint:25} {result.detail}")
# Test 4: Glyph Types
print("\n[4] Glyph Type Validation")
print("-" * 70)
validator.results = []
glyph_map = {"aleph": "number", "beth": "letter", "gimel": "symbol"}
glyph_valid = validator.validate_glyph_types(glyph_map)
for result in validator.results:
status = "✓ PASS" if result.passed else "✗ FAIL"
print(f" {status:8} {result.constraint:25} {result.detail}")
# Test 5: DAG
print("\n[5] DAG Validation")
print("-" * 70)
validator.results = []
adjacency = {
"start": ["middle"],
"middle": ["end"],
"end": []
}
dag_valid = validator.validate_dag(adjacency)
for result in validator.results:
status = "✓ PASS" if result.passed else "✗ FAIL"
print(f" {status:8} {result.constraint:25} {result.detail}")
# Generate proof hash
print("\n[6] Proof Hash Generation")
print("-" * 70)
all_results = bool_results + validator.results
proof_hash = generate_proof_hash(all_results)
print(f" Blake2b-256: {proof_hash}")
print(f" Total constraints validated: {len(all_results)}")
|