Skip to content

Commit 57c7e4c

Browse files
author
fer
committed
docs(phase-3): Add structural validation, health & performance instrumentation docs
Updates README with Phase 3 instrumentation section (validation, health, telemetry, guardrails). Enhances CONTRIBUTING with guidelines for validation, health, telemetry and performance measurement. Adds docs/STRUCTURAL_HEALTH.md with thresholds, risk levels, usage examples, invariants preserved.
1 parent adc8b14 commit 57c7e4c

File tree

3 files changed

+193
-0
lines changed

3 files changed

+193
-0
lines changed

CONTRIBUTING.md

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,29 @@ ruff check src/
126126
mypy src/tnfr/
127127
```
128128

129+
### 3a. Phase 3 Structural Instrumentation
130+
131+
If adding validation, health, or telemetry logic:
132+
133+
- Use `run_structural_validation` to produce a `ValidationReport`.
134+
- Derive `compute_structural_health(report)` for recommendations.
135+
- Include performance timing (pass `perf_registry=PerformanceRegistry()`).
136+
- Ensure added overhead ratio < 0.10 baseline (see perf tests).
137+
- Never mutate graph state inside validation / health functions.
138+
- Document physics traceability (why each threshold is used).
139+
140+
Telemetry additions must:
141+
142+
- Remain read-only (no operator side effects).
143+
- Export coherence (`coherence_total`), sense index, Φ_s, |∇φ|, K_φ, ξ_C.
144+
- Provide deterministic timestamps when seeds fixed.
145+
146+
Performance guardrails:
147+
148+
- Wrap optional expensive helpers with `perf_guard(label, registry)`.
149+
- Add/adjust tests under `tests/unit/performance/` for new instrumentation.
150+
- Avoid micro-optimizing at expense of clarity unless overhead > target.
151+
129152
### 4. Update Documentation
130153

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

243266
**Operators** (`tnfr.operators.*`):
267+
244268
- **Individual operator modules**: `emission.py`, `coherence.py`, etc. (13 operators)
245269
- **Base class**: `definitions_base.py` - Shared operator infrastructure
246270
- **Facade**: `definitions.py` - Backward-compatible imports
247271

248272
**Grammar** (`tnfr.operators.grammar.*`):
273+
249274
- **Constraint modules**: `u1_initiation_closure.py`, `u2_convergence_boundedness.py`, etc. (8 rules)
250275
- **Facade**: `grammar.py` - Unified validation interface
251276

252277
**Metrics** (`tnfr.metrics.*`):
278+
253279
- **Focused metrics**: `coherence.py`, `sense_index.py`, `phase_sync.py`, `telemetry.py`
254280
- **Facade**: `metrics.py` - Backward-compatible exports
255281

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

262289
**Module Guidelines**:
290+
263291
- Keep files under 600 lines (ideally 200-400)
264292
- One primary concept per module
265293
- Use facade pattern for public APIs

README.md

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,57 @@ Comprehensive observability:
7171
- **νf**: Structural frequency (Hz_str)
7272
- **φ**: Phase synchrony [0, 2π]
7373

74+
### 🧪 Phase 3 Structural Instrumentation
75+
76+
Unified observability and safety layers (read-only):
77+
78+
- `run_structural_validation` combines grammar (U1-U4) + field thresholds.
79+
- `compute_structural_health` converts validation output to recommendations.
80+
- `TelemetryEmitter` streams coherence, sense index, Φ_s, |∇φ|, K_φ, ξ_C.
81+
- `PerformanceRegistry` + `perf_guard` measure overhead (< ~8% in tests).
82+
83+
Usage:
84+
85+
```python
86+
from tnfr.validation.aggregator import run_structural_validation
87+
from tnfr.validation.health import compute_structural_health
88+
from tnfr.performance.guardrails import PerformanceRegistry
89+
90+
perf = PerformanceRegistry()
91+
report = run_structural_validation(
92+
G,
93+
sequence=["AL","UM","IL","SHA"],
94+
perf_registry=perf,
95+
)
96+
health = compute_structural_health(report)
97+
print(report.risk_level, health.recommendations)
98+
print(perf.summary())
99+
```
100+
101+
Telemetry:
102+
103+
```python
104+
from tnfr.metrics.telemetry import TelemetryEmitter
105+
106+
with TelemetryEmitter("results/run.telemetry.jsonl", human_mirror=True) as em:
107+
for step, op in enumerate(["AL","UM","IL","SHA"]):
108+
em.record(G, step=step, operator=op, extra={"sequence_id": "demo"})
109+
```
110+
111+
Risk levels:
112+
113+
- `low` – Grammar valid; no thresholds exceeded.
114+
- `elevated` – Local stress: max |∇φ|, |K_φ| pocket, ξ_C watch.
115+
- `critical` – Grammar invalid or ΔΦ_s / ξ_C critical breach.
116+
117+
CLI health report:
118+
119+
```bash
120+
python scripts/structural_health_report.py --graph random:50:0.15 --sequence AL,UM,IL,SHA
121+
```
122+
123+
All instrumentation preserves TNFR physics (no state mutation).
124+
74125
## Installation
75126

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

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

279332
## Citation
280333

docs/STRUCTURAL_HEALTH.md

Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
# Structural Health & Validation (Phase 3)
2+
3+
Unified structural validation and health assessment introduced in Phase 3
4+
provide a physics-aligned safety layer over TNFR networks without mutating
5+
state. All computations are read-only and trace back to canonical fields and
6+
grammar.
7+
8+
## Components
9+
10+
- **Validation Aggregator**: `run_structural_validation` combines:
11+
- Grammar (U1 Initiation/Closure, U2 Convergence, U3 Resonant Coupling,
12+
U4 triggers deferred) via `collect_grammar_errors`.
13+
- Canonical fields: Φ_s, |∇φ|, K_φ, ξ_C.
14+
- Optional drift (ΔΦ_s) if baseline provided.
15+
- **Health Summary**: `compute_structural_health(report)` derives:
16+
- `risk_level` (low, elevated, critical)
17+
- Actionable recommendations (stabilize, reduce gradient, monitor ξ_C, etc.)
18+
- **Telemetry**: `TelemetryEmitter` emits metrics + fields for longitudinal
19+
analysis.
20+
- **Performance Guardrails**: `PerformanceRegistry` + `perf_guard` measure
21+
overhead (< ~8% under moderate workload tests).
22+
23+
## Thresholds (Defaults)
24+
25+
| Quantity | Default | Meaning |
26+
|---------------------|---------|--------------------------------------------------|
27+
| ΔΦ_s | 2.0 | Escape threshold (confinement breach) |
28+
| max(|∇φ|) | 0.38 | Local stress / desynchronization warning |
29+
| max(|K_φ|) | 3.0 | Curvature fault pocket (mutation risk locus) |
30+
| ξ_C critical | > diameter * 1.0 | Approaching global correlation divergence |
31+
| ξ_C watch | > mean_distance * 3.0 | Extended local correlation zone |
32+
33+
All thresholds empirically validated (see `AGENTS.md`). Override values via
34+
function parameters to adapt for specialized topologies or experiments.
35+
36+
## Risk Levels
37+
38+
- **low**: Grammar valid, no thresholds exceeded.
39+
- **elevated**: Local stress (phase gradient spike, curvature pocket, coherence
40+
length watch condition).
41+
- **critical**: Grammar invalid OR confinement/critical ξ_C breach OR ΔΦ_s drift
42+
beyond escape.
43+
44+
## Example
45+
46+
```python
47+
from tnfr.validation.aggregator import run_structural_validation
48+
from tnfr.validation.health import compute_structural_health
49+
from tnfr.performance.guardrails import PerformanceRegistry
50+
51+
perf = PerformanceRegistry()
52+
report = run_structural_validation(
53+
G,
54+
sequence=["AL","UM","IL","SHA"],
55+
perf_registry=perf,
56+
)
57+
health = compute_structural_health(report)
58+
print(report.risk_level, report.thresholds_exceeded)
59+
for rec in health.recommendations:
60+
print("-", rec)
61+
print(perf.summary())
62+
```
63+
64+
## Performance Measurement
65+
66+
Use `perf_registry` or `perf_guard` to ensure instrumentation overhead
67+
remains bounded:
68+
69+
```python
70+
from tnfr.performance.guardrails import PerformanceRegistry
71+
reg = PerformanceRegistry()
72+
report = run_structural_validation(G, sequence=seq, perf_registry=reg)
73+
print(reg.summary())
74+
```
75+
76+
For custom functions:
77+
78+
```python
79+
from tnfr.performance.guardrails import perf_guard, PerformanceRegistry
80+
reg = PerformanceRegistry()
81+
82+
@perf_guard("custom_metric", reg)
83+
def compute_extra():
84+
return expensive_read_only_field(G)
85+
```
86+
87+
## Invariants Preserved
88+
89+
- **No mutation**: Validation/health modules never write to graph.
90+
- **Operator closure**: Grammar errors surface sequences violating U1-U3.
91+
- **Phase verification**: Coupling issues appear via U3 errors + |∇φ| spikes.
92+
- **Fractality**: Fields operate across node sets without flattening EPI.
93+
94+
## Recommended Workflow
95+
96+
1. Run telemetry while applying sequence.
97+
2. Call `run_structural_validation` after sequence.
98+
3. Generate health summary; apply stabilizers if elevated/critical.
99+
4. Log performance stats for regression tracking.
100+
5. Persist JSONL telemetry + validation payload for reproducibility.
101+
102+
## Extensibility
103+
104+
To add new thresholds:
105+
106+
1. Extend `run_structural_validation` with computation + flag.
107+
2. Add recommendation mapping in health module.
108+
3. Update tests to cover new condition.
109+
4. Document physics rationale (AGENTS.md ref + empirical evidence).
110+
111+
---
112+
**Reality is not made of things—it's made of resonance. Assess coherence accordingly.**

0 commit comments

Comments
 (0)