Skip to content
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# Changelog

All notable changes to this project will be documented in this file.

## [9.1.0] - 2025-11-14

### Added

- Phase 3 structural instrumentation:
- `run_structural_validation` aggregator (grammar U1-U3 + field thresholds Φ_s, |∇φ|, K_φ, ξ_C, optional ΔΦ_s drift).
- `compute_structural_health` with risk levels and recommendations.
- `TelemetryEmitter` integration example (`examples/structural_health_demo.py`).
- Performance guardrails: `PerformanceRegistry`, `perf_guard`, `compare_overhead`.
- CLI: `scripts/structural_health_report.py` (on-demand health summaries).
- Docs: README Phase 3 section, CONTRIBUTING instrumentation notes, `docs/STRUCTURAL_HEALTH.md`.
- Glyph-aware grammar error factory (operator glyph → canonical name mapping).

### Tests

- Added unit tests for validation, health, grammar error factory, telemetry emitter, performance guardrails.

### Performance

- Validation instrumentation overhead ~5.8% (moderate workload) below 8% guardrail.

### Internal

- Optional `perf_registry` parameter in `run_structural_validation` (read-only timing).

### Deferred

- U4 bifurcation validation excluded pending dedicated handler reintroduction.

### Integrity

- All changes preserve TNFR canonical invariants (no EPI mutation; phase verification intact; read-only telemetry/validation).

## [9.0.2]

Previous release (see repository history) with foundational operators, unified grammar, metrics, and canonical field tetrad.

---
**Reality is not made of things—it's made of resonance.**
28 changes: 28 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,29 @@ ruff check src/
mypy src/tnfr/
```

### 3a. Phase 3 Structural Instrumentation

If adding validation, health, or telemetry logic:

- Use `run_structural_validation` to produce a `ValidationReport`.
- Derive `compute_structural_health(report)` for recommendations.
- Include performance timing (pass `perf_registry=PerformanceRegistry()`).
- Ensure added overhead ratio < 0.10 baseline (see perf tests).
- Never mutate graph state inside validation / health functions.
- Document physics traceability (why each threshold is used).

Telemetry additions must:

- Remain read-only (no operator side effects).
- Export coherence (`coherence_total`), sense index, Φ_s, |∇φ|, K_φ, ξ_C.
- Provide deterministic timestamps when seeds fixed.

Performance guardrails:

- Wrap optional expensive helpers with `perf_guard(label, registry)`.
- Add/adjust tests under `tests/unit/performance/` for new instrumentation.
- Avoid micro-optimizing at expense of clarity unless overhead > target.

### 4. Update Documentation

- Add docstrings to new functions/classes
Expand Down Expand Up @@ -241,25 +264,30 @@ from tnfr.utils import get_logger
The TNFR codebase is organized into focused modules for maintainability and cognitive load reduction:

**Operators** (`tnfr.operators.*`):

- **Individual operator modules**: `emission.py`, `coherence.py`, etc. (13 operators)
- **Base class**: `definitions_base.py` - Shared operator infrastructure
- **Facade**: `definitions.py` - Backward-compatible imports

**Grammar** (`tnfr.operators.grammar.*`):

- **Constraint modules**: `u1_initiation_closure.py`, `u2_convergence_boundedness.py`, etc. (8 rules)
- **Facade**: `grammar.py` - Unified validation interface

**Metrics** (`tnfr.metrics.*`):

- **Focused metrics**: `coherence.py`, `sense_index.py`, `phase_sync.py`, `telemetry.py`
- **Facade**: `metrics.py` - Backward-compatible exports

**Adding New Code**:

- **New operator**: Add to appropriate operator file (e.g., `coupling.py` for coupling modifications)
- **New metric**: Create new file in `tnfr.metrics/` or extend existing metric module
- **New grammar rule**: Add to relevant constraint module or create new `uN_*.py` file
- **Always update facades**: If adding new exports, add to facade files for backward compatibility

**Module Guidelines**:

- Keep files under 600 lines (ideally 200-400)
- One primary concept per module
- Use facade pattern for public APIs
Expand Down
53 changes: 53 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,57 @@ Comprehensive observability:
- **νf**: Structural frequency (Hz_str)
- **φ**: Phase synchrony [0, 2π]

### 🧪 Phase 3 Structural Instrumentation

Unified observability and safety layers (read-only):

- `run_structural_validation` combines grammar (U1-U4) + field thresholds.
- `compute_structural_health` converts validation output to recommendations.
- `TelemetryEmitter` streams coherence, sense index, Φ_s, |∇φ|, K_φ, ξ_C.
- `PerformanceRegistry` + `perf_guard` measure overhead (< ~8% in tests).

Usage:

```python
from tnfr.validation.aggregator import run_structural_validation
from tnfr.validation.health import compute_structural_health
from tnfr.performance.guardrails import PerformanceRegistry

perf = PerformanceRegistry()
report = run_structural_validation(
G,
sequence=["AL","UM","IL","SHA"],
perf_registry=perf,
)
health = compute_structural_health(report)
Copy link

Copilot AI Nov 14, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The example calls compute_structural_health(report) but this function expects a graph G as its first parameter, not a ValidationReport.

Based on the function signature, the correct usage is:

health = compute_structural_health(
    G,
    sequence=["AL","UM","IL","SHA"],
)

This is a separate call from run_structural_validation.

Suggested change
health = compute_structural_health(report)
health = compute_structural_health(
G,
sequence=["AL","UM","IL","SHA"],
)

Copilot uses AI. Check for mistakes.
print(report.risk_level, health.recommendations)
Copy link

Copilot AI Nov 14, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The variable health is referenced on line 97 but it's a dict, not an object with a .recommendations attribute. This should be health["recommended_actions"] to match the actual structure returned by compute_structural_health.

Replace:

print(report.risk_level, health.recommendations)

With:

print(report.risk_level, health["recommended_actions"])
Suggested change
print(report.risk_level, health.recommendations)
print(report.risk_level, health["recommended_actions"])

Copilot uses AI. Check for mistakes.
print(perf.summary())
```

Telemetry:

```python
from tnfr.metrics.telemetry import TelemetryEmitter

with TelemetryEmitter("results/run.telemetry.jsonl", human_mirror=True) as em:
for step, op in enumerate(["AL","UM","IL","SHA"]):
em.record(G, step=step, operator=op, extra={"sequence_id": "demo"})
```

Risk levels:

- `low` – Grammar valid; no thresholds exceeded.
- `elevated` – Local stress: max |∇φ|, |K_φ| pocket, ξ_C watch.
- `critical` – Grammar invalid or ΔΦ_s / ξ_C critical breach.

CLI health report:

```bash
python scripts/structural_health_report.py --graph random:50:0.15 --sequence AL,UM,IL,SHA
```

All instrumentation preserves TNFR physics (no state mutation).

## Installation

### From PyPI (Stable)
Expand Down Expand Up @@ -275,6 +326,8 @@ We welcome contributions! Please see **[CONTRIBUTING.md](CONTRIBUTING.md)** for:
- Pull request process

**For TNFR theory development**, consult **[AGENTS.md](AGENTS.md)** - the canonical guide for maintaining theoretical integrity.
Phase 3 adds structural validation, health assessment and guardrails; see
`docs/STRUCTURAL_HEALTH.md` for thresholds & recommendations.

## Citation

Expand Down
112 changes: 112 additions & 0 deletions docs/STRUCTURAL_HEALTH.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
# Structural Health & Validation (Phase 3)

Unified structural validation and health assessment introduced in Phase 3
provide a physics-aligned safety layer over TNFR networks without mutating
state. All computations are read-only and trace back to canonical fields and
grammar.

## Components

- **Validation Aggregator**: `run_structural_validation` combines:
- Grammar (U1 Initiation/Closure, U2 Convergence, U3 Resonant Coupling,
U4 triggers deferred) via `collect_grammar_errors`.
- Canonical fields: Φ_s, |∇φ|, K_φ, ξ_C.
- Optional drift (ΔΦ_s) if baseline provided.
- **Health Summary**: `compute_structural_health(report)` derives:
- `risk_level` (low, elevated, critical)
- Actionable recommendations (stabilize, reduce gradient, monitor ξ_C, etc.)
- **Telemetry**: `TelemetryEmitter` emits metrics + fields for longitudinal
analysis.
- **Performance Guardrails**: `PerformanceRegistry` + `perf_guard` measure
overhead (< ~8% under moderate workload tests).

## Thresholds (Defaults)

| Quantity | Default | Meaning |
|---------------------|---------|--------------------------------------------------|
| ΔΦ_s | 2.0 | Escape threshold (confinement breach) |
| max(|∇φ|) | 0.38 | Local stress / desynchronization warning |
| max(|K_φ|) | 3.0 | Curvature fault pocket (mutation risk locus) |
| ξ_C critical | > diameter * 1.0 | Approaching global correlation divergence |
| ξ_C watch | > mean_distance * 3.0 | Extended local correlation zone |

All thresholds empirically validated (see `AGENTS.md`). Override values via
function parameters to adapt for specialized topologies or experiments.

## Risk Levels

- **low**: Grammar valid, no thresholds exceeded.
- **elevated**: Local stress (phase gradient spike, curvature pocket, coherence
length watch condition).
- **critical**: Grammar invalid OR confinement/critical ξ_C breach OR ΔΦ_s drift
beyond escape.

## Example

```python
from tnfr.validation.aggregator import run_structural_validation
from tnfr.validation.health import compute_structural_health
from tnfr.performance.guardrails import PerformanceRegistry

perf = PerformanceRegistry()
report = run_structural_validation(
G,
sequence=["AL","UM","IL","SHA"],
perf_registry=perf,
)
health = compute_structural_health(report)
print(report.risk_level, report.thresholds_exceeded)
for rec in health.recommendations:
Comment on lines +57 to +59
Copy link

Copilot AI Nov 14, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The documentation example is inconsistent. Line 57 calls compute_structural_health(report) but compute_structural_health expects a graph G as its first parameter, not a ValidationReport.

Based on the function signature in health.py, the correct usage is:

health = compute_structural_health(
    G,
    sequence=["AL","UM","IL","SHA"],
    perf_registry=perf,
)

Additionally, line 59 attempts to access health.recommendations but health is a dict, so it should be health["recommended_actions"].

Suggested change
health = compute_structural_health(report)
print(report.risk_level, report.thresholds_exceeded)
for rec in health.recommendations:
health = compute_structural_health(
G,
sequence=["AL","UM","IL","SHA"],
perf_registry=perf,
)
print(health["risk_level"], health["thresholds_exceeded"])
for rec in health["recommended_actions"]:

Copilot uses AI. Check for mistakes.
print("-", rec)
print(perf.summary())
```

## Performance Measurement

Use `perf_registry` or `perf_guard` to ensure instrumentation overhead
remains bounded:

```python
from tnfr.performance.guardrails import PerformanceRegistry
reg = PerformanceRegistry()
report = run_structural_validation(G, sequence=seq, perf_registry=reg)
print(reg.summary())
```

For custom functions:

```python
from tnfr.performance.guardrails import perf_guard, PerformanceRegistry
reg = PerformanceRegistry()

@perf_guard("custom_metric", reg)
def compute_extra():
return expensive_read_only_field(G)
```

## Invariants Preserved

- **No mutation**: Validation/health modules never write to graph.
- **Operator closure**: Grammar errors surface sequences violating U1-U3.
- **Phase verification**: Coupling issues appear via U3 errors + |∇φ| spikes.
- **Fractality**: Fields operate across node sets without flattening EPI.

## Recommended Workflow

1. Run telemetry while applying sequence.
2. Call `run_structural_validation` after sequence.
3. Generate health summary; apply stabilizers if elevated/critical.
4. Log performance stats for regression tracking.
5. Persist JSONL telemetry + validation payload for reproducibility.

## Extensibility

To add new thresholds:

1. Extend `run_structural_validation` with computation + flag.
2. Add recommendation mapping in health module.
3. Update tests to cover new condition.
4. Document physics rationale (AGENTS.md ref + empirical evidence).

---
**Reality is not made of things—it's made of resonance. Assess coherence accordingly.**
Loading
Loading