Skip to content

Concrete Examples

Jeremy H. Carroll edited this page Nov 2, 2026 · 8 revisions

Concrete Worked Examples & Executable Python Suite

AuthorityEffect: None (certified_implies_authorized: false)
⬅ Back to Wiki Home

Normal Forms Overview 3


1. Running the Standalone Python Verifier, Examples & Simplex-NF Studio

All examples, contract validators, and the interactive Simplex-NF Studio web workbench live in the normal_forms/ and web/ packages and contracts/ directory:

# 1. Install in editable mode (or wheel distribution)
pip install -e ".[web,dev]"

# 2. Validate all 112 YAML normal form contracts against standard.yaml
python -m normal_forms.catalog

# 3. Run Demo 01: BQNF Incremental Revenue Repair on CDC Events
python -m normal_forms.paid_revenue_example

# 4. Run Demo 02: Unverified Certificate Refusal Gate
python -m normal_forms.unverified_certificate_example

# 5. Run Demo 03: Observer-Relative Freshness SLA Poset Evaluation
python -m normal_forms.observer_freshness_example

# 6. Run Cross-Domain Reconciliation & Loss Ledger Example
python -m normal_forms.reconciliation_example

# 7. Run Demo 05: 4-Hop Composition (3NF/BCNF -> Extrema & Quantile Cochains -> CODA_MUR -> Observer Poset)
python -m normal_forms.multi_hop_composition

# 8. Run Demo 06: AI RAG / MCP Pipeline with @coda_mur_projection & @observer_freshness_gate
python -m normal_forms.ai

# 9. Launch the Simplex-NF Studio Interactive Web Workbench (smplxnf.anomalon.com)
uvicorn web.app:app --host 0.0.0.0 --port 8000

2. Example A: Classical 0NF $\to$ 1NF Flattening & 5NF Consulting Witness (NormalFormsEvaluator)

from normal_forms import NormalFormsEvaluator

with NormalFormsEvaluator() as ev:
    # 1. Flatten repeating CSV groups (0NF -> 1NF)
    rows_1nf = ev.normalize_0nf_to_1nf([
        (1, "Alice", "Math,Physics"),
        (2, "Bob", "Chemistry"),
    ])
    print("1NF rows:", rows_1nf)

    # 2. Check 5NF Project-Join witness (Shell2 EXCEPT Fill2)
    witness = ev.evaluate_5nf_project_join_integrity([
        ("Alice", "Acme", "Widget"),
        ("Alice", "Globex", "Gadget"),
        ("Bob", "Acme", "Gadget"),
        ("Alice", "Acme", "Gadget"),  # closes the 3-way cycle
    ])
    print("5NF witness:", witness)

3. Example B: 3NF Bernstein Synthesis vs BCNF (normal_forms.domain)

Consider the classic Address(street, city, zip) schema (Date & Darwen's street_journal_title isomorphism) with functional dependencies ${(\text{street}, \text{city}) \to \text{zip},; \text{zip} \to \text{city}}:$

  • Candidate keys: ${(\text{street}, \text{city}),; (\text{street}, \text{zip})}$.
  • Every attribute (street, city, zip) is prime (belongs to at least one candidate key).
  • Therefore, Address passes 3NF ($\text{zip} \to \text{city}$ has a prime dependent city), but fails BCNF because determinant zip is not a superkey!
  • Decomposing into $R_1(\text{zip}, \text{city})$ and $R_2(\text{street}, \text{zip})$ achieves BCNF losslessly by Heath's Theorem, while illustrating why BCNF does not always preserve all original functional dependencies within single tables.
from normal_forms.domain import (
    street_journal_title,
    street_journal_title_passes_third_and_fails_boyce_codd,
)

print("Passes 3NF and fails BCNF:", street_journal_title_passes_third_and_fails_boyce_codd())

4. Example C: BQNF Change Data Capture Incremental Repair (nf.change.bqnf)

Given base relation Orders(order_id, customer_id, status, amount, updated_at) and boundary view:

SELECT customer_id, SUM(amount) AS paid_revenue
FROM Orders
WHERE status = 'paid'
GROUP BY customer_id;
Case CDC Event Defect Class in $Q^1$ Terminal Route Output Repair / Reason
1. Pending $\to$ Paid old: {status: 'pending', amount: 100} $\to$ new: {status: 'paid', amount: 120} [0] (Exact Coboundary) Repair {customer_id: 7, delta_revenue: +120.0}
2. Paid Amount Update old: {status: 'paid', amount: 100} $\to$ new: {status: 'paid', amount: 120} [0] (Exact Coboundary) Repair {customer_id: 7, delta_revenue: +20.0}
3. Paid $\to$ Pending old: {status: 'paid', amount: 100} $\to$ new: {status: 'pending', amount: 100} [0] (Exact Coboundary) Repair {customer_id: 7, delta_revenue: -100.0}
4. Timestamp Only updated_at changed; status, amount, customer_id unchanged [0] (Zero Defect) Preserve No boundary columns modified
5. Missing Evidence old / new missing status and amount [NonZero - MissingEvidence] Invalidate Fails closed when CDC before/after image is incomplete
6. Unsupported Extremum MAX(amount) boundary without auxiliary extremum cochain [NonZero - LimitOfSubstrate] Unsupported Requires priority-queue cochain or partition recomputation

5. Example D: 4-Hop Composition (3NF/BCNF $\to$ Extrema & $\epsilon$-Quantile Cochains $\to$ CODA_MUR $\to$ Observer Poset)

normal_forms/multi_hop_composition.py chains four normal-form domains end to end:

  1. Hop 1 (3NF / BCNF Relational Synthesis): Decomposes Sales(sale_id, customer_id, customer_zip, region, amount, audit_nonce) via Bernstein 3NF synthesis and Tsou-Fischer BCNF tree decomposition, verifying lossless join reconstruction.
  2. Hop 2b (Non-Invertible MIN/MAX Priority-Queue Cochains + Dynamic $\epsilon$-BQNF Quantile Sketches over Composite Keys): Streams INSERT/UPDATE/DELETE CDC operations through NormalFormsEvaluator (normal_forms/bqnf_extrema.py, normal_forms/bqnf_repair.py, normal_forms/sales_cochain.py), supporting canonical multi-column composite grouping keys (encode_composite_group_key, e.g., ("region", "channel") or ("region", "channel", "tier")). Repairs destructive MIN/MAX deletions in $O(\log K)$ via region_extremum_cochain (or routes to bounded partition Recompute when disabled) and repairs regional medians within tolerance $\epsilon$ via region_quantile_cochain. When dynamic_buckets=True, rebalance_quantile_cochain recursively bisects overloaded buckets (count > split_threshold) down to min_bucket_width in dense power-law heads and coalesces under-populated dyadic sibling/cousin sub-buckets (combined count <= merge_threshold) bottom-up during stream drains, while verify_quantile_cochain_invariants checks mass conservation, disjoint ordering, and exact point-to-bucket membership.
  3. Hop 3 (CODA_MUR Representation Transport nf.coda.mur.transport): Projects across multi-hop target schemas with cryptographically sealed LossLedger bookings (coda_mur.unmapped_field_drop), authenticated target verifiers, and commutation square checks $D_{\text{target}}(F(r)) = \bar{F}(D_{\text{source}}(r))$.
  4. Hop 4 (Observer-Relative Freshness Poset nf.epistemic.freshness & Watermarked Out-of-Order Streams): Evaluates the transported packet across a stringency-ordered observer poset chain $O_1 \le O_2 \le \dots \le O_m$, checking upward admissibility monotonicity ($O_i \text{ fresh} \implies O_{i+1} \text{ fresh}$), lag-shift anti-monotonicity ($\ell_1 \le \ell_2 \implies \text{Admitted}(\ell_2) \subseteq \text{Admitted}(\ell_1)$), and fail-closed scope/SLA enforcement. Under evaluate_watermarked_cdc_stream_with_observer_poset (WatermarkSpec), out-of-order late-arriving CDC events within the watermark horizon ($W_k \le t_{\text{event}}(e_k) &lt; E_{\max}^{(k-1)}$) retroactively split or merge historical quantile buckets in region_quantile_cochain while shifting effective replica lag across observer poset SLA thresholds, whereas events falling behind the advancing watermark ($t_{\text{event}}(e_k) &lt; W_k$) fail closed (LateEventExceedsWatermark $\to$ Invalidate) or route to WatermarkedQuarantine.

6. Example E: AI RAG / MCP Decorator Layer (normal_forms.ai)

normal_forms/ai.py provides decorators for Retrieval-Augmented Generation (RAG) context compression and Model Context Protocol (MCP) tool execution:

  • Stage 0 (evaluate_wdnf_candidate_cut — nf.wdp.wdnf / nf.derivation.pdnf): Checks the support floor ($|X| \ge 2$), irreflexivity ($\neg(x \mathrel{\Delta} x)$), and constructive witness presence on retrieved RAG candidate chunks.
  • Stage 1 (@coda_mur_projection — nf.coda.mur.transport & nf.representation.tbnf): Tracks dropped metadata attributes, truncated token suffixes, and budget-evicted chunks in a SHA-256 Merkle-sealed LossLedger while checking exact additive token conservation (retained_token_count + truncated_token_count == source_token_count).
  • Stage 2 (@observer_freshness_gate — nf.epistemic.freshness & nf.recursion.asrf): Enforces LossLedger seal verification, ASRF call-graph acyclicity (producer_identity != evaluator_identity), observer poset SLA lag bounds, and the epistemic authority firewall (certified_implies_authorized == False).

7. Example F: The 4-Layer NF-IR Compiler Stack (ir_kernel, ir_subsumption, ir_wiring, ir_lowering)

The internal Normal-Form Intermediate Representation (NF-IR) stack lowers normal-form contracts into composable passes and multi-target enforcement artifacts:

  1. Layer 1 (normal_forms/ir_kernel.py): Evaluates NFKernelSpec(carrier, collapse_fields, protected_law_fields) (evaluate_nf_kernel, lower_fd_to_kernel_spec, lower_coda_mur_to_kernel_spec) and extracts minimal 2-row counterexample pairs (ConstructiveWitnessPair).
  2. Layer 2 (normal_forms/ir_subsumption.py): Encodes the refinement poset $\text{NF}_A \preceq \text{NF}_B$ (subsumes_contract, subsumes_kernel_spec) and eliminates redundant downstream checks via run_kernel_pipeline_with_dce.
  3. Layer 3 (normal_forms/ir_wiring.py): Composes NFKernelSpec passes into sequential (seq_passes), parallel (par_passes), and policy-guarded (guard_pass) DAGs (evaluate_wiring_dag) with cumulative SHA-256 Merkle loss-chain tracking.
  4. Layer 4 (normal_forms/ir_lowering.py): Compiles any NFKernelSpec into a Python @nf_kernel_guard decorator (compile_to_python_decorator), SQLite BEFORE INSERT / BEFORE UPDATE triggers (compile_to_sqlite_triggers), and automated counterexample fuzzers (synthesize_counterexample_fixtures).

8. Example G: Simplex-NF Studio Interactive Web Workbench (web/app.py, IMPORT_GUIDE.md)

Simplex-NF Studio (web/app.py, configured for Render deployment at smplxnf.anomalon.com via render.yaml) exposes four interactive REST & browser studios backed by the top-level normal_forms exports documented in IMPORT_GUIDE.md, docs/MVP_SELECTION.md, docs/CORRECTNESS_SCOPE.md, and docs/DISTRIBUTION.md:

  • Studio 1 (POST /api/relational/normalize): Evaluates relational headings and functional dependencies across 1NF–3NF and BCNF, synthesizes Bernstein 3NF and Tsou-Fischer BCNF decompositions, runs the Tableau Chase (chase_lossless_join) to detect spurious tuple counterexamples, and emits copy-pasteable SQLite DDL + Python import snippets.
  • Studio 2 (POST /api/bqnf/simulate): Simulates CDC event streams (INSERT/UPDATE/DELETE) with priority-queue extremum cochains and dynamic dyadic quantile sketches, recording per-event terminal routing (Repair, Preserve, Recompute, Invalidate) and exact bucket boundary alignments.
  • Studio 3 (POST /api/compiler/lower): Lowers functional dependency rules into NFKernelSpec, applies poset subsumption Dead-Check Elimination (run_kernel_pipeline_with_dce), generates SQLite BEFORE INSERT/BEFORE UPDATE triggers with scalar null-safe semantics, and executes live carrier verification.
  • Studio 4 (POST /api/ai/lossledger): Executes @coda_mur_projection and @observer_freshness_gate over RAG context chunks, verifying additive token conservation and SHA-256 Merkle LossLedger seals.

9. Epistemic Claim Hygiene Quadrant

  1. What it supports:
    • Demonstrates in this toy setting that the Python evaluators and the Simplex-NF Studio web workbench reproduce the declared terminal routes for 0NF–5NF, BQNF additive and cochain-backed extrema/quantile repair, CODA_MUR representation transport, observer-relative freshness posets, the normal_forms.ai RAG/MCP decorator pipeline, and the 4-layer NF-IR compiler stack.
  2. What it does not support:
    • Does not substitute for production database concurrency control or physical distributed consensus.
  3. The narrowest defensible claim:
    • Each worked example, multi-hop property test, and FastAPI workbench endpoint executes deterministically against the fixtures and randomized schemas in tests/ with AuthorityEffect: None.
  4. The next test needed:
    • Concurrent multi-writer transaction interleaving over persistent disk-backed SQLite WAL journals.

🏛️ Simplex Normal Forms


📚 112 Normal Forms by Family

shape (17)
change (6)
coda (2)
representation (5)
transport (3)
compilation (1)
epistemic (15)
authority (1)
evidence (8)
derivation (12)
topology (2)
physics (20)
relativistic (2)
motion (3)
runtime (3)
experimental (8)
bridge (1)
query (1)
recursion (1)
security (1)

Clone this wiki locally