# SpeyTech — Full Documentation > Deterministic computing systems for safety-critical environments. This document contains the complete text of key SpeyTech pages and articles for LLM consumption. For a summary version, see: https://speytech.com/llms.txt --- # Company Overview SpeyTech develops deterministic software platforms for aerospace, medical devices, and autonomous systems. Founded by William Murray, a Regenerative Systems Architect with 30 years of UNIX infrastructure experience, based in the Scottish Highlands. **Founder**: William Murray **Location**: Inverness, Scottish Highlands, UK **Academic affiliation**: Visiting Scholar, Heriot-Watt University **Experience**: 30 years UNIX systems engineering --- # Concept Registry 41 concepts defined across 69 articles. BIT-IDENTITY GATE Defined in: undefined A benchmark showing "RISC-V is 2.3x slower than x86" is meaningless if the outputs don't match. certifiable-bench introduces a simple but critical concept: the bit-identity gate. BIT-PERFECT REPRODUCIBILITY Defined in: undefined This article examines what bit-perfect reproducibility actually requires, why it matters for certification, and how to design systems that achieve it. CERTIFIABLE-* ECOSYSTEM Defined in: undefined There's a question that blocks AI adoption in safety-critical systems: "Can you prove the model running on deployed hardware is exactly the same as what you tested?" Not "similar". CLOSURE AND TOTALITY Defined in: undefined Designing for closure and totality requires upfront investment in type design, state machine specification, and formal property verification. CROSS-PLATFORM BIT-IDENTITY Defined in: undefined Not "similar" results. CRYPTOGRAPHIC ATTESTATION Defined in: undefined You've trained a model deterministically. CRYPTOGRAPHIC EXECUTION TRACING Defined in: undefined Conventional logging captures fragments, but cryptographic execution tracing can provide tamper-evident, verifiable records of every state transition. DEPLOY-GATE SEO VALIDATION Defined in: undefined Deploy-gate SEO validation runs an SEO audit inside the build pipeline, with a non-zero exit code blocking release and triggering rollback to the previous build. DETERMINISTIC DATA PIPELINE Defined in: undefined A deterministic data pipeline produces bit-identical batches for any given dataset, seed, and epoch — eliminating shuffling, normalisation, and augmentation as sources of non-reproducibility. DETERMINISTIC INCIDENT RECONSTRUCTION Defined in: undefined An autonomous vehicle strikes a pedestrian. DETERMINISTIC INFERENCE Defined in: undefined Deterministic inference produces bit-identical neural network outputs across platforms and builds by using fixed-point arithmetic, static allocation, and a single canonicalised execution path. DETERMINISTIC ML PIPELINE Defined in: undefined A deterministic ML pipeline guarantees bit-identical output across platforms for every stage from data loading through inference, using fixed-point arithmetic and cryptographic provenance. DETERMINISTIC QUANTIZATION Defined in: undefined Deterministic quantization converts floating-point model weights to fixed-point representation with formal error bounds and cryptographic certificates, ensuring the conversion is reproducible and auditable. DETERMINISTIC RUNTIME MONITORING Defined in: undefined Deploying an ML model isn't the end of the story. DETERMINISTIC STOCHASTIC ROUNDING Defined in: undefined Deterministic stochastic rounding: The key difference: `ct_prng_next(prng)` is deterministic. DETERMINISTIC TRAINING Defined in: undefined Deterministic training guarantees bit-identical model weights from identical inputs, seeds, and hyperparameters by using fixed-point arithmetic, deterministic reduction, and cryptographic audit trails. DO-178C CERTIFICATION Defined in: undefined DO-178C Level A is the highest aerospace software assurance level, requiring MC/DC structural coverage, complete requirements traceability, and deterministic execution evidence for flight-critical systems. EXPONENTIAL MOVING AVERAGE Defined in: undefined An exponential moving average is a recursive filter that weights recent observations more heavily, requiring O(1) memory and bounded state for deterministic anomaly detection. FEISTEL SHUFFLE Defined in: undefined The Feistel shuffle solves this: a deterministic permutation that looks random but is completely reproducible. FIXED-POINT ARITHMETIC Defined in: undefined Fixed-point arithmetic represents real numbers as scaled integers, eliminating IEEE 754 floating-point variance and ensuring identical results across platforms under C99. FSM COMPOSITION Defined in: undefined Note: This article discusses architectural patterns for composing finite state machines. HEARTBEAT MONITORING Defined in: undefined Heartbeat monitoring uses a deterministic FSM to prove that a subsystem is alive and responsive by tracking inter-arrival times of periodic signals. INIT-UPDATE-STATUS-RESET Defined in: undefined The Init-Update-Status-Reset pattern is the minimal interface that simultaneously enables static analysis, bounded resource usage, deterministic execution, and compositional verification. INTEGER PROMOTION Defined in: undefined Integer promotion is the implicit conversion of types narrower than int to int (or unsigned int) before any arithmetic operation. MERKLE AUDIT CHAIN Defined in: undefined A Merkle audit chain links sequential operations through cryptographic hashes, making each step independently verifiable and the complete history tamper-evident. MERKLE CHAIN VERSION CONTROL Defined in: undefined Cryptographic attestation binds build artifacts to their source through Merkle trees and digital signatures, providing tamper-evident proof that deployed software matches certified source. OPERATIONAL SEO OBSERVABILITY Defined in: undefined Operational SEO observability is the practice of reading live web-server access logs to verify what real search and AI crawlers experienced, rather than inferring it from synthetic audits or stabilised dashboard summaries. PIPELINE VERIFICATION Defined in: undefined Regulators ask one question that kills most ML deployments: "how do you know the deployed model matches what was trained?" Spreadsheets, manual checksums, and "we have a process" don't survive that question. Q16.16 FIXED-POINT ARITHMETIC Defined in: undefined Q16.16 fixed-point arithmetic represents numbers as 32-bit integers with 16 integer bits and 16 fractional bits, enabling deterministic computation without platform-dependent floating-point variance. ROTATIONAL BOT-IDENTITY SPOOFING Defined in: undefined Rotational bot-identity spoofing is an attacker pattern where a single source IP issues requests under multiple distinct named-bot user agents within a short time window. ROUND-TO-NEAREST-EVEN Defined in: undefined Round-to-nearest-even rounds halfway values to the nearest even integer, eliminating the systematic positive bias that conventional round-half-up introduces across repeated calculations. SAFETY-CRITICAL C Defined in: undefined Safety-critical C is a constrained subset of the C language that prohibits dynamic allocation, unbounded loops, and implicit behaviour to satisfy certification requirements. SEMANTIC OBSERVABILITY Defined in: undefined C-Sentinel takes a different approach: semantic observability. SOFTWARE CONTRACTS Defined in: undefined Consider this function: The comment says "safely." The code doesn't check for overflow. STATIC ALLOCATION Defined in: undefined Static allocation provides all memory through caller-supplied buffers at compile time, eliminating heap fragmentation, allocation failures, and the verification burden of dynamic memory management. STATISTICS AS STATE TRANSITIONS Defined in: undefined Statistics and state machines rarely appear in the same sentence. STRUCT BYTE COMPARISON Defined in: undefined Struct byte comparison using memcmp reads every byte in a structure sequentially and reports whether all bytes match, without knowledge of field boundaries, types, or semantic meaning. TICK-BASED SCHEDULING Defined in: undefined A tick-based system is a 5-tuple (S, Σ, δ, s₀, T) where S is a finite set of states, Σ is the input alphabet, δ: S × Σ → S is the transition function, s₀ ∈ S is the initial state, and T is a monotonically increasing sequence of discrete time values {t₀, t₁, t₂, ...} at which transitions occur. UNDEFINED BEHAVIOUR Defined in: undefined Undefined behaviour is any operation whose result the C standard does not define, granting the compiler unrestricted freedom to assume it never occurs and to optimise accordingly. WCET ANALYSIS Defined in: undefined By analysing code structure, loop bounds, and hardware behaviour, WCET analysis determines the maximum time a computation can take. ZERO-VARIANCE PROBLEM Defined in: undefined Yet in statistical monitoring systems, this simple edge case manifests in a form that is both mathematically subtle and practically dangerous: the zero-variance problem. --- # Core Q&A ### What is deterministic computing? Deterministic computing produces identical outputs for identical inputs across every run, platform, and build by eliminating non-deterministic execution paths. ### What is deterministic inference? Deterministic inference produces bit-identical neural network outputs across platforms and builds by using fixed-point arithmetic and a single canonicalised execution path. ### What is fixed-point arithmetic? Fixed-point arithmetic represents real numbers as scaled integers, eliminating IEEE 754 floating-point variance and ensuring identical results across platforms under C99. ### What is a certifiable ML pipeline? A certifiable ML pipeline produces bit-identical, auditable outputs at every stage — data, training, quantisation, inference — with cryptographic proof of each transition. ### What is the MDCP (Murray Deterministic Computing Platform)? MDCP is a tick-based deterministic execution substrate providing mathematical reproducibility guarantees for safety-critical systems through architectural constraints. Patent GB2521625.0. ### What is canonicalisation in deterministic systems? Canonicalisation transforms data into a single, unambiguous byte representation so that identical inputs always produce identical hashes regardless of struct layout or compiler. ### Why does floating-point arithmetic break reproducibility? IEEE 754 floating-point permits platform-specific optimisations such as FMA fusion, producing different results on x86 vs ARM and making bit-identical reproducibility impossible. ### What is safety-critical software certification? Safety-critical certification (DO-178C, IEC 62304, ISO 26262) requires provable, reproducible behaviour — deterministic systems satisfy this where conventional systems cannot. ### What is verifiable AI execution? Verifiable AI execution provides cryptographic proof that an AI system ran correctly — same inputs, same model, same outputs — with an auditable trail of every decision. ### What is round-to-nearest-even (RNE) rounding? Round-to-nearest-even rounds 0.5 cases to the nearest even digit, eliminating systematic bias and ensuring bit-identical results across platforms for fixed-point ML. --- # Core Concepts ## Why Deterministic Computing Deterministic computing ensures that given the same inputs, a system will always produce the same outputs, in the same order, with the same timing. This property is fundamental to safety-critical systems. ### The Problem with Non-Determinism Conventional software exhibits non-deterministic behaviour due to: - **Race conditions** — Thread scheduling varies between runs - **Floating-point variance** — Results differ across platforms and compilers - **Memory allocation** — Dynamic allocation introduces unpredictable timing - **External dependencies** — Network, disk, and OS interactions vary In safety-critical domains (aerospace, medical devices, autonomous vehicles), non-determinism creates: - **Certification challenges** — Cannot prove behaviour without reproducibility - **Debugging complexity** — Heisenbugs that disappear under observation - **Incident reconstruction** — Cannot replay failures accurately - **Liability exposure** — Cannot demonstrate due diligence ### The Deterministic Alternative Deterministic systems provide: - **Bit-identical execution** — Same results across platforms, compilers, runs - **Provable timing** — Worst-case execution time (WCET) guarantees - **Complete reproducibility** — Any execution can be replayed exactly - **Simplified certification** — Demonstrate compliance through replay ### When Determinism Matters Deterministic computing is essential for: - DO-178C Level A aerospace systems - IEC 62304 Class C medical devices - ISO 26262 ASIL-D automotive systems - Any system where failure has safety implications --- # Products ## MDCP — Murray Deterministic Computing Platform MDCP is a tick-based deterministic execution substrate for safety-critical systems. It provides mathematical guarantees of reproducibility through architectural constraints rather than testing. **Patent**: GB2521625.0 ### Core Architecture MDCP replaces conventional scheduling with tick-based execution: - **Tick-based scheduling** — All operations occur at defined tick boundaries - **Deterministic memory** — Static allocation with bounded access patterns - **Lock-free coordination** — No mutexes, no deadlocks, no priority inversion - **Cryptographic sealing** — Every state transition is hash-chained ### Technical Properties | Property | Guarantee | |----------|-----------| | Execution order | Identical across runs | | Timing | Bounded worst-case (WCET) | | Memory | O(1) static allocation | | State transitions | Hash-chained audit trail | ### Kernel Components MDCP comprises 14 kernel components: - Core scheduling and tick management - Deterministic memory allocation - Inter-process communication - Cryptographic state binding - Health monitoring and fault detection ### Certification Alignment MDCP is designed to support certification under: - DO-178C (aerospace) — Levels A through D - IEC 62304 (medical devices) — Classes A, B, C - ISO 26262 (automotive) — ASIL A through D - IEC 61508 (industrial) — SIL 1 through 4 --- ## MDLCE — Murray Deterministic Liability Closure Engine MDLCE provides cryptographic execution binding for compliance attestation and post-incident analysis. It creates unforgeable proof of what code executed, when, and with what results. **Patent**: GB2522369.4 ### Purpose When incidents occur in safety-critical systems, investigators need to answer: - What code was running? - What were the inputs? - What decisions did the system make? - Can we reproduce the failure? MDLCE provides cryptographic answers to all four questions. ### Technical Approach - **Execution binding** — Hash-chain links code version to execution trace - **Input attestation** — All inputs cryptographically timestamped - **Decision logging** — State machine transitions recorded with proofs - **Replay capability** — Byte-identical reconstruction of any execution ### Liability Protection MDLCE supports: - **Regulatory compliance** — Demonstrate adherence to standards - **Incident investigation** — Prove what happened, not what might have happened - **Product liability defence** — Unforgeable evidence of correct operation - **Insurance requirements** — Quantifiable risk through provable behaviour --- ## CardioCore — Deterministic Medical Device Kernel CardioCore is a deterministic kernel reference implementation for implantable cardiac devices. It demonstrates how MDCP principles apply to IEC 62304 Class C medical device software. ### Safety Philosophy CardioCore implements the VITA-SB (Verified Implantable Technology Architecture — Safety Bounded) philosophy: - **Fail-safe defaults** — Every state has a safe fallback - **Bounded execution** — All operations complete within defined time - **Triple redundancy** — Critical calculations verified independently - **Deterministic pacing** — Timing guarantees for life-critical functions ### Technical Properties | Property | Implementation | |----------|----------------| | Execution model | Tick-based, deterministic | | Memory model | Static allocation only | | Timing model | WCET-proven operations | | Fault handling | TMR with voting | ### Regulatory Alignment CardioCore is designed to align with: - **IEC 62304** — Software lifecycle for medical devices - **IEC 60601** — Medical electrical equipment safety - **FDA guidance** — Software as a Medical Device (SaMD) ### Why It Matters Implantable cardiac devices face unique challenges: - **Zero tolerance for failure** — Device failure can be fatal - **Long operational life** — Devices operate for years without service - **Limited observability** — Cannot easily debug in-situ - **Regulatory scrutiny** — Extensive pre-market and post-market requirements Deterministic execution addresses these by making behaviour provable rather than merely tested. --- # Open Source Projects All projects available at: https://github.com/SpeyTech ## Fixed-Point Fundamentals **Repository**: https://github.com/SpeyTech/fixed-point-fundamentals **License**: MIT **Documentation**: https://speytech.com/open-source/fixed-point-fundamentals/ **Defines**: Fixed-point arithmetic KEY_CLAIMS: - Most engineers learn floating-point arithmetic and never question it. - Fixed-point arithmetic represents real numbers as scaled integers, eliminating IEEE 754 floating-point variance and ensuring identical results across platforms under C99. EVIDENCE: - IEEE 754 is convenient, widely supported, and "good enough" for most applications. - View on GitHub Definition: Fixed-Point Arithmetic Fixed-point arithmetic represents real numbers as scaled integers, eliminating IEEE 754 floating-point variance and ensuring identical results across platforms under C99. - Floating-point arithmetic has three fundamental issues for safety-critical systems: The same floating-point code can produce different results on different hardware: The x87 FPU uses 80-bit extended precision internally. - The Patriot missile failure in 1991 was caused by exactly this kind of accumulated error — a 0.000000095 second timing drift that, over 100 hours, caused a 573-metre targeting error. RELATES_TO: - ai-architecture/floating-point-danger - insights/bit-perfect-reproducibility - insights/fixed-point-neural-networks - insights/round-to-nearest-even Learn fixed-point arithmetic from first principles — because 'close enough' isn't deterministic Most engineers learn floating-point arithmetic and never question it. IEEE 754 is convenient, widely supported, and "good enough" for most applications. Until it isn't. When you need **deterministic results** — the same output for the same input, every time, on every platform — floating-point becomes a liability. When certification bodies ask you to prove your arithmetic is bounded, floating-point makes that proof difficult. When accumulated rounding errors cause your control system to drift, floating-point is the culprit. Fixed-point arithmetic solves these problems. But most engineers never learned it properly. [View on GitHub](https://github.com/SpeyTech/fixed-point-fundamentals) Definition: Fixed-Point Arithmetic Fixed-point arithmetic represents real numbers as scaled integers, eliminating IEEE 754 floating-point variance and ensuring identical results across platforms under C99. ## The Problem with Floating-Point Floating-point arithmetic has three fundamental issues for safety-critical systems: ### 1. Non-Determinism Across Platforms The same floating-point code can produce different results on different hardware: ```c // This may give different answers on x87 vs SSE vs ARM float result = a * b + c * d; ``` The x87 FPU uses 80-bit extended precision internally. SSE uses 64-bit. ARM has its own quirks. Compiler flags like `-ffast-math` change behaviour. The "same" computation isn't the same at all. ### 2. Accumulation Drift Small rounding errors compound over time: ```c float sum = 0.0f; for (int i = 0; i > 16); } ``` Without widening, the multiplication would overflow silently. With widening, you have room for the full result before narrowing back to your target format. This pattern — widen, compute, narrow — appears everywhere in fixed-point code. Master it and you've mastered half of fixed-point arithmetic. ## Rounding: Why It Matters More Than You Think When you narrow a result, you lose precision. How you handle that loss matters: **Truncation** (round toward zero) introduces systematic bias. If you truncate repeatedly, errors accumulate in one direction. **Round-half-up** (school rounding) has the same problem — it biases toward positive infinity. **Round-to-nearest-even** (banker's rounding) is statistically unbiased. When the value is exactly halfway between two representable numbers, it rounds to the nearest even number. Over many operations, the positive and negative roundings cancel out. ```c // Round-to-nearest-even for Q16.16 division q16_16_t q16_div_rne(q16_16_t a, q16_16_t b) { int64_t wide = ((int64_t)a 0) ? b/2 : -b/2; if (remainder > half || (remainder == half && (quotient & 1))) { quotient += (b > 0) ? 1 : -1; } return (q16_16_t)quotient; } ``` Lesson 04 demonstrates this with a 1-million-operation test. Truncation drifts to zero. Round-half-up drifts positive. RNE stays centred. ## Overflow: The Silent Killer In C, signed integer overflow is **undefined behaviour**. The compiler is free to assume it never happens, which can lead to surprising optimisations that break your code. Fixed-point code must handle overflow explicitly: ```c typedef struct { q16_16_t value; uint8_t flags; // Sticky fault flags } q16_16_result_t; #define FAULT_OVERFLOW 0x01 #define FAULT_UNDERFLOW 0x02 #define FAULT_SATURATED 0x04 q16_16_result_t q16_add_safe(q16_16_t a, q16_16_t b, uint8_t *flags) { int64_t wide = (int64_t)a + (int64_t)b; q16_16_result_t result; if (wide > INT32_MAX) { result.value = INT32_MAX; *flags |= FAULT_OVERFLOW | FAULT_SATURATED; } else if (wide kp, error); // Integral term (accumulate in Q32.32 to prevent overflow) pid->integral = q32_add(pid->integral, q_mul_q8_24_q16_16(pid->ki, q_mul(error, dt))); // Derivative term q16_16_t derivative = q_div(q_sub(error, pid->last_error), dt); q32_32_t d_term = q_mul_q8_24_q16_16(pid->kd, derivative); pid->last_error = error; // Sum and convert to output format q32_32_t output = q32_add(q32_add(p_term, pid->integral), d_term); return q32_to_q16(output); // Saturate if needed } ``` Coefficients use Q8.24 (small values, high precision). The integral accumulator uses Q32.32 (wide range, prevents overflow). Inputs and outputs use Q16.16 (general purpose interface). ### Sine Lookup Table with Linear Interpolation When you can't afford the cycles for CORDIC or polynomial approximation: ```c // 256-entry quarter-wave table static const q16_16_t sine_table[257] = { 0x00000000, 0x00000648, 0x00000C8F, /* ... */ }; q16_16_t q16_sin(q16_16_t angle) { // Reduce to [0, 2π) angle = angle & 0x0000FFFF; // Assuming 2π = 0x10000 // Determine quadrant and index uint32_t quadrant = (angle >> 14) & 0x3; uint32_t index = (angle >> 6) & 0xFF; uint32_t frac = angle & 0x3F; // Lookup with linear interpolation q16_16_t y0 = sine_table[index]; q16_16_t y1 = sine_table[index + 1]; q16_16_t result = y0 + (((y1 - y0) * frac) >> 6); // Apply quadrant symmetry // ... return result; } ``` A 257-entry table (1KB) gives you better than 16-bit precision with simple linear interpolation. No floating-point transcendentals required. ## The Certification Bridge This course teaches the **fundamentals** with standalone, copy-paste-friendly code under the MIT license. For **production safety-critical systems**, the [certifiable-inference](https://github.com/SpeyTech/certifiable-inference) project provides: | This Course | certifiable-* Ecosystem | |:------------|:------------------------| | Teaching implementations | Production implementations | | Standalone examples | Ecosystem integration | | MIT license | GPL + CLA for IP protection | | "Here's how it works" | "Here's proof it works" | The certifiable-* ecosystem adds Merkle audit trails, cross-platform bit-identity verification, and documentation templates aligned with DO-178C, IEC 62304, and ISO 26262. If you're building systems that need certification, that's where you go after learning the fundamentals here. ## Getting Started ```bash git clone https://github.com/SpeyTech/fixed-point-fundamentals.git cd fixed-point-fundamentals make ``` Each lesson is self-contained. Start with Lesson 00 to understand why floating-point fails, or jump to the topic you need. **Prerequisites:** C programming (comfortable with integers and bit operations), basic arithmetic, a C compiler. No external dependencies. ## What You'll Build By the end of this course, you'll be able to: - Implement fixed-point arithmetic in strict C99 - Choose appropriate Q formats for your signal characteristics - Handle overflow, underflow, and rounding correctly - Build production-grade control systems with bounded, deterministic behaviour - Understand the path from teaching implementations to certified production code ## Reference Materials The course includes formal specifications following the same methodology used in aerospace and medical device development: - **FPF-MATH-001** — Mathematical closure architecture - **FPF-STRUCT-001** — Data structure specification Plus quick-reference materials: - **Q Formats** — Common formats and their properties - **Common Pitfalls** — Mistakes to avoid - **Further Reading** — Where to go next ## Related Reading - [Fixed-Point Neural Networks: The Math Behind Q16.16](https://speytech.com/insights/fixed-point-neural-networks/) - [Round-to-Nearest-Even: The Rounding Mode That Makes Determinism Possible](https://speytech.com/insights/round-to-nearest-even/) - [Why Floating Point Is Dangerous](https://speytech.com/ai-architecture/floating-point-danger/) - [Bit-Perfect Reproducibility: Why It Matters and How to Prove It](https://speytech.com/insights/bit-perfect-reproducibility/) --- *Prove first, code second. MIT licensed.* As with any architectural approach, suitability depends on system requirements, risk classification, and regulatory context. --- ## certifiable-bench **Repository**: https://github.com/SpeyTech/certifiable-bench **License**: GPL-3.0 **Documentation**: https://speytech.com/open-source/certifiable-bench/ **Defines**: Bit-identity gate KEY_CLAIMS: - Performance benchmarking in safety-critical systems has a fundamental problem: you can't compare performance across platforms unless you first prove the outputs are identical. EVIDENCE: - DO-178C, IEC 62304, and ISO 26262 all require evidence of correct behaviour. - For aerospace (DO-178C), medical devices (IEC 62304), and automotive (ISO 26262), timing data is part of the certification evidence package. - Section 6.3.4 of DO-178C specifically requires "Software Timing and Sizing Data" as a verification output. Performance benchmarking for deterministic ML — because 'fast' means nothing if you can't prove it's correct Performance benchmarking in safety-critical systems has a fundamental problem: you can't compare performance across platforms unless you first prove the outputs are identical. [View on GitHub](https://github.com/SpeyTech/certifiable-bench) ## The Problem Standard benchmarking tools measure how fast code runs. They don't verify that the code produces the same results on different hardware. For most software, this doesn't matter. For safety-critical ML inference, it matters enormously. Consider deploying a neural network trained on x86 to a RISC-V edge device. The standard approach: benchmark both, compare latency. But what if floating-point rounding differences, SIMD variations, or library implementations cause the outputs to differ? You've optimised for speed on a system that's now producing different results. DO-178C, IEC 62304, and ISO 26262 all require evidence of correct behaviour. A benchmark showing "RISC-V is 2.3x slower than x86" is meaningless if the outputs don't match. ## The Solution: The Bit-Identity Gate certifiable-bench introduces a simple but critical concept: the bit-identity gate. You can only compare performance after proving the outputs are identical. ```c cb_compare_results(&x86_result, &riscv_result, &comparison); if (comparison.outputs_identical) { // Outputs match — performance comparison is meaningful printf("RISC-V is %.2fx slower\n", comparison.latency_ratio_q16 / 65536.0); } else { // Outputs differ — comparison is invalid printf("ERROR: Outputs differ, comparison invalid\n"); } ``` This changes the workflow. Instead of "benchmark first, hope outputs match", it's "verify outputs, then benchmark". The verification uses FIPS 180-4 SHA-256 to hash outputs during the benchmark run (outside the timing loop), then compares hashes across platforms. ## What's Implemented The harness provides six modules, each with formal requirements documentation: | Module | SRS | Tests | Purpose | |--------|-----|-------|---------| | Timer | SRS-001 | 10,032 | High-resolution timing with 23ns measured overhead | | Metrics | SRS-002 | 1,502 | Statistics, histograms, outlier detection, WCET estimation | | Platform | SRS-006 | 35 | CPU detection, hardware counters, environment monitoring | | Verify | SRS-004 | 113 | SHA-256 hashing, golden references, result binding | | Runner | SRS-003 | 92 | Warmup phases, critical loop, configurable iterations | | Report | SRS-005 | 66 | JSON/CSV output, cross-platform comparison | Total: 11,840 assertions across approximately 233 SHALL statements in the requirements documentation. ## The Critical Loop The benchmark runner separates timing from verification: ```c for (i = 0; i measure_iterations; i++) { /* === CRITICAL LOOP START === */ t_start = cb_timer_now_ns(); rc = fn(ctx, input, output); t_end = cb_timer_now_ns(); /* === CRITICAL LOOP END === */ samples[i] = t_end - t_start; /* Verification OUTSIDE critical timing */ if (config->verify_outputs) { cb_verify_ctx_update(&verify_ctx, output, output_size); } } ``` Verification happens outside the timed region. The final hash covers all outputs from all iterations, ensuring determinism across the entire run. ## Statistics That Matter for Certification Beyond mean and standard deviation, certifiable-bench computes metrics required for safety certification: **WCET Estimation**: Worst Case Execution Time bound calculated as `max + 6×stddev`. This provides a conservative estimate for real-time scheduling. **Percentiles**: p50, p95, p99 for understanding tail latency. **Outlier Detection**: MAD-based detection (Iglewicz & Hoaglin method) to identify anomalous samples from thermal throttling, interrupts, or other interference. **Histogram**: Configurable bins with overflow/underflow tracking for visualising the full latency distribution. All statistics use integer-only arithmetic where possible, avoiding floating-point non-determinism in the measurement infrastructure itself. ## Platform Detection The harness automatically detects: - **Architecture**: x86_64, aarch64, riscv64 - **CPU model**: From `/proc/cpuinfo` - **Frequency**: From sysfs, with stability monitoring - **Hardware counters**: Via `perf_event` (cycles, instructions, cache misses, branch mispredictions) - **Environment**: Temperature, throttle events A stability check flags results if CPU frequency drifts more than 5% during the benchmark run. ## Result Binding Each benchmark result is cryptographically bound to its context: ``` H(output_hash || platform || config || stats || timestamp) ``` This creates a tamper-evident record. If someone claims "we achieved X latency on platform Y", the hash can be verified against the full result data. ## Usage ```c #include "cb_runner.h" #include "cb_report.h" cb_result_code_t my_inference(void *ctx, const void *in, void *out) { // Your neural network inference return CB_OK; } int main(void) { cb_config_t config; cb_result_t result; cb_config_init(&config); config.warmup_iterations = 100; config.measure_iterations = 1000; cb_run_benchmark(&config, my_inference, model_ctx, input_data, input_size, output_data, output_size, &result); cb_print_summary(&result); cb_write_json(&result, "benchmark_x86.json"); return 0; } ``` ## Pipeline Context certifiable-bench sits between certifiable-inference (the deterministic ML engine) and certifiable-harness (the end-to-end verification system): ``` certifiable-inference ──→ certifiable-bench ──→ certifiable-harness ↑ │ └───────────────────────┘ Performance data ``` The harness runs the inference engine with benchmark instrumentation, produces JSON reports, and the harness consumes these for cross-platform comparison. Model bundles from certifiable-deploy can include baseline benchmark data for regression testing. ## Why This Matters For aerospace (DO-178C), medical devices (IEC 62304), and automotive (ISO 26262), timing data is part of the certification evidence package. Section 6.3.4 of DO-178C specifically requires "Software Timing and Sizing Data" as a verification output. But timing data without correctness verification is incomplete evidence. certifiable-bench provides both: proof of determinism and measurement of performance. The bit-identity gate ensures you never accidentally compare apples to oranges. If x86 and RISC-V produce different outputs, you find out immediately, before drawing conclusions about relative performance. ## Getting Started ```bash git clone https://github.com/SpeyTech/certifiable-bench cd certifiable-bench mkdir build && cd build cmake .. -DCMAKE_BUILD_TYPE=Release make ctest --output-on-failure ``` ## Documentation The repository includes formal documentation: - **CB-MATH-001**: Mathematical foundations (statistics, verification, comparison algorithms) - **CB-STRUCT-001**: Data structure specifications - **SRS-001 through SRS-006**: Requirements documents with ~233 SHALL statements ## Current Status The harness is feature-complete and ready for integration testing: - ✅ All statistics and verification tests pass - ✅ JSON/CSV reporting working - ✅ Cross-platform comparison implemented - ⏳ Bit-identity verification on RISC-V pending hardware access - ⏳ CI regression detection pending infrastructure setup As with any architectural approach, suitability depends on system requirements, risk classification, and regulatory context. --- ## certifiable-harness **Repository**: https://github.com/SpeyTech/certifiable-harness **License**: GPL-3.0 **Documentation**: https://speytech.com/open-source/certifiable-harness/ **Defines**: Cross-platform bit-identity EVIDENCE: - The harness generates a 368-byte golden reference file containing: The file hash covers bytes 0x00–0x14F, enabling tamper detection. - Safety-Critical Deployments: When a regulator asks "how do you know the deployed model is the same as what you tested?", you have a 368-byte answer. End-to-end test harness for deterministic ML — because 'it works on my machine' isn't certifiable How do you prove that your ML pipeline produces identical results on different hardware? Not "similar" results. Not "statistically equivalent" results. *Identical* — bit for bit, hash for hash. I ran the certifiable-harness on Linux with GCC and macOS with Clang. Different operating system. Different compiler. Seven pipeline stages. Same SHA-256 hashes. Every stage. Every time. **certifiable-harness** orchestrates all seven stages of the certifiable-* pipeline, captures cryptographic commitments, and compares them against a golden reference. [View on GitHub](https://github.com/SpeyTech/certifiable-harness) ## The Problem Traditional ML frameworks don't even try for cross-platform determinism. Floating-point rounding varies by CPU. Memory allocation affects hash table iteration order. Thread scheduling is inherently non-deterministic. For most applications, that's fine. A 0.001% difference in model output doesn't matter. For safety-critical systems, it's a fundamental problem. If you can't prove that the model running on deployed hardware is *exactly* the same as what you tested, you can't certify it. The certifiable-* ecosystem solves this through fixed-point arithmetic, static allocation, and deterministic algorithms throughout. But how do you *prove* it works? You run the harness. ## How It Works ```bash $ ./certifiable-harness --golden result.golden --output verify.json ═══════════════════════════════════════════════════════════════ Certifiable Harness v1.0.0 Platform: x86_64 ═══════════════════════════════════════════════════════════════ [0] data ✓ (OK, 4 µs) [1] training ✓ (OK, 3 µs) [2] quant ✓ (OK, 3 µs) [3] deploy ✓ (OK, 3 µs) [4] inference ✓ (OK, 3 µs) [5] monitor ✓ (OK, 4 µs) [6] verify ✓ (OK, 8 µs) Status: ALL STAGES PASSED ✓ Bit-identical: YES ✓ ═══════════════════════════════════════════════════════════════ ``` If any stage produces a different hash, the harness tells you exactly which one diverged. No more "it works on my machine" — either the hashes match or they don't. ## The Golden Reference The harness generates a 368-byte golden reference file containing: | Offset | Size | Field | |--------|------|-------| | 0x00 | 4 | Magic ("CHGR") | | 0x04 | 4 | Version | | 0x08 | 32 | Platform string | | 0x28 | 8 | Timestamp | | 0x30 | 32 | Config hash | | 0x50 | 32 | Harness hash | | 0x70 | 224 | Stage commitments (7 × 32) | | 0x150 | 32 | File hash | The file hash covers bytes 0x00–0x14F, enabling tamper detection. If anyone modifies the golden reference, verification fails. ### Generating a Golden Reference ```bash ./certifiable-harness --generate-golden --output result.json ``` This produces: - `result.json` — Human-readable report - `result.json.golden` — 368-byte binary for cross-platform comparison ### Verifying Against Golden Copy the golden file to another platform and run: ```bash ./certifiable-harness --golden result.json.golden --output their_result.json ``` If the hashes match: `Bit-identical: YES ✓` ## Verified Platforms | Platform | OS | Compiler | Result | |----------|-----|----------|--------| | x86_64 | Linux (Ubuntu) | GCC 12.2.0 | ✓ Bit-identical | | x86_64 | macOS 11.7 | Apple Clang | ✓ Bit-identical | | aarch64 | — | — | Pending | | riscv64 | — | — | Pending | The Linux and macOS results were generated on different machines, different operating systems, different compilers. Same hashes. ## Seven Pipeline Stages Each stage corresponds to a certifiable-* project: | Stage | Project | Commitment | |-------|---------|------------| | 0 | certifiable-data | Merkle root of batches | | 1 | certifiable-training | Training chain hash | | 2 | certifiable-quant | Quantization certificate | | 3 | certifiable-deploy | Attestation root | | 4 | certifiable-inference | Predictions hash | | 5 | certifiable-monitor | Ledger digest | | 6 | certifiable-verify | Report hash | The harness runs them in sequence, passing context between stages. Each stage's commitment includes the previous stage's commitment, forming an unbroken cryptographic chain. ## Test Coverage | Component | Tests | Description | |-----------|-------|-------------| | Harness | 4 | Orchestration, config, platform detection | | Golden | 3 | Load, save, compare, integrity | | Stages | 4 | Stage wrappers, dependency management | | Report | 2 | JSON generation, console output | 4 test suites, all passing. 81 traceable requirements across 4 SRS documents. ## Part of a Complete Pipeline certifiable-harness orchestrates the entire certifiable-* ecosystem: ``` data → training → quant → deploy → inference → monitor → verify ↑ ↓ └──────────────── certifiable-harness ────────────────────┘ ``` It's the proving ground — the place where cross-platform determinism is verified, not assumed. ## When You Need This **Hardware Vendors**: If you're building AI accelerators — RISC-V, custom silicon, FPGAs — certifiable-harness lets you prove your hardware produces bit-identical results to reference implementations. **Certification Bodies**: The harness produces machine-verifiable evidence. No manual inspection required. Run the harness, check the hashes, file the report. **Safety-Critical Deployments**: When a regulator asks "how do you know the deployed model is the same as what you tested?", you have a 368-byte answer. ## Getting Started ```bash git clone https://github.com/SpeyTech/certifiable-harness.git cd certifiable-harness mkdir build && cd build cmake .. make ctest --output-on-failure # Generate golden reference ./certifiable-harness --generate-golden --output result.json # Verify (should show Bit-identical: YES) ./certifiable-harness --golden result.json.golden --output verify.json ``` ## Documentation The repository includes formal documentation suitable for certification evidence: - **CH-MATH-001.md** — Mathematical specification (18KB) - **CH-STRUCT-001.md** — Data structure specification - **SRS-HARNESS** — Harness orchestration (16 requirements) - **SRS-GOLDEN** — Golden reference (23 requirements) - **SRS-STAGES** — Stage wrappers (25 requirements) - **SRS-REPORT** — Report generation (17 requirements) ## License Dual licensed under GPLv3 (open source) and commercial terms for proprietary safety-critical systems. The implementation builds on the [Murray Deterministic Computing Platform](/mdcp/) (UK Patent GB2521625.0). --- For teams building safety-critical ML systems, certifiable-harness provides the proving ground that certification demands. As with any architectural approach, suitability depends on system requirements, risk classification, and regulatory context. [View on GitHub](https://github.com/SpeyTech/certifiable-harness) · [Request Technical Brief](/contact/) --- ## certifiable-verify **Repository**: https://github.com/SpeyTech/certifiable-verify **License**: GPL-3.0 **Documentation**: https://speytech.com/open-source/certifiable-verify/ **Defines**: Pipeline verification KEY_CLAIMS: - Regulators ask one question that kills most ML deployments: "how do you know the deployed model matches what was trained?" Spreadsheets, manual checksums, and "we have a process" don't survive that question. EVIDENCE: - Medical Devices (IEC 62304): Class C software requires rigorous verification. certifiable-verify provides automated, repeatable verification that can be run before every deployment — not just during initial certification. - Automotive (ISO 26262): ASIL-D requires evidence that safety-critical software behaves as specified. certifiable-verify produces that evidence in a format that's machine-verifiable and auditable. Pipeline verification for the certifiable-* ecosystem — because 'we checked it manually' isn't certifiable Regulators ask one question that kills most ML deployments: "how do you know the deployed model matches what was trained?" Spreadsheets, manual checksums, and "we have a process" don't survive that question. Not because those approaches don't work — but because they don't *prove* anything in a way that can be independently verified. **certifiable-verify** validates the complete provenance chain through cryptographic binding verification. [View on GitHub](https://github.com/SpeyTech/certifiable-verify) ## The Problem The certifiable-* ecosystem produces cryptographic commitments at every stage: - **certifiable-data** produces a Merkle root of training batches - **certifiable-training** produces a gradient chain hash - **certifiable-quant** produces an error certificate - **certifiable-deploy** produces an attestation tree - **certifiable-inference** produces a predictions hash - **certifiable-monitor** produces a ledger digest But commitments alone aren't enough. You need to verify that each commitment *binds correctly* to the previous stage. That the training hash actually includes the data Merkle root. That the deployment bundle contains the quantized model that was certified. That the chain is unbroken from input data to deployed inference. That's what certifiable-verify does. ## Two Verification Modes **Hash-Only Mode** — Fast verification using pre-computed commitments: ```c cv_config_t config; cv_config_default(&config); config.mode = CV_MODE_HASH_ONLY; cv_artifacts_t artifacts; /* Load commitments from each stage... */ cv_report_t report; cv_fault_flags_t faults = {0}; cv_result_t rc = cv_verify(&config, &artifacts, &report, &faults); if (report.pipeline_valid) { printf("Pipeline verified ✓\n"); } ``` **Full Replay Mode** — Complete re-execution for maximum assurance: ```c config.mode = CV_MODE_FULL_REPLAY; config.data_path = "training_data.csv"; config.model_path = "model.cbf"; /* Re-runs entire pipeline, compares against recorded commitments */ cv_result_t rc = cv_verify(&config, &artifacts, &report, &faults); ``` ## Six Cross-Artifact Bindings certifiable-verify validates six cryptographic bindings between pipeline stages: | Binding | From | To | What's Verified | |---------|------|----|-----------------| | 0 | data | training | Training includes data Merkle root | | 1 | training | quant | Quantization includes model hash | | 2 | quant | deploy | Bundle includes certificate hash | | 3 | deploy | inference | Inference loads correct bundle | | 4 | inference | monitor | Monitor records prediction hash | | 5 | deploy | monitor | Monitor binds to bundle root | Each binding is verified independently. If binding 2 fails but others pass, you know exactly where the chain broke. ```c cv_binding_result_t binding; cv_verify_binding(CV_BINDING_QUANT_DEPLOY, &artifacts, &binding, &faults); if (!binding.valid) { printf("Bundle doesn't match quantization certificate\n"); printf("Expected: %s\n", binding.expected_hex); printf("Found: %s\n", binding.actual_hex); } ``` ## Report Generation certifiable-verify produces machine-readable reports with self-integrity hashes: ```c cv_report_write_json(&report, "verification_report.json", &faults); ``` ```json { "version": "1.0.0", "timestamp": "2026-01-19T21:00:00Z", "pipeline_valid": true, "bindings": [ {"id": 0, "name": "data→training", "valid": true}, {"id": 1, "name": "training→quant", "valid": true}, {"id": 2, "name": "quant→deploy", "valid": true}, {"id": 3, "name": "deploy→inference", "valid": true}, {"id": 4, "name": "inference→monitor", "valid": true}, {"id": 5, "name": "deploy→monitor", "valid": true} ], "report_hash": "a3f2c8..." } ``` The `report_hash` covers the entire report content, enabling tamper detection. ## Test Coverage | Test Suite | Coverage | |------------|----------| | test_provenance | Data lineage verification | | test_training | Training chain validation | | test_quant | Certificate binding | | test_bundle | Bundle attestation | | test_inference | Prediction hash verification | | test_ledger | Audit trail integrity | | test_binding | Cross-artifact bindings | | test_report | Report generation | | test_hash | Hash utilities | | test_serialize | Serialization | All 10 test suites passing. ## Part of a Complete Pipeline certifiable-verify is stage 6 in the certifiable-* ecosystem: ``` data → training → quant → deploy → inference → monitor → verify ``` It's the final stage — the one that answers "is this pipeline intact?" ## When You Need This **Aerospace (DO-178C)**: Requires traceability from requirements through implementation to test. certifiable-verify extends this to the ML pipeline itself — proving that the deployed model traces back to specific training data through an unbroken chain of cryptographic commitments. **Medical Devices (IEC 62304)**: Class C software requires rigorous verification. certifiable-verify provides automated, repeatable verification that can be run before every deployment — not just during initial certification. **Automotive (ISO 26262)**: ASIL-D requires evidence that safety-critical software behaves as specified. certifiable-verify produces that evidence in a format that's machine-verifiable and auditable. ## Getting Started ```bash git clone https://github.com/SpeyTech/certifiable-verify.git cd certifiable-verify mkdir build && cd build cmake .. make ctest --output-on-failure ``` ## Documentation The repository includes formal documentation suitable for certification evidence: - **CV-MATH-001.md** — Mathematical specification (47KB) - **CV-STRUCT-001.md** — Data structure specification - **SRS-001 through SRS-008** — Software Requirements Specifications ## License Dual licensed under GPLv3 (open source) and commercial terms for proprietary safety-critical systems. The implementation builds on the [Murray Deterministic Computing Platform](/mdcp/) (UK Patent GB2521625.0). --- For teams building safety-critical ML systems, certifiable-verify provides the formal rigour that certification demands. As with any architectural approach, suitability depends on system requirements, risk classification, and regulatory context. [View on GitHub](https://github.com/SpeyTech/certifiable-verify) · [Request Technical Brief](/contact/) --- ## certifiable-monitor **Repository**: https://github.com/SpeyTech/certifiable-monitor **License**: GPL-3.0 **Documentation**: https://speytech.com/open-source/certifiable-monitor/ **Defines**: Deterministic runtime monitoring KEY_CLAIMS: - Deploying an ML model isn't the end of the story. EVIDENCE: - IEC 62304 Class C requires traceable, reproducible software. - ISO 26262 ASIL-D demands provable behavior under all conditions. - Input drift detection with cryptographic proof isn't optional — it's the difference between "we think the model was stable" and "here's the hash chain proving it." DO-178C Level A requires complete requirements traceability. Deterministic runtime monitoring — because 'the model drifted' isn't certifiable Deploying an ML model isn't the end of the story. In safety-critical systems, you need to know — with cryptographic certainty — when that model is operating outside its certified envelope. Standard monitoring tools use floating-point statistics, produce non-deterministic results, and leave no verifiable audit trail. certifiable-monitor changes that. [View on GitHub](https://github.com/SpeyTech/certifiable-monitor) ## The Problem When an ML model runs in production, things drift: - **Input distributions shift** — Real-world data diverges from training - **Activations exceed bounds** — Internal values go where they shouldn't - **Output patterns change** — Predictions no longer match expectations - **Faults accumulate silently** — Overflow and saturation events go unnoticed Current monitoring approaches have fundamental problems for certification: **Non-deterministic metrics.** Floating-point drift calculations produce different results on different platforms. How do you validate something that changes? **No audit trail.** When an incident occurs, there's no cryptographic proof of what the monitor observed. It's your word against the logs. **Ambiguous reactions.** "Log a warning" isn't a deterministic specification. What action, exactly, should the system take when TV exceeds 0.15? For DO-178C Level A, IEC 62304 Class C, or ISO 26262 ASIL-D certification, "the model drifted so we logged it" isn't acceptable evidence. ## The Solution certifiable-monitor provides deterministic runtime monitoring through three core mechanisms: ### 1. Fixed-Point Drift Detection All statistical metrics computed in fixed-point arithmetic: **Total Variation (TV)** — The safest detector, no logarithms required: ``` TV(p, q) = (1/2) Σ_b |p_b - q_b| ``` Output in Q0.32. Zero means identical distributions. UINT32_MAX means completely disjoint. **Jensen-Shannon Divergence (JSD)** — Symmetric divergence measure: ``` JSD(p, q) = (1/2) KL(p ∥ m) + (1/2) KL(q ∥ m) ``` Uses a 512-entry LUT for log2 computation. No floating-point. Bit-identical on x86, ARM, and RISC-V. **Population Stability Index (PSI)** — Directional sensitivity: ``` PSI(p, q) = Σ_b (p_b - q_b) ln(p_b / q_b) ``` Epsilon smoothing prevents log(0). Policy defines operational thresholds. Same inputs produce the same drift scores. Every time. Every platform. ### 2. Cryptographic Audit Ledger Every monitoring event is logged to a SHA-256 hash chain: ``` L_0 = SHA256("CM:LEDGER:GENESIS:v1" ∥ R ∥ H_P) L_t = SHA256("CM:LEDGER:v1" ∥ L_{t-1} ∥ e_t) ``` The genesis block binds to the deployment bundle root `R` and policy hash `H_P`. Every subsequent entry chains to the previous digest. Tampering is detectable. Truncation is detectable. Reordering is detectable. Post-incident analysis can replay the entire monitoring history with cryptographic verification. ### 3. Deterministic Health FSM A state machine with formally defined transitions: ``` UNINIT → INIT → ENABLED → ALARM → DEGRADED → STOPPED ``` Fault budgets define thresholds. Violations trigger transitions. Once stopped, only manual intervention restarts. No ambiguity about system state. ## What's Implemented 253 Tests Passing 11 Test Suites ~13,700 Lines of Code | Module | Purpose | Tests | |--------|---------|-------| | DVM Primitives | Saturating arithmetic, LUT log2 | 33 | | Audit Ledger | SHA-256 hash chain | 18 | | Drift Detectors | TV, JSD, PSI computation | 20 | | Policy Parser | COE JSON parsing, JCS hash | 25 | | Input Monitor | Feature envelope checking | 22 | | Activation Monitor | Layer bounds checking | 24 | | Output Monitor | Output envelope checking | 19 | | Health FSM | Monitor state machine | 19 | | Reaction Handler | Violation → action mapping | 14 | | Ledger Verification | Offline chain verification | 32 | | Bit-Identity | Cross-platform determinism | 27 | Every module traces to formal specifications in CM-MATH-001, CM-STRUCT-001, and the SRS documents. ## Usage Example ```c #include "policy.h" #include "input.h" #include "health.h" #include "ledger.h" #include "react.h" ct_fault_flags_t faults = {0}; // Load policy and initialize ledger cm_policy_t policy; cm_policy_parse(policy_json, policy_len, &policy, &faults); cm_ledger_ctx_t ledger; cm_ledger_init(&ledger); cm_ledger_genesis(&ledger, policy.bundle_root, policy.policy_hash, &faults); // Initialize monitors cm_input_ctx_t input_mon; cm_input_init(&input_mon, &policy.input); cm_health_ctx_t health; cm_health_init(&health, &policy.fault_budget); cm_health_enable(&health); // Per-inference: check input envelope cm_input_result_t result; cm_input_check(&input_mon, input_vector, num_features, &result, &faults); if (result.violations > 0) { // Log to cryptographic ledger uint8_t L_out[32]; cm_ledger_append_violation(&ledger, window_id, CM_VIOL_INPUT_RANGE, result.first_violation_idx, result.first_violation_value, result.first_violation_bound, L_out, &faults); // Get policy-defined reaction cm_reaction_t action = cm_policy_get_reaction(&policy, CM_VIOL_INPUT_RANGE); // Update health state cm_health_report_violation(&health, CM_VIOL_INPUT_RANGE); } // Check if system should halt if (cm_health_get_state(&health) == CM_HEALTH_STOPPED) { // Emergency stop — do not proceed with inference } ``` All buffers statically allocated. No malloc. Deterministic execution path. ## The Pipeline certifiable-monitor completes the deterministic ML ecosystem: ``` certifiable-data → certifiable-training → certifiable-quant → certifiable-deploy → certifiable-inference ↓ certifiable-monitor ↓ Audit Ledger ``` The monitor receives: - **From certifiable-deploy:** Bundle attestation root and policy hash - **From certifiable-inference:** Input vectors, activation values, output vectors, fault flags - **From policy:** Thresholds, envelopes, reaction mappings Six interlocking projects. One coherent vision: deterministic ML from data to monitored production. ## Why This Matters ### Medical Devices IEC 62304 Class C requires traceable, reproducible software. When a diagnostic AI flags an anomaly, the response must be deterministic. The audit trail must be verifiable. ### Autonomous Vehicles ISO 26262 ASIL-D demands provable behavior under all conditions. Input drift detection with cryptographic proof isn't optional — it's the difference between "we think the model was stable" and "here's the hash chain proving it." ### Aerospace DO-178C Level A requires complete requirements traceability. Every drift metric traces to CM-MATH-001. Every state transition traces to CM-ARCH-MATH-001. Every test traces to an SRS requirement. This is the monitoring layer that makes ML certification possible. ## Getting Started ```bash git clone https://github.com/SpeyTech/certifiable-monitor cd certifiable-monitor mkdir build && cd build cmake .. make make test-all # 253 tests ``` Expected output: ``` 100% tests passed, 0 tests failed out of 11 ``` ## Documentation The implementation traces to formal specifications: - **CM-MATH-001** — Mathematical foundations (drift metrics, ledger hashing, log2 LUT) - **CM-STRUCT-001** — Data structure specifications - **CM-ARCH-MATH-001** — Architecture-level math (health FSM, window semantics) - **SRS-001 through SRS-008** — Module requirements with full traceability Every function documents its traceability reference. Every test validates a specification clause. ## The Trade-Off Deterministic monitoring isn't free. Fixed-point arithmetic requires careful scaling. Hash chain updates add overhead. Static allocation means pre-sized buffers. For systems where "it probably works" is acceptable, standard monitoring tools are simpler. For systems where lives depend on the answer — where regulators demand proof, where post-incident analysis requires cryptographic verification, where "the model drifted" needs to be a traceable, reproducible, auditable event — certifiable-monitor provides the foundation. As with any architectural approach, suitability depends on system requirements, risk classification, and regulatory context. --- *Built by SpeyTech in the Scottish Highlands. 30 years of UNIX systems engineering applied to making ML safe enough to certify.* [View on GitHub](https://github.com/SpeyTech/certifiable-monitor) · [Documentation](https://github.com/SpeyTech/certifiable-monitor/tree/main/docs) --- ## Certifiable Deploy **Repository**: https://github.com/SpeyTech/certifiable-deploy **License**: GPL-3.0 **Documentation**: https://speytech.com/open-source/certifiable-deploy/ **Defines**: Cryptographic attestation KEY_CLAIMS: - You've trained a model deterministically. EVIDENCE: - When a regulator asks "prove this is the model you certified," a Docker image hash doesn't satisfy DO-178C. certifiable-deploy provides five core components that work together to create a verifiable deployment chain. - IEC 62304 Class C requires traceable, reproducible software. - ISO 26262 ASIL-D demands provable behaviour. - DO-178C Level A requires complete requirements traceability. "We deployed the model" satisfies no one. Deterministic model packaging and cryptographic attestation — because 'trust me, it's the right model' isn't certifiable You've trained a model deterministically. You've quantized it with formal error bounds. Now you need to deploy it to production hardware. How do you prove the deployed model matches what was certified? How do you verify weights haven't been tampered with? How do you maintain cryptographic provenance from training to deployment? For safety-critical systems, "trust me, it's the right model" is not certifiable. **certifiable-deploy** implements the "Execution ⇒ Verification" invariant: the inference API is enabled only after cryptographic attestation confirms that measured hashes of weights and kernels match the certificate claims and attestation root. [View on GitHub](https://github.com/SpeyTech/certifiable-deploy) ## The Problem Deploying ML models to safety-critical systems faces fundamental challenges: 1. **Provenance**: How do you prove the deployed model matches what was certified? 2. **Integrity**: How do you verify weights haven't been tampered with in transit or at rest? 3. **Binding**: How do you ensure the model runs only on approved hardware? 4. **Auditability**: How do you maintain cryptographic proof linking deployment back to training? Standard deployment pipelines—containers, model registries, package managers—assume trust. They provide checksums for convenience, not for certification. When a regulator asks "prove this is the model you certified," a Docker image hash doesn't satisfy DO-178C. ## The Solution certifiable-deploy provides five core components that work together to create a verifiable deployment chain. ### 1. Canonical Bundle Format (CBF v1) A deterministic container with no ambient metadata. Payloads, table of contents, and attestation in a single verifiable package: ``` ┌─────────────────────────────────────┐ │ Global Header │ │ magic(4) | version(4) | offsets │ ├─────────────────────────────────────┤ │ File Payloads │ │ (raw bytes, no metadata) │ ├─────────────────────────────────────┤ │ Table of Contents │ │ entry_count | entries[] │ │ (sorted by normalized path) │ ├─────────────────────────────────────┤ │ Footer │ │ merkle_root | signature | magic │ └─────────────────────────────────────┘ ``` No timestamps. No filesystem metadata. No ambient authority. The same content produces the same bundle produces the same hash, forever. ### 2. Merkle Attestation A 4-leaf Merkle tree binds manifest, weights, certificates, and inference artifacts into a single attestation root: ``` R (root) / \ R₁ R₂ / \ / \ L_M L_W L_C L_I ``` Where: - `L_M` = domain hash of manifest - `L_W` = domain hash of weights - `L_C` = domain hash of certificate chain - `L_I` = domain hash of inference kernels The root `R` is what gets signed. Tampering with any leaf changes the root. ### 3. JCS Manifest (RFC 8785) The manifest uses JSON Canonicalization Scheme for deterministic serialization. Same content = same bytes = same hash: ```c cdm_builder_t mb; cdm_builder_init(&mb); cdm_set_mode(&mb, "deterministic"); cdm_set_created_at(&mb, 0); // No timestamps cdm_set_target(&mb, &target); cdm_set_weights_hash(&mb, &h_weights); cdm_set_certs_hash(&mb, &h_certs); cdm_set_inference_hash(&mb, &h_inference); uint8_t manifest_json[4096]; size_t manifest_len = sizeof(manifest_json); cdm_finalize_jcs(&mb, manifest_json, &manifest_len); ``` JCS ensures key ordering and numeric representation are canonical. No "semantically equivalent but different bytes" ambiguity. ### 4. Target Binding Lock bundles to specific platforms with target tuples: ``` arch-vendor-device-abi ``` Examples: - `riscv64-tenstorrent-p150-lp64d` - `x86_64-intel-xeon-sysv` - `aarch64-nvidia-orin-lp64` Wildcards (`generic`) allow bundles to match multiple devices while maintaining architecture/ABI safety. A bundle built for `x86_64-generic-cpu-sysv` runs on any x86_64 SYSV system. A bundle built for `riscv64-tenstorrent-p150-lp64d` runs only on that specific accelerator. ### 5. Runtime Loader (CD-LOAD) The loader implements a fail-closed state machine. JIT hash verification at every stage: ``` INIT → HEADER_READ → TOC_READ → MANIFEST_VERIFIED → WEIGHTS_STREAMING → WEIGHTS_VERIFIED → INFERENCE_STREAMING → INFERENCE_VERIFIED → CHAIN_VERIFIED → ENABLED Any State --[error]--> FAILED (terminal) ``` Any verification failure immediately transitions to `FAILED`, which cannot be exited. The inference API is unreachable without completing the full verification chain. ```c cd_load_ctx_t ctx; cd_target_t device_target; // Set device target cdt_set(&device_target, CD_ARCH_X86_64, "intel", "xeon", CD_ABI_SYSV); // Initialize loader cdl_init(&ctx, &device_target); // Open bundle (verifies header, TOC, manifest, target) cdl_open_bundle(&ctx, bundle_data, bundle_len); // Load weights with JIT hash verification cdl_load_weights(&ctx, weights, weights_size); // Load inference kernels with JIT hash verification cdl_load_kernels(&ctx, kernels, kernel_size); // Finalize (verifies Merkle root) cdl_finalize(&ctx); // Only now is execution permitted if (cdl_is_enabled(&ctx)) { run_inference(weights, kernels); } ``` ## Domain-Separated Hashing All hashes use domain separation to prevent cross-protocol attacks: ``` DH(tag, payload) = SHA256(tag || LE64(|payload|) || payload) ``` Domain tags include: - `CD:MANIFEST:v1` — Manifest hash - `CD:WEIGHTS:v1` — Weights hash - `CD:CERTSET:v1` — Certificate chain hash - `CD:INFERSET:v1` — Inference set hash - `CD:LEAF:*:v1` — Merkle leaf hashes - `CD:MERKLENODE:v1` — Merkle internal nodes A weights file cannot be substituted for a manifest, even if they happen to have the same content. The domain tag makes them cryptographically distinct. 201 Tests 7/7 Test Suites CBF v1 Format RFC 8785 JCS ## What's Implemented All modules complete — 201 tests passing across 7 test suites: | Module | Tests | Coverage | |--------|-------|----------| | Audit | 18 | SHA-256, domain-separated hashing | | Attest | 18 | Merkle tree construction, attestation | | Bundle | 37 | CBF v1 builder, reader, format compliance | | Manifest | 57 | JCS canonicalization, parsing, roundtrip | | Target | 32 | Parse, encode, match, wildcard | | Verify | 23 | Offline bundle verification | | Loader | 16 | Runtime JIT verification, state machine | ## The Complete Pipeline certifiable-deploy bridges the gap between quantization and inference: ``` certifiable-data → certifiable-training → certifiable-quant → certifiable-deploy → certifiable-inference ↓ ↓ ↓ ↓ ↓ Load data Train model Quantize model Package bundle Run inference Normalise Merkle chain Error bounds Attestation Bit-perfect Shuffle Audit trail Certificate Target binding execution ``` Each project maintains the same principles: pure C99, zero dynamic allocation, formal verification patterns, and cryptographic audit trails. ## Why It Matters ### Medical Devices IEC 62304 Class C requires traceable, reproducible software. When a pacemaker's ML model makes a decision, you need to prove it's running exactly what was validated. certifiable-deploy provides cryptographic evidence linking the deployed binary to the certified source. ### Autonomous Vehicles ISO 26262 ASIL-D demands provable behaviour. The perception model that passed simulation must be bit-identical to the perception model in the vehicle. Target binding ensures the certified bundle only runs on approved hardware configurations. ### Aerospace DO-178C Level A requires complete requirements traceability. "We deployed the model" satisfies no one. The Merkle attestation provides cryptographic proof linking each deployment artifact back through quantization, training, and data preparation. ## Integration Points certifiable-deploy is designed for integration with existing security infrastructure: **Ed25519 Signing**: The `cda_sign()` function provides the interface for signing attestation roots. Integrators provide their own Ed25519 implementation appropriate for their security requirements (HSM, libsodium, certified library). **Certificate Chain**: Certificate parsing requires integration with the deployer's PKI infrastructure. The certificate format is defined by the upstream certifiable-* pipeline. ## Getting Started ```bash git clone https://github.com/SpeyTech/certifiable-deploy cd certifiable-deploy mkdir build && cd build cmake .. make make test-all ``` Expected output: ``` 100% tests passed, 0 tests failed out of 7 Total Test time (real) = 0.02 sec ``` ## Documentation The repository includes formal documentation suitable for certification evidence: - **CD-MATH-001.md** — Mathematical foundations - **CD-STRUCT-001.md** — Data structure specifications - **SRS documents** — Software Requirements Specifications: - SRS-001-BUNDLE — CBF v1 format - SRS-002-ATTEST — Merkle attestation - SRS-003-TARGET — Target binding - SRS-004-MANIFEST — JCS canonicalization - SRS-005-VERIFY — Offline verification - SRS-006-LOADER — Runtime loader ## License Dual licensed under GPLv3 (open source) and commercial terms for proprietary safety-critical systems. The implementation builds on the [Murray Deterministic Computing Platform](/mdcp/) (UK Patent GB2521625.0). --- For teams deploying ML to safety-critical systems, certifiable-deploy provides the cryptographic rigour that certification demands. As with any architectural approach, suitability depends on system requirements, risk classification, and regulatory context. [View on GitHub](https://github.com/SpeyTech/certifiable-deploy) · [Request Technical Brief](/contact/) --- ## Certifiable Quant **Repository**: https://github.com/SpeyTech/certifiable-quant **License**: GPL-3.0 **Documentation**: https://speytech.com/open-source/certifiable-quant/ **Defines**: Deterministic quantization KEY_CLAIMS: - Standard quantization tools treat model compression as an optimisation problem: shrink the weights, benchmark accuracy, ship it. - Deterministic quantization converts floating-point model weights to fixed-point representation with formal error bounds and cryptographic certificates, ensuring the conversion is reproducible and auditable. EVIDENCE: - For safety-critical systems—where a misclassified obstacle or miscalculated dosage can cost lives—"approximately equivalent" isn't certifiable. certifiable-quant provides provable FP32→Q16.16 quantization with formal error bounds and cryptographic audit trails. - For DO-178C Level A aerospace software, IEC 62304 Class C medical devices, or ISO 26262 ASIL-D automotive systems, these aren't nice-to-haves. - Before touching any weights, compute theoretical error bounds: This establishes the entry error (ε₀ = 2⁻¹⁷ for Q16.16) and computes Lipschitz constants for layer-by-layer error propagation. - Q16.16 uses 16 fractional bits, giving an entry error of: Error propagates through layers according to: Where ρ_ℓ is the layer's Lipschitz constant (operator norm) and δ_ℓ is the layer's quantization error. Deterministic model quantization with formal error certificates for safety-critical ML Standard quantization tools treat model compression as an optimisation problem: shrink the weights, benchmark accuracy, ship it. For most applications, that's fine. For safety-critical systems—where a misclassified obstacle or miscalculated dosage can cost lives—"approximately equivalent" isn't certifiable. **certifiable-quant** provides provable FP32→Q16.16 quantization with formal error bounds and cryptographic audit trails. [View on GitHub](https://github.com/SpeyTech/certifiable-quant) Definition: Deterministic Quantization Deterministic quantization converts floating-point model weights to fixed-point representation with formal error bounds and cryptographic certificates, ensuring the conversion is reproducible and auditable. ## The Problem with Black-Box Quantization When you run a neural network through TensorFlow Lite or an ONNX quantizer, you get a smaller model. What you don't get: - **Error bounds**: How far can the quantized output deviate from the original? - **Reproducibility**: Will the same input produce identical output on different hardware? - **Audit trail**: Can you prove, years later, which original model produced this quantized version? For DO-178C Level A aerospace software, IEC 62304 Class C medical devices, or ISO 26262 ASIL-D automotive systems, these aren't nice-to-haves. They're certification requirements. ## How certifiable-quant Works The pipeline has five stages, each producing a cryptographic digest that feeds into a final Merkle-rooted certificate. ### 1. Analyze Before touching any weights, compute theoretical error bounds: ```c cq_analysis_ctx_t analysis; cq_analysis_init(&analysis, num_layers); cq_compute_weight_range(weights, n, &w_min, &w_max); cq_compute_overflow_proof(w_max, x_max, n, &overflow_proof); cq_analysis_digest_generate(&analysis, &analysis_digest); ``` This establishes the entry error (ε₀ = 2⁻¹⁷ for Q16.16) and computes Lipschitz constants for layer-by-layer error propagation. ### 2. Calibrate Collect runtime statistics from representative data: ```c cq_tensor_stats_t stats; cq_tensor_stats_init(&stats, CQ_FORMAT_Q16); for (int i = 0; i < num_samples; i++) { cq_tensor_stats_update(&stats, activations[i], size); } cq_calibration_digest_generate(&calib, &calib_digest); ``` The calibration module tracks min/max ranges, coverage percentages, and flags degenerate distributions that might indicate insufficient calibration data. ### 3. Convert Quantize with explicit fault detection: ```c cq_convert_ctx_t convert; cq_convert_init(&convert, CQ_FORMAT_Q16); cq_quantize_tensor(fp32_weights, q16_weights, n, &convert, &faults); ``` All arithmetic uses widening multiplication and Round-to-Nearest-Even (RNE) rounding—no silent overflow, no undefined behaviour. ### 4. Verify Check quantized values against theoretical bounds: ```c cq_verify_ctx_t verify; cq_verify_init(&verify, &analysis); bool passed = cq_verify_tensor(q16_weights, &analysis.contracts[layer], &verify); cq_verify_digest_generate(&verify, &verify_digest); ``` If any value exceeds its computed bound, verification fails. No silent degradation. ### 5. Certificate Generate the final proof object: ```c cq_certificate_builder_t builder; cq_certificate_builder_init(&builder); cq_certificate_builder_set_analysis(&builder, &analysis_digest); cq_certificate_builder_set_calibration(&builder, &calib_digest); cq_certificate_builder_set_verification(&builder, &verify_digest); cq_certificate_t cert; cq_certificate_build(&builder, &cert, &faults); ``` The certificate contains a Merkle root linking all three digests. Years later, you can prove exactly which analysis, calibration, and verification produced this quantized model. ## Error Bound Theory Q16.16 uses 16 fractional bits, giving an entry error of: ``` ε₀ = 2^(-f-1) = 2^(-17) ≈ 7.6 × 10⁻⁶ ``` Error propagates through layers according to: ``` ε_{ℓ+1} = ρ_ℓ · ε_ℓ + δ_ℓ ``` Where ρ_ℓ is the layer's Lipschitz constant (operator norm) and δ_ℓ is the layer's quantization error. The analysis module computes these bounds before conversion begins—if the theoretical maximum error exceeds tolerance, you know before wasting compute on quantization. ## The Fault Model Every operation signals faults explicitly: ```c typedef struct { uint32_t overflow : 1; /* Saturated high */ uint32_t underflow : 1; /* Saturated low */ uint32_t div_zero : 1; /* Division by zero */ uint32_t domain : 1; /* Invalid input */ uint32_t precision : 1; /* Precision loss detected */ } ct_fault_flags_t; ``` No silent failures. If something goes wrong, the fault flags tell you what and where. ## Test Coverage All core modules are complete with 150 tests across 7 test suites: | Module | Tests | Coverage | |--------|-------|----------| | Analyze | 30 | Overflow proofs, range propagation, norms | | Bit Identity | 9 | RNE patterns, SHA-256 vectors, cross-platform | | Calibrate | 28 | Statistics, coverage, degenerate handling | | Certificate | 27 | Builder, Merkle, serialization, roundtrip | | Convert | 21 | RNE quantization, BatchNorm folding, dyadic | | Primitives | 13 | Arithmetic, saturation, overflow safety | | Verify | 22 | Bound checking, L∞ norm, contract validation | ## Part of a Complete Pipeline certifiable-quant is one component of a deterministic ML ecosystem: **certifiable-data** → **certifiable-training** → **certifiable-quant** → **certifiable-deploy** → **certifiable-inference** Each project maintains the same principles: pure C99, zero dynamic allocation, formal error tracking, and cryptographic audit trails. Together, they provide end-to-end traceability from training data through deployed inference. ## When You Need This **Medical devices**: IEC 62304 Class C requires traceable, validated transformations. "We quantized it and it still works" isn't evidence. **Autonomous vehicles**: ISO 26262 ASIL-D demands provable error bounds. Unbounded quantization error is a safety hazard. **Aerospace**: DO-178C Level A requires complete requirements traceability. Every weight transformation must be auditable. If your model makes decisions that affect human safety, black-box quantization creates certification risk. certifiable-quant is designed to address that gap. ## Getting Started ```bash git clone https://github.com/SpeyTech/certifiable-quant cd certifiable-quant mkdir build && cd build cmake .. make make test ``` Expected output: ``` 100% tests passed, 0 tests failed out of 7 Total Test time (real) = 0.02 sec ``` ## Documentation The repository includes formal documentation suitable for certification evidence: - **CQ-MATH-001.md** — Mathematical foundations and error theory - **CQ-STRUCT-001.md** — Data structure specifications - **SRS documents** — Software Requirements Specifications for each module ## License Dual licensed under GPLv3 (open source) and commercial terms for proprietary safety-critical systems. The implementation builds on the [Murray Deterministic Computing Platform](/mdcp/) (UK Patent GB2521625.0). --- For teams building safety-critical ML systems, certifiable-quant provides the formal rigour that certification demands. As with any architectural approach, suitability depends on system requirements, risk classification, and regulatory context. [View on GitHub](https://github.com/SpeyTech/certifiable-quant) · [Request Technical Brief](/contact/) --- ## C-From-Scratch **Repository**: https://github.com/SpeyTech/c-from-scratch **License**: MIT **Documentation**: https://speytech.com/open-source/c-from-scratch/ **Defines**: Safety-critical C KEY_CLAIMS: - Most programming courses start with "Hello World" and work up to toy applications. - Safety-critical C is a constrained subset of the C language that prohibits dynamic allocation, unbounded loops, and implicit behaviour to satisfy certification requirements. EVIDENCE: - When a heartbeat should arrive every 800ms ± 50ms, we need to detect when intervals drift outside tolerance. Learn to build safety-critical systems in C — mathematical rigour, not 'Hello World' Most programming courses start with "Hello World" and work up to toy applications. They teach syntax but not thinking. They produce programmers who can write code that compiles, but not code that meets the demands of safety-critical C — where lives depend on correctness. C-From-Scratch takes the opposite approach. We start with the question: **what would it take to build software for a pacemaker?** Then we work backwards to the fundamentals. Definition: Safety-Critical C Safety-critical C is a constrained subset of the C language that prohibits dynamic allocation, unbounded loops, and implicit behaviour to satisfy certification requirements. ## The Methodology Core Principle "Sensors report. The Captain decides." Every module follows the same pattern: ``` Problem → Math Model → Proof → Structs → Code → Verification │ │ │ │ │ │ │ │ │ │ │ └── Does code match math? │ │ │ │ └── Direct transcription │ │ │ └── Every field justified │ │ └── Contracts proven │ └── State machine defined └── Failure modes analysed ``` This is the "Math → Structs → Code" methodology. We don't write code until we can prove properties about our design. The code is a transcription of the math, not an invention. ## The Safety Stack Seven modules build from simple monitors to a complete safety-critical system: 7 Modules 42 Lessons 98 Tests MIT License ### The Sensors (Modules 1-4) **Module 1: Pulse** — Is the signal alive? The simplest possible monitor. A signal either arrives within a timeout or it doesn't. Two states, deterministic transitions, provable properties. This is the foundation everything else builds on. **Module 2: Baseline** — Is the signal normal? Exponential moving averages with O(1) memory. Statistical anomaly detection without storing history. We prove bounds on memory usage and numerical stability. **Module 3: Timing** — Is the rhythm healthy? Interval analysis and jitter detection. When a heartbeat should arrive every 800ms ± 50ms, we need to detect when intervals drift outside tolerance. **Module 4: Drift** — Trending toward failure? Long-term trend detection. A sensor might be "normal" right now but drifting toward failure. Linear regression with bounded memory and deterministic computation. ### The Decision Layer (Modules 5-7) **Module 5: Consensus** — Which sensor to trust? Triple Modular Redundancy (TMR) voting. When three sensors disagree, how do you decide which one is right? Byzantine fault tolerance in 200 lines of C. **Module 6: Pressure** — Handle overflow Bounded queues with backpressure. When events arrive faster than you can process them, what do you drop? We prove the queue never overflows and never loses critical events. **Module 7: Mode** — The Captain System mode management with permission matrices. Some actions are only safe in certain modes. Transitions between modes must be controlled. This is where everything comes together. ### The Composition ``` Sensors (1-4) → Judge (5) → Buffer (6) → Captain (7) ``` Each module is independently verified. The composition preserves the properties of the components. This is how you build complex systems you can trust. ## What You'll Learn This isn't a syntax course. You'll learn: - **Failure mode analysis** — Enumerate what can go wrong before writing code - **State machine design** — Define all states and all transitions explicitly - **Property proofs** — Prove bounds, invariants, and safety properties - **Data structure justification** — Every field serves a proven purpose - **TMR voting** — Implement Byzantine fault tolerance - **Backpressure handling** — Manage overflow without losing critical data - **Mode management** — Control system behaviour through state transitions - **Compositional verification** — Build complex systems from verified components ## Example: The Pulse Monitor Here's what a lesson looks like. The Pulse monitor answers one question: is the signal alive? ### The Math ``` State: { ALIVE, DEAD } Input: { tick, heartbeat } Transition: ALIVE + tick → if (ticks_since_heartbeat > TIMEOUT) then DEAD else ALIVE ALIVE + heartbeat → ALIVE (reset counter) DEAD + heartbeat → ALIVE DEAD + tick → DEAD ``` ### The Proof Property: "If heartbeats arrive faster than TIMEOUT, the system stays ALIVE." Proof: Each heartbeat resets the counter. If heartbeats arrive every T ticks where T state == PULSE_ALIVE) { pm->ticks_since_heartbeat++; if (pm->ticks_since_heartbeat > pm->timeout) { pm->state = PULSE_DEAD; } } return pm->state; } pulse_state_t pulse_heartbeat(pulse_monitor_t *pm) { pm->ticks_since_heartbeat = 0; pm->state = PULSE_ALIVE; return pm->state; } ``` The code is a direct transcription of the state machine. No creativity required — creativity in safety-critical code is a bug. ### The Test ```c void test_timeout_triggers_dead(void) { pulse_monitor_t pm; pulse_init(&pm, 3); // Timeout after 3 ticks assert(pulse_tick(&pm) == PULSE_ALIVE); // tick 1 assert(pulse_tick(&pm) == PULSE_ALIVE); // tick 2 assert(pulse_tick(&pm) == PULSE_ALIVE); // tick 3 assert(pulse_tick(&pm) == PULSE_DEAD); // tick 4 - timeout! } ``` The test verifies the proof. If the test passes, the code matches the math. ## Why This Approach Works Traditional programming education teaches you to write code that works. This approach teaches you to write code that **cannot fail** — because failure modes are eliminated by design, not by testing. Testing can only show the presence of bugs, not their absence. Proofs show absence. When you prove a property about your state machine, it holds for all possible inputs, not just the ones you thought to test. This is how aerospace software is written. This is how medical device software is written. And now it's how you can learn to write software. ## Getting Started ```bash git clone https://github.com/SpeyTech/c-from-scratch cd c-from-scratch make make test ``` Start with Module 1 (Pulse). Each module builds on the previous. By Module 7, you'll have built a complete safety-critical monitoring system. ## Community Response The course has resonated with engineers who want more than syntax: > "Finally, a C course that treats the language seriously. The math-first approach changed how I think about all my code." > "I've been writing C for 15 years and I learned more about safety-critical design in Module 5 than in my entire career." The repository has seen significant engagement on GitHub, and the LinkedIn posts about the methodology have reached over 66,000 impressions. Turns out there's demand for rigour. --- *Prove first, code second. MIT licensed.* --- ## Certifiable Data **Repository**: https://github.com/SpeyTech/certifiable-data **License**: GPL-3.0 **Documentation**: https://speytech.com/open-source/certifiable-data/ **Defines**: Deterministic data pipeline KEY_CLAIMS: - Standard ML data pipelines are a major source of non-determinism. - A deterministic data pipeline produces bit-identical batches for any given dataset, seed, and epoch — eliminating shuffling, normalisation, and augmentation as sources of non-reproducibility. EVIDENCE: - IEC 62304 Class C (medical devices) requires traceable software. - DO-178C Level A (aerospace) requires complete requirements traceability. "We shuffled the data randomly" satisfies neither. Deterministic data pipelines for safety-critical ML — because 'we shuffled the data' isn't reproducible Standard ML data pipelines are a major source of non-determinism. Floating-point normalisation varies across platforms. Random shuffling produces different orders each run. Data augmentation introduces uncontrolled variation. When you can't reproduce your data pipeline, you can't reproduce your training. When you can't reproduce your training, you can't certify your model. `certifiable-data` makes data loading a pure function: `B_t = Pipeline(D, seed, epoch, t)`. Given the same dataset, seed, and indices, you get the same batch — bit for bit, every time. Definition: Deterministic Data Pipeline A deterministic data pipeline produces bit-identical batches for any given dataset, seed, and epoch — eliminating shuffling, normalisation, and augmentation as sources of non-reproducibility. ## The Problem Consider a typical PyTorch data loader: ```python loader = DataLoader(dataset, shuffle=True, num_workers=4) ``` This single line introduces multiple sources of non-determinism: 1. **Shuffle order** depends on PRNG state, which depends on when you called it 2. **Floating-point normalisation** varies by platform 3. **Worker processes** may return batches in different orders 4. **Augmentation** (if any) introduces random transformations For research, this doesn't matter. For safety-critical systems, it's disqualifying. ## The Solution ### Deterministic Normalisation Standard normalisation uses floating-point: `y = (x - mean) / std`. The division introduces platform-dependent rounding. `certifiable-data` uses fixed-point with precomputed inverse: ```c // Q16.16 fixed-point normalisation // y = (x - μ) * (1/σ) // All operations use DVM primitives with RNE rounding int32_t normalise(int32_t x, int32_t mean, int32_t inv_std, ct_fault_flags_t *faults) { int64_t diff = (int64_t)x - (int64_t)mean; int64_t product = diff * (int64_t)inv_std; return dvm_round_shift_rne(product, 16, faults); } ``` The result is deterministic because: - All arithmetic is integer (no floating-point) - Rounding uses Round-to-Nearest-Even (RNE), explicitly - Overflow is handled by saturation with fault flags ### Feistel Shuffling Standard shuffling (Fisher-Yates) requires sequential access and maintains internal state. Different execution orders produce different shuffles. We use a Cycle-Walking Feistel network — a cryptographic permutation that maps any index to its shuffled position in O(1) time: ```c uint32_t permute_index(uint32_t index, uint32_t N, uint64_t seed, uint32_t epoch) { // Feistel network with cycle-walking // π: [0, N-1] → [0, N-1] (bijection) // Same (seed, epoch, index) → same output, always } ``` Test vectors from CT-MATH-001 §7.2: ``` N=100, seed=0x123456789ABCDEF0, index=0 → 26 N=100, seed=0x123456789ABCDEF0, index=99 → 41 N=60000, seed=0xFEDCBA9876543210, index=0 → 26382 ``` The permutation is a true bijection — every input maps to exactly one output, and every output comes from exactly one input. ### Deterministic Augmentation Data augmentation typically uses random number generators. We use counter-based PRNG with explicit operation IDs: ```c // Horizontal flip (50% probability) uint64_t rng = ct_prng(seed, epoch, sample_idx 142 Tests 8/8 Test Suites O(1) Shuffle Time RNE Rounding ## What's Implemented All core modules complete — 142 tests passing across 8 test suites: | Module | Tests | Coverage | |--------|-------|----------| | DVM Primitives | 38 | CT-MATH-001 §3 test vectors | | PRNG | 13 | Determinism, distribution quality | | Shuffle | 19 | Bijection verification | | Normalise | 13 | Correctness, overflow handling | | Augment | 10 | Flip, crop, noise | | Batch | 12 | Construction, verification | | Merkle | 20 | Hashing, provenance chain | | Bit-Identity | 17 | Cross-platform verification | ## Usage Example ```c #include "ct_types.h" #include "loader.h" #include "normalize.h" #include "shuffle.h" #include "batch.h" #include "merkle.h" // Pre-allocated buffers ct_sample_t dataset_samples[60000]; ct_dataset_t dataset = { .samples = dataset_samples, .num_samples = 60000 }; ct_fault_flags_t faults = {0}; // Load data (deterministic decimal parsing) ct_load_csv("mnist.csv", &dataset, &faults); // Setup normalisation ct_normalize_ctx_t norm_ctx; ct_normalize_init(&norm_ctx, means, inv_stds, 784); // Create batch via deterministic shuffle ct_batch_t batch; ct_batch_init(&batch, batch_samples, batch_hashes, 32); ct_batch_fill(&batch, &dataset, batch_index, epoch, seed); // Verify integrity int valid = ct_batch_verify(&batch); // Initialize provenance chain ct_provenance_t prov; ct_provenance_init(&prov, dataset_hash, config_hash, seed); ``` ## The Complete Pipeline `certifiable-data` completes the deterministic ML pipeline: ``` certifiable-data → certifiable-training → certifiable-inference ↓ ↓ ↓ Load data Train model Deploy model Normalise Merkle chain Bit-perfect Shuffle Audit trail inference Batch ``` Every step is deterministic. Every step is auditable. The same seed produces the same model produces the same predictions, forever. ## Why It Matters ### Reproducibility Crisis The ML reproducibility crisis is well-documented. Papers can't be replicated. Models can't be reconstructed. Part of the problem is non-deterministic data pipelines — you can't reproduce training if you can't reproduce the exact data order. ### Certification Requirements IEC 62304 Class C (medical devices) requires traceable software. DO-178C Level A (aerospace) requires complete requirements traceability. "We shuffled the data randomly" satisfies neither. With `certifiable-data`, you can prove: - Exactly what data was used - In exactly what order - With exactly what transformations - And verify it cryptographically ### Debugging Training When training fails or produces unexpected results, you need to understand what happened. With deterministic data loading, you can replay exact batches and inspect exact transformations. No "it worked differently yesterday" mysteries. ## Getting Started ```bash git clone https://github.com/SpeyTech/certifiable-data cd certifiable-data mkdir build && cd build cmake .. make make test ``` Expected output: ``` 100% tests passed, 0 tests failed out of 8 Total Test time (real) = 0.04 sec ``` ## Documentation - **CT-MATH-001.md** — Mathematical foundations (normalisation, Feistel, Merkle) - **CT-STRUCT-001.md** — Data structure specifications - **docs/requirements/** — SRS documents with full traceability --- *Data loading as a pure function. Merkle-proven provenance. GPL-3.0 licensed.* --- ## C-Sentinel **Repository**: https://github.com/SpeyTech/c-sentinel **License**: MIT **Documentation**: https://speytech.com/open-source/c-sentinel/ **Defines**: Semantic observability KEY_CLAIMS: - Most security monitoring tools are black boxes. EVIDENCE: - The entire binary compiles to 104KB. 104KB Binary Size Zero Dependencies <1% CPU Overhead O(1) Memory per Probe This matters for deployment in constrained environments. Semantic observability for UNIX systems — lightweight system probing with explainable risk scoring Most security monitoring tools are black boxes. They tell you something is wrong, but not why. They flag anomalies without explaining the reasoning. When the alert fires at 3 AM, you're left guessing. C-Sentinel takes a different approach: **semantic observability**. Every risk score comes with an explanation. Every alert tells you exactly which factors contributed and how much weight each carried. ## The Problem with Traditional Monitoring Traditional security monitoring operates on pattern matching. A process opens a network connection — is that suspicious? It depends on context that pattern matchers can't see. Consider a system administrator running `curl` to download a patch. Normal behaviour. Now consider the same command executed by a web server process. That's worth investigating. The difference isn't in the action itself but in **who** is performing it, **when**, and **why** it deviates from established baselines. This requires semantic understanding, not just pattern matching. ## How C-Sentinel Works C-Sentinel captures "system fingerprints" — snapshots of system state that include process trees, network connections, file system changes, and user activity. These fingerprints are then analysed for anomalies using explainable scoring. ### Explainable Risk Scoring Every risk score is decomposed into contributing factors: ``` Risk Score: 73/100 (High) Contributing Factors: ├── Process ancestry anomaly: +25 │ └── /usr/bin/curl spawned by httpd (unusual parent) ├── Network connection timing: +18 │ └── Connection established outside business hours ├── File access pattern: +15 │ └── Accessed /etc/shadow (sensitive file) └── User context: +15 └── Action performed by service account ``` You don't just see the score — you see the reasoning. This transforms alert investigation from guesswork into directed analysis. ### Auditd Integration C-Sentinel integrates with the Linux audit framework to provide process chain attribution. When an alert fires, you can trace the exact sequence of events: ``` Process Chain: systemd → httpd → /bin/sh → curl → [network connection] Timeline: 14:23:01 httpd receives request from 192.168.1.45 14:23:01 httpd spawns /bin/sh with args "-c curl ..." 14:23:02 curl connects to 203.0.113.50:443 14:23:02 curl writes to /tmp/.cache_xyz ``` This attribution chain is essential for incident response. You can see not just what happened, but how the system got into that state. ## Architecture C-Sentinel is written in pure C with zero external dependencies. The entire binary compiles to 104KB. 104KB Binary Size Zero Dependencies <1% CPU Overhead O(1) Memory per Probe This matters for deployment in constrained environments. No Python runtime. No Node.js. No container orchestration. Just a single binary that runs anywhere Linux runs. ### Web Dashboard The dashboard provides real-time visibility with multi-user authentication and role-based access control: - **Two-factor authentication** with TOTP and QR code setup - **Role-based access** — separate permissions for viewers, analysts, and administrators - **Public demo mode** for showcasing without exposing sensitive data - **Email and Slack alerts** with rich formatting ### Security Posture Summary Beyond individual alerts, C-Sentinel generates plain-English summaries of overall system security posture: > "System posture: Moderate risk. Three service accounts have accessed sensitive files in the past 24 hours. Network connection patterns show 12% deviation from baseline, primarily due to increased API calls to external services. No privilege escalation attempts detected." This summary helps communicate security status to non-technical stakeholders without drowning them in technical detail. ## Design Philosophy C-Sentinel follows the same principles as our commercial safety-critical work: **Minimal footprint.** The smaller the codebase, the smaller the attack surface. Every line of code is a potential vulnerability. **Explainable behaviour.** Security tools that operate as black boxes are security liabilities. If you can't explain why an alert fired, you can't trust it. **No external dependencies.** Dependencies are inherited vulnerabilities. C-Sentinel's only dependency is the Linux kernel itself. **Deterministic operation.** Given the same system state, C-Sentinel produces the same risk score. This enables regression testing and makes behaviour predictable. ## Getting Started ```bash git clone https://github.com/SpeyTech/c-sentinel cd c-sentinel make ./c-sentinel --config /etc/c-sentinel/config.yaml ``` The default configuration provides sensible defaults for most Linux systems. Customisation is available for specific environments. ## Roadmap Current development focuses on: - **Solaris port** — returning to my Solaris 2.6 roots - **macOS support** — extending coverage to development workstations - **Container-aware probing** — understanding container boundaries in risk assessment - **Historical trend analysis** — detecting slow-moving attacks that evade point-in-time detection ## Why Open Source? Security through obscurity doesn't work. The only way to build trustworthy security tools is to make them auditable. By releasing C-Sentinel under the MIT license, anyone can verify that it does what it claims and nothing more. The open source also outlives us. When I'm gone, the code remains. Others can build on it, improve it, adapt it to their needs. That's the point. --- *Built in the Scottish Highlands. MIT licensed. Zero dependencies.* --- ## Certifiable Inference **Repository**: https://github.com/SpeyTech/certifiable-inference **License**: GPL-3.0 **Documentation**: https://speytech.com/open-source/certifiable-inference/ **Defines**: Deterministic inference KEY_CLAIMS: - Most AI infrastructure is built for research, where "mostly reproducible" is good enough. - Deterministic inference produces bit-identical neural network outputs across platforms and builds by using fixed-point arithmetic, static allocation, and a single canonicalised execution path. EVIDENCE: - With 16 integer bits and 16 fractional bits, we get: Range: -32768.0 to +32767.99998 Precision: 0.0000152588 (1/65536) Determinism: Bit-identical across any compliant platform No `malloc()` after initialisation. - This enables static memory analysis required for DO-178C Level A certification. - ISO 26262 ASIL-D requires provable worst-case execution time (WCET). Deterministic, bit-perfect neural network inference for safety-critical systems Most AI infrastructure is built for research, where "mostly reproducible" is good enough. In aerospace, medical devices, and autonomous vehicles, non-determinism isn't just a bug — it's a liability. Modern ML inference engines like TensorFlow Lite, ONNX Runtime, and PyTorch Mobile are fundamentally non-deterministic. Floating-point operations vary across platforms. Hash table iteration is unpredictable. Memory allocation affects behaviour. For safety-critical systems, you cannot prove correctness if behaviour varies. Definition: Deterministic Inference Deterministic inference produces bit-identical neural network outputs across platforms and builds by using fixed-point arithmetic, static allocation, and a single canonicalised execution path. ## The Three Pillars `certifiable-inference` replaces the "black box" of modern ML with a deterministic pipeline: ### 1. Exact Math Fixed-point arithmetic (Q16.16) ensures `Input A + Model B = Output C` across all platforms — x86, ARM, RISC-V — forever. No floating-point drift. No platform-dependent rounding. ```c typedef int32_t fixed_t; #define FIXED_SHIFT 16 #define FIXED_ONE (1 Q16.16 Fixed-Point Zero malloc() calls <5% P95 Jitter C99 Standard ## What's Implemented The engine provides the core building blocks for convolutional neural networks: - **Fixed-point arithmetic** — Q16.16 with deterministic rounding - **Matrix operations** — Multiply, transpose, element-wise ops - **2D Convolution** — Zero dynamic allocation, O(OH×OW×KH×KW) - **Activation functions** — ReLU, deterministic thresholding - **Max Pooling** — 2×2 stride-2 dimension reduction - **Timing verification** — Proven <5% jitter at 95th percentile ## Usage Example ```c #include "matrix.h" #include "convolution.h" #include "activation.h" #include "pooling.h" // Pre-allocated buffers (no malloc) fixed_t input_buf[256]; // 16×16 input fixed_t kernel_buf[9]; // 3×3 kernel fixed_t conv_buf[196]; // 14×14 after conv fixed_t pool_buf[49]; // 7×7 after pooling // Initialize matrices fx_matrix_t input, kernel, conv_out, pool_out; fx_matrix_init(&input, input_buf, 16, 16); fx_matrix_init(&kernel, kernel_buf, 3, 3); fx_matrix_init(&conv_out, conv_buf, 14, 14); fx_matrix_init(&pool_out, pool_buf, 7, 7); // Inference pipeline fx_conv2d(&input, &kernel, &conv_out); // Convolution fx_relu(&conv_out, &conv_out); // Activation fx_maxpool_2x2(&conv_out, &pool_out); // Pooling // Result: 7×7 feature map, bit-perfect across all platforms ``` ## Why It Matters ### Medical Devices A pacemaker must deliver a signal within a 10ms window. Non-deterministic timing causes life-threatening delays. With fixed-point arithmetic and bounded execution time, timing is provable. ### Autonomous Vehicles ISO 26262 ASIL-D requires provable worst-case execution time (WCET). Floating-point variance makes this impossible — the same operation can take different amounts of time depending on input values. Fixed-point operations have constant timing. ### Aerospace DO-178C Level A demands complete requirements traceability. "The model runs inference" is not certifiable. "The model executes exactly these operations in exactly this order with exactly this memory footprint" is certifiable. ## The Certifiable Pipeline `certifiable-inference` is part of a complete deterministic ML pipeline: | Project | Purpose | Status | |---------|---------|--------| | [certifiable-data](https://github.com/SpeyTech/certifiable-data) | Deterministic data loading and augmentation | ✅ Released | | [certifiable-training](https://github.com/SpeyTech/certifiable-training) | Deterministic training with Merkle audit trail | ✅ Released | | **certifiable-inference** | Deterministic inference | ✅ Released | Together, these provide end-to-end determinism: from data loading through training to deployment. The same seed produces the same model produces the same predictions, forever. ## Certification Support The implementation is designed to support certification under: - **DO-178C** — Aerospace software (Level A capable) - **IEC 62304** — Medical device software (Class C capable) - **ISO 26262** — Automotive functional safety (ASIL-D capable) - **IEC 61508** — Industrial safety systems (SIL-4 capable) Documentation includes Software Requirements Specifications (SRS), verification methods, and traceability matrices. ## Getting Started ```bash git clone https://github.com/SpeyTech/certifiable-inference cd certifiable-inference mkdir build && cd build cmake .. make make test ``` ## Roadmap - **Model loader** — ONNX import for pre-trained models - **Quantisation tools** — FP32 to Q16.16 conversion with error bounds - **Additional layers** — Batch normalisation, additional pooling modes ## Patent Protection This implementation is built on the Murray Deterministic Computing Platform (MDCP), protected by UK Patent GB2521625.0. Commercial licensing available for proprietary use in safety-critical systems. --- *Same input. Same output. Always. GPL-3.0 licensed.* --- ## Certifiable Training **Repository**: https://github.com/SpeyTech/certifiable-training **License**: GPL-3.0 **Documentation**: https://speytech.com/open-source/certifiable-training/ **Defines**: Deterministic training KEY_CLAIMS: - Training machine learning models is inherently non-deterministic. - Deterministic training guarantees bit-identical model weights from identical inputs, seeds, and hyperparameters by using fixed-point arithmetic, deterministic reduction, and cryptographic audit trails. EVIDENCE: - Q16.16 for weights, Q8.24 for gradients, Q32.32 for accumulators. - IEC 62304 (medical devices) requires traceable, reproducible software. - ISO 26262 (automotive) demands provable behaviour. - DO-178C (aerospace) requires complete requirements traceability. "We trained a neural network and it works" satisfies none of these. "Here is the cryptographic proof that this model was produced by this exact training process" is a foundation for certification. Deterministic ML training with Merkle audit trails — because 'we trained it' isn't certifiable Training machine learning models is inherently non-deterministic. Floating-point operations vary across platforms. Parallel reductions produce different results each run. Data shuffling depends on random number generators that aren't truly random. For safety-critical systems, you cannot certify what you cannot reproduce. `certifiable-training` redefines training as a **deterministic state evolution**. Training becomes a pure function: `θ_T = T^(T)(θ_0, D, seed)`. Given the same initial weights, data, and seed, you get the same final model — bit for bit, every time, on every platform. Definition: Deterministic Training Deterministic training guarantees bit-identical model weights from identical inputs, seeds, and hyperparameters by using fixed-point arithmetic, deterministic reduction, and cryptographic audit trails. ## The Four Mechanisms ### 1. Fixed-Point Arithmetic Q16.16 for weights, Q8.24 for gradients, Q32.32 for accumulators. Same math, same result, every platform. | Format | Use Case | Range | Precision | |--------|----------|-------|-----------| | Q16.16 | Weights, activations | ±32768 | 1.5×10⁻⁵ | | Q8.24 | Gradients | ±128 | 5.9×10⁻⁸ | | Q32.32 | Accumulators | ±2³¹ | 2.3×10⁻¹⁰ | The higher precision for gradients prevents small updates from being rounded away. The wide accumulators prevent overflow during summation. ### 2. Deterministic Reduction Parallel gradient reduction is a major source of non-determinism. The order of floating-point additions affects the result. Different thread scheduling produces different sums. `certifiable-training` uses fixed tree topology with Neumaier compensated summation: ```c // Fixed reduction tree — same topology every time // [sum] // / \ // [a+b] [c+d] // / \ / \ // a b c d ``` The tree topology is determined at compile time, not runtime. Combined with compensated arithmetic, the reduction is deterministic regardless of hardware parallelism. ### 3. Reproducible "Randomness" Data shuffling and dropout require random numbers. But standard PRNGs maintain internal state that varies with execution order. We use counter-based PRNG: `PRNG(seed, op_id, step) → deterministic bits`. The output depends only on the inputs, not on hidden state. Same seed produces same sequence. For data shuffling, we use a Cycle-Walking Feistel network that provides true bijection for any dataset size: ``` π: [0, N-1] → [0, N-1] (one-to-one and onto) ``` This isn't "shuffle and hope" — it's a cryptographic permutation with proven properties. ### 4. Merkle Audit Trail Every training step produces a cryptographic commitment: ``` h_t = SHA256(h_{t-1} || H(θ_t) || H(B_t) || t) ``` Where: - `h_{t-1}` is the previous hash (chain link) - `H(θ_t)` is the hash of current weights - `H(B_t)` is the hash of the current batch - `t` is the step number Any step can be independently verified. If you claim "model X was produced by training Y," the Merkle chain proves it — or proves you're lying. 10/10 Test Suites SHA-256 Audit Chain Feistel Shuffle O(1) Verify Time ## What's Implemented All core modules complete — 10/10 test suites passing: | Module | Description | |--------|-------------| | DVM Primitives | Fixed-point arithmetic with fault detection | | Counter-based PRNG | Deterministic pseudo-random generation | | Compensated Summation | Neumaier algorithm for precision | | Reduction Tree | Fixed-topology parallel reduction | | Forward Pass | Q16.16 activations (ReLU, sigmoid, tanh) | | Backward Pass | Q8.24 gradient computation | | Optimizers | SGD, Momentum, Adam | | Merkle Chain | SHA256 audit trail with checkpoints | | Data Permutation | Cycle-Walking Feistel bijection | | Bit Identity | Cross-platform reproducibility tests | ## The Fault Model Every arithmetic operation can overflow, underflow, or divide by zero. Traditional code either ignores these (undefined behaviour) or throws exceptions (non-deterministic control flow). `certifiable-training` uses sticky fault flags: ```c typedef struct { uint32_t overflow : 1; // Saturated high uint32_t underflow : 1; // Saturated low uint32_t div_zero : 1; // Division by zero uint32_t domain : 1; // Invalid input uint32_t precision : 1; // Precision loss } ct_fault_flags_t; ``` Operations saturate rather than overflow. Faults are recorded but execution continues deterministically. If any fault occurs during a training step, the Merkle chain is invalidated — you know something went wrong, and you know exactly when. ## Usage Example ```c #include "ct_types.h" #include "forward.h" #include "backward.h" #include "optimizer.h" #include "merkle.h" // All buffers pre-allocated fixed_t weights[784 * 128]; grad_t gradients[784 * 128]; ct_fault_flags_t faults = {0}; // Initialize Merkle chain ct_merkle_ctx_t merkle; ct_merkle_init(&merkle, &weights_tensor, config, config_size, seed); // Training step ct_forward_linear(&layer, input, output, &faults); ct_backward_linear(&layer, grad_in, &faults); ct_sgd_step(&sgd, weights, gradients, size, &faults); // Commit to audit trail ct_merkle_step(&merkle, &weights_tensor, indices, batch_size, &step_record, &faults); if (ct_has_fault(&faults)) { // Training step invalid — chain not extended } ``` ## Why It Matters ### Regulatory Compliance IEC 62304 (medical devices) requires traceable, reproducible software. ISO 26262 (automotive) demands provable behaviour. DO-178C (aerospace) requires complete requirements traceability. "We trained a neural network and it works" satisfies none of these. "Here is the cryptographic proof that this model was produced by this exact training process" is a foundation for certification. ### Incident Investigation When an autonomous vehicle makes a bad decision, investigators need to understand why. With Merkle-chained training, you can prove exactly what training data and process produced the model. You can replay any training step and verify it matches the logged hash. ### Model Provenance In an era of model theft and supply chain attacks, proving where a model came from matters. The Merkle chain provides cryptographic attestation of model lineage. ## The Certifiable Pipeline `certifiable-training` is part of a complete deterministic ML pipeline: | Project | Purpose | |---------|---------| | [certifiable-data](https://github.com/SpeyTech/certifiable-data) | Deterministic data loading, shuffling, augmentation | | **certifiable-training** | Deterministic training with Merkle audit | | [certifiable-inference](https://github.com/SpeyTech/certifiable-inference) | Deterministic inference | The chain is complete: deterministic data → deterministic training → deterministic inference. End-to-end reproducibility. ## Getting Started ```bash git clone https://github.com/SpeyTech/certifiable-training cd certifiable-training mkdir build && cd build cmake .. make make test ``` Expected output: ``` 100% tests passed, 0 tests failed out of 10 Total Test time (real) = 0.04 sec ``` ## Documentation - **CT-MATH-001.md** — Mathematical foundations - **CT-STRUCT-001.md** — Data structure specifications - **docs/requirements/** — SRS documents with full traceability --- *Training as a pure function. Merkle-chained proof. GPL-3.0 licensed.* --- # Technical Articles — Insights Technical articles on deterministic systems, formal methods, and safety certification. ## One IP, Six Crawler Identities, One Second: Detection Built Against Real Production Logs **URL**: https://speytech.com/insights/rotational-bot-identity-detection/ **Published**: May 17, 2026 **Topic**: Operational Security **Answers**: How do you detect a single attacker IP claiming multiple trusted crawler identities while probing security-sensitive paths in nginx access logs, and what failure modes does the detector itself ship with that only production observation surfaces after the synthetic test suite has already passed? **Defines**: Rotational bot-identity spoofing KEY_CLAIMS: - Rotational bot-identity spoofing is an attacker pattern where one source IP issues requests under multiple named-bot user agents within a short time window. - Rotational bot-identity spoofing is an attacker pattern where a single source IP issues requests under multiple distinct named-bot user agents within a short time window. - Rotational bot-identity spoofing is detectable by combining four conditions on a single source IP within a short time window. - User-agent allowlists cannot catch rotational spoofing because the attack works by claiming valid identities, not by using exotic user-agent strings. - Log-based detection sees only the requests that actually reached the server, not the ones blocked upstream or targeted elsewhere. EVIDENCE: - The pattern was caught in raw form on the axilog.io seo log on 16 May 2026. - Legitimate named-bot traffic on legitimate paths from the same IP is untouched. v1.10.0 shipped on 16 May 2026 with twenty-three tests, all green. RELATES_TO: - insights/operational-seo-observability How three production patches in 24 hours closed two leaks that synthetic testing missed Rotational bot-identity spoofing is an attacker pattern where one source IP issues requests under multiple named-bot user agents within a short time window. On 16 May 2026 the axilog.io access log captured the pattern cleanly: source IP `5.255.104.83` issuing thirteen requests in one second under six distinct named-bot identities — ClaudeBot, GPTBot, PerplexityBot, YandexBot, Baiduspider, and bingbot — across `/api/env`, `/actuator/env`, `/api/config`, `/config.json`, `/secrets.json`, `/appsettings.json`, and the canonical-form variants of the same paths with trailing slashes. No published crawler operates under multiple identities from a single egress IP. The combination is unambiguous. This article describes the pattern, the four-part discriminator used to detect it, and the three-patch sequence in which the v1.10.0 detector shipped, then revealed two false-positive failure modes against the production log within the same day, then closed both in v1.10.1 and v1.10.2. The empirical claims are traceable: the nginx access log line excerpt is reproducible from any host running the attack, the analyser is open source under AGPL-3.0-or-later, and every fix described below corresponds to a tagged release with its own test suite. By William Murray, Founder of SpeyTech — deterministic computing for safety-critical systems. Inverness, Scottish Highlands. Definition: Rotational bot-identity spoofing Rotational bot-identity spoofing is an attacker pattern where a single source IP issues requests under multiple distinct named-bot user agents within a short time window. ## What the production log captured The pattern was caught in raw form on the axilog.io seo log on 16 May 2026. The lines below are real production capture, abbreviated only in the user-agent column where the recognisable bot identifier is sufficient. Timestamps, IP, paths, and status codes are intact: ``` 5.255.104.83 [16/May/2026:15:54:14] "GET /" 200 "ClaudeBot/1.0..." 5.255.104.83 [16/May/2026:15:54:14] "GET /robots.txt" 200 "YandexBot/3.0..." 5.255.104.83 [16/May/2026:15:54:14] "GET /config.json" 404 "YandexBot/3.0..." 5.255.104.83 [16/May/2026:15:54:14] "GET /actuator/env" 301 "PerplexityBot/1.0..." 5.255.104.83 [16/May/2026:15:54:14] "GET /api/env" 301 "ClaudeBot/1.0..." 5.255.104.83 [16/May/2026:15:54:14] "GET /appsettings.json" 404 "YandexBot/3.0..." 5.255.104.83 [16/May/2026:15:54:14] "GET /api/config" 301 "Baiduspider/2.0..." 5.255.104.83 [16/May/2026:15:54:14] "GET /sitemap.xml" 301 "GPTBot/1.3..." 5.255.104.83 [16/May/2026:15:54:14] "GET /secrets.json" 404 "bingbot/2.0..." 5.255.104.83 [16/May/2026:15:54:14] "GET /api/env/" 404 "ClaudeBot/1.0..." 5.255.104.83 [16/May/2026:15:54:14] "GET /actuator/env/" 404 "PerplexityBot/1.0..." 5.255.104.83 [16/May/2026:15:54:14] "GET /api/config/" 404 "Baiduspider/2.0..." 5.255.104.83 [16/May/2026:15:54:14] "GET /sitemap-index.xml" 200 "GPTBot/1.3..." ``` Thirteen requests, one source IP, one second, six distinct named-bot identities. Four 301 redirects — three from nginx normalising `/api/env`, `/actuator/env`, and `/api/config` onto trailing-slash canonical forms that then 404, plus one content-route redirect from `/sitemap.xml` to `/sitemap-index.xml` that the attacker followed to a 200 on row 13. Six 404 probe failures. Three 2xx exploratory fetches. The 2xx requests under multiple identities serve a different purpose to the 404 probes: they fingerprint what an unknown server returns to each named bot before the targeted probes begin. A reader running the analyser against this log will see the rotation section report five identities, not six. The path-class gate excludes the two GPTBot rows, because `/sitemap.xml` and `/sitemap-index.xml` are not in `ROTATION_TRIGGER_PATHS` and are not in the security-probe regex set. This is the gate doing its job: the same source IP issuing legitimate sitemap fetches under a verifiable public crawler stays attributed to GPTBot in the report, while its rotation-probe traffic under five other identities gets reclassified as `SuspectedBotIdentityRotation`. The discriminator is the combination of conditions, not any single one of them. The attacker IP `5.255.104.83` is already publicly known through its probe campaigns against thousands of hosts. The paths probed are commodity exploit fingerprints. Nothing about either is sensitive. What matters is the *combination* visible in the log: one IP, multiple trusted-crawler identities, security-sensitive paths, sub-minute window. That combination is the signal. ## Why naive detection approaches do not catch this Three obvious detection approaches each fail in their own way. An **IP blocklist** is reactive and lags the threat — the same toolkit appears tomorrow from a different /24, and blocklists never catch up. A **user-agent blocklist** is structurally wrong here, because the entire premise of the attack is that the user-agent strings *are* valid — blocking the Googlebot user-agent string blocks Googlebot. Verifying a claimed crawler identity properly requires reverse-DNS lookups, which are too slow for log-time classification and only validate Googlebot in practice. A **404-rate detector** sees the rotation entries as a content-404 burst inside a one-minute window, which fires the deploy-window anomaly detector with a false positive that looks like a real symptom — which is exactly what happened in production on the first deployment. The signal that holds is the *combination* of four conditions: one source IP, multiple distinct named-bot identities, a short time window, and at least one path in a security-sensitive class. Each condition individually is benign. Two real crawlers can share a datacentre egress IP; two distinct named bots in one log is not suspicious. A single bot probing `/api/env` once is not suspicious either. The combination of all four is. The v1.10 detector implements this as a stateful post-aggregation override. The `detect_rotation_indices()` function walks a per-IP identity log and returns indices that participate in any sliding window containing at least three distinct identities, bounded by a configurable `--rotation-window-minutes` value (default 5). The algorithm is O(N²) per IP in the worst case, bounded by a per-IP entry cap of 100. The reclassification then re-attributes counters from the named-bot buckets to a synthetic `SuspectedBotIdentityRotation` row, leaving the legitimate crawler statistics untouched. Rotation-detection is signal *plus* path-class gate. A request only reclassifies if its path is in `ROTATION_TRIGGER_PATHS` (`/api/env`, `/actuator/env`, `/config.json`, and so on — nineteen entries) or matches the existing security-probe regex set. Legitimate named-bot traffic on legitimate paths from the same IP is untouched. ## What synthetic testing missed and production revealed ### Synthetic verification before the first deployment v1.10.0 shipped on 16 May 2026 with twenty-three tests, all green. The suite included an end-to-end check against a synthetic fourteen-line fixture reproducing the `5.255.104.83` pattern: one IP, multiple identities, probe paths, sub-minute window. The override reclassified everything correctly. The synthetic verification was thorough by every measure available before deployment. ### Two leaks visible on the first production run Then the first production run against the real axilog.io seo log surfaced two leaks immediately. **Leak one: trailing-slash variants.** The override caught `/api/env` (in `ROTATION_TRIGGER_PATHS`) but missed `/api/env/`. The attacker's first request to each path hit the no-slash form, which nginx redirected (301) to the canonical-form `/api/env/`, which then 404'd. Both forms entered the log under the same source IP and the same rotation burst, but only the no-slash form matched the exact-string set lookup. The trailing-slash 404s remained attributed to ClaudeBot and Baiduspider in the *Crawler-Visible 404s* section, exactly as if they were real crawler failures. **Leak two: stale burst counters.** The deploy-window anomaly detector tracks content-404s in one-minute buckets. The aggregation pass populated those buckets during initial classification, when the rotation entries were still attributed to named bots. The post-aggregation override then re-attributed them to `SuspectedBotIdentityRotation`, but did not decrement the bucket counters. The result: a `[HIGH] Content-404 burst: 5 404s` finding for the rotation minute, fired by traffic that had already been reattributed and should no longer have contributed to the burst signal. ### v1.10.1: trailing-slash normalisation and burst-counter decrement v1.10.1 shipped within an hour. Two fixes. The first normalised a single trailing slash in `is_rotation_trigger_path()` before the set lookup, with a `len > 1` guard to prevent root-path collapse and a query-string strip to match the analyser's existing `clean_path` convention. The second extended `apply_rotation_override()` to decrement `minute_404s` and `minute_content_404s` for any rotation entry that originally contributed to them, with gating conditions that mirror the aggregation increment gate exactly. Eleven new tests including a regression guard that proves probe-matched rotation entries (which never entered the burst counter in the first place) do not double-decrement on their way out. ### v1.10.2: redirect-counter migration and the consistency invariant The second production run confirmed both fixes. But the *Redirect Analysis* section now showed three distinct named-bot rows — Baiduspider, ClaudeBot, PerplexityBot, each with one redirect — while the *Status Code Breakdown By Bot* correctly unified the same three 301s under `SuspectedBotIdentityRotation`. The two views disagreed. The override had migrated `bot_status`, `bot_urls`, `bot_url_status`, `bot_ips`, `special_files`, `crawler_404s`, and the Googlebot-specific caches. It had not migrated `redirects` or `redirect_attribution`. Another leak in the same family of mistake: a counter populated at aggregation time, not migrated by the override. v1.10.2 shipped twenty minutes later. The 3xx rotation entries now migrate `agg.redirects` and `agg.redirect_attribution` alongside the other counters. Five more tests. One of them is the consistency invariant in test form: after the override runs, the total 3xx count in `bot_status[ROTATION_DETECTION_NAME]` must equal the sum of `redirects[ROTATION_DETECTION_NAME]` across all paths. v1.10.0 violated it silently. v1.10.1 violated it silently. v1.10.2 holds it as a test that will fail loudly if any future override forgets to migrate a counter. ### What the synthetic test fixture missed The fixture reproduced the *shape* of the attack — one IP, multiple identities, probe paths, short window. The override caught it. What the fixture did not contain was two properties of the real attack as it actually appears in nginx: that nginx redirects no-slash forms to canonical-form slash variants before serving 404s, and that the attacker's first probe of each path hits both forms. The test fixture was constructed with the same mental model that produced the override. Production was the only place that mental model met an adversarial environment it had not been built against. Synthetic tests verify the algorithm. Production observation verifies the algorithm meets the system. Both passes are necessary. The work done before deployment caught everything that had been imagined; the work done after deployment caught what had not. ## Three properties that earned the right to ship The analyser runs in cron against speytech.com daily and against axilog.io on demand. A feature that broke output on the common case (no rotation traffic) would be a regression in everyone's pipeline. Three properties of the v1.10 design protected against that, and each maps to a specific failure mode it prevents. **Byte-identical output for the no-rotation case.** The override only fires when at least three distinct named-bot identities appear from one IP inside the configured window, against trigger paths. On a clean log — speytech.com today, 1,178 lines, no rotation traffic — the override never activates. Verified with `diff` between v1.9.1 and v1.10.2 on the same input: zero differences in text, zero differences in JSON. The failure mode this prevents is cosmetic drift in routine reports being treated as a substantive change by operators who monitor the output for actual change. **Conditional JSON keys, not null placeholders.** The `rotational_bot_identity` top-level key is emitted only when rotation is detected — not as `null`, not as `{}`, simply absent. Downstream JSON consumers that look for the key on the days it matters get structured data; consumers that have never seen the key get identical output on every other day. The failure mode this prevents is schema-stability anxiety: a consumer treating the appearance of a new key on a quiet day as a schema migration to handle. **Test-driven counter consistency.** The internal invariant — that Status Code Breakdown and Redirect Analysis must agree on rotation attribution after the override runs — is now a property a test enforces, not a property the implementer remembers to maintain. v1.10.0 and v1.10.1 both violated it silently. The cost of v1.10.0 → .1 → .2 was three iterations. The cost of v1.11 forgetting to migrate counter X will be zero, because the test catches it before the commit. The failure mode this prevents is the same gap that produced the v1.10.2 patch in the first place: a counter migrated correctly in one place, forgotten in another, and the disagreement only visible against real production output. ## Cross-reference: the broader operational case The detector described here is one capability inside a tool whose origin is documented separately. The original purpose was deploy-window 404 detection on a static Astro site, which then revealed a much larger chronic crawl-rate suppression — both covered in the [operational SEO observability case](/insights/operational-seo-observability/) for speytech.com. The rotation detector is the v1.10 addition to the same tool; the two stories share the analyser and the access logs but solve different problems. ## Frequently Asked Questions ### What is rotational bot-identity spoofing? Rotational bot-identity spoofing is an attacker pattern where a single source IP issues requests under multiple distinct named-bot user agents within a short time window. The attack tests whether a server treats trusted-crawler user-agents differently — by exempting them from rate limits, returning verbose errors, or relaxing security headers. Real published crawlers do not operate under multiple identities from a single egress IP, so the pattern is unambiguous when observed in raw access logs. ### How do I detect rotational bot-identity spoofing in nginx access logs? Rotational bot-identity spoofing is detectable by combining four conditions on a single source IP within a short time window. The four are: multiple distinct named-bot identities, a short window holding them all, at least one security-sensitive path, and the trusted-crawler character of the identities claimed. Each condition individually is benign; the combination is the signal. A practical implementation walks a per-IP identity log and reclassifies entries that fall inside any window meeting all four conditions, leaving legitimate crawler statistics untouched. ### Why don't user-agent allowlists catch rotational spoofing? User-agent allowlists cannot catch rotational spoofing because the attack works *by claiming valid identities*, not by using exotic user-agent strings. Blocking the Googlebot user-agent string blocks Googlebot. Verifying a claimed crawler identity properly requires reverse-DNS lookups, which are too slow for log-time classification and only validate Googlebot reliably in practice. The detection signal has to come from request behaviour, not from the user-agent string in isolation. ### What are the limitations of log-based rotational spoofing detection? Log-based detection sees only the requests that actually reached the server, not the ones blocked upstream or targeted elsewhere. A determined attacker can defeat the per-IP signal by rotating source IPs alongside identities, though doing so loses the operational advantage the original attack was testing for. The minimum-identities threshold is a tunable — too low and shared datacentre egress for two real crawlers can false-positive; too high and slower-paced campaigns slip past the window. The detector surfaces patterns upstream security controls did not catch; it does not replace them. ## Closing Rotational bot-identity spoofing is detectable in nginx access logs through a stateful per-IP identity-counting algorithm that combines four discriminating conditions against a configurable time window. The trade-off is that the detector itself must verify against live production traffic — synthetic tests reproduce the attack signature but not the structural behaviour of the system being attacked. As with any architectural approach, suitability depends on system requirements, risk classification, and regulatory context. The analyser is open source under AGPL-3.0-or-later at [github.com/SpeyTech/crawler-log-analyser](https://github.com/SpeyTech/crawler-log-analyser). The v1.10.2 tag corresponds to every claim in this article; the changelog records the three-patch sequence in the order it happened. Hope this helps. — William --- ## SEO Validator: A Deploy Gate for SEO Regressions **URL**: https://speytech.com/insights/seo-validator-deploy-gate/ **Published**: May 14, 2026 **Topic**: DevOps **Answers**: How can SEO regression testing be integrated as a deploy gate that automatically rolls back broken builds, and why does an SEO validator that reads nginx configuration files catch redirect and asset failures that traditional URL-list-based SEO audit tools miss? **Defines**: Deploy-gate SEO validation KEY_CLAIMS: - Deploy-gate SEO validation runs an SEO audit inside the build pipeline, with a non-zero exit code blocking release and triggering rollback to the previous build. - Run the validator after your atomic deploy step inside `build.sh`, using `if ! - A periodic SEO crawler runs after deploy and reports tomorrow. - An nginx-config-driven audit catches broken redirect targets, missing 410 Gone responses, and orphan image assets: failures that exist outside the sitemap and link graph. - A deploy gate covers regression prevention at release time but not historical trend analysis, competitor tracking, backlink graphs, or content scoring. EVIDENCE: - The speytech.com run on 14 May 2026 reported: The `/home-temp/ -> 410` line shows the validator handling 410 Gone correctly. RELATES_TO: - insights/operational-seo-observability How an SEO audit that reads your nginx config can catch broken redirects before they reach production Deploy-gate SEO validation runs an SEO audit inside the build pipeline, with a non-zero exit code blocking release and triggering rollback to the previous build. The pattern moves SEO from an overnight monitoring concern to a release-blocking check. This article describes the open-source SEO Validator that implements it, the nginx-config-driven audits that make it different from existing tools, and the build.sh wiring that turns it into a true deploy gate. By William Murray, Founder of SpeyTech: deterministic computing for safety-critical systems. Inverness, Scottish Highlands. ## A Failure Mode That Most SEO Tools Cannot Catch Yesterday I renamed five SVG assets on speytech.com to match their article slugs. One example: `cardiocore-litigation.svg` became `implantable-device-litigation.svg`. The new file shipped. The nginx redirect from the old path to the new one shipped too. If I had missed a file-permission step on any of the new assets, the redirect target would have served a 404. The old URL would still have looked correct in any SEO tool that only checked URLs it was given. Googlebot would have found the broken target before I did. Traditional SEO audit tools work by following links from a sitemap or seed URL. They check what the site exposes. They cannot check what the nginx config *promises* to serve, because they have no view into the config. If a redirect target is broken but no page links to it, the audit reports a clean site. The companion problem on the same site is documented in [operational SEO observability](/insights/operational-seo-observability/): a 6.83-Googlebot-requests-per-day baseline that was invisible to Lighthouse, Search Console summaries, and synthetic monitors, but obvious in the nginx access log. The deploy gate prevents regressions before they ship; the log analyser surfaces what shipped behaviour actually looks like once it is live. Both belong in the same operational toolbox. The SEO Validator described here closes that gap. It reads `/etc/nginx/sites-available/` directly, discovers every exact-match redirect rule, and verifies each one resolves to a live target. And it runs inside `build.sh`, not as an overnight job, so a regression fails the build before the change reaches production. ## What Deploy-Gate SEO Validation Means Definition: Deploy-Gate SEO Validation Deploy-gate SEO validation runs an SEO audit inside the build pipeline, with a non-zero exit code blocking release and triggering rollback to the previous build. The distinction matters. Most SEO tools are *inspection* tools: Screaming Frog, Sitebulb, Ahrefs, Semrush. They run on a schedule, produce a report, and surface issues for a human to triage. By the time the human reads the report, the regression has been live for hours. A deploy gate runs at the moment of release. It either passes, and the build goes live, or it fails, and the build does not go live. There is no window between "broken build deployed" and "human notices report tomorrow." The window is closed by design. This article is not arguing that deploy-gate validation replaces inspection tools. Inspection tools cover surface area a deploy gate cannot: historical trend analysis, competitor tracking, backlink graphs, content scoring. The two are complementary. For the specific class of regressions that occur at release time, a deploy gate is the right control. The deploy gate eliminates the gap between regression introduction and detection. ## What the Validator Audits The validator runs 22 audit sections, grouped by concern. The grouping matters more than the individual section count, because each group represents a class of failure with its own detection strategy. **Document integrity (sections 2–8)** covers status codes, title and description lengths, meta robots directives, Open Graph completeness, viewport tags, favicon presence, and heading hierarchy. These are the standard surface-level checks any SEO audit runs. Section 5 additionally verifies every `og:image` URL returns HTTP 200, which catches social-card breakage that pure-HTML audits miss. **Accessibility and canonicalisation (sections 9–11)** covers image alt-text coverage, canonical tag correctness on a random page sample, and a full trailing-slash redirect audit. The trailing-slash audit catches Google Search Console "Alternate page with proper canonical tag" warnings before they appear in GSC, by verifying every URL-without-slash returns a 301 to the URL-with-slash on the same path. **Behavioural correctness (sections 12–17)** covers redirect chain detection, duplicate title and description detection, mixed-content scanning, and soft-404 detection. Sections 16–17 (broken link and orphan page detection) are gated behind `--thorough` because they are crawl-intensive; the default mode skips them. **Infrastructure discoverability (sections 18–19)** verifies that `robots.txt`, `llms.txt`, `llms-full.txt`, and the JSON-LD schema blocks resolve and parse. The llms.txt checks are AEO-specific; not every audit tool covers them. **Nginx-config-driven verification (sections 20–22)** is the differentiator. Section 20 audits image-asset redirects discovered from the nginx config. Section 21 verifies the full redirect set, including 410 Gone rules. Section 22 audits for orphan image assets: SVG files that exist in the dist tree but no page references and no redirect points at. The 22 sections produce structured terminal output with exit-code-driven success or failure. Every section that catches a regression flags it and contributes to a non-zero exit code. ## How the Validator Plugs Into build.sh The validator is wired into the speytech.com deploy pipeline as a post-swap gate. The relevant shape of `build.sh`: ```bash #!/bin/bash set -e trap 'echo "Build interrupted"; exit 1' INT TERM # 1. Content-level checks against markdown source node scripts/aeo_lint.js || exit 1 # 2. Build into a staging directory + static search index rm -rf dist.new .astro npx astro build --outDir ./dist.new npx pagefind --site dist.new # 3. Fix ownership on the staged build sudo chown -R www-data:www-data dist.new # 4. Atomic swap: dist.new becomes the live tree in one rename(2) call if [ -d dist ]; then sudo mv dist dist.old fi sudo mv dist.new dist # 5. Deploy-gate SEO validation against the now-live site if ! python3 scripts/seo_validator.py --domain speytech.com; then echo "Validation failed. Rolling back." if [ -d dist.old ]; then sudo mv dist dist.failed sudo mv dist.old dist exit 1 fi exit 1 fi # 6. Success path sudo python3 scripts/notify_indexnow.py || true sudo rm -rf dist.old & git add -A git commit -m "Build: $(date '+%Y-%m-%d %H:%M')" || echo "Nothing to commit" git push ``` Three details in that flow matter. First, the atomic swap is a single `rename(2)` syscall on the same filesystem. `mv` of a directory over another existing directory on the same filesystem translates to one `rename(2)` call: instantaneous, with no intermediate state visible to nginx. Requests in flight either complete against the old `dist` or land on the new one. There is no window where the live tree is missing, partial, or half-permitted. The earlier pattern of `rm -rf dist && npm run build` leaves `dist` empty for 30 seconds to two minutes, which is long enough for Googlebot to hit a 404 on `robots.txt` and back off crawling for days. The atomic swap closes that window. Second, the validator is invoked as `if ! python3 ...`, which honours its exit code directly. Piping the output through `tee` or `grep` would break this: the pipe consumes the validator's exit status and replaces it with the exit status of the last command in the pipeline. The standard fix is `set -o pipefail` and `${PIPESTATUS[0]}`, but the simpler discipline is to avoid piping a deploy-gate command. To capture both the exit code and the log, write the output to a file and check `$?` separately, or use `PIPESTATUS` explicitly. Third, the IndexNow ping is suffixed with `|| true`. A failure to notify a search engine should not roll back a deploy that has already passed validation. The rollback path is reserved for things that genuinely make the site worse than the previous build; a missed ping is recoverable on the next deploy. Distinguishing recoverable side-effects from validation failures keeps the rollback path narrow and the gate trustworthy. The default invocation runs in sampling mode (a 20-URL subset of trailing-slash and redirect-chain checks) so the gate stays fast on every deploy. Adding `--full` exhaustively checks every URL and is appropriate before a major release or as a nightly cron job rather than on every push. The deploy gate runs after the atomic swap, against the live site, and rolls back on any non-zero exit. ## What Section 20 Does: Image-Asset Redirect Verification Section 20 reads the nginx config, extracts every `location = /images/old.svg { return 301 /images/new.svg; }` rule, fetches each old URL, and verifies the redirect target returns HTTP 200. The rules are extracted with a single regex applied to the config file: ``` location\s*=\s*(\S+)\s*\{\s*return\s+(301|302|303|307|308)\s+(\S+?)\s*;\s*\} ``` The validator pulls source path, status code, and target path. For each rule where the source path has an image extension, it issues a request, follows the redirect, and checks the final response. The output from a recent speytech.com run, after yesterday's image-rename work: ``` === 20. Image-Asset Redirect Audit === Discovered 5 image redirect rule(s) from /etc/nginx/sites-available/speytech.com. Verifying... ✓ /images/cardiocore-litigation.svg -> 301 -> /images/implantable-device-litigation.svg -> 200 ✓ /images/hash-chain-diagram.svg -> 301 -> /images/cryptographic-proof-execution.svg -> 200 ✓ /images/mycoeco-architecture.svg -> 301 -> /images/mycoeco-kernel.svg -> 200 ✓ /images/nvidia-asil-comparison.svg -> 301 -> /images/nvidia-asil-determinism.svg -> 200 ✓ /images/semantic-security-hero.svg -> 301 -> /images/semantic-security-monitoring.svg -> 200 Image-asset redirect summary: 0 issues found ``` **Without section 20:** five rename operations require five hand-tested URLs after deploy. Either the operator forgets one, or the test is shallow (HEAD only, no status check on the redirected target). The failure mode is silent: Googlebot finds the broken target before the operator does. **With section 20:** every rule is verified empirically on every deploy. The discipline is automatic rather than manual. ## What Section 21 Does: Full Redirect Set Verification Section 21 generalises section 20 to every exact-match redirect in the nginx config, not just image redirects. Path consolidations, RSS feed redirects, sitemap aliases, and 410 Gone rules are all verified together. The speytech.com run on 14 May 2026 reported: ``` === 21. Redirect Set Verification === Discovered 17 exact-match redirect rule(s) from /etc/nginx/sites-available/speytech.com. Verifying... ✓ /contact-us/ -> 301 -> /contact/ -> 200 ✓ /data-policy/ -> 301 -> /privacy/ -> 200 ✓ /mdcp-vs-alternatives/ -> 301 -> /insights/mdcp-vs-conventional-rtos/ -> 200 ✓ /sitemap.xml -> 301 -> /sitemap-index.xml -> 200 ✓ /feed/ -> 301 -> /rss.xml -> 200 ✓ /feed -> 301 -> /rss.xml -> 200 ✓ /rss/ -> 301 -> /rss.xml -> 200 ✓ /atom/ -> 301 -> /rss.xml -> 200 ✓ /atom.xml -> 301 -> /rss.xml -> 200 ✓ /index.xml -> 301 -> /rss.xml -> 200 ✓ /home-temp/ -> 410 ... (rules omitted for brevity) Redirect set summary: 0 issues found ``` The `/home-temp/ -> 410` line shows the validator handling 410 Gone correctly. A 410 response is a deliberate "this resource is permanently removed" signal, different from 404 which means "we have no idea." Search engines treat the two differently for crawl-budget allocation. A misconfigured 410 rule that accidentally returns 404 (because the `return 410;` directive was removed during a config edit) would degrade indexing quietly. Section 21 catches that. Section 21 verifies every exact-match redirect resolves correctly, including 410 Gone responses for deliberately deleted paths. ## What Section 22 Does: Orphan Image Detection Section 22 walks the dist tree under each configured image directory (default `images/` and `og/`), collects every image file on disk, then builds a reference set from rendered HTML, og:image tags, favicon links, and redirect targets. Files on disk minus files referenced equals the orphan set. ``` === 22. Orphan Image Audit === Walked dist/images/ (66 assets), dist/og/ (70 assets). 136 image asset(s) total, 136 referenced from rendered HTML, og:image tags, favicon links, or redirect targets. Orphan image summary: 0 issues found ``` Orphan detection surfaces two different kinds of finding. The first is dead weight: assets generated for an article that was later removed, or experimental SVGs left behind during design iteration. These cost deploy time and bandwidth but do not cause user-visible failures. The second is more valuable: assets created for an article whose markdown does not yet reference them. A hero SVG sitting orphaned in `dist/images/` often means the matching article is missing its `` tag, an operational signal that something was forgotten during writing. On an earlier speytech.com run, section 22 surfaced six SVG files that no article referenced. Investigation showed they were intended-but-unwired hero images for articles still in draft. Adding the references was a small content improvement; without the audit, the omissions would have stayed invisible. Section 22 turns "an asset exists on disk" into "an asset exists on disk and is reachable from somewhere a crawler will see." ## Why Pipe-Based Logging Breaks the Gate The deploy-gate pattern depends on the validator's exit code propagating into `build.sh`. A common mistake is to pipe the validator output to `tee` or `grep`: ```bash # WRONG: exit code is replaced by tee's exit code python3 scripts/seo_validator.py --domain x.com --full | tee validator.log # WRONG: exit code is replaced by grep's exit code python3 scripts/seo_validator.py --domain x.com --full | grep -v "^\\s*$" ``` Both forms appear to "work" because the output looks right. They silently break the gate. `tee` returns 0 on a successful write regardless of what its stdin produced; `grep` returns 0 if it matched at least one line. The validator's non-zero exit on failure is discarded. The correct shapes: ```bash # Direct invocation: exit code propagates cleanly if ! python3 scripts/seo_validator.py --domain x.com --full; then rollback fi # Log to file and check exit code separately python3 scripts/seo_validator.py --domain x.com --full > validator.log 2>&1 status=$? cat validator.log if [ "$status" -ne 0 ]; then rollback fi # Pipe + PIPESTATUS (works but easy to forget) set -o pipefail python3 scripts/seo_validator.py --domain x.com --full | tee validator.log if [ "${PIPESTATUS[0]}" -ne 0 ]; then rollback fi ``` Test the failure path before trusting the gate. Move a redirect target out of the way temporarily, run a deploy, and confirm the build fails and `dist.old` is restored. A gate that has only ever seen the success path is not a gate. ## How Deploy-Gate Validation Compares to Inspection Tools Inspection Tools (Screaming Frog, Sitebulb, Ahrefs) Run on a schedule (overnight or weekly) Produce reports for human triage Check URLs they discover by following links Cover historical trends, backlinks, competitors Cannot see the nginx config Cannot block a release Deploy-Gate Validator (SpeyTech SEO Validator) Runs at deploy time, inside build.sh Exit code drives automatic rollback Checks URLs nginx config promises to serve Focused on regression prevention, not historical analysis Parses /etc/nginx/sites-available/ directly Blocks broken builds before they go live The two tool categories solve different problems. Inspection tools answer "what is the current state of my SEO surface?": a question that benefits from breadth, history, and external data sources. Deploy gates answer "did this specific change introduce a regression?": a question that benefits from speed, narrowness, and exit-code propagation. Suggesting the validator as a replacement for Ahrefs or Sitebulb misunderstands what it is for. It is a focused tool that closes a specific control gap in CI/CD pipelines, not a comprehensive SEO platform. A deploy gate and an inspection tool address different points on the regression-detection timeline. ## What the Validator Deliberately Is Not The validator's restraint is part of the design. Several capabilities are intentionally absent. **Not a crawler.** The validator uses the site's sitemap as the source of truth for URL discovery, not link-following from a seed URL. This is faster and produces deterministic runs (every build audits the same URLs) but it will not catch pages that exist on the server but are not in the sitemap. If sitemap completeness is suspect, a crawl-based tool covers that gap. **Not a performance auditor.** No Lighthouse score, no Core Web Vitals, no resource-size analysis, no JavaScript-execution profiling. Performance is a different tool category with different latency and infrastructure requirements; folding it into a deploy gate would slow every release without serving the gate's purpose. **Not a content auditor.** No readability scoring, no keyword density, no semantic analysis. On speytech.com, content concerns are handled by a separate AEO lint that runs earlier in `build.sh` against the markdown source files, not against rendered HTML. Separating content audits from rendered-site audits keeps each tool's responsibility clear. **Not a SaaS.** The validator runs locally as part of CI/build. No web UI, no API, no dashboards, no hosted service. Output is structured text suitable for both human reading and exit-code-driven automation. The decision to ship as a Python script under MIT rather than a SaaS product was deliberate: deploy gates belong inside the pipeline, not behind an API call to someone else's infrastructure. ## Frequently Asked Questions ### What is deploy-gate SEO validation? Deploy-gate SEO validation runs an SEO audit inside the build pipeline, with a non-zero exit code blocking release and triggering rollback to the previous build. The pattern moves SEO from an overnight monitoring concern to a release-blocking check. It complements rather than replaces inspection tools. ### How do I integrate the validator into my build pipeline? Run the validator after your atomic deploy step inside `build.sh`, using `if ! python3 seo_validator.py ...` to honour the exit code. On non-zero exit, restore the previous build by renaming `dist.old` back to `dist`. The validator needs the live site to be reachable at the domain you pass; run it after the swap, not before. ### Why doesn't a periodic SEO crawler catch the same regressions? A periodic SEO crawler runs after deploy and reports tomorrow. By then, broken redirects have been live for hours, Googlebot has indexed the bad responses, and the operator is reacting to historical damage rather than preventing it. Deploy-gate validation closes the gap by checking at release time. ### What does an nginx-config-driven audit catch that a sitemap crawl misses? An nginx-config-driven audit catches broken redirect targets, missing 410 Gone responses, and orphan image assets: failures that exist outside the sitemap and link graph. A sitemap crawler only checks URLs the site exposes through its own pages; redirect rules and removed-resource declarations live in the nginx config, invisible to crawlers. ### What are the limitations of using only a deploy gate for SEO? A deploy gate covers regression prevention at release time but not historical trend analysis, competitor tracking, backlink graphs, or content scoring. Inspection tools like Screaming Frog or Sitebulb handle those concerns better. The two tool categories are complementary; treating the gate as a complete SEO programme would leave material surface uncovered. ### How do I avoid silently breaking the gate? Invoke the validator directly in an `if` statement rather than piping its output through `tee` or `grep`. Piping replaces the validator's exit code with the pipe-terminator's exit code, which is almost always zero on a successful write. The validator's non-zero exit on failure is discarded, and the gate becomes a no-op that always passes. ## Try It Yourself The validator is open-source under MIT, the most permissive licence available: an explicit choice to make the tool widely adoptable inside private CI pipelines without licence friction. **Repository:** [github.com/SpeyTech/seo-validator](https://github.com/SpeyTech/seo-validator) **Dependencies:** Python 3.8+, `requests`, `beautifulsoup4`, `lxml` **Quick start:** ```bash git clone https://github.com/SpeyTech/seo-validator cd seo-validator pip install -r requirements.txt ./seo_validator.py --domain example.com --full \ --nginx-config /etc/nginx/sites-available/example.com \ --dist-path /var/www/example.com/dist ``` The `--nginx-config` and `--dist-path` arguments are optional. Without them, sections 20–22 fall back to an inline redirect list and skip the dist walk. With them, the full deploy-gate behaviour activates. Issues, feature suggestions, and pull requests are welcome through GitHub. Particular interest in: extending the nginx-config parser to handle additional rule shapes (regex-match locations, map-based redirects), and adding support for Caddy and Apache config formats. ## Closing Deploy-gate SEO validation closes the regression-detection window from hours-to-days down to zero, by failing the build instead of filing a report. The trade-off is that the gate covers a narrower surface than a full inspection tool. The gate answers "did this change break something?" rather than "what is the current state of my SEO surface?", so the two tool categories should be run together, not interchangeably. As with any architectural approach, suitability depends on system requirements, risk classification, and regulatory context. --- ## Self-Hosted Static Sites Need Operational SEO Observability **URL**: https://speytech.com/insights/operational-seo-observability/ **Published**: May 12, 2026 **Topic**: Operational SEO **Answers**: How do you detect crawler-visible SEO failures on self-hosted static sites when conventional tools like Search Console and Lighthouse cannot see them, and what does the operational recovery actually look like in measured nginx log data when sitemap freshness signals are remediated and the site's Googlebot crawl rate jumps from a 6.83-per-day baseline? **Defines**: Operational SEO observability KEY_CLAIMS: - Update — May 16, 2026: The analyser described here is at v1.3 as published. - Operational SEO observability is the practice of reading live web-server access logs to verify what real search and AI crawlers experienced, rather than inferring it from synthetic audits or stabilised dashboard summaries. - Operational SEO observability is reading live web-server access logs to verify what real crawlers experienced, rather than inferring it from synthetic audits. - Filter by known crawler user-agents (Googlebot, Bingbot, AI crawlers) and look at status codes, request timing, and URL paths. - Lighthouse audits run on demand against a stabilised site, not during the deployment window itself. EVIDENCE: - Update — May 16, 2026: The analyser described here is at v1.3 as published. - Search Console reported an average of 6.83 Googlebot requests per day on speytech.com across the 89 days between February 9 and May 8, 2026. - The Search Console crawl-stats export for the 89 days from February 9 to May 8, 2026 contained 608 total Googlebot requests. - On May 10, 2026, the nginx access log for speytech.com recorded 568 Googlebot requests across the day, restricted to the main Googlebot user-agent (Googlebot-Image excluded). How one open-source nginx log analyser surfaced both an acute crawler failure and a chronic crawl-rate suppression that conventional SEO tooling could not see Update — May 16, 2026: The analyser described here is at v1.3 as published. The repository currently sits at v1.10.2, which adds SuspectedUASpoof behavioural detection, SuspectedBotIdentityRotation for attacker IPs cycling through named-bot identities, framework-fingerprint opacity scoring, a TOML config file, and AI crawler discovery-window classification. The minimum Python is now 3.11. The capabilities described in this article are a strict subset of what is live; the empirical claims and operational pattern are unchanged. The rotation detector and the three-patch sequence that produced v1.10.2 are covered in detail in the follow-up: One IP, Six Crawler Identities, One Second. See the repository README for the current capability set. Search Console reported an average of 6.83 Googlebot requests per day on speytech.com across the 89 days between February 9 and May 8, 2026. Twenty-three of those days saw zero crawl activity at all. The site was passing Lighthouse, the sitemap was submitted, robots.txt was correct. The crawl rate was just quietly low. On May 10, the same site received 568 Googlebot requests in a single day. That is 93.4% of the entire preceding three-month total of 608 requests. Lighthouse was unchanged. The sitemap location was unchanged. The robots.txt was unchanged. What changed was a small set of operational fixes that the conventional SEO tooling had no way to surface, because the conventional SEO tooling does not look at nginx access logs. This article describes what the gap looks like in measured data, why standard SEO tooling cannot see it, what closing it required, and the open-source tool that made the diagnosis possible. The empirical claims are traceable: the Search Console crawl-stats export is reproducible, the nginx logs are timestamped, and the analyser used to read them is publicly available under AGPL-3.0-or-later. Operational SEO concerns the runtime behaviour crawlers actually experience, not just the static correctness of pages at rest. Definition: Operational SEO observability Operational SEO observability is the practice of reading live web-server access logs to verify what real search and AI crawlers experienced, rather than inferring it from synthetic audits or stabilised dashboard summaries. ## What the data shows The Search Console crawl-stats export for the 89 days from February 9 to May 8, 2026 contained 608 total Googlebot requests. That distributes as a mean of 6.83 requests per day, a median of 4, a peak of 30 (on April 26), and 23 days with zero activity. Nearly a quarter of the period saw no Googlebot crawling at all. On May 10, 2026, the nginx access log for speytech.com recorded 568 Googlebot requests across the day, restricted to the main Googlebot user-agent (Googlebot-Image excluded). The activity was not spread evenly. It clustered in two distinct passes: - Pass 1: 16:10 to 16:11 UTC, 142 requests, two minutes. - Pass 2: 20:26 to 20:40 UTC, 426 requests, roughly fourteen minutes. The first pass started seven hours after a build that added per-URL `` timestamps to the sitemap. The second pass started within one minute of a further build which refreshed the `` values again. Pass 1 reads as the initial response to a freshness signal Google had not seen before; pass 2 reads as a follow-up triggered by the same signal advancing. The same May 10 produced 100/100/100/100 Lighthouse scores on both mobile (emulated Moto G Power, Slow 4G throttling, Lighthouse 13.0.1) and desktop, captured at 22:39 UTC. The scores were the same before the crawl burst as after. Lighthouse measures page quality and conformance to documented SEO checks; it does not measure whether Googlebot is actually fetching the page. Those are two different questions, and the second one is the operational one. The sequence is suggestive of causation but not directly observable. The sitemap freshness signal was the input, and the burst was the output. Google's scheduler made some decision between them. This is observed correlation consistent with Google's documented use of sitemap signals, not directly observed causation. ## The failure mode the tool was originally built to detect The tool that produced the May 10 measurement was not built for sitemap diagnosis. It was built earlier this year, in response to a different and more acute problem: transient Googlebot 404s during atomic deployment windows on a static Astro site. The mechanism is structural. A site deployed via rsync, symlink swap, or atomic-rename strategies appears atomic at the directory level but is not atomic at the per-request level. A crawler request that begins reading file paths during the swap window can observe an inconsistent state: the new build's HTML references new asset hashes, but the asset directory has not been swapped in yet, or vice versa. CDN cache invalidation can fall out of sync with origin file availability. The combination produces transient 404 responses that resolve themselves within seconds, but only after the crawler has logged the failure. Synthetic monitoring misses this entirely. A monitoring agent that polls the site every five minutes is overwhelmingly likely to poll outside the swap window and see a clean 200. Lighthouse audits are run on demand and are not in flight during deploys. Search Console reports daily aggregates that smooth bursts into averages. The failure mode is invisible to every observational tool except the one that captures every actual request: the web server's own access log. The acute incident produced a clear signature in the logs: a tight cluster of Googlebot 404 responses, all within the same two-minute window, all on URLs that were known to exist before and after the window. That signature has a name in the analyser's output now (deploy-window anomaly), but at the time of the original investigation it had no name and no tool. There was just the raw log and the question "is this a thing that is happening, or am I imagining it." ## The first investigation The first instinct was to write a one-shot awk script. That instinct lasted approximately one hour. Real production nginx logs contain a category of traffic that swamps any naive grep: security probes. A substantial fraction of the lines in a typical day on speytech.com are WordPress probe attempts, PHP exploit fingerprinting, `.env` scans, `phpmyadmin` discovery, and similar background noise. Filtering this out is straightforward conceptually but tedious in practice, and any analysis that does not filter it cleanly drowns the actual SEO signal. The second instinct was to look for an off-the-shelf tool. The category of "log analyser for SEO" exists, but everything in it is either commercial SaaS that expects log shipping to a third-party service, general-purpose log management software with no SEO-specific classification, or hand-rolled awk scripts in blog posts that do not handle the messy realities of production logs (HTTP/2 requests, IPv6 source addresses, binary noise in URLs from probe traffic, gzip-rotated history). The diagnostic question was specific enough to require its own tool: "did Googlebot receive any 404s in the time window around my deploy, and if so, on which URLs, and at what rate, and how does it compare to the surrounding hours of crawl activity." That question is not naturally answered by log management software. It needs an analyser that knows what Googlebot is, what a deploy window looks like, and what to ignore. ## Building the analyser The design discipline was constrained from the start. Single-file Python, standard library only, runs on any nginx host that has Python 3.8 or later, no telemetry, no dashboards, no SaaS dependencies, no database. The output formats are plain text, markdown, and JSON, intended for terminal viewing, file-based reporting, and machine consumption respectively. The licence is AGPL-3.0-or-later, which permits commercial and internal use while keeping any networked modifications open. Three iteration rounds against real production data shaped the analyser. The first round handled the parser tolerance problem. Real production nginx logs contain malformed probes, HTTP/2 requests, IPv6 traffic, binary URL payloads, and crawler behaviours that textbook combined-log parsers do not tolerate cleanly. The naive regex for the combined log format rejected approximately 41% of real production lines. The fix was a two-stage parser: a permissive skeleton regex extracts structural fields without imposing assumptions on the request line, and the request line is parsed separately with fallback behaviour for anything unusual. The second round handled the probe-suppression problem. Once parsing was tolerant, the volume of probe traffic became visible: hundreds of `.php` requests, exploit fingerprints, `.env` scans, framework-manifest discovery. Including this in the 404 report drowned the actual signal. Excluding it required two separate detectors (security probes proper, and framework fingerprint probes like `/_next/`, `/_nuxt/`, `webpack-stats.json`), each summarised in its own section so that operators could see what was being filtered without it polluting SEO conclusions. The third round added the deploy-window anomaly detector that was the original purpose. The detector watches three signals at one-minute resolution: robots.txt failures from any crawler, content-404 bursts (five or more within two minutes, excluding probe and framework traffic), and Googlebot 404 events followed by a crawl gap of two hours or more. Each signal is tiered by severity based on which bot family is affected. A Googlebot robots.txt failure is CRITICAL. The same failure from an AI crawler is a WARNING. The same failure from a generic bot is INFO. The tiering matches the operational reality: Google's reaction to a robots.txt failure is the one that meaningfully suppresses crawling. A fourth and more recent round, released as v1.3 the same week as this article, added support for nginx's extended `seo_crawl` log format with `$host`, `$scheme`, `$request_time`, and `$upstream_response_time`. This enables concrete redirect attribution (`HTTP→HTTPS` vs `www→apex` vs trailing-slash, with the configuration-bug case flagged when a request was already on the canonical host and scheme) and per-request latency analysis. The standard combined format remains fully supported, and output for combined-format inputs is byte-identical to v1.2. The format is auto-detected per file. The Googlebot health score is the analyser's summary metric, a 0–100 number with explicit deduction reasons. The deduction logic is auditable: a 404 rate over 1% deducts 10 points, any 5xx response deducts 15, robots.txt failures deduct 25, and so on, with each deduction visible in the report. The score is not a magic number; it is an arithmetic summary of observable facts. The v1.3 release added a latency-based deduction when seo_crawl data is present and Googlebot's p95 response time exceeds the Search Console "Average response time" warning threshold. Crawl health is now expressible as a single integer the operator can monitor without staring at the underlying log. The output of a healthy daily run looks like this: ``` Deploy-Window Anomaly Detection ─────────────────────────────── No deploy-window symptoms detected. ✓ Checks performed: - robots.txt 404/5xx for any crawler - content-404 bursts (≥5 within 2 minutes) - Googlebot 404 followed by >2h crawl gap Googlebot Crawl Health Score ──────────────────────────── Score: 100/100 Verdict: Excellent No deductions applied. ``` The format is deliberately readable in a terminal without any rendering. The same content is available as markdown or JSON via `--format` for downstream tooling. ## The chronic finding The analyser was built to detect the acute incident. Once it was built and running over historical logs, it surfaced a second and unanticipated finding. The acute deploy-window 404s had stopped. The atomic deploy fix had worked. But the analyser's daily reports kept showing Googlebot activity well below what the site's content volume would suggest. Forty articles published, multiple sitemaps, full structured data, sensible internal linking, conformant robots.txt, and Googlebot was visiting at a rate of fewer than seven requests per day with nearly a quarter of days seeing no visits at all. The acute fix had stopped the bleeding, but the patient was not recovering. The discovery of the chronic state was not the analyser's intended purpose. It was a side effect of having continuous visibility into crawler behaviour. Without the tool, the suppressed crawl rate was visible only in Search Console's smoothed daily averages, which read like a baseline rather than like a symptom. With the tool, the per-request granularity made it obvious that "low and steady" was the pathology, not the steady state. The remediation was operational SEO work that any SaaS audit would have flagged but no SaaS audit had pushed to the top of the queue: adding per-URL `` timestamps to the sitemap, fixing a `sitemap.xml` redirect that returned 404 in some cache states, adding a plain-text `sitemap.txt` for crawlers that prefer it, consolidating legacy redirected URLs. The work was done on the morning of May 10. The first major Googlebot recheck pass began at 16:10 UTC the same day. The second, larger pass began at 20:26 UTC. By the end of the day the site had received 568 Googlebot requests. Today's 568-request figure is a burst, not a new steady state. Google's scheduler front-loads recheck activity when a site's freshness signals advance, then settles into a higher steady-state cadence proportional to the new signals. The honest projection from this data is a sustained 7-15x improvement over the previous baseline, which corresponds to roughly 50-100 requests per day; that projection should be checkable in Search Console by late May. The 568-request day shows the ceiling of Google's current interest in the site; the steady state will reveal itself over the coming weeks in Search Console. ## What the tool teaches A tool built to detect one specific failure mode surfaced a second, larger failure mode that no acute fix would have addressed. This is a familiar pattern in operational engineering. Tooling built for an acute issue produces visibility into the chronic conditions that surround it. The acute fix stops the bleeding; the observability reveals what was happening beneath. The pattern generalises beyond SEO. Adding access logs to a web service to debug one incident often reveals a second class of slow queries that had been silently degrading performance. Adding tracing to a distributed system to find one race condition often reveals an entire category of latency tail behaviour. The instrumentation built for an emergency tends to outlast the emergency, and its second use is usually the more valuable one. The lesson for self-hosted static sites specifically is that observability for outputs matters as much as observability for inputs. The build-time correctness of a site (its HTML, its sitemap, its robots.txt) is necessary but not sufficient. The deployment-time and crawl-time behaviour (whether deploys produce transient 404s, whether crawlers are actually fetching, whether the right URLs are being returned to the right user-agents) is observable only in live logs. Lighthouse runs against the deployed site after stabilisation; Search Console reports aggregated data after Google's own batch processing; synthetic monitors poll on intervals that miss bursts. The access log is the only artefact that records what actually happened, in order, with timestamps, for every request. The same discipline applied to a Content Security Policy rollout the next day caught a Partytown sandbox iframe issue during the Report-Only observation phase, before any visitor experience could be affected. Different concern, same pattern: structured observation reveals what assumption-driven deployment would have missed. The pattern only works if the surrounding system is observable. Defensive deployment that silences error output also silences the diagnostic surface that would surface failure. Build it defensively and visibly; the second adjective is non-negotiable. The general lesson is not "every site needs this tool." The general lesson is "every site that cares about real-world crawler behaviour needs some way to read its own logs." The tool described here is one shape that observability can take. It is small on purpose. Three honest limitations apply to the analysis presented here. The analyser is built for nginx and would require parser changes for Apache or Caddy. The Search Console baseline figures describe one site over one 89-day period; broader empirical claims would require multiple sites measured comparably. The 568-request figure is a burst triggered by simultaneous remediation of multiple freshness signals on a single day, not a sustainable daily rate. The durable claim is a 7-15x sustained improvement, not 83x. ## The tool The analyser is a single-file Python script with no external dependencies, runs on Python 3.8 or later, parses nginx logs in either the combined or extended `seo_crawl` format, and produces text, markdown, or JSON output. It supports the `--strict` flag for cron and CI integration, exiting non-zero on critical findings. The full source, README, changelog, and AGPL-3.0-or-later licence are at [github.com/SpeyTech/crawler-log-analyser](https://github.com/SpeyTech/crawler-log-analyser). The repository contains no dashboard, no SaaS component, no database backend, and no external service dependency. It does not replace Search Console; it complements it. The tool's value is concentrated in the parser tolerance, the classification of probe versus real traffic, and the deploy-window detector. The rest is plumbing. ## Frequently Asked Questions ### What is operational SEO observability? Operational SEO observability is reading live web-server access logs to verify what real crawlers experienced, rather than inferring it from synthetic audits. The practice complements Search Console rather than replacing it. Lighthouse measures page quality; access logs measure actual crawler fetches. Both are needed, and they answer different questions. ### How do I read my own nginx access logs for SEO signals? Filter by known crawler user-agents (Googlebot, Bingbot, AI crawlers) and look at status codes, request timing, and URL paths. The raw approach is `grep` plus `awk`, which works for a one-off look. For ongoing use, an analyser that handles HTTP/2, IPv6, probe filtering, and crawler classification is more sustainable. The `crawler-log-analyser` tool described in this article is one such option; the broader category of log-based SEO tooling exists for those who prefer a different shape. ### Why doesn't Lighthouse catch deploy-window 404s? Lighthouse audits run on demand against a stabilised site, not during the deployment window itself. The transient 404 occurs in a brief inconsistent state between the HTML and asset directory swap, typically lasting seconds. A Lighthouse audit triggered before or after the swap sees a fully consistent site. Only continuous request-level logging captures requests that landed inside the window. ### What are the limitations of log-based SEO observability? Log-based observability sees only what crawlers actually fetched, not what they decided not to fetch or rank. It cannot replace Search Console for impressions, click-through rates, or search position data. The analyser is built for nginx; Apache or Caddy would require parser changes. The 568-request burst documented here is one site over one day, not a generalised effect size. ## Closing Whether the steady-state recovery sustains will be visible in Search Console over the coming weeks, and the claims above should be verifiable from that data rather than from this one day's burst. The 568-request day shows the ceiling of Google's current interest in the site; the durable number is whatever the median settles at by the end of June. Twenty-two independent engineers cloned the analyser repository in its first 36 hours, with no promotional activity. The audience exists for tools that take static-site SEO observability seriously. The discipline that produced the measurement is portable. Most static-site operators have nginx logs they have never read. Most of them would find at least one surprising thing in the first reading. Hope this helps. — William --- ## Undefined Behaviour: Compiler's Licence to Delete Your Code **URL**: https://speytech.com/insights/undefined-behaviour-compiler/ **Published**: April 17, 2026 **Topic**: C Fundamentals **Answers**: What is undefined behaviour in C, how do C compilers exploit undefined behaviour to remove safety checks and reorder code, what are the most common sources of undefined behaviour including signed overflow and null pointer dereference and strict aliasing, and how do compiler flags like -fwrapv and -fno-strict-aliasing control UB-related optimisations? **Defines**: Undefined behaviour KEY_CLAIMS: - Undefined behaviour in C gives the compiler permission to silently remove safety checks and delete code the programmer intended to execute. - Undefined behaviour is any operation whose result the C standard does not define, granting the compiler unrestricted freedom to assume it never occurs and to optimise accordingly. - Undefined behaviour in C grants the compiler permission to remove, reorder, or transform any code that depends on operations the standard does not define. - Undefined behaviour is any operation for which the C standard imposes no requirements on the result. - The compiler reasons that if an operation before a safety check would be UB, those inputs cannot occur. EVIDENCE: - The Linux kernel encountered this exact bug in the TUN/TAP driver (CVE-2009-1897). - The fix is straightforward - check before you dereference: The strict aliasing rule (C99 section 6.5, paragraph 7) states that an object can only be accessed through a pointer of its declared type, a compatible type, or `char `. - C23 finally mandated two's complement for signed integers, eliminating one source of undefined behaviour. - DO-178C requires demonstrating that the source code accurately represents the intended behaviour. RELATES_TO: - insights/do178c-certification - insights/fixed-point-neural-networks - insights/fixed-point-vs-floating-point-tradeoffs How undefined behaviour allows C compilers to silently remove safety checks, reorder operations, and optimise away code that appears correct Undefined behaviour in C gives the compiler permission to silently remove safety checks and delete code the programmer intended to execute. The result is compiled output that does not match what the source code appears to do. This is not a compiler bug. It is an optimisation strategy that the C standard explicitly permits. By William Murray, Founder of SpeyTech - deterministic computing for safety-critical systems. Inverness, Scottish Highlands. This article explains what undefined behaviour is, how compilers exploit it to transform correct-looking code into incorrect programs, demonstrates five patterns where UB silently changes program behaviour, and provides the compiler flags and coding practices that make UB visible. ## What Undefined Behaviour Means Definition: Undefined Behaviour Undefined behaviour is any operation whose result the C standard does not define, granting the compiler unrestricted freedom to assume it never occurs and to optimise accordingly. The C standard (C99 section 3.4.3) defines undefined behaviour as "behavior, upon use of a nonportable or erroneous program construct or of erroneous data, for which this International Standard imposes no requirements." The key phrase is "no requirements." The compiler is not required to produce an error. It is not required to produce a warning. It is not required to do what the programmer intended. It is free to do anything at all. In practice, "anything at all" means the compiler treats undefined behaviour as an optimisation opportunity. If the standard says a particular operation has no defined result, the compiler assumes the operation never happens. This assumption propagates through the optimiser, eliminating branches, removing checks, and reordering operations in ways that change the program's observable behaviour. The programmer writes a safety check. The compiler proves the check is unreachable (because reaching it would require undefined behaviour). The compiler removes the check. The safety check the programmer relied on is not present in the compiled binary. ## How Compilers Exploit Undefined Behaviour Compilers do not introduce bugs through undefined behaviour. They remove code that appears to handle situations that the standard says cannot occur. The optimiser's reasoning is formally correct according to the standard. The problem is that the standard's model and the programmer's model of the code do not agree. ### The Optimiser's Logic The optimiser works backward from the standard's guarantees: 1. The standard says operation X is undefined behaviour 2. A well-formed program never exhibits undefined behaviour 3. Therefore operation X never occurs in this program 4. Therefore any code that only executes when X occurs is dead code 5. Dead code can be removed This chain of reasoning is applied at every optimisation level above `-O0`. At `-O2` and `-O3`, the optimiser aggressively exploits UB assumptions to eliminate branches, hoist operations out of loops, and reduce instruction count. The resulting binary may bear little resemblance to the source code's apparent control flow. ## Five Patterns Where UB Deletes Your Code ### Pattern 1: Signed Integer Overflow Signed integer overflow is undefined behaviour in C. The compiler is free to assume it never happens. This has consequences for overflow checks written after the operation: ```c int x = get_value(); int result = x + 1; if (result type; // Dereference first if (dev == NULL) { // Null check after dereference return; } configure(dev, type); } ``` The compiler reasons: `dev->type` dereferences `dev`. Dereferencing a null pointer is undefined behaviour. Therefore `dev` cannot be null at that point. Therefore `dev` cannot be null anywhere in the function (since no assignment occurs between the dereference and the check). Therefore the null check is dead code. The check is removed. The Linux kernel encountered this exact bug in the TUN/TAP driver (CVE-2009-1897). A null pointer dereference occurred before the null check, GCC removed the check at `-O2`, and the kernel became vulnerable to a privilege escalation attack. The fix is straightforward - check before you dereference: ```c void process(struct device *dev) { if (dev == NULL) { return; } int type = dev->type; // Safe: dev is known non-null configure(dev, type); } ``` ### Pattern 3: Strict Aliasing Violations The strict aliasing rule (C99 section 6.5, paragraph 7) states that an object can only be accessed through a pointer of its declared type, a compatible type, or `char *`. Accessing an object through a pointer of a different type is undefined behaviour. This commonly breaks when programmers use type-punning to reinterpret data: ```c uint32_t float_to_bits(float f) { // UB: accessing float through uint32_t pointer return *(uint32_t *)&f; } ``` The compiler may assume that the `uint32_t *` pointer and the `float` variable do not alias (refer to the same memory). The optimiser may reorder reads and writes, return stale values, or eliminate the read entirely because it "knows" the uint32_t pointer cannot refer to the float. The correct approach uses `memcpy`, which is the only standard-sanctioned way to reinterpret bytes between types: ```c uint32_t float_to_bits(float f) { uint32_t bits; memcpy(&bits, &f, sizeof(bits)); // Defined behaviour return bits; } ``` Modern compilers optimise the `memcpy` approach to the same single instruction as the pointer cast, but without the undefined behaviour. The compiled output is identical. The semantics are defined. `-fno-strict-aliasing` disables the aliasing assumption, making type-punning through pointer casts safe at the cost of some optimisations. The Linux kernel compiles with this flag because the kernel relies heavily on type-punning. ### Pattern 4: Infinite Loop Removal C11 introduced a rule (section 6.8.5, paragraph 6) that allows the compiler to assume that loops with no observable side effects will terminate. An infinite loop with no I/O, no volatile access, and no synchronisation operations is undefined behaviour. ```c void wait_for_hardware(volatile int *flag) { // This loop is fine - volatile prevents removal while (*flag == 0) { } } void spin_forever(void) { // UB in C11: no side effects, compiler may remove while (1) { } unreachable_code(); // Compiler may execute this } ``` The practical impact is limited because most real loops have side effects. However, busy-wait loops in embedded firmware that poll non-volatile memory-mapped registers can be silently removed by an optimising compiler. The `volatile` qualifier prevents removal by making each read an observable side effect. ### Pattern 5: Out-of-Bounds Access Assumptions Accessing an array out of bounds is undefined behaviour. The compiler can use this to eliminate range checks in surprising ways: ```c int table[4] = {10, 20, 30, 40}; int lookup(int index) { if (index = 4) { return -1; // Bounds check } return table[index]; } int get_value(int index) { int val = table[index]; // Access before check - UB if out of bounds if (index = 4) { return -1; // Compiler may remove this } return val; } ``` In `get_value`, the array access occurs before the bounds check. The compiler reasons that `table[index]` with an out-of-bounds index is UB, so `index` must be in bounds. The bounds check is dead code. This mirrors the null pointer pattern: the operation that would be UB is performed before the check that would prevent it. The fix is the same principle: validate before you use. ## Why the Standard Permits Undefined Behaviour Undefined behaviour exists in C for two historical reasons, both rooted in portability and performance. ### Hardware Diversity When C was standardised, it needed to run on machines with different integer representations (two's complement, one's complement, sign-magnitude), different byte orders, different alignment requirements, and different overflow behaviour. Rather than mandating one behaviour and making C slow or impossible on some hardware, the standard left these operations undefined. The compiler could generate whatever the hardware naturally produced. C23 finally mandated two's complement for signed integers, eliminating one source of undefined behaviour. But signed overflow remains undefined because compilers have spent decades building optimisations around the assumption that it does not occur. ### Optimisation Opportunities Undefined behaviour gives the compiler room to optimise. If signed overflow is undefined, the compiler can assume `x + 1 > x` is always true. This enables loop unrolling, strength reduction, and branch elimination that would be impossible if overflow had defined semantics. The performance impact is real - some benchmarks show 5-15% improvement from UB-based optimisations. The trade-off is that code which accidentally triggers UB may be silently transformed into code with different behaviour. The compiler is optimising for the common case (well-formed code) at the expense of the uncommon case (code with latent bugs). ## Compiler Flags That Control UB Several compiler flags modify how GCC and Clang handle undefined behaviour: `-fwrapv` defines signed integer overflow as two's complement wraparound. This eliminates Pattern 1 (overflow check removal) at the cost of some optimisations. Programs that depend on overflow detection should use this flag. `-fno-strict-aliasing` disables the strict aliasing assumption, allowing type-punning through pointer casts. This eliminates Pattern 3. The Linux kernel uses this flag. `-fsanitize=undefined` (UBSan) instruments the program to detect undefined behaviour at runtime. Instead of silently exploiting UB, the compiler inserts checks that report violations. This is a development and testing tool, not a production flag, because of the performance overhead. `-ftrapv` causes signed integer overflow to generate a trap (abort) rather than continuing silently. This is more aggressive than `-fwrapv` - instead of defining the overflow, it terminates the program. The recommended approach for safety-critical development is to compile with UBSan during testing, use `-fwrapv` in production if overflow handling is required, and use `-fno-strict-aliasing` if type-punning is unavoidable. The following table summarises which flags address which patterns: | Flag | Pattern 1 | Pattern 2 | Pattern 3 | Pattern 4 | Pattern 5 | |------|-----------|-----------|-----------|-----------|-----------| | `-fwrapv` | Yes | - | - | - | - | | `-fno-strict-aliasing` | - | - | Yes | - | - | | `-fsanitize=undefined` | Yes | Yes | Yes | Yes | Yes | | `-ftrapv` | Yes | - | - | - | - | No single flag addresses all patterns. UBSan is the closest to comprehensive but is not suitable for production deployment. The fundamental fix is to write code that does not invoke undefined behaviour rather than relying on compiler flags to change how UB is handled. ## The Safety-Critical Connection In safety-critical systems, undefined behaviour is a certification obstacle. [DO-178C](/insights/do178c-certification/) requires demonstrating that the source code accurately represents the intended behaviour. If the compiler removes a safety check through UB exploitation, the compiled binary no longer matches the source code's intent. The traceability requirement between source and object code is violated. MISRA C addresses this directly. MISRA C:2012 Rule 1.3 states that there shall be no occurrence of undefined behaviour. This is a mandatory rule, not advisory. MISRA C also includes specific rules that target individual UB sources: Rule 12.1 requires parenthesisation of expressions to prevent evaluation order ambiguity, Rule 12.2 prohibits shift operations that exceed the bit width, and Rule 17.2 prohibits recursion to prevent stack overflow. [Fixed-point arithmetic](/insights/fixed-point-vs-floating-point-tradeoffs/) eliminates one major source of UB by design. [Q16.16 fixed-point](/insights/fixed-point-neural-networks/) uses explicit saturation arithmetic with overflow checks before every operation. Signed overflow never occurs because every operation is range-checked. The arithmetic is fully defined under C99. The [c-from-scratch](https://github.com/SpeyTech/c-from-scratch) course covers undefined behaviour, compiler optimisation, and defensive coding practices in depth. ## Frequently Asked Questions ### What is undefined behaviour in C? Undefined behaviour is any operation for which the C standard imposes no requirements on the result. The compiler may assume UB never occurs in a correct program and optimise accordingly, which can result in code removal, reordering, or transformation that changes the program's observable behaviour. ### How does the compiler remove safety checks through undefined behaviour? The compiler reasons that if an operation before a safety check would be UB, those inputs cannot occur. The safety check for those inputs is therefore dead code and can be removed. This happens silently at optimisation levels above `-O0`. ### Why does signed integer overflow cause undefined behaviour? The C standard leaves signed overflow undefined to enable optimisations that assume arithmetic behaves mathematically. C23 mandated two's complement representation but kept overflow undefined because changing it would break existing optimisations. ### How do I detect undefined behaviour in my code? Compile with `-fsanitize=undefined` (UBSan) during development and testing. UBSan instruments the program to detect and report UB at runtime, including signed overflow, null pointer dereferences, out-of-bounds access, and alignment violations. Run UBSan across the full test suite before production deployment. ### Does -O0 prevent undefined behaviour problems? `-O0` reduces the likelihood of UB-related surprises because the compiler performs fewer optimisations that exploit UB assumptions. However, UB is still present in the source code and will manifest when the code is compiled at `-O2` or higher for production. Developing at `-O0` and shipping at `-O2` creates a class of bugs that only appear in production builds. ## Conclusion Undefined behaviour in C grants the compiler permission to remove, reorder, or transform any code that depends on operations the standard does not define. The only reliable defence is to eliminate undefined behaviour from the source rather than relying on compiler flags to change how it is exploited. As with any architectural approach, suitability depends on system requirements, risk classification, and regulatory context. --- --- ## Why memcmp Fails on Structs: Padding, Floats, Silent Bugs **URL**: https://speytech.com/insights/memcmp-struct-comparison/ **Published**: April 16, 2026 **Topic**: C Fundamentals **Answers**: Why does memcmp produce incorrect results when comparing C structs containing padding bytes or floating-point fields, how do positive zero and negative zero and NaN break byte-level equality, and what is the correct approach to struct comparison in safety-critical C code? **Defines**: Struct byte comparison KEY_CLAIMS: - memcmp on a struct compares bytes, not values, and produces silently incorrect results when structs contain padding or floating-point fields. - Struct byte comparison using memcmp reads every byte in a structure sequentially and reports whether all bytes match, without knowledge of field boundaries, types, or semantic meaning. - memcmp on structs compares bytes rather than values, producing silently incorrect results when structs contain padding or IEEE 754 floating-point fields. - memcmp compares raw bytes without knowledge of struct field boundaries, compiler-inserted padding, or IEEE 754 floating-point semantics. - Compare each field individually using a dedicated comparison function. EVIDENCE: - The difference matters whenever the byte representation of a value does not uniquely correspond to its semantic meaning. memcmp on a struct is unreliable whenever the struct contains compiler-inserted padding or IEEE 754 floating-point fields. - On most platforms, a 4-byte `int` must start at an address divisible by 4. - An 8-byte `double` must start at an address divisible by 8. - Consider this struct on a typical 64-bit platform: The struct occupies 8 bytes, not 5. RELATES_TO: - insights/do178c-certification - insights/fixed-point-neural-networks - insights/fixed-point-vs-floating-point-tradeoffs - insights/iec-62304-class-c How struct padding and IEEE 754 float representation cause memcmp to produce incorrect equality results, and why field-by-field comparison is the only fix memcmp on a struct compares bytes, not values, and produces silently incorrect results when structs contain padding or floating-point fields. The function answers "are the bytes identical?" which is not the same question as "are the values equal?" This distinction is responsible for an entire class of equality bugs that compile without errors, pass unit tests on one platform, and fail in production on another. By William Murray, Founder of SpeyTech - deterministic computing for safety-critical systems. Inverness, Scottish Highlands. This article explains the two categories of memcmp failure on structs - padding bytes and floating-point representation - demonstrates each with concrete examples, and provides the compiler flags and coding practices that prevent these bugs. ## What memcmp Actually Does Definition: Struct Byte Comparison Struct byte comparison using memcmp reads every byte in a structure sequentially and reports whether all bytes match, without knowledge of field boundaries, types, or semantic meaning. memcmp is defined in C99 section 7.21.4.1. It compares `n` bytes starting from two memory addresses and returns zero if all bytes match. It has no knowledge of what those bytes represent. It does not know where one struct field ends and another begins. It does not know whether a byte is part of a float, an integer, or padding inserted by the compiler. This makes memcmp a byte-identity function, not an equality function. The difference matters whenever the byte representation of a value does not uniquely correspond to its semantic meaning. memcmp on a struct is unreliable whenever the struct contains compiler-inserted padding or IEEE 754 floating-point fields. ## Bug One: Padding Bytes C compilers insert invisible padding bytes between struct fields to satisfy alignment requirements. These padding bytes are uninitialised by default. memcmp reads them. Two structs with identical field values can compare as different because their padding bytes do not match. ### How Padding Works The C standard requires that each data type be stored at a memory address that is a multiple of its alignment requirement. On most platforms, a 4-byte `int` must start at an address divisible by 4. An 8-byte `double` must start at an address divisible by 8. When struct fields have different alignment requirements, the compiler inserts padding bytes between them to satisfy these constraints. Consider this struct on a typical 64-bit platform: ```c struct sensor { char id; // 1 byte at offset 0 // 3 bytes padding (to align int to offset 4) int reading; // 4 bytes at offset 4 }; // sizeof(struct sensor) == 8, not 5 ``` The struct occupies 8 bytes, not 5. The compiler inserts 3 bytes of padding after `id` to align `reading` on a 4-byte boundary. These 3 bytes are not initialised by field assignment. The padding is worse with mixed types: ```c struct record { char flag; // 1 byte at offset 0 // 7 bytes padding (to align double to offset 8) double value; // 8 bytes at offset 8 char status; // 1 byte at offset 16 // 7 bytes trailing padding (to align struct size to 8) }; // sizeof(struct record) == 24, not 10 ``` This struct has 14 bytes of padding out of 24 total bytes. More than half of the bytes that memcmp reads are uninitialised padding. The `sizeof` operator reports the padded size, so `memcmp(&a, &b, sizeof(struct record))` reads all 24 bytes including every padding byte. ### The memcmp Failure ```c struct sensor a, b; a.id = 'A'; a.reading = 42; b.id = 'A'; b.reading = 42; // a and b have identical field values // memcmp(&a, &b, sizeof(struct sensor)) may return non-zero ``` The field values are identical. The padding bytes are whatever happened to be in memory at allocation time. memcmp reads all 8 bytes, including the 3 padding bytes, and reports a difference that does not exist at the value level. ### Why memset Does Not Fully Solve Padding The common fix is to zero the struct before use: ```c memset(&a, 0, sizeof(struct sensor)); memset(&b, 0, sizeof(struct sensor)); a.id = 'A'; a.reading = 42; b.id = 'A'; b.reading = 42; // Now memcmp returns 0 - padding is zeroed ``` This works if every code path that creates or modifies the struct remembers to zero it first. In practice, this discipline breaks down. A struct returned from a function, copied from a network buffer, or deserialised from storage may not have zeroed padding. A single missed memset in a large codebase reintroduces the bug. memset also does not help when structs are copied with assignment. The C standard does not require assignment to copy padding bytes, and compilers may or may not copy them. Two structs that were zeroed and then assigned identical values through different code paths may still have different padding. Padding bytes are a reliability problem because they are invisible in the source code and their values depend on memory history rather than field assignment. ## Bug Two: IEEE 754 Float Representation The second category of memcmp failure is more subtle. Even with zeroed padding, memcmp produces incorrect results on structs containing floating-point fields. IEEE 754 defines values whose byte representation violates the assumption that "same bytes means same value" and "different bytes means different value." ### Positive Zero and Negative Zero IEEE 754 defines two representations of zero: ```c float pos_zero = +0.0f; // bytes: 0x00000000 float neg_zero = -0.0f; // bytes: 0x80000000 // (pos_zero == neg_zero) is true - same value // memcmp: not equal - different bytes ``` Positive zero and negative zero are equal values with different byte representations. The sign bit differs, but the IEEE 754 standard specifies that +0.0 and -0.0 compare as equal. memcmp sees different bytes and reports inequality. A struct containing a float field set to +0.0 in one instance and -0.0 in another will fail a memcmp equality check despite having semantically identical values. Negative zero arises naturally from operations like `1.0f / -INFINITY` or `0.0f * -1.0f`. Code does not need to explicitly assign -0.0 for this bug to manifest. ### NaN is Not Equal to Itself IEEE 754 defines that NaN (Not a Number) is not equal to any value, including itself: ```c float nan1 = 0.0f / 0.0f; // NaN, bytes: 0x7FC00000 float nan2 = 0.0f / 0.0f; // NaN, bytes: 0x7FC00000 // (nan1 == nan2) is false - NaN != NaN by IEEE 754 // memcmp: equal - identical bytes ``` NaN values with identical bit patterns compare as unequal under IEEE 754 arithmetic but as equal under memcmp. A struct containing a NaN field will pass a memcmp check when it should fail an equality check. This is the opposite direction from the zero problem: memcmp reports equality when the values are not equal. IEEE 754 also permits multiple NaN representations. Quiet NaN and signalling NaN have different bit patterns, and the payload bits of a NaN can vary. Two NaN values that are both "not a number" may have different byte representations, causing memcmp to report inequality between values that are both NaN. ### The Two Directions of Failure memcmp fails in both directions on float-containing structs: | Scenario | Value comparison | memcmp result | Correct answer | |----------|-----------------|---------------|----------------| | +0.0 vs -0.0 | equal | not equal | equal | | NaN vs NaN (same bits) | not equal | equal | not equal | | NaN vs NaN (different bits) | not equal | not equal | not equal | One comparison says different when the values are the same. Another says same when the values are different. Both are silent. Both compile without error. memcmp has no mechanism to detect or report these cases because it operates on bytes, not on IEEE 754 semantics. memcmp on a float-containing struct is fundamentally broken for equality testing, regardless of padding. ## Where This Bug Hides in Practice ### Deduplication and Caching Systems that deduplicate records or cache computed results often use memcmp for fast equality checking. A cache keyed on a struct containing a float field will store duplicate entries for +0.0 and -0.0 values, or will incorrectly return cached results for NaN inputs. In a sensor aggregation pipeline processing millions of readings per day, the duplicate entries accumulate silently. The cache grows unbounded because readings that should be deduplicated are stored as distinct entries. ### Change Detection Monitoring systems that detect state changes by comparing current and previous struct snapshots with memcmp will generate false change notifications when padding bytes differ, or will miss genuine changes when NaN fields remain byte-identical. A safety monitoring system that suppresses alerts because "the state hasn't changed" when the float field transitioned from a valid reading to NaN is a potential safety failure. ### Network Protocol Comparison Structs received from network buffers may have different padding byte values depending on the sender's memory state. Two messages with identical payloads can fail memcmp comparison because the padding bytes were not zeroed before transmission. This is particularly common in embedded systems where structs are transmitted directly over serial or CAN bus without serialisation. The sender and receiver may have different compilers, different alignment rules, and different padding layouts for the same struct definition. ### Serialisation Round-Trip A struct serialised to disk and deserialised back may not have the same padding byte values as the original. The serialisation format may not preserve padding, and the deserialised struct may be allocated in different memory with different residual byte values. A system that uses memcmp to verify serialisation integrity will report corruption that does not exist. ### Hash Table Keys Using memcmp as the equality function for hash table keys containing structs leads to hash collisions that are never resolved. Two structs with identical field values but different padding bytes will hash to different buckets (if the hash function also reads padding) or the same bucket (if it doesn't), but the equality check will fail in either case. The result is duplicate entries in the hash table that should have been matches. ### Test Assertions Unit tests that use memcmp to assert struct equality may pass on one platform and fail on another due to different padding layouts. A struct with the same field values can have different sizes on different platforms due to different alignment requirements, making memcmp-based tests non-portable. A test suite that passes on x86 and fails on ARM due to different struct padding is a waste of debugging time. memcmp-based equality checks are unreliable in any system where structs contain padding or floating-point fields. ## The Correct Approach: Field-by-Field Comparison The only reliable approach to struct equality is comparing each field individually: ```c bool sensor_equal(const struct sensor *a, const struct sensor *b) { return a->id == b->id && a->reading == b->reading; } ``` For structs containing floating-point fields, the comparison function must handle the IEEE 754 edge cases explicitly: ```c #include struct measurement { int sensor_id; float value; float uncertainty; }; bool measurement_equal(const struct measurement *a, const struct measurement *b) { if (a->sensor_id != b->sensor_id) return false; // Handle NaN: both NaN is considered equal for our domain if (isnan(a->value) && isnan(b->value)) { // Domain decision: are two NaN readings "equal"? // This depends on the application. } else if (a->value != b->value) { return false; } if (isnan(a->uncertainty) && isnan(b->uncertainty)) { // Same domain decision } else if (a->uncertainty != b->uncertainty) { return false; } return true; } ``` The field-by-field approach makes the comparison semantics explicit. The programmer decides whether NaN equals NaN, whether +0.0 equals -0.0, and whether floating-point comparison should use exact equality or an epsilon tolerance. memcmp makes all of these decisions for you, and makes them incorrectly. ### The Cost of Field-by-Field Comparison Field-by-field comparison is slower than memcmp for large structs. memcmp can use word-aligned reads and SIMD instructions, while field-by-field comparison generates individual load and compare instructions per field. For a struct with 20 fields, the performance difference is measurable. In practice, the performance difference rarely matters. Struct comparison is almost never the bottleneck. And when it is, a hand-optimised comparison function that handles padding and floats correctly will still be faster than debugging a memcmp failure in production. Performance is not a valid reason to use memcmp on structs that contain padding or floats. Correctness is not optional. ## Compiler Flags and Static Analysis GCC and Clang do not warn about memcmp on structs by default. The compiler cannot always determine whether a struct contains padding or floats at the call site, particularly when memcmp receives `void *` arguments. `-Wclass-memaccess` (C++ only, GCC) warns when memory functions like memcmp are used on non-trivial class types. This does not help in C. Static analysis tools provide better coverage: - **Clang Static Analyzer** can detect memcmp on structs with padding in some cases - **Coverity** flags memcmp on structs as a potential defect - **MISRA C Rule 21.16** prohibits memcmp for comparison of objects with padding bytes or floating-point members - **CERT C EXP42-C** warns against comparing padding data For safety-critical code compiled under [DO-178C](/insights/do178c-certification/) or [IEC 62304](/insights/iec-62304-class-c/), memcmp on structs is an audit finding. Certification requires demonstrating that every comparison produces the intended result. A comparison that reads uninitialised padding or misinterprets IEEE 754 values is a gap in that demonstration. The recommended approach is to ban memcmp on structs by policy and enforce it through code review and static analysis. ## The Safety-Critical Connection In safety-critical systems, struct comparison errors are not just correctness issues - they are potential safety failures. A sensor reading comparison that reports "no change" when the reading has changed can suppress critical alerts. A state machine transition guard that uses memcmp to detect state changes can miss transitions or trigger spurious transitions. [Fixed-point arithmetic](/insights/fixed-point-vs-floating-point-tradeoffs/) addresses the float comparison problem by construction. [Q16.16 fixed-point](/insights/fixed-point-neural-networks/) uses `int32_t` exclusively for all values. Integer comparison has none of the IEEE 754 edge cases: there is no negative zero, no NaN, and identical values always have identical bit patterns. Field-by-field comparison of a fixed-point struct reduces to integer comparison, which is both correct and fast. The [c-from-scratch](https://github.com/SpeyTech/c-from-scratch) course covers struct layout, padding, and comparison as part of the C type system fundamentals. ## Frequently Asked Questions ### Why does memcmp fail on structs in C? memcmp compares raw bytes without knowledge of struct field boundaries, compiler-inserted padding, or IEEE 754 floating-point semantics. Padding bytes are uninitialised and vary between allocations. Float values like +0.0 and -0.0 have different byte representations despite being equal. These cause memcmp to report incorrect equality results. ### How do I correctly compare two structs in C? Compare each field individually using a dedicated comparison function. For integer fields, use `==`. For float fields, handle NaN and signed zero explicitly based on the application's equality semantics. Never use memcmp on structs that contain padding or floating-point members. ### Does memset zeroing the struct before use fix the memcmp problem? memset zeroing eliminates the padding problem only if every code path that creates or modifies the struct zeros it consistently. Assignment does not guarantee padding bytes are copied, so structs initialised through different paths may still differ. memset does not fix the IEEE 754 float problem - +0.0 and -0.0 remain byte-different even in zeroed structs. ### What compiler flags detect memcmp struct comparison bugs? No standard GCC or Clang warning specifically targets memcmp on padded structs in C. Static analysis tools like Coverity and the Clang Static Analyzer provide partial coverage. MISRA C Rule 21.16 prohibits memcmp for struct comparison. The most reliable prevention is a project-wide policy enforced through code review. ### Why does fixed-point arithmetic avoid the float comparison problem? Fixed-point arithmetic represents values as integers, eliminating IEEE 754 edge cases entirely. Integer comparison in C is exact: identical values always have identical bit patterns, there is no negative zero, and there is no NaN. Struct comparison reduces to integer field comparison, which is both correct and deterministic. ## Conclusion memcmp on structs compares bytes rather than values, producing silently incorrect results when structs contain padding or IEEE 754 floating-point fields. The only correct approach is field-by-field comparison that makes equality semantics explicit. As with any architectural approach, suitability depends on system requirements, risk classification, and regulatory context. --- --- ## The Type Promotion Trap: C's Silent Integer Conversion Bugs **URL**: https://speytech.com/insights/type-promotion-trap/ **Published**: April 15, 2026 **Topic**: C Fundamentals **Answers**: How do C's integer promotion rules cause silent bugs when comparing signed and unsigned integers, why does the expression 0u > -1 evaluate to false, what are the common type conversion patterns that create logic errors in embedded and safety-critical C code, and which compiler flags like -Wsign-compare and -Wconversion catch implicit promotion bugs? **Defines**: Integer promotion KEY_CLAIMS: - C's integer promotion rules silently convert signed values to unsigned during mixed-type operations, producing results that contradict the developer's intent. - Integer promotion is the implicit conversion of types narrower than int to int (or unsigned int) before any arithmetic operation. - C's integer promotion rules silently convert negative values to large unsigned numbers, invalidating comparisons and bounds checks in compiled code. - Integer promotion is the implicit conversion of types narrower than `int` to `int` before arithmetic. - Enable `-Wsign-compare` (included in `-Wall`) and `-Werror` to make the compiler reject mixed-signedness comparisons. EVIDENCE: - The expression `0u > -1` evaluates to `false` because `-1` is converted to `4294967295` before the comparison. - This single rule - codified in C99 section 6.3.1.8 - is responsible for an entire class of bugs that compile without errors and pass casual code review. - The compiler now applies the usual arithmetic conversions from C99 section 6.3.1.8: when a signed `int` meets an `unsigned int` of the same conversion rank, the signed value converts to unsigned. - Reinterpreted as unsigned on a 32-bit system, that value is `4294967295` - `UINT_MAX`. RELATES_TO: - insights/fixed-point-vs-floating-point-tradeoffs - open-source/fixed-point-fundamentals How implicit type promotion rules turn correct-looking comparisons into logic errors in C -1 evaluates to true but 0u > -1 evaluates to false due to C integer promotion rules converting -1 to 4294967295" width="800" height="400" /> C's integer promotion rules silently convert signed values to unsigned during mixed-type operations, producing results that contradict the developer's intent. The expression `0u > -1` evaluates to `false` because `-1` is converted to `4294967295` before the comparison. This single rule - codified in C99 section 6.3.1.8 - is responsible for an entire class of bugs that compile without errors and pass casual code review. By William Murray, Founder of SpeyTech - deterministic computing for safety-critical systems. Inverness, Scottish Highlands. This article explains the complete integer promotion hierarchy, demonstrates six patterns where implicit conversions create bugs, and provides the compiler flags and coding practices that make these conversions visible. ## The Contradiction That Starts It All Two expressions. One character difference. Opposite results. ```c 0 > -1 // evaluates to 1 (true) - both operands are int 0u > -1 // evaluates to 0 (false) - -1 becomes 4294967295u ``` The first comparison works as expected: zero is greater than negative one. The second comparison adds a single `u` suffix, making the left operand `unsigned int`. The compiler now applies the usual arithmetic conversions from C99 section 6.3.1.8: when a signed `int` meets an `unsigned int` of the same conversion rank, the signed value converts to unsigned. The two's complement representation of `-1` is all ones. Reinterpreted as unsigned on a 32-bit system, that value is `4294967295` - `UINT_MAX`. The comparison becomes `0u > 4294967295u`, which is `false`. No warning is emitted by default. The code compiles cleanly. The bug is invisible without `-Wsign-compare`. ## How C's Integer Promotion Rules Work Definition: Integer Promotion Integer promotion is the implicit conversion of types narrower than int to int (or unsigned int) before any arithmetic operation. C's type conversion happens in two stages, both invisible in the source code. **Stage 1: Integer promotions.** Any type with a conversion rank lower than `int` - including `char`, `short`, `int8_t`, `uint8_t`, `int16_t`, and `uint16_t` - is promoted to `int` before any arithmetic or comparison. If all values of the original type fit in an `int`, the promotion is to `int`. Otherwise, it is to `unsigned int`. On any platform where `int` is 32 bits, every sub-`int` type promotes to signed `int`. **Stage 2: Usual arithmetic conversions.** When two operands have different types after integer promotion, C applies a second conversion to find a common type. The rules, specified in C99 section 6.3.1.8, follow a hierarchy based on conversion rank: 1. If either operand is `long long`, the other converts to `long long` (signed or unsigned, depending on the next rules). 2. If either operand is `long`, the other converts to `long`. 3. If either operand is `unsigned int`, the other converts to `unsigned int`. The critical rule is number 3. When a signed `int` meets an `unsigned int`, the signed value is converted to unsigned. The conversion is defined by C99 section 6.3.1.3: the value is reduced modulo `UINT_MAX + 1`. For `-1`, that means `(-1) mod 4294967296 = 4294967295`. The signed value does not become "unsigned negative one." It becomes a large positive number. This is not a bug in the compiler. It is the language specification working exactly as written. ## Six Patterns That Create Bugs ### Pattern 1: Signed/Unsigned Comparison ```c unsigned int count = 10; int index = -1; if (index 10) process(index); } ``` The developer intends to guard against negative indices. The guard fails because `-1` converts to `4294967295u` before the comparison. The `process()` call never executes for the one case it was designed to catch. **Fix:** Cast explicitly, or use matching types. ```c if (index -1) { // Developer expects: always true (length is non-negative) // Actual: always false handle(s); } ``` `strlen()` returns `size_t`, which is `unsigned long` on 64-bit platforms. The literal `-1` has type `int`. Under the usual arithmetic conversions, `-1` converts to `SIZE_MAX` (`18446744073709551615` on a 64-bit system). No string can have a length exceeding `SIZE_MAX`, so the comparison is always `false`. **Fix:** The comparison is logically unnecessary - `strlen()` already returns an unsigned value that is always non-negative. If a minimum-length check is the intent, compare against the actual threshold: ```c if (strlen(s) > 0) { handle(s); } ``` ### Pattern 3: Narrowing Assignment ```c uint8_t sensor_reading = 256; // becomes 0: 256 mod 256 = 0 int16_t temperature = 40000; // becomes -25536: wraps past INT16_MAX ``` When a value is assigned to a narrower type, the high bits are discarded. For unsigned targets, the result is the value modulo 2^N where N is the bit width. For signed targets, the result is implementation-defined in C99 (C23 defines it as two's complement). On a system using two's complement, `40000` stored in an `int16_t` wraps to `-25536`. A sensor returning 256 reads as 0 after this assignment. A temperature of 40000 (perhaps in hundredths of a degree) becomes negative. Both compile without error. **Fix:** Validate range before narrowing, or use appropriately-sized types. ```c int raw = read_sensor(); if (raw UINT8_MAX) { report_error(raw); return; } uint8_t sensor_reading = (uint8_t)raw; ``` ### Pattern 4: printf Format Mismatch ```c unsigned int x = 4294967295u; printf("%d\n", x); // prints -1 ``` The `%d` format specifier tells `printf` to interpret the argument as a signed `int`. The bit pattern of `4294967295u` is identical to `-1` in two's complement. The compiler may warn, but the behaviour is undefined per C99 section 7.19.6.1 - the format specifier does not match the argument type. **Fix:** Match the format specifier to the type. ```c printf("%u\n", x); // prints 4294967295 ``` ### Pattern 5: Bitwise Shift on Signed Types ```c int x = -1; int result = x >> 1; // implementation-defined ``` Right-shifting a negative signed integer is implementation-defined in C99 (section 6.5.7). The compiler may perform an arithmetic shift (preserving the sign bit, giving `-1`) or a logical shift (filling with zeros, giving `2147483647`). GCC performs arithmetic shifts on x86, but the C standard does not require this. Code that depends on arithmetic shift behaviour is not portable. **Fix:** Use unsigned types for bitwise operations. ```c unsigned int x = 0xFFFFFFFFu; unsigned int result = x >> 1; // defined: 0x7FFFFFFF ``` ### Pattern 6: Ternary Operator Type Coercion ```c int a = -1; unsigned int b = 1; unsigned int result = (condition) ? a : b; ``` The ternary operator applies the usual arithmetic conversions to determine the common type of its second and third operands. Since `b` is `unsigned int`, `a` converts to `unsigned int` before the selection. If `condition` is true, `result` is `4294967295u` - not `-1`. The conversion happens regardless of which branch is taken. The common type is determined at compile time, and both operands are converted to it. **Fix:** Ensure both operands have the same type, or cast explicitly. ```c int result = (condition) ? a : (int)b; // if int is the intended type ``` ## Why the Rules Exist C's integer promotion rules are not arbitrary. They reflect hardware constraints from the 1970s and a backward-compatibility chain that stretches across five decades. ### The PDP-11 and Word-Sized Arithmetic The PDP-11, the machine C was designed for, performed arithmetic in 16-bit words. Operations on `char` (8-bit) required promotion to the machine's native word size before the ALU could process them. Integer promotion codified this hardware reality into the language: sub-word types promote to `int` because the hardware could not operate on them directly. ### Value-Preserving vs Unsigned-Preserving Early C (K&R) used "unsigned-preserving" rules: if either operand was unsigned, the result was unsigned. This was simple but produced surprising results when mixing signed and unsigned types of different widths. C89 adopted "value-preserving" rules instead: a narrower unsigned type promotes to signed `int` if `int` can represent all its values. This reduced some surprises for `uint16_t` on 32-bit platforms but did not eliminate the core problem of same-rank signed/unsigned mixing. ### Why C99 Did Not Fix It The signed-to-unsigned conversion rule for same-rank operands has survived every revision of the C standard because changing it would break existing code. Billions of lines of C depend on the current conversion behaviour. Some code intentionally exploits unsigned wraparound for hash functions, checksums, and bit manipulation. Altering the conversion rules would silently change the semantics of that code - the same class of silent breakage the rules themselves cause. Backward compatibility is load-bearing in C. The committee chose a known set of problems over an unknown set of regressions. ## What Modern Languages Learned Each language that followed C made a deliberate choice about implicit numeric conversions, and each paid a different cost. **Rust** requires explicit conversion with the `as` keyword. `let x: u32 = y as u32;` makes every conversion visible in the source. The trade-off is verbosity - numeric code in Rust contains conversion syntax that does not appear in C. The benefit is that no conversion happens without the developer's knowledge. **Go** prohibits all implicit numeric conversions. Adding an `int32` to an `int64` requires an explicit cast. This eliminates an entire class of promotion bugs at the cost of requiring conversion boilerplate in arithmetic-heavy code. **Swift** enforces strict type safety with no implicit promotion between integer types. `Int8` and `Int16` are distinct types that cannot be mixed without explicit initialisation. The compiler rejects mixed-type arithmetic at compile time rather than converting silently. Each of these languages made implicit conversions impossible and explicit conversions verbose. The result is that type promotion bugs do not exist in these languages. The cost is that developers write more conversion syntax. C chose the opposite trade-off: less syntax, more implicit behaviour, and a class of bugs that has persisted for fifty years. ## Compiler Flags That Catch Type Promotion Bugs GCC and Clang provide flags that make implicit conversions visible. The compiler already detects these conversions internally - the flags control whether it reports them. `-Wsign-compare` warns when a comparison has operands of different signedness. This catches Pattern 1 and Pattern 2 directly. It is included in `-Wall`. `-Wconversion` warns on implicit conversions that may change a value, including narrowing conversions. This catches Pattern 3. It is not included in `-Wall` or `-Wextra` and must be enabled explicitly. `-Wsign-conversion` warns specifically on implicit conversions that change signedness. This catches cases where a signed value is assigned to an unsigned variable or vice versa, even when the value is not changed. `-Wformat` warns on `printf` format mismatches. This catches Pattern 4. It is included in `-Wall`. The following table summarises which flags catch which patterns: | Flag | Pattern 1 | Pattern 2 | Pattern 3 | Pattern 4 | Pattern 5 | Pattern 6 | |------|-----------|-----------|-----------|-----------|-----------|-----------| | `-Wsign-compare` | Yes | Yes | - | - | - | Yes | | `-Wconversion` | Yes | Yes | Yes | - | - | Yes | | `-Wsign-conversion` | Yes | Yes | Yes | - | - | Yes | | `-Wformat` | - | - | - | Yes | - | - | | `-Wall` | Yes | Yes | - | Yes | - | Yes | | `-Wextra` | Yes | Yes | - | Yes | - | Yes | The recommended baseline for any C project is: ``` -Wall -Wextra -Wpedantic -Werror ``` `-Werror` promotes warnings to errors, preventing code with implicit conversions from compiling. Every SpeyTech project uses this baseline. For safety-critical code, add `-Wconversion -Wsign-conversion` to catch narrowing and sign-changing conversions that `-Wall` misses. ## The Safety-Critical Connection Implicit type conversions are not just a code quality concern. In safety-critical systems, they are an audit liability and a certification obstacle. MISRA C Rule 10.4 requires that both operands of an arithmetic operation have the same essential type category. Mixing a signed integer with an unsigned integer violates this rule. MISRA C Rule 10.1 further restricts which essential types are appropriate for specific operations - bitwise operations on signed types, for example, are prohibited. In DO-178C-governed aerospace software, implicit type conversions are a common audit finding. Certification requires demonstrating that every operation produces the intended result. An implicit conversion that changes a value's magnitude or sign is a gap in that demonstration. Auditors flag mixed-type comparisons because the developer's intent cannot be determined from the source code alone. [Fixed-point arithmetic](/insights/fixed-point-vs-floating-point-tradeoffs/) addresses this problem by construction. Q16.16 fixed-point uses `int32_t` exclusively for all arithmetic. There are no mixed-type operations because there is only one type. Multiplication uses an intermediate `int64_t`, but the widening is explicit and controlled. The absence of implicit conversions is not a side effect - it is a design property that makes the arithmetic auditable. The [fixed-point-fundamentals](/open-source/fixed-point-fundamentals/) course covers this approach in detail. Integer promotion bugs in safety-critical systems are not theoretical. A sensor reading that wraps from 256 to 0 due to a narrowing assignment (Pattern 3) produces incorrect control outputs. A bounds check that fails due to signed/unsigned mismatch (Pattern 1) allows out-of-range access. These are the failure modes that MISRA and DO-178C exist to prevent. ## Frequently Asked Questions ### What is integer promotion in C? Integer promotion is the implicit conversion of types narrower than `int` to `int` before arithmetic. C99 section 6.3.1.1 specifies that `char`, `short`, and their sized variants (`int8_t`, `uint16_t`, etc.) promote to `int` if `int` can represent all values of the original type. This promotion is invisible in the source code and occurs before any operator is applied. ### How do I prevent signed/unsigned comparison bugs? Enable `-Wsign-compare` (included in `-Wall`) and `-Werror` to make the compiler reject mixed-signedness comparisons. When a comparison between signed and unsigned types is intentional, add an explicit cast and a comment explaining why the conversion is safe. Prefer matching types in function signatures and variable declarations to avoid the comparison arising in the first place. ### Why does -1 become 4294967295 when converted to unsigned int? C99 section 6.3.1.3 defines unsigned conversion as reduction modulo `UINT_MAX + 1`. On a 32-bit system, `UINT_MAX` is `4294967295`, so `UINT_MAX + 1` is `4294967296`. The value `-1 mod 4294967296` equals `4294967295`. This is not a reinterpretation of bits - it is a defined arithmetic operation, though on two's complement hardware the bit pattern happens to be the same. ### Why doesn't the C standard fix implicit type promotion? Backward compatibility prevents changes to the conversion rules. Billions of lines of existing C code depend on the current behaviour, including code that intentionally uses unsigned wraparound for hash functions, checksums, and modular arithmetic. Changing the rules would silently alter the semantics of that code, trading one class of silent bugs for another. ### What are the limitations of compiler warnings for type promotion? Compiler warnings catch many but not all promotion-related bugs. `-Wconversion` and `-Wsign-conversion` are not included in `-Wall`, so projects using only `-Wall` miss narrowing conversions. Warnings also cannot distinguish between intentional and accidental conversions - a legitimate use of unsigned wraparound triggers the same warning as a bug. In codebases with many legacy warnings, developers may disable conversion warnings entirely, removing the safety net. ## Conclusion C's integer promotion rules silently convert negative values to large unsigned numbers, invalidating comparisons and bounds checks in compiled code. The trade-off for catching these bugs at compile time is a stricter warning configuration and more explicit type management in source code. As with any architectural approach, suitability depends on system requirements, risk classification, and regulatory context. The [c-from-scratch](https://github.com/SpeyTech/c-from-scratch) course covers integer promotion, type conversion, and related C fundamentals with compiler-verified examples throughout. The companion book, "C From Scratch: Learn Safety-Critical C the Right Way," is available on Leanpub. --- ## When Fixed-Point Beats Floating-Point (And When It Doesn't) **URL**: https://speytech.com/insights/fixed-point-vs-floating-point-tradeoffs/ **Published**: January 26, 2026 21:30 **Topic**: Deterministic Computing **Answers**: When is Q16.16 fixed-point arithmetic the right engineering choice over IEEE 754 floating-point for ML inference in safety-critical systems, when is floating-point perfectly acceptable, and what are the honest trade-offs in numerical precision, dynamic range, runtime performance, and certification effort? KEY_CLAIMS: - The certifiable- ecosystem uses Q16.16 fixed-point arithmetic throughout. - Fixed-point arithmetic isn't universally better than floating-point. - Use fixed-point when certification demands reproducible cross-platform results or when targeting hardware without an FPU. - Analyse the value ranges in your computation: the integer part must cover the maximum magnitude, and the fractional part must provide sufficient precision. - Fixed-point has limited dynamic range — Q16.16 covers ±32767 with 16 bits of fractional precision. EVIDENCE: - The certifiable- ecosystem uses Q16.16 fixed-point arithmetic throughout. - In Q16.16 format: The "Q16.16" notation means 16 bits for the integer part and 16 bits for the fractional part. - A 32-bit signed integer represents values from approximately -32,768 to +32,767, with precision of 1/65,536 ≈ 0.000015. - IEEE 754 floating-point seems deterministic - the standard specifies exact behaviour. RELATES_TO: - insights/fixed-point-neural-networks - insights/round-to-nearest-even - open-source/fixed-point-fundamentals An honest analysis of when Q16.16 is the right choice and when floating-point is acceptable The [certifiable-* ecosystem](https://github.com/SpeyTech) uses Q16.16 fixed-point arithmetic throughout. This isn't because floating-point is inherently evil - it's because the specific properties of fixed-point arithmetic align with the specific requirements of safety-critical systems. But fixed-point has real costs. Limited range. Manual overflow handling. More development effort. For many applications, these costs outweigh the benefits. This article provides an honest framework for deciding when fixed-point is worth it. ## What Fixed-Point Actually Is Fixed-point arithmetic represents fractional numbers using integers with an implicit scale factor. In Q16.16 format: ``` Raw integer value: 0x00018000 (98,304) Interpreted value: 98,304 / 65,536 = 1.5 ``` The "Q16.16" notation means 16 bits for the integer part and 16 bits for the fractional part. A 32-bit signed integer represents values from approximately -32,768 to +32,767, with precision of 1/65,536 ≈ 0.000015. ### Basic Operations Addition and subtraction work directly on the raw integers: ```c // Q16.16 addition: just integer addition q16_t q16_add(q16_t a, q16_t b) { return a + b; // Same scale factor, direct addition } // Example: 1.5 + 2.25 = 3.75 // 98,304 + 147,456 = 245,760 // 245,760 / 65,536 = 3.75 ✓ ``` Multiplication requires a shift to maintain the scale: ```c // Q16.16 multiplication q16_t q16_mul(q16_t a, q16_t b) { int64_t product = (int64_t)a * (int64_t)b; return (q16_t)(product >> 16); // Divide by scale factor } // Example: 1.5 × 2.0 = 3.0 // 98,304 × 131,072 = 12,884,901,888 // 12,884,901,888 >> 16 = 196,608 // 196,608 / 65,536 = 3.0 ✓ ``` Division is the inverse: ```c // Q16.16 division q16_t q16_div(q16_t a, q16_t b) { int64_t scaled = (int64_t)a > 16); // Truncation ``` Simple right-shift truncates toward negative infinity. This is deterministic but introduces bias. The solution is explicit round-to-nearest-even (RNE): ```c q16_t q16_mul_rne(q16_t a, q16_t b) { int64_t product = (int64_t)a * (int64_t)b; // Round to nearest, ties to even int64_t round_bit = (product >> 15) & 1; int64_t guard_bit = (product >> 14) & 1; int64_t sticky = (product & 0x3FFF) != 0; int64_t round_up = round_bit & (guard_bit | sticky); return (q16_t)((product >> 16) + round_up); } ``` This is more code than truncation, but it's pure integer arithmetic, fully deterministic, and produces the same result on every platform. For details on why RNE matters, see [Round-to-Nearest-Even: The Rounding Mode That Makes Determinism Possible](/insights/round-to-nearest-even/). ### No Special Values Floating-point has special values: positive/negative infinity, positive/negative zero, NaN (Not a Number), denormalised numbers. Each creates edge cases: ```c double x = 0.0 / 0.0; // NaN double y = 1.0 / 0.0; // Infinity double z = x == x; // false (NaN != NaN) ``` Fixed-point has none of this. Overflow produces defined (if incorrect) results. Division by zero is undefined behaviour that can be guarded against. There's no NaN to propagate silently through computations. ## The Range-Precision Trade-off Fixed-point's determinism comes at a cost: limited range. ### Q16.16 Limits ``` Maximum value: 32,767.999985 (0x7FFFFFFF) Minimum value: -32,768.0 (0x80000000) Precision: 0.000015 (1/65536) ``` For neural network weights typically in the range [-2, 2], this is ample precision. For financial calculations involving millions of dollars, it's insufficient. ### Choosing the Format Different applications need different trade-offs: | Format | Integer Bits | Fraction Bits | Range | Precision | |--------|-------------|---------------|-------|-----------| | Q8.24 | 8 | 24 | ±127 | 0.00000006 | | Q16.16 | 16 | 16 | ±32,767 | 0.000015 | | Q24.8 | 24 | 8 | ±8,388,607 | 0.004 | | Q31.1 | 31 | 1 | ±1,073,741,823 | 0.5 | **High precision, low range (Q8.24):** Signal processing, audio, small neural networks with normalised weights. **Balanced (Q16.16):** General-purpose, neural network inference, control systems. **High range, low precision (Q24.8):** Financial calculations with large integers, counters, timestamps. The format choice is a design decision that must be made upfront and documented. ### Overflow Handling Fixed-point overflow wraps silently: ```c q16_t max = 0x7FFFFFFF; // 32,767.999985 q16_t result = max + 1; // 0x80000000 = -32,768.0 (wrapped!) ``` This must be handled explicitly: ```c q16_t q16_add_saturate(q16_t a, q16_t b) { int64_t sum = (int64_t)a + (int64_t)b; if (sum > INT32_MAX) return INT32_MAX; if (sum > 16); } ``` Accumulating in 64-bit prevents overflow during the convolution. The final shift returns to Q16.16 format. For more on the mathematics, see [Fixed-Point Neural Networks: The Math Behind Q16.16](/insights/fixed-point-neural-networks/). ### Safety Monitors The [c-from-scratch](https://github.com/SpeyTech/c-from-scratch) modules support fixed-point for embedded deployment: ```c // EMA update in Q16.16 void baseline_update_q16(baseline_q16_t *ctx, q16_t value) { // ema_new = alpha * value + (1 - alpha) * ema_old q16_t weighted_value = q16_mul(ctx->alpha, value); q16_t weighted_ema = q16_mul(ctx->one_minus_alpha, ctx->ema); ctx->ema = q16_add(weighted_value, weighted_ema); } ``` The same algorithm, deterministic across all platforms, no FPU required. ### Financial Calculations For financial applications, larger integer parts may be needed: ```c // Q40.24 for large currency values with high precision typedef int64_t money_t; // 40 integer bits, 24 fractional #define MONEY_SCALE (1LL > 24) // ≈ 549 trillion money_t money_mul(money_t a, money_t b) { // Use 128-bit intermediate (compiler extension or manual) __int128 product = (__int128)a * b; return (money_t)(product >> 24); } ``` This handles values up to hundreds of trillions with sub-cent precision - adequate for most financial applications while remaining deterministic. ## Common Pitfalls ### Silent Overflow The most dangerous fixed-point bug: ```c q16_t large = 30000 32,767, so overflow! ``` **Solution:** Guard against division by small values, or use saturation. ### Mixing Formats Accidentally mixing Q8.24 and Q16.16 values produces garbage: ```c q8_24_t a = /* Q8.24 value */; q16_16_t b = /* Q16.16 value */; q16_16_t c = a + b; // Wrong! Different scales! ``` **Solution:** Use strong types and conversion functions. Consider the approach in [Fixed-Point Fundamentals](/open-source/fixed-point-fundamentals/). ## Frequently Asked Questions ### When should I use fixed-point instead of floating-point arithmetic? Use fixed-point when certification demands reproducible cross-platform results or when targeting hardware without an FPU. Use floating-point when dynamic range exceeds ±32767, when extensive scientific library support is needed, or when certification is not a constraint. ### How do I decide the fixed-point format for a specific application? Analyse the value ranges in your computation: the integer part must cover the maximum magnitude, and the fractional part must provide sufficient precision. Q16.16 suits most neural network inference. Narrower formats like Q8.8 save memory but reduce range and precision. Always validate against representative input data. ### Why doesn't fixed-point arithmetic work well for all numerical computations? Fixed-point has limited dynamic range — Q16.16 covers ±32767 with 16 bits of fractional precision. Computations that span many orders of magnitude, such as scientific simulation or financial derivatives pricing, may require floating-point's adaptive exponent. Division by small values can overflow, requiring explicit guards. ### What are the common pitfalls when converting floating-point code to fixed-point? Overflow from missing 64-bit intermediates, accumulated precision loss, division-by-small-value errors, and implicit type mixing are the primary pitfalls. ## Conclusion Fixed-point arithmetic isn't universally better than floating-point. It's a trade-off: **Fixed-point offers:** Determinism, reproducibility, analysability, no FPU requirement. **Fixed-point costs:** Limited range, manual overflow handling, more development effort, less library support. For safety-critical systems where certification requires deterministic behaviour and reproducible results, fixed-point is often the right choice. The costs are real but manageable, and the benefits - proving that the same code produces the same results everywhere - are essential. For research, prototyping, and non-critical applications, floating-point's convenience usually wins. The non-determinism rarely matters in practice. The key is making a conscious choice based on requirements, not defaulting to floating-point because it's familiar. When determinism matters more than dynamic range, fixed-point delivers. The [Fixed-Point Fundamentals](/open-source/fixed-point-fundamentals/) course provides a complete introduction to fixed-point arithmetic. The [certifiable-* ecosystem](https://github.com/SpeyTech) demonstrates production use in ML pipelines. As with any engineering decision, context matters. Know what you need, understand the trade-offs, and choose accordingly. --- ## Init-Update-Status-Reset: O(1) Safety Guarantees **URL**: https://speytech.com/insights/init-update-status-reset-pattern/ **Published**: January 26, 2026 20:05 **Topic**: Systems Architecture **Answers**: What is the Init-Update-Status-Reset four-function interface pattern used in safety-critical C programming, and how does this fixed and minimal API contract enable O(1) resource bounds, static analysis feasibility, bounded deterministic memory usage, and compositional verification across all modular system components? **Defines**: Init-Update-Status-Reset KEY_CLAIMS: - Every module in the c-from-scratch framework implements the same four-function interface: This isn't arbitrary convention. - The Init-Update-Status-Reset pattern is the minimal interface that provides O(1) resource bounds, deterministic execution, and compositional verification. - Init-Update-Status-Reset is a four-function interface pattern for safety-critical C modules that provides O(1) resource bounds and compositional verification. - By constraining the API surface to four functions with explicit preconditions, all resource usage is bounded at design time. - Additional functions create additional interaction paths, precondition combinations, and state transitions that must be verified. EVIDENCE: - Safety-critical standards like DO-178C, IEC 62304, and ISO 26262 require properties that the Init-Update-Status-Reset pattern provides by design. RELATES_TO: - insights/heartbeats-state-machines A four-function interface that enables static analysis, bounded resources, and compositional verification Every module in the [c-from-scratch](https://github.com/SpeyTech/c-from-scratch) framework implements the same four-function interface: ```c int module_init(module_t *ctx, const module_config_t *cfg); int module_update(module_t *ctx, input_t input, uint64_t timestamp); module_state_t module_status(const module_t *ctx); void module_reset(module_t *ctx); ``` This isn't arbitrary convention. The Init-Update-Status-Reset pattern is the minimal interface that simultaneously enables static analysis, bounded resource usage, deterministic execution, and compositional verification. Each function has a specific role in the module lifecycle, and the boundaries between them are load-bearing. Blur those boundaries and the guarantees collapse. ## The Four Functions ### init(): Configure Without Allocating ```c int baseline_init(baseline_t *ctx, const baseline_config_t *cfg) { if (ctx == NULL || cfg == NULL) { return BASELINE_ERR_NULL; } if (cfg->alpha alpha > 1.0) { return BASELINE_ERR_CONFIG; } ctx->cfg = *cfg; // Copy configuration ctx->state = BASELINE_LEARNING; ctx->sample_count = 0; ctx->ema = 0.0; ctx->variance = 0.0; ctx->last_timestamp = 0; return BASELINE_OK; } ``` **What init() does:** - Validates configuration parameters - Copies configuration into the context (caller owns the memory) - Sets initial state - Zeroes runtime fields **What init() doesn't do:** - Allocate memory (caller provides the context) - Perform any I/O - Depend on external state - Do anything that could fail unpredictably The caller owns memory allocation: ```c // Stack allocation - automatic lifetime baseline_t monitor; baseline_init(&monitor, &config); // Static allocation - program lifetime static baseline_t global_monitor; baseline_init(&global_monitor, &config); // Caller-managed heap - explicit lifetime baseline_t *monitors = malloc(n * sizeof(baseline_t)); for (int i = 0; i last_timestamp) return BASELINE_ERR_TEMPORAL; if (!isfinite(value)) return BASELINE_ERR_DOMAIN; // Update timestamp ctx->last_timestamp = timestamp; // State machine transition switch (ctx->state) { case BASELINE_LEARNING: update_learning(ctx, value); break; case BASELINE_MONITORING: update_monitoring(ctx, value); break; case BASELINE_FAULT: // Remain in fault until reset break; } return BASELINE_OK; } ``` **The critical constraint: all state changes happen in update().** This isn't a stylistic preference. It's what makes the module analysable: **Determinism:** If all state changes occur in `update()`, then given the same sequence of `update()` calls with the same inputs, the module will always reach the same state. Execution can be replayed exactly. **Atomicity:** Each `update()` call is a complete state transition. There's no partial update, no intermediate state visible to other code. Either the update completes or it fails cleanly. **Testability:** To test any state, construct the sequence of `update()` calls that reaches it. No hidden dependencies, no setup that isn't explicitly part of the test. **Traceability:** In safety-critical systems, auditors need to trace how state evolved. With all changes in `update()`, the trace is the sequence of inputs. ### status(): Pure Query Function ```c baseline_state_t baseline_status(const baseline_t *ctx) { if (ctx == NULL) return BASELINE_FAULT; return ctx->state; } ``` **The critical constraint: status() has no side effects.** The `const` qualifier on the context pointer isn't optional decoration - it's a contract enforced by the compiler. `status()` cannot modify the context, cannot increment counters, cannot update timestamps. This purity enables: **Concurrent access:** Multiple threads can call `status()` simultaneously without synchronisation. The function only reads. **Idempotent queries:** Calling `status()` twice returns the same result (assuming no intervening `update()`). There's no observer effect. **Debug instrumentation:** Logging, monitoring, and debugging code can query `status()` freely without affecting behaviour. The act of observing doesn't change what's observed. **Formal verification:** Pure functions are easier to reason about mathematically. The output depends only on the input, with no hidden state. ### reset(): Return to Known State ```c void reset(baseline_t *ctx) { if (ctx == NULL) return; // Preserve configuration baseline_config_t saved_cfg = ctx->cfg; // Clear all runtime state ctx->state = BASELINE_LEARNING; ctx->sample_count = 0; ctx->ema = 0.0; ctx->variance = 0.0; ctx->last_timestamp = 0; // Restore configuration ctx->cfg = saved_cfg; } ``` **The critical constraint: reset() is always safe to call.** This seems trivial but has profound implications: **Recovery:** When a module enters a fault state or behaves unexpectedly, `reset()` provides a guaranteed escape. The system can recover without restarting. **Testing:** Tests can reset between scenarios without reinitialising. State from one test doesn't leak into the next. **Long-running systems:** Systems that run for months need a way to clear accumulated state. `reset()` provides this without the complexity of full reinitialisation. **Composition:** When composing modules, a supervisor can reset any subordinate module at any time. This simplifies error handling at the system level. Note what `reset()` preserves: configuration. The module returns to its initial state but remembers how it was configured. This distinction matters - configuration represents design-time choices, while runtime state represents execution history. ## Why This Pattern Enables Certification Safety-critical standards like DO-178C, IEC 62304, and ISO 26262 require properties that the Init-Update-Status-Reset pattern provides by design. ### Bounded Memory (MC/DC Coverage) ```c // Maximum memory usage is sizeof(baseline_t) // This is known at compile time // No allocation = no fragmentation = no memory exhaustion ``` Certification requires proving that software cannot exhaust memory. Dynamic allocation makes this proof difficult or impossible. With caller-provided memory and no internal allocation, the proof is trivial: memory usage equals the sum of context struct sizes. ### Bounded Execution Time (WCET) ```c int baseline_update(baseline_t *ctx, double value, uint64_t timestamp) { // Fixed number of operations // No loops with data-dependent bounds // No recursion // WCET can be computed by static analysis } ``` Worst-Case Execution Time analysis requires that every code path have a provable upper bound. The pattern enforces this: - `init()`: Fixed sequence of assignments - `update()`: Fixed state machine with bounded transitions - `status()`: Single field access - `reset()`: Fixed sequence of assignments No function contains unbounded loops, recursion, or data-dependent iteration. WCET tools can analyse each function automatically. ### Deterministic Execution ```c // Same sequence of inputs → same sequence of states // No hidden state, no external dependencies, no randomness ``` Reproducibility is fundamental to testing and certification. If a test passes, it must continue to pass. If a failure occurs, it must be reproducible for diagnosis. The pattern guarantees determinism: - `init()` depends only on configuration (static) - `update()` depends only on context and input (explicit) - `status()` depends only on context (read-only) - `reset()` depends only on context (deterministic) There are no hidden inputs: no global variables, no system calls, no timestamps from hardware clocks (timestamps are passed as parameters). ### Traceability ```c // Every state is reachable via a sequence of update() calls // That sequence is the trace // The trace is the specification for reproduction ``` When something goes wrong, auditors need to know how the system reached that state. With all state changes in `update()`, the trace is simply the sequence of `(input, timestamp)` pairs passed to `update()`. This trace can be: - Logged for post-incident analysis - Replayed for debugging - Analysed for coverage - Verified against requirements ## Comparison with Object-Oriented Patterns Traditional OOP approaches to stateful components look different: ```cpp class BaselineMonitor { public: BaselineMonitor(const Config& cfg); ~BaselineMonitor(); void processValue(double value); // Modifies state State getState() const; // Queries state double getEMA() const; // Queries state void setThreshold(double t); // Modifies config AND state? private: State state_; double ema_; // ... }; ``` This design has several properties that complicate certification: **Constructor allocation:** The constructor may allocate memory, making resource bounds harder to prove. **Multiple mutators:** Both `processValue()` and `setThreshold()` modify state. State changes aren't localised. **Blurred boundaries:** Does `setThreshold()` just change configuration, or does it also affect runtime state? The interface doesn't say. **Destructor complexity:** Destructors can fail, throw exceptions, or have side effects. Resource cleanup is implicit. **No explicit reset:** How do you return the object to initial state? Destroy and reconstruct? That involves allocation. The Init-Update-Status-Reset pattern makes explicit what OOP often leaves implicit: | Concern | OOP Approach | IUSR Pattern | |---------|--------------|--------------| | Memory | Constructor allocates | Caller provides | | State change | Multiple methods | Only `update()` | | Configuration | Mixed with runtime | Separate in `init()` | | Reset | Unclear/reconstruct | Explicit `reset()` | | Analysis | Requires whole-program | Per-function | ## Pattern Composition Modules following the pattern compose naturally. Consider a system with temperature and pressure monitors: ```c typedef struct { temp_monitor_t temp; pressure_monitor_t pressure; system_state_t state; } system_t; int system_init(system_t *sys, const system_config_t *cfg) { int err; err = temp_init(&sys->temp, &cfg->temp); if (err != TEMP_OK) return SYSTEM_ERR_TEMP_INIT; err = pressure_init(&sys->pressure, &cfg->pressure); if (err != PRESSURE_OK) return SYSTEM_ERR_PRESSURE_INIT; sys->state = SYSTEM_NOMINAL; return SYSTEM_OK; } int system_update(system_t *sys, sensor_data_t *data, uint64_t timestamp) { int temp_err = temp_update(&sys->temp, data->temperature, timestamp); int press_err = pressure_update(&sys->pressure, data->pressure, timestamp); // Compose component states into system state if (temp_err != TEMP_OK || press_err != PRESSURE_OK) { sys->state = SYSTEM_SENSOR_FAULT; } else if (temp_status(&sys->temp) == TEMP_ALARM || pressure_status(&sys->pressure) == PRESSURE_ALARM) { sys->state = SYSTEM_ALARM; } else { sys->state = SYSTEM_NOMINAL; } return SYSTEM_OK; } system_state_t system_status(const system_t *sys) { return sys->state; } void system_reset(system_t *sys) { temp_reset(&sys->temp); pressure_reset(&sys->pressure); sys->state = SYSTEM_NOMINAL; } ``` The system-level module follows the same pattern as its components. This fractal structure means: - The system can be tested the same way as components - System-level guarantees derive from component guarantees - Another system can compose this system as a component Composition preserves properties. If all components have O(1) memory, the composition has O(1) memory. If all components are deterministic, the composition is deterministic. ## Implementing the Pattern ### State Machine Structure Most modules following this pattern contain an explicit finite state machine: ```c typedef enum { STATE_INIT, STATE_LEARNING, STATE_MONITORING, STATE_ALARM, STATE_FAULT } module_state_t; // Transition table (documentation) // STATE_INIT + init() → STATE_LEARNING // STATE_LEARNING + enough_samples → STATE_MONITORING // STATE_MONITORING + anomaly → STATE_ALARM // STATE_ALARM + normal → STATE_MONITORING // ANY + fault → STATE_FAULT // STATE_FAULT + reset() → STATE_LEARNING ``` The state machine makes transitions explicit and analysable. Tools can verify that all states are reachable, all transitions are handled, and no invalid transitions occur. This connects to [Heartbeats and State Machines](/insights/heartbeats-state-machines/) - the same FSM principles apply to any temporal monitoring problem. ### Error Handling The pattern uses return codes rather than exceptions: ```c typedef enum { MODULE_OK = 0, MODULE_ERR_NULL = -1, MODULE_ERR_TEMPORAL = -2, MODULE_ERR_DOMAIN = -3, MODULE_ERR_OVERFLOW = -4, MODULE_ERR_STATE = -5, MODULE_ERR_CONFIG = -6 } module_error_t; ``` Return codes are: - Analysable (static analysis can track error propagation) - Predictable (no hidden control flow) - Explicit (callers must handle them) The pattern requires that `update()` returns an error code. Even when the update succeeds, the return value confirms it. ### Time Handling Time is passed as a parameter, not read from system clocks: ```c int module_update(module_t *ctx, double input, uint64_t timestamp); ``` This design choice enables: **Deterministic replay:** Given recorded inputs and timestamps, execution can be replayed exactly. **Testing:** Tests can simulate arbitrary time progressions without mocking system calls. **Portability:** No dependency on platform-specific time APIs. **Analysis:** Time-dependent behaviour is explicit in the interface. The module enforces monotonic time internally: ```c if (timestamp last_timestamp) { return MODULE_ERR_TEMPORAL; } ``` Out-of-order timestamps are rejected rather than causing undefined behaviour. ## When Not to Use This Pattern The Init-Update-Status-Reset pattern optimises for specific properties. It's not always the right choice. **Interactive applications:** GUI components often need multiple entry points, event handlers, and partial updates. The strict lifecycle is too rigid. **Streaming data:** When processing continuous streams with complex dependencies, the single `update()` entry point may force awkward batching. **Performance-critical inner loops:** The precondition checks in `update()` add overhead. In tight loops where inputs are guaranteed valid, this overhead matters. **Exploratory development:** When requirements are unclear, the upfront design required by this pattern can slow iteration. The pattern shines when: - Correctness must be provable - Behaviour must be reproducible - Resources must be bounded - Components must compose reliably - Certification is required For safety-critical systems, these properties aren't optional. For other systems, they're often valuable but not mandatory. ## Frequently Asked Questions ### What is the Init-Update-Status-Reset pattern? Init-Update-Status-Reset is a four-function interface pattern for safety-critical C modules that provides O(1) resource bounds and compositional verification. Every module exposes exactly four functions — init() to set up state, update() to process input, status() to query state, and reset() to return to initial conditions. ### How does the four-function interface enable O(1) resource guarantees? By constraining the API surface to four functions with explicit preconditions, all resource usage is bounded at design time. Init allocates once, update processes in constant time per call, status queries without allocation, and reset restores initial state. No function path can allocate unbounded memory or execute unbounded computation. ### Why can't a well-designed API with more functions provide the same guarantees? Additional functions create additional interaction paths, precondition combinations, and state transitions that must be verified. The four-function pattern's power comes from its constraint: every module behaves identically, enabling automated verification tools and compositional reasoning. Uniformity reduces the verification surface to a single proven pattern. ### When should I not use the Init-Update-Status-Reset pattern? Avoid this pattern for interactive applications, streaming data with complex dependencies, and performance-critical inner loops. ## Conclusion The Init-Update-Status-Reset pattern is the minimal interface that provides O(1) resource bounds, deterministic execution, and compositional verification. The four functions aren't arbitrary - each serves a specific purpose: - **init()** separates configuration from allocation - **update()** localises all state changes - **status()** guarantees side-effect-free queries - **reset()** provides guaranteed recovery Together, they enable the properties that safety-critical certification requires: bounded memory, bounded time, deterministic behaviour, and complete traceability. The [c-from-scratch](https://github.com/SpeyTech/c-from-scratch) repository demonstrates this pattern across multiple modules. Each module - Pulse, Baseline, Timing - implements the same interface, enabling composition and consistent testing. The pattern's constraints feel restrictive at first. All state changes in one function? No internal allocation? Explicit time parameters? These choices force discipline that pays off during testing, debugging, and certification. As with any architectural pattern, appropriateness depends on requirements. For systems where "it usually works" isn't acceptable, the Init-Update-Status-Reset pattern provides a foundation for code that provably works. Four functions. Complete lifecycle. Verifiable contracts. --- ## Contracts as Documentation: Why Comments Lie **URL**: https://speytech.com/insights/contracts-as-documentation/ **Published**: January 26, 2026 19:00 **Topic**: Formal Methods **Answers**: How do software contracts using explicit preconditions, postconditions, and class invariants serve as machine-verifiable living documentation that stays permanently synchronised with actual source code behaviour, and why are traditional code comments and separate external documents unreliable compared to enforced contract specifications? **Defines**: Software contracts KEY_CLAIMS: - Consider this function: The comment says "safely." The code doesn't check for overflow. - Comments describe what programmers hope code does. - Contracts express preconditions, postconditions, and invariants directly in source code. - Comments describe intent but are not enforced — they become stale as code changes. - Unit tests verify specific input-output pairs but do not document the general contract a function satisfies. RELATES_TO: - insights/mathematical-proofs-to-code How preconditions, postconditions, and invariants become living documentation Consider this function: ```c // Adds two numbers safely int add(int a, int b) { return a + b; } ``` The comment says "safely." The code doesn't check for overflow. When `a + b` exceeds `INT_MAX`, the result is undefined behaviour - not just a wrong answer, but a license for the compiler to do anything it wants. The comment lied. And there's no mechanism to detect the lie. This isn't a contrived example. Production codebases are filled with comments that describe what the author *intended*, not what the code *guarantees*. Comments rot as code evolves. Nobody updates the "safely" comment when a rushed bug fix removes the overflow check. Six months later, a new engineer trusts the comment and builds a system that crashes in production. Contracts offer an alternative: documentation that can't lie because it's enforced by the code itself. ## What Contracts Actually Are A contract is a formal specification of what a function requires and what it guarantees. The terminology comes from design-by-contract, pioneered by Bertrand Meyer in Eiffel, but the concept predates any programming language - it's just mathematics applied to software. A complete contract has three components: **Preconditions (PRE):** What must be true before the function is called. These are the caller's obligations. **Postconditions (POST):** What will be true after the function returns, assuming preconditions were met. These are the function's guarantees. **Invariants (INV):** What must remain true throughout the function's execution and across all calls. These are the system's consistency rules. Here's the "safe add" function with an actual contract: ```c /* * PRE: overflow != NULL * POST: If (a + b) would overflow int32_t, *overflow = true and returns INT32_MAX or INT32_MIN * POST: If no overflow, *overflow = false and returns exact result a + b * INV: Function is pure - no side effects except writing to *overflow */ int32_t safe_add(int32_t a, int32_t b, bool *overflow) { // Check for positive overflow if ((b > 0) && (a > INT32_MAX - b)) { *overflow = true; return INT32_MAX; } // Check for negative overflow if ((b full_name; } ``` The comment says "Unknown" but the code returns NULL. Someone changed the behaviour but not the documentation. Any code relying on the comment will dereference NULL and crash. ### Comments Can't Be Tested There's no automated way to verify that a comment matches the code's actual behaviour. You can lint for missing comments, but not for lying ones. Code review might catch discrepancies, but code review is fallible and doesn't scale. Contracts, expressed as preconditions and postconditions, can be mechanically tested. The test suite becomes a formal verification that the contract holds. ## Contracts in Practice The [c-from-scratch](https://github.com/SpeyTech/c-from-scratch) framework uses contracts throughout. Here's how they appear in a real module: ### Header File Contracts The public interface declares contracts in header comments: ```c /** * baseline_update - Process a new input value * * PRE: ctx != NULL * PRE: ctx initialised via baseline_init() * PRE: timestamp > ctx->last_timestamp (monotonic time) * PRE: value is finite (not NaN or Inf) * * POST: ctx->state updated according to FSM rules * POST: If value is anomalous, ctx->anomaly_count incremented * POST: If in MONITORING state, EMA and variance updated * POST: Returns BASELINE_OK on success, error code on precondition violation * * INV: O(1) time complexity * INV: O(1) space complexity (no allocation) * INV: Deterministic (same inputs -> same outputs) */ int baseline_update(baseline_t *ctx, double value, uint64_t timestamp); ``` This contract tells you everything you need to call the function correctly: - What you must provide (non-null, initialised context, monotonic time, finite value) - What you'll get back (updated state, incremented counters, specific return codes) - What's guaranteed about execution (bounded time, bounded space, deterministic) ### Implementation Enforces Contracts The implementation's first job is to verify preconditions: ```c int baseline_update(baseline_t *ctx, double value, uint64_t timestamp) { // Verify preconditions if (ctx == NULL) { return BASELINE_ERR_NULL; } if (timestamp last_timestamp) { return BASELINE_ERR_TEMPORAL; } if (!isfinite(value)) { return BASELINE_ERR_DOMAIN; } // Preconditions satisfied - proceed with update // ... } ``` This pattern - check preconditions first, return error codes on violation - ensures that: 1. The function never operates on invalid input 2. Callers get explicit notification of violations 3. The system fails safely rather than corrupting state ### Tests Verify Contracts Each contract clause becomes one or more tests: ```c // Test: PRE ctx != NULL void test_null_context_rejected(void) { int result = baseline_update(NULL, 1.0, 1000); assert(result == BASELINE_ERR_NULL); } // Test: PRE timestamp > ctx->last_timestamp void test_non_monotonic_timestamp_rejected(void) { baseline_t ctx; baseline_init(&ctx, &default_config); baseline_update(&ctx, 1.0, 1000); int result = baseline_update(&ctx, 2.0, 500); // Earlier timestamp assert(result == BASELINE_ERR_TEMPORAL); } // Test: PRE value is finite void test_nan_rejected(void) { baseline_t ctx; baseline_init(&ctx, &default_config); int result = baseline_update(&ctx, NAN, 1000); assert(result == BASELINE_ERR_DOMAIN); } // Test: POST deterministic void test_determinism(void) { baseline_t ctx1, ctx2; baseline_init(&ctx1, &default_config); baseline_init(&ctx2, &default_config); // Same inputs baseline_update(&ctx1, 1.0, 1000); baseline_update(&ctx2, 1.0, 1000); // Must produce same state assert(ctx1.state == ctx2.state); assert(ctx1.ema == ctx2.ema); assert(ctx1.variance == ctx2.variance); } ``` When these tests pass, the contracts are verified. When code changes break a contract, tests fail. The documentation can't lie because the tests enforce it. ## The Contract Hierarchy Contracts exist at multiple levels, from individual functions to entire systems. ### Function-Level Contracts The most granular level. Each function specifies what it requires and guarantees: ```c // PRE: 0 = min_samples * - variance >= 0 (never negative) * - ema is finite (never NaN or Inf) when state != FAULT */ ``` Every function that modifies `baseline_t` must preserve these invariants. Tests verify the invariants hold before and after each operation. ### System-Level Contracts Contracts between components. The Init-Update-Status-Reset pattern described in [c-from-scratch](https://github.com/SpeyTech/c-from-scratch) is itself a system-level contract: ```c /* * SYSTEM CONTRACT: Init-Update-Status-Reset Lifecycle * * 1. init() must be called before any other function * 2. update() is the only function that modifies state * 3. status() is a pure function (no side effects) * 4. reset() returns module to post-init state * 5. reset() is safe to call at any time * 6. After reset(), module behaves as if freshly initialised */ ``` Any module implementing this pattern can be composed with any other such module. The contract guarantees interoperability. ## Contracts vs. Assertions Some languages provide `assert()` for runtime checks. How do contracts differ? ### Assertions Check Implementation Details ```c void process_buffer(char *buf, int len) { assert(len > 0); // Catch programmer errors assert(buf != NULL); // ... implementation } ``` These assertions help during debugging but disappear in release builds (when `NDEBUG` is defined). They're not part of the interface - they're implementation sanity checks. ### Contracts Define the Interface ```c /* * PRE: len > 0 * PRE: buf != NULL */ int process_buffer(char *buf, int len) { if (len temp, data->temperature, time); int press_result = press_update(&sys->press, data->pressure, time); // Compose results according to system contract if (temp_result == TEMP_FAULT || press_result == PRESS_FAULT) { sys->state = SYSTEM_FAULT; return SYSTEM_FAULT; } return SYSTEM_OK; } ``` Because each module's contracts are known, the composition's behaviour is predictable. The system-level contract can be derived from the component contracts. This is how safety-critical systems are built: verified components with known contracts, composed into verified systems. The alternative - hoping that components interact correctly - doesn't scale and can't be certified. ## Contracts in Documentation For projects with external users, contracts belong in documentation as well as code: ### API Documentation ```markdown ## baseline_update Updates the baseline monitor with a new value. ### Parameters - `ctx`: Pointer to initialised baseline_t structure - `value`: New measurement value (must be finite) - `timestamp`: Current time in nanoseconds (must be monotonically increasing) ### Returns - `BASELINE_OK` (0): Success - `BASELINE_ERR_NULL` (-1): ctx was NULL - `BASELINE_ERR_TEMPORAL` (-2): timestamp was not greater than previous - `BASELINE_ERR_DOMAIN` (-3): value was NaN or infinite ### Contract **Preconditions:** - `ctx != NULL` - `ctx` has been initialised via `baseline_init()` - `timestamp > ctx->last_timestamp` - `isfinite(value)` **Postconditions:** - State machine updated according to current state and value - If anomaly detected, `ctx->anomaly_count` incremented - Returns appropriate status code **Invariants:** - O(1) time complexity - O(1) space complexity - Deterministic execution ``` This documentation can't rot because it matches the code's actual behaviour - the tests verify it. ## From Proofs to Code Contracts bridge the gap between mathematical specification and implementation, as discussed in [From Proofs to Code: Mathematical Transcription in C](/insights/mathematical-proofs-to-code/). The mathematical model defines what *should* happen: ``` State transition: MONITORING + anomaly → increment counter Formally: anomaly(v) ∧ state = MONITORING → counter' = counter + 1 ``` The contract specifies the function's obligations: ```c // POST: If value is anomalous and state == MONITORING, anomaly_count incremented ``` The implementation fulfills the contract: ```c if (is_anomaly(ctx, value) && ctx->state == MONITORING) { ctx->anomaly_count++; } ``` The test verifies the contract: ```c void test_anomaly_increments_counter(void) { baseline_t ctx; baseline_init(&ctx, &config); advance_to_monitoring(&ctx); // Helper to reach MONITORING state uint32_t count_before = ctx.anomaly_count; baseline_update(&ctx, ANOMALOUS_VALUE, next_time()); assert(ctx.anomaly_count == count_before + 1); } ``` This chain - math → contract → code → test - is traceable. An auditor can verify that requirements flow through to implementation. ## Practical Contract Patterns ### The Guard Pattern Check preconditions immediately, return on violation: ```c int process(context_t *ctx, input_t input) { // Guards - check all preconditions first if (ctx == NULL) return ERR_NULL; if (!is_valid_input(input)) return ERR_INVALID; if (ctx->state == STATE_FAULT) return ERR_FAULT; // All preconditions satisfied - do the work // ... } ``` Guards make precondition checking explicit and consistent. The function's "happy path" only executes when all preconditions are met. ### The State Machine Pattern Model valid states and transitions explicitly: ```c typedef enum { STATE_INIT, STATE_READY, STATE_RUNNING, STATE_FAULT } state_t; // CONTRACT: Valid transitions // INIT -> READY (via initialise) // READY -> RUNNING (via start) // RUNNING -> READY (via stop) // ANY -> FAULT (via error) // FAULT -> INIT (via reset) int transition(context_t *ctx, event_t event) { switch (ctx->state) { case STATE_INIT: if (event == EVENT_INIT_COMPLETE) { ctx->state = STATE_READY; return OK; } break; // ... other transitions } return ERR_INVALID_TRANSITION; } ``` The state machine is the contract. Invalid transitions return errors rather than corrupting state. ### The Result Pattern Return structured results that capture success, failure, and context: ```c typedef struct { int status; // OK or error code double value; // Result if OK const char *message; // Human-readable status } result_t; // CONTRACT: // If result.status == OK, result.value contains valid output // If result.status != OK, result.message describes the failure result_t calculate(double input) { if (!isfinite(input)) { return (result_t){ERR_DOMAIN, 0, "Input must be finite"}; } double output = /* calculation */; if (!isfinite(output)) { return (result_t){ERR_OVERFLOW, 0, "Calculation overflowed"}; } return (result_t){OK, output, "Success"}; } ``` Callers can't accidentally use invalid results because the contract ties validity to the status code. ## Frequently Asked Questions ### How do software contracts serve as machine-verifiable documentation? Contracts express preconditions, postconditions, and invariants directly in source code. Unlike comments or external documents, contracts are checked at compile time or runtime — they cannot drift from implementation because they are the implementation. Violations produce immediate, specific error messages identifying the broken guarantee. ### How do contracts differ from comments and external documentation? Comments describe intent but are not enforced — they become stale as code changes. External documents live separately from code and require manual synchronisation. Contracts are co-located with the code they describe and are machine-verified, making it impossible for the specification to silently diverge from the implementation. ### Why can't comprehensive unit tests replace contracts as documentation? Unit tests verify specific input-output pairs but do not document the general contract a function satisfies. Tests can pass while the function violates its intended preconditions for untested inputs. Contracts document and enforce the general rule — every call, every input, every execution path is checked, not just the tested cases. ### What are the limitations of contracts as documentation? Contracts add syntactic overhead to function signatures. Complex invariants may be difficult to express as executable assertions. Performance-sensitive code may need contract checking disabled in release builds, reducing runtime protection. The documentation value is highest for interfaces and boundaries, diminishing for trivial internal helper functions. ## Conclusion Comments describe what programmers hope code does. Contracts specify what code must do - and tests verify that it does. The shift from comments to contracts isn't just better documentation. It's a different way of thinking about software: - Functions have obligations (postconditions), not just behaviours - Callers have obligations (preconditions), not just inputs - Systems have consistency rules (invariants), not just states This thinking leads naturally to code that can be reasoned about, tested systematically, and trusted in production. It's the foundation of safety-critical development, but it benefits any codebase where correctness matters. Comments will always have a place - explaining *why* decisions were made, providing context, helping humans understand code. But for specifying *what* code guarantees, contracts are the tool that can't lie. The [c-from-scratch](https://github.com/SpeyTech/c-from-scratch) framework provides working examples of contract-based development. The patterns described here - guards, state machines, structured results - appear throughout. For a structured introduction to this methodology, ["C From Scratch"](https://leanpub.com/c-from-scratch) covers contracts from first principles. As with any engineering practice, the appropriate level of formality depends on context. Not every function needs a full contract specification. But understanding what contracts *are* and when to use them is essential knowledge for engineers building systems that matter. Documentation should tell the truth. Contracts make sure it does. --- ## Why 'Hello World' Fails Safety-Critical Engineers **URL**: https://speytech.com/insights/hello-world-fails-safety-critical/ **Published**: January 26, 2026 18:30 **Topic**: Safety-Critical Programming **Answers**: Why does the traditional C hello world programme and conventional C tutorial teaching approach actively fail to prepare engineers for safety-critical software development, and what specific coding habits and assumptions do certification auditors routinely reject that introductory tutorials commonly teach? **Defines**: Safety-critical C KEY_CLAIMS: - Every C programmer's journey starts the same way: Compile. - Safety-critical C is a constrained subset of the C language that prohibits dynamic allocation, unbounded loops, and implicit behaviour to satisfy certification requirements. - Traditional hello world teaches implicit dependencies, unverified assumptions, and printf-based output — habits that certification auditors routinely reject. - Start with mathematical contracts and preconditions before writing implementation code. - Retrofitting contracts onto code designed without them requires fundamental restructuring. EVIDENCE: - For safety-critical systems governed by DO-178C, IEC 62304, or ISO 26262, dynamic memory allocation is either prohibited entirely or requires extensive justification and analysis. - DO-178C Level A (for flight-critical avionics software) requires: 100% code coverage. - Consider: Medical devices: IEC 62304 Class C software (which can cause death or serious injury) has requirements similar to DO-178C. - Automotive: ISO 26262 ASIL-D (highest automotive safety level) requires similar rigour. Traditional C tutorials teach habits that certification auditors reject Every C programmer's journey starts the same way: ```c #include int main(void) { printf("Hello, World!\n"); return 0; } ``` Compile. Run. Celebrate. You're a C programmer now. Except you're not. You've just learned that C is a language where you type things and hope they work. That lesson - hope as a development strategy - will follow you through pointers, memory allocation, and eventually into production systems where hope gets people killed. This isn't hyperbole. The Therac-25 killed patients because of race conditions that "usually worked." Knight Capital lost $440 million in 45 minutes because of code that "worked in testing." The traditional C tutorial path doesn't just fail to prepare engineers for safety-critical work - it actively teaches habits that certification auditors will reject. Definition: Safety-Critical C Safety-critical C is a constrained subset of the C language that prohibits dynamic allocation, unbounded loops, and implicit behaviour to satisfy certification requirements. ## The Problem with printf The first line of most C tutorials introduces a function that violates nearly every principle of safety-critical software: **printf uses dynamic memory.** The format string parsing, buffer management, and output handling all involve allocation patterns that cannot be statically analysed for worst-case behaviour. **printf has unbounded execution time.** Depending on the format string, arguments, and output device, the same printf call can take microseconds or seconds. In a system with real-time constraints, this is unacceptable. **printf can fail silently.** Most tutorials ignore the return value. In safety-critical systems, every function call must have its return value checked and its failure modes handled. **printf teaches output-first thinking.** The programmer's first instinct becomes "print something to see if it worked" rather than "prove it works before running it." None of this means printf is evil. It's a useful debugging tool and perfectly appropriate for user-facing applications. The problem is that it's the *first* thing we teach, and first lessons shape everything that follows. ## The Malloc Mindset After "Hello World," tutorials progress to dynamic memory: ```c int *numbers = malloc(n * sizeof(int)); if (numbers == NULL) { // handle error... somehow } // use numbers free(numbers); ``` This teaches several dangerous patterns: **Memory size determined at runtime.** The program cannot know its memory requirements until execution. Static analysis cannot prove memory bounds. The certifier cannot verify worst-case resource usage. **Allocation can fail.** And the tutorial's "handle error... somehow" comment reveals that nobody really knows what to do when it does. In safety-critical systems, "somehow" isn't a specification. **Manual lifetime management.** The programmer must remember to free memory, in the right order, exactly once. Forget and you leak. Free twice and you corrupt. Use after free and you get undefined behaviour. **Heap fragmentation is invisible.** A program can run successfully for months, then fail when fragmentation finally prevents allocation. No amount of testing catches this reliably. For safety-critical systems governed by DO-178C, IEC 62304, or ISO 26262, dynamic memory allocation is either prohibited entirely or requires extensive justification and analysis. Yet it's the second thing we teach new C programmers. ## The Undefined Behaviour Trap By lesson three or four, most tutorials have introduced undefined behaviour without naming it: ```c int array[10]; for (int i = 0; i last_pulse_time = current_time; ctx->state = PULSE_ALIVE; return PULSE_OK; } // No pulse - check timeout if (ctx->state == PULSE_ALIVE) { uint64_t elapsed = current_time - ctx->last_pulse_time; if (elapsed > ctx->timeout_ns) { ctx->state = PULSE_DEAD; } } return PULSE_OK; } ``` This code contains no creativity. It's a direct translation of the state machine. The creativity happened in the mathematical design, where it could be analysed and proven correct. ### Step 6: Test the Proofs Tests don't verify that the code "seems to work." They verify that the mathematical contracts hold: ```c // CONTRACT: Pulse within timeout maintains ALIVE state void test_alive_maintained(void) { pulse_monitor_t mon; pulse_init(&mon, TIMEOUT_NS); pulse_update(&mon, 1000, true); // First pulse assert(pulse_status(&mon) == PULSE_ALIVE); pulse_update(&mon, 1000 + TIMEOUT_NS - 1, true); // Just before timeout assert(pulse_status(&mon) == PULSE_ALIVE); } // CONTRACT: Missing pulse beyond timeout transitions to DEAD void test_timeout_detected(void) { pulse_monitor_t mon; pulse_init(&mon, TIMEOUT_NS); pulse_update(&mon, 1000, true); // First pulse pulse_update(&mon, 1000 + TIMEOUT_NS + 1, false); // Beyond timeout assert(pulse_status(&mon) == PULSE_DEAD); } ``` Each test corresponds to a mathematical property. If the test fails, either the implementation is wrong or the proof was flawed. Either way, we know exactly what to fix. ## The Init-Update-Status-Reset Pattern The [c-from-scratch](https://github.com/SpeyTech/c-from-scratch) framework standardises on a four-function interface for all safety monitors: ```c int module_init(module_t *ctx, const module_config_t *cfg); int module_update(module_t *ctx, input_t input, uint64_t timestamp); module_state_t module_status(const module_t *ctx); void module_reset(module_t *ctx); ``` This pattern enables: **Static allocation.** The caller provides memory. The module never allocates. **Deterministic state transitions.** All state changes happen in `update()`. Status queries are pure functions. **Composability.** Modules with identical interfaces can be combined, chained, and verified independently. **Testability.** Each function has clear preconditions and postconditions that tests can verify. This isn't an arbitrary convention. It's the minimal interface that supports formal verification while remaining practical for real systems. ## Why This Matters Beyond Aerospace The math-first approach isn't just for flight software. Consider: **Medical devices:** IEC 62304 Class C software (which can cause death or serious injury) has requirements similar to DO-178C. The same methodology applies. **Automotive:** ISO 26262 ASIL-D (highest automotive safety level) requires similar rigour. Self-driving systems need provable behaviour. **Financial systems:** Knight Capital's $440 million loss came from code that "worked" until it didn't. Deterministic, provable systems prevent this class of failure. **Infrastructure:** Power grids, water treatment, and industrial control systems increasingly require formal methods. The traditional tutorial path doesn't prepare engineers for this work. Even in non-safety-critical domains, the discipline pays off. Code designed mathematically is easier to test, easier to maintain, and easier to reason about. The techniques scale down gracefully. ## Unlearning Hello World The first step is recognising that traditional C education optimises for the wrong thing. It optimises for "getting something working quickly" when it should optimise for "knowing why it works." The second step is accepting that correctness requires more upfront effort. Defining invariants before writing code feels slow. It is slow - initially. The time is recovered many times over during testing, debugging, and maintenance. The third step is building new habits: - Before writing a function, write its contract (preconditions, postconditions, invariants) - Before designing a struct, draw the state machine it represents - Before implementing a loop, prove it terminates - Before allocating memory, prove you know the maximum These habits feel awkward at first. Like all habits, they become automatic with practice. ## Getting Started The [c-from-scratch](https://github.com/SpeyTech/c-from-scratch) repository provides a complete framework for learning this approach. Each module includes: - Mathematical specification with proofs - Struct design with field-by-field justification - Implementation as literal math transcription - Contract-based tests with 100k+ input fuzzing Start with the Pulse module. It's roughly 200 lines of code, but those 200 lines demonstrate every principle: closed state, total functions, bounded resources, deterministic execution. **A note on output:** The examples in this article focus on the methodology rather than console output - safety-critical code communicates through return codes and state queries, not printf. The repository includes complete working demos for each module that show the contracts in action with visible results you can run and observe. For a structured learning path, ["C From Scratch: Learn Safety-Critical C the Right Way"](https://leanpub.com/c-from-scratch) walks through the methodology from first principles, building toward a complete capstone project. ## Frequently Asked Questions ### Why does the traditional C hello world programme fail safety-critical engineers? Traditional hello world teaches implicit dependencies, unverified assumptions, and printf-based output — habits that certification auditors routinely reject. Safety-critical C requires explicit contracts, precondition validation, no global state, and return-code communication instead of console output. The tutorial approach builds the wrong instincts. ### How should engineers learn C for safety-critical development? Start with mathematical contracts and preconditions before writing implementation code. Each function should have explicit preconditions verified at entry, postconditions guaranteed at exit, and documented invariants. The [C From Scratch](https://github.com/SpeyTech/c-from-scratch) course teaches this methodology from first principles with seven modules of contract-based exercises. ### Why can't safety-critical engineers just add contracts to existing C code? Retrofitting contracts onto code designed without them requires fundamental restructuring. Code written with implicit assumptions, global state, and unchecked inputs embeds those assumptions into every caller. The dependency graph must be rebuilt to make contracts enforceable, which often costs more than rewriting from a verified foundation. ### What coding habits from C tutorials do certification auditors reject? Auditors reject unchecked return values, printf-based communication, global state, and functions lacking documented contracts. Each represents an unverified assumption that certification standards require eliminating. ## Conclusion "Hello World" isn't wrong. It's just the wrong starting point for engineers who will work on systems that matter. The traditional C tutorial path teaches hope-based development: write code, run it, hope it works, debug when it doesn't. This approach cannot produce software that meets safety certification requirements, and it builds habits that must be painfully unlearned. The alternative - proving correctness before implementation - requires more discipline but produces code that can be trusted. When that code controls an aircraft, monitors a pacemaker, or manages a power grid, "can be trusted" isn't a nice-to-have. It's the entire point. As with any methodology, suitability depends on context. Not every program needs formal verification. But every programmer benefits from understanding what formal verification requires - because it clarifies what "correct" actually means. Hope is not a certification strategy. Mathematics is. --- ## C From Scratch: Learning Safety-Critical C **URL**: https://speytech.com/insights/c-from-scratch-book-launch/ **Published**: January 24, 2026 22:31 **Topic**: Announcements **Answers**: What is the C From Scratch approach to learning C programming specifically for safety-critical systems development, and how does the methodology of proving code correct through mathematical contracts and preconditions before writing the implementation differ from traditional C tutorial approaches? **Defines**: Safety-critical C KEY_CLAIMS: - Most C tutorials teach you to write code that seems to work. - Contract-first C programming verifies correctness through mathematical preconditions and postconditions before writing implementation code, ensuring every function meets its specification. - The gap between "knowing C syntax" and "writing certifiable C" is real, but it doesn't have to take a decade to cross. - C From Scratch teaches C programming through mathematical contracts and formal verification from the first chapter. - Traditional tutorials start with printf and progress through syntax. EVIDENCE: - The Ariane 5 rocket exploded because of an integer overflow. - The Therac-25 killed patients because of race conditions. - Knight Capital lost $440 million in 45 minutes because of a deployment bug. - The final chapter bridges to production: DO-178C for aerospace, IEC 62304 for medical devices, ISO 26262 for automotive. Why proving code correct before writing it changes everything Most C tutorials teach you to write code that seems to work. They show syntax, patterns, maybe some best practices. Then you ship, and something explodes. The Ariane 5 rocket exploded because of an integer overflow. The Therac-25 killed patients because of race conditions. Knight Capital lost $440 million in 45 minutes because of a deployment bug. These weren't written by bad programmers. They were written by engineers who didn't have a methodology for proving their code correct. **C From Scratch** is now available on [Leanpub](https://leanpub.com/c-from-scratch). It teaches a different approach: prove your code correct *before* you write it. Definition: Contract-First C Programming Contract-first C programming verifies correctness through mathematical preconditions and postconditions before writing implementation code, ensuring every function meets its specification. ## The Problem with Traditional C Education Traditional C courses follow a predictable path: variables, loops, functions, pointers, then "good luck with memory management." They teach syntax but not safety. They show how to write code but not how to verify it works. The result is a generation of programmers who can write C but can't prove their C is correct. In web development, this leads to bugs. In safety-critical systems, it leads to disasters. The gap between "learning C" and "writing certified C" shouldn't require a decade of on-the-job training to bridge. The methodology exists. It just hasn't been taught to beginners. ## The MATH → STRUCT → CODE → TEST Methodology The book introduces a four-phase approach used in safety-critical development: **MATH**: Before writing any code, define the mathematical properties. What invariants must hold? What are the preconditions and postconditions? What does "correct" even mean for this function? **STRUCT**: Design data structures that make incorrect states unrepresentable. If the structure enforces the invariants, the code can't violate them. **CODE**: Implementation becomes transcription. The mathematics tells you what to write. The structure tells you how to write it. **TEST**: Verify that the implementation satisfies the mathematical specification. Every contract clause becomes a test case. This isn't academic exercise. It's how flight control software, pacemakers, and automotive safety systems are actually built. The book makes that methodology accessible to anyone learning C. ## What the Book Covers ### Part I: Foundations (Chapters 1-3) The book opens with philosophy — why undefined behaviour exists, why the C standard allows it, and why this matters. Then fixed-width integers (and why `int` destroyed a $370 million rocket), followed by booleans and decision logic. Every chapter opens with a real disaster. Ariane 5 for integer overflow. Therac-25 for state machine failures. These aren't scare tactics — they're motivation for why rigour matters. ### Part II: Memory (Chapters 4-7) Arrays with bounds checking. Strings done right (why `gets()` was removed from C11, why `strncpy()` isn't the answer). Structures that enforce invariants at compile time. Pointers without the mystery. The memory chapters emphasise static allocation over dynamic. In safety-critical systems, `malloc()` is often forbidden entirely. The book teaches patterns that work within those constraints. ### Part III: Behaviour (Chapters 8-9) Functions with contracts — preconditions, postconditions, and how to enforce them. State machines that can't enter invalid states, with transitions defined as mathematical functions. The state machine chapter introduces the dense matrix pattern for O(1) transition lookup, and explains why the order of operations (update state, then run action) matters for crash safety. ### Part IV: Integration (Chapters 10-11) A complete tic-tac-toe implementation that treats a toy problem with the severity of flight control software. Every function has contracts. Every invariant is enforced. The validator proves the game state is mathematically consistent. The final chapter bridges to production: DO-178C for aerospace, IEC 62304 for medical devices, ISO 26262 for automotive. It shows how the book's methodology maps directly to certification requirements. ### Appendices Four appendices cover practical tooling: development environment setup (compiler flags, static analysis, CI), a contracts quick reference, further reading (from MISRA to Nancy Leveson), and a comprehensive catalogue of undefined behaviours. ## Who This Book Is For **Self-taught developers** wanting rigorous foundations. If you've learned C from tutorials and Stack Overflow, this book fills the gaps they left. **Engineers transitioning to safety-critical domains**. The methodology translates directly to certification work. The book explains what DO-178C, IEC 62304, and ISO 26262 actually require. **Students tired of "just trust me" explanations**. Every claim is grounded in mathematics or demonstrated with code. No magic, no hand-waving. **Embedded developers** wanting formal verification intuition. Even without using formal methods tools, thinking in contracts catches bugs at design time. **Anyone burned by undefined behaviour**. If you've ever had code that "works in debug but fails in release," this book explains why and how to prevent it. ## The Companion Course The book accompanies the open-source [c-from-scratch](https://github.com/SpeyTech/c-from-scratch) course, which provides hands-on modules for building safety-critical components: - **Pulse**: Existence detection - **Baseline**: Statistical normalcy - **Timing**: Jitter analysis - **Drift**: Trend detection - **Consensus**: Triple modular redundancy - **Pressure**: Bounded queues with backpressure - **Mode**: System orchestration Each module follows the same MATH → STRUCT → CODE → TEST methodology, with complete implementations and test suites. ## Why Now Safety-critical software is expanding beyond traditional domains. Autonomous vehicles, medical AI, drone delivery, industrial automation — all require software that doesn't just work but can be *proven* to work. The engineers building these systems need training. Not just syntax tutorials, but methodology. Not just "how to write C" but "how to write C that won't kill someone." That's what this book teaches. ## Getting the Book **C From Scratch** is available now on [Leanpub](https://leanpub.com/c-from-scratch). The book includes: - 11 chapters covering philosophy through production - 4 appendices with practical tooling and references - Complete, compilable code examples throughout - Exercises with the "prove first, then implement" pattern Leanpub's model means you get updates as the book evolves. Buy once, receive all future revisions. ## Frequently Asked Questions ### What is the C From Scratch approach to learning C? C From Scratch teaches C programming through mathematical contracts and formal verification from the first chapter. Every function has explicit preconditions and postconditions. Students prove code correct before running it — building the safety-critical C discipline that certified development requires rather than the ad-hoc habits tutorials typically teach. ### How does C From Scratch differ from traditional C tutorials? Traditional tutorials start with printf and progress through syntax. C From Scratch starts with mathematical contracts and progresses through proof-based development. Students learn to specify what a function must guarantee before writing it, then verify the implementation satisfies the specification — the methodology used in certified aerospace and medical software. ### Why does a contracts-first approach matter for career development? Safety-critical industries — aerospace, medical devices, automotive, defence — require engineers who can produce certification evidence. The contracts-first methodology taught in C From Scratch transfers directly to DO-178C, IEC 62304, and ISO 26262 compliance work. Engineers with this foundation are immediately productive in regulated domains. ### Who should not use C From Scratch? C From Scratch is not suited for quick syntax reference, hobbyist projects, or algorithm competition preparation. The book is designed for professional engineering, not rapid prototyping. ## Conclusion The gap between "knowing C syntax" and "writing certifiable C" is real, but it doesn't have to take a decade to cross. The methodology exists. It's been used in aerospace, medical devices, and automotive systems for years. **C From Scratch** makes that methodology accessible to anyone willing to think before they code. The disasters that opened each chapter didn't happen because engineers were careless. They happened because engineers lacked a systematic approach to proving correctness. This book provides that approach. Write code as if lives depend on it. Sometimes they will. --- *C From Scratch is available on [Leanpub](https://leanpub.com/c-from-scratch). The companion course is open-source at [github.com/SpeyTech/c-from-scratch](https://github.com/SpeyTech/c-from-scratch).* --- ## Stochastic Rounding Without the Stochastic **URL**: https://speytech.com/insights/stochastic-rounding-deterministic/ **Published**: January 20, 2026 22:00 **Topic**: Deterministic Computing **Answers**: How can the regularisation benefits of stochastic rounding be achieved fully deterministically using PRNG-controlled probability distributions rather than true hardware randomness, and does this deterministic approach preserve the training accuracy and convergence benefits of probabilistic rounding while also enabling bit-identical reproducibility? **Defines**: Deterministic stochastic rounding KEY_CLAIMS: - Stochastic rounding is a technique for training neural networks at low precision. - Stochastic rounding demonstrates that determinism and "randomness" aren't opposites. - Deterministic stochastic rounding replaces hardware randomness with a seeded PRNG (pseudo-random number generator) that produces identical rounding decisions given the same seed. - The PRNG produces a uniform probability distribution matching hardware randomness, so rounding decisions follow the same statistical profile. - Round-to-nearest-even is deterministic and unbiased but does not provide the regularisation effect that stochastic rounding offers during training. EVIDENCE: - A gradient of 0.0001 truncates to 0, every time. - With stochastic rounding, that 0.0001 gradient occasionally rounds to 0.0001/quantum, preserving signal. - The sequence 0x24F74A49, 0xA96E3F40, 0xC1C8ECFB... has no relation to the gradients being rounded. - Stochastic rounding integrates with the Q16.16 arithmetic: The 64-bit intermediate preserves precision. How PRNG-controlled rounding can provide regularisation benefits deterministically Stochastic rounding is a technique for training neural networks at low precision. Instead of always rounding 2.7 to 3 and 2.3 to 2, you round probabilistically based on the fractional part. 2.7 rounds to 3 with 70% probability, to 2 with 30% probability. The benefit: unbiased gradients. Over many operations, the expected value equals the true value. Models train better at low precision. The problem: randomness. Different random seeds, different training runs. Non-reproducible results. But here's the insight: the "random" numbers don't need to be random. They just need to be unpredictable *from the perspective of the computation*. A deterministic PRNG, seeded from the operation context, provides the same regularisation effect — with full reproducibility. ## The Mechanism Traditional stochastic rounding: ```python def stochastic_round(x): floor = int(x) frac = x - floor if random() > shift; /* Generate threshold from PRNG */ uint32_t rand = ct_prng_next(prng); uint32_t threshold = rand >> (32 - shift); /* Compare fractional part to threshold */ if ((uint64_t)frac > threshold) { truncated += (x >= 0) ? 1 : -1; } return dvm_clamp32(truncated, faults); } ``` The key difference: `ct_prng_next(prng)` is deterministic. Given the same PRNG state, we get the same "random" number. The rounding decision is reproducible. ## The PRNG Design The counter-based PRNG in [certifiable-training](https://github.com/SpeyTech/certifiable-training) is a pure function: ``` output = f(seed, operation_id, step) ``` Where: - **seed**: Fixed for the entire training run - **operation_id**: Unique per operation (layer × tensor × element) - **step**: Monotonically increasing counter ```c typedef struct { uint64_t seed; uint64_t op_id; uint64_t step; } ct_prng_t; uint32_t ct_prng_next(ct_prng_t *prng) { /* Combine state components */ uint64_t x = prng->seed; x ^= prng->op_id; x += prng->step; /* Mix with multiply-xorshift */ x ^= x >> 33; x *= 0xFF51AFD7ED558CCDULL; x ^= x >> 33; x *= 0xC4CEB9FE1A85EC53ULL; x ^= x >> 33; prng->step++; return (uint32_t)(x >> 32); } ``` The operation_id ensures different elements get different sequences. The step ensures repeated operations on the same element get different values. The seed allows reproducibility: same seed, same training run. ## Why This Works The magic of stochastic rounding isn't randomness per se — it's that the rounding errors are uncorrelated with the values being rounded. Consider gradient accumulation. With truncation (round toward zero), small gradients are systematically lost. A gradient of 0.0001 truncates to 0, every time. Information disappears. With stochastic rounding, that 0.0001 gradient occasionally rounds to 0.0001/quantum, preserving signal. Not every time — but often enough that the expected value is correct. The PRNG provides this uncorrelated behaviour. The sequence 0x24F74A49, 0xA96E3F40, 0xC1C8ECFB... has no relation to the gradients being rounded. Statistically, it behaves like true randomness. But unlike true randomness, we can replay it. Given the same (seed, op_id, step), we get the same sequence. Training is reproducible. ## The Tradeoff True stochastic rounding provides strong theoretical guarantees about unbiasedness. Our deterministic version provides *empirically equivalent* behaviour with reproducibility. The difference: with true randomness, you can prove statistical properties from first principles. With a PRNG, you're relying on the PRNG quality to not introduce systematic bias. Modern PRNGs pass all standard statistical tests. For practical training, they're indistinguishable from true randomness. But for formal analysis, you'd need to verify PRNG properties explicitly. ## Implementation Details ### Operation ID Construction Each weight update needs a unique operation_id: ```c uint64_t ct_prng_make_op_id(uint32_t layer_id, uint32_t tensor_id, uint32_t element_idx) { /* Combine with bit-shifting to avoid collisions */ return ((uint64_t)layer_id << 48) | ((uint64_t)tensor_id << 32) | (uint64_t)element_idx; } ``` Layer 3, tensor 1, element 42 → unique op_id. Layer 3, tensor 1, element 43 → different op_id. Different sequences, uncorrelated rounding decisions. ### Step Synchronisation The step counter must advance consistently across platforms: ```c /* Wrong: step based on loop iteration */ for (int i = 0; i < batch_size; i++) { ct_prng_init(&prng, seed, op_id); prng.step = global_step * batch_size + i; /* Platform-dependent ordering */ ... } /* Right: step derived from operation context */ for (int i = 0; i < batch_size; i++) { uint64_t step = global_step * max_batch_size + i; ct_prng_init(&prng, seed, op_id); prng.step = step; ... } ``` The max_batch_size constant ensures the same step values regardless of actual batch size. No platform-dependent ordering. ### Fixed-Point Integration Stochastic rounding integrates with the Q16.16 arithmetic: ```c /* Multiply two Q16.16 values with stochastic rounding */ int32_t mul_sr(int32_t a, int32_t b, ct_prng_t *prng, ct_fault_flags_t *faults) { int64_t product = (int64_t)a * (int64_t)b; /* Product is Q32.32, need to round back to Q16.16 */ return ct_stochastic_round(product, 16, prng, faults); } ``` The 64-bit intermediate preserves precision. The stochastic round preserves expected value while reducing to 32 bits. ## When to Use Stochastic Rounding **Use it for:** - Gradient accumulation (small gradients matter) - Weight updates (preserve small changes) - Activation functions (reduce quantisation noise) **Don't use it for:** - Loss calculation (deterministic RNE preferred) - Inference (reproducibility more important than regularisation) - Checkpointing (exact values needed for resumption) The certifiable-* ecosystem uses stochastic rounding selectively — during training where regularisation helps, RNE elsewhere for strict determinism. ## Test Vectors For compliance, these test cases must pass: ```c ct_prng_t prng; ct_fault_flags_t faults = {0}; /* Seed 0, op_id 0: verify sequence */ ct_prng_init(&prng, 0, 0); assert(ct_prng_next(&prng) == 0x24F74A49); assert(ct_prng_next(&prng) == 0xA96E3F40); /* Same seed, same op_id: same sequence */ ct_prng_t prng2; ct_prng_init(&prng2, 0, 0); assert(ct_prng_next(&prng2) == 0x24F74A49); /* Different op_id: different sequence */ ct_prng_init(&prng, 0, 1); assert(ct_prng_next(&prng) != 0x24F74A49); /* Stochastic round determinism */ ct_prng_init(&prng, 12345, 500); ct_prng_t prng_copy = prng; int32_t r1 = ct_stochastic_round(0x18000LL, 16, &prng, &faults); int32_t r2 = ct_stochastic_round(0x18000LL, 16, &prng_copy, &faults); assert(r1 == r2); ``` ## The Broader Picture Stochastic rounding is one example of a broader principle: "random" behaviours in ML often don't need true randomness. They need unpredictability — which a good PRNG provides deterministically. Dropout? PRNG-controlled. Data augmentation? PRNG-controlled. Initialisation? PRNG-controlled. Seed everything from a single master seed, derive operation-specific sequences, and the entire training run becomes reproducible. Different seed → different run. Same seed → identical run. For safety-critical systems, this is more than convenient. It's a requirement. When you claim "this model was trained with these hyperparameters," you need to be able to prove it. Reproducibility is the foundation of that proof. ## Frequently Asked Questions ### How can stochastic rounding be deterministic? Deterministic stochastic rounding replaces hardware randomness with a seeded PRNG (pseudo-random number generator) that produces identical rounding decisions given the same seed. The probability distribution matches true stochastic rounding, preserving training regularisation benefits while enabling bit-identical reproducibility across runs and platforms. ### How does deterministic stochastic rounding preserve training accuracy? The PRNG produces a uniform probability distribution matching hardware randomness, so rounding decisions follow the same statistical profile. Over many operations, the regularisation effect is preserved — gradient updates receive the same unbiased rounding treatment. Only the sequence is deterministic, not biased. ### Why can't standard round-to-nearest-even replace stochastic rounding for training? Round-to-nearest-even is deterministic and unbiased but does not provide the regularisation effect that stochastic rounding offers during training. Stochastic rounding prevents gradient updates from getting trapped in quantisation basins by probabilistically rounding small updates that would otherwise be rounded to zero. ### What PRNG is suitable for deterministic stochastic rounding? PCG-64 provides the statistical quality, speed, and reproducibility needed for deterministic stochastic rounding. The PRNG must pass standard randomness test suites, be fast enough not to bottleneck training, and produce identical sequences across platforms given the same seed. Hardware random number generators are unsuitable because they are not reproducible. ## Conclusion Stochastic rounding demonstrates that determinism and "randomness" aren't opposites. The regularisation benefits of stochastic methods come from uncorrelated errors, not from true randomness. A well-designed PRNG provides uncorrelated sequences. Seeded from operation context, it provides reproducibility. The training benefits of stochastic rounding, without the reproducibility costs. The certifiable-* ecosystem uses this approach throughout. Random-looking behaviour, fully deterministic implementation. Train on Monday, train on Friday, get identical results. As with any architectural approach, suitability depends on system requirements, risk classification, and regulatory context. For systems where reproducibility is mandatory, PRNG-controlled stochastic rounding provides the best of both worlds. --- *Explore the PRNG implementation in [certifiable-training](https://github.com/SpeyTech/certifiable-training) or see the test vectors in the CT-MATH-001 specification.* --- ## Cross-Platform Bit-Identity: Theory to Practice **URL**: https://speytech.com/insights/cross-platform-bit-identity/ **Published**: January 20, 2026 20:45 **Topic**: Deterministic Computing **Answers**: How do you practically verify bit-identical execution of deterministic ML inference across different platforms, compilers, and operating systems in production, and what specific engineering steps are needed to achieve matching SHA-256 cryptographic hashes from the same computation running on different hardware? **Defines**: Cross-platform bit-identity KEY_CLAIMS: - "It works on my machine." That phrase has ended more debugging sessions — and started more arguments — than any other in software engineering. - Cross-platform bit-identity transforms "we believe this is reproducible" into "we can prove this is reproducible." The proof is simple: run the pipeline on different platforms, compare the hashes. - Cross-platform bit-identity means the same computation produces identical binary results on different processor architectures, operating systems, and compilers. - Use Q16.16 fixed-point integer arithmetic instead of IEEE 754 floating-point, eliminate all platform-dependent operations, use static memory allocation, and apply round-to-nearest-even consistently. - IEEE 754 permits platform-specific optimisations including fused multiply-add availability, SIMD lane ordering, and extended precision intermediate values. EVIDENCE: - Q16.16 fixed-point uses integer arithmetic only. `3 + 5 = 8` on every CPU ever made. - DO-178C, IEC 62304, and ISO 26262 all require evidence of reproducibility. "We ran it twice and got the same result" is weak evidence. "Here are the cryptographic hashes from three different platforms, all identical" is strong evidence. - Use Q16.16 fixed-point integer arithmetic instead of IEEE 754 floating-point, eliminate all platform-dependent operations, use static memory allocation, and apply round-to-nearest-even consistently. - IEEE 754 permits platform-specific optimisations including fused multiply-add availability, SIMD lane ordering, and extended precision intermediate values. The practical journey of verifying deterministic ML across platforms "It works on my machine." That phrase has ended more debugging sessions — and started more arguments — than any other in software engineering. For machine learning, it's worse: "The model trained on my machine." Does that mean it will train identically on a cloud server? On your colleague's laptop? On the production hardware? Usually, no. But for safety-critical systems, "usually" isn't good enough. We need "always." ## The Goal The [certifiable-*](https://github.com/SpeyTech/certifiable-harness) ecosystem makes a strong claim: run the same training pipeline with the same inputs, and you get the same outputs — bit-for-bit identical — regardless of platform. Not "close enough." Not "within floating-point tolerance." Identical. Here's what that looks like in practice: ```json { "platform": "x86_64-linux", "stages": [ {"name": "data", "hash": "2f0c6228001d125032afbe..."}, {"name": "training", "hash": "36b34d87459ead09c5349d..."}, {"name": "quant", "hash": "8c78bae645d6f06a3bdd6c..."}, {"name": "deploy", "hash": "32296bbc342c91ba0c95d1..."}, {"name": "inference", "hash": "48f4ecebc0eec79ab15fe6..."}, {"name": "monitor", "hash": "da7f49992d875a6390cb3c..."}, {"name": "verify", "hash": "33e41fcaaa25c405fbb44f..."} ], "bit_identical": true } ``` Same JSON from a Google Cloud Debian VM. Same JSON from an 11-year-old MacBook. The hashes match, byte for byte. ## What Makes This Hard Cross-platform determinism is simple in theory and subtle in practice. Here are the traps: ### Floating-Point Inconsistency IEEE-754 floating point has platform-dependent behaviour: - x87 FPU uses 80-bit extended precision internally - Fused multiply-add changes rounding sequences - Compiler optimisations reorder operations - `-ffast-math` abandons all guarantees Even "compliant" implementations can disagree at the last bit. **Solution**: Don't use floating point. Q16.16 fixed-point uses integer arithmetic only. `3 + 5 = 8` on every CPU ever made. ### PRNG Divergence Standard library random functions vary between platforms: - Different algorithms (LCG vs Mersenne Twister vs xorshift) - Different seeding behaviour - Different default states **Solution**: Implement your own PRNG. The certifiable-* ecosystem uses a counter-based PRNG that's a pure function of (seed, operation_id, step). No state, no platform dependencies. ### Memory Layout Struct padding, alignment, and byte order vary: - sizeof(int) differs between platforms - Compilers insert padding for alignment - Big-endian vs little-endian matters for serialisation **Solution**: Explicit serialisation with fixed byte order. All data structures use little-endian encoding with no padding. The canonical form is defined in the spec, not left to the compiler. ### Library Inconsistency Even deterministic algorithms can have non-deterministic implementations: - qsort() stability varies - Hash table iteration order varies - Floating-point math library functions vary **Solution**: Implement core algorithms from scratch. No standard library dependencies for anything that affects determinism. ## The Verification Architecture The [certifiable-harness](https://github.com/SpeyTech/certifiable-harness) runs all seven pipeline stages and produces a commitment hash for each: 1. **Data** — Load samples, shuffle with Feistel, hash the batch structure 2. **Training** — Forward pass, backward pass, weight updates, Merkle chain 3. **Quantisation** — FP32 to Q16.16 conversion with error certificates 4. **Deploy** — Bundle packaging with manifest and attestation 5. **Inference** — Forward pass on test data, prediction hashes 6. **Monitor** — Drift detection, operational envelope checks 7. **Verify** — Cross-stage binding verification Each stage produces a deterministic hash. The harness collects them, compares against golden references, and reports pass/fail. ## The Test Matrix We verified bit-identity across: | Platform | Architecture | OS | Compiler | |----------|-------------|-----|----------| | Google Cloud | x86_64 | Debian 12 | GCC 12 | | MacBook (2013) | x86_64 | macOS | Clang 15 | | Raspberry Pi 4 | ARM64 | Ubuntu 22.04 | GCC 11 | | RISC-V (SiFive) | RV64 | Buildroot | GCC 13 | All platforms produce identical hashes. Not similar. Identical. ## What We Learned ### Compiler Flags Matter Debug builds (`-O0`) and release builds (`-O3`) must produce the same results. Our code does. But we had to verify this — some "equivalent" optimisations change floating-point behaviour. Since we don't use floating point, this wasn't an issue. ### Integer Overflow Is Defined In C, signed integer overflow is undefined behaviour. Compilers can assume it never happens and optimise accordingly. We use explicit overflow checks with saturation: ```c int32_t dvm_add(int32_t a, int32_t b, ct_fault_flags_t *faults) { int64_t result = (int64_t)a + (int64_t)b; if (result > INT32_MAX) { faults->overflow = 1; return INT32_MAX; /* Saturate */ } if (result underflow = 1; return INT32_MIN; /* Saturate */ } return (int32_t)result; } ``` Well-defined behaviour on every platform. ### Endianness Must Be Explicit We chose little-endian for all serialisation. ARM and x86 are native little-endian; RISC-V can be either but defaults to little-endian. For big-endian platforms (rare now), we'd need byte-swap routines. ```c static inline uint32_t to_le32(uint32_t x) { #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ return x; #else return __builtin_bswap32(x); #endif } ``` ### The SHA-256 Implementation Matters We embed our own SHA-256, derived from a public domain implementation. Why not use OpenSSL? Because OpenSSL versions differ. The algorithm is identical, but linking against different library versions introduces a dependency we can't control. Our SHA-256 produces the NIST test vectors: - SHA256("") = `e3b0c44298fc1c14...` - SHA256("abc") = `ba7816bf8f01cfea...` If your implementation matches these, it'll match ours. ## The Practical Impact ### For Development When a test fails, you know it's your code, not platform variance. Debugging is deterministic. Run the same inputs, get the same outputs, every time. ### For Certification DO-178C, IEC 62304, and ISO 26262 all require evidence of reproducibility. "We ran it twice and got the same result" is weak evidence. "Here are the cryptographic hashes from three different platforms, all identical" is strong evidence. ### For Incident Investigation When a deployed model misbehaves, you can reproduce the exact conditions. Not approximately. Exactly. The training data, the hyperparameters, the weight evolution — all reconstructible from the audit trail. ### For Collaboration Share a seed, share the results. Your colleague in another timezone, on different hardware, will get the same outputs. No more "it works on my machine" debates. ## The Cost Determinism isn't free: - **Development Effort**: Implementing from scratch rather than using libraries - **Performance**: Some optimisations aren't available (SIMD with platform-specific rounding) - **Constraints**: No floating point, no standard library random, explicit everything For many ML applications, this cost isn't justified. For safety-critical applications, it's the cost of doing business. ## Frequently Asked Questions ### What is cross-platform bit-identity in deterministic systems? Cross-platform bit-identity means the same computation produces identical binary results on different processor architectures, operating systems, and compilers. Verification uses SHA-256 hash comparison — if the hashes match across x86, ARM, and RISC-V, the execution is bit-identical. ### How do I achieve bit-identical output across x86 and ARM? Use Q16.16 fixed-point integer arithmetic instead of IEEE 754 floating-point, eliminate all platform-dependent operations, use static memory allocation, and apply round-to-nearest-even consistently. Integer operations have defined behaviour under C99, producing identical results on any conformant platform regardless of architecture. ### Why doesn't IEEE 754 compliance guarantee cross-platform bit-identity? IEEE 754 permits platform-specific optimisations including fused multiply-add availability, SIMD lane ordering, and extended precision intermediate values. These permitted variations mean the same floating-point computation can produce different bit-level results on different hardware, even when both platforms are fully IEEE 754 compliant. ### What is the cost of achieving cross-platform bit-identity? Constraining computation to fixed-point arithmetic limits dynamic range and requires explicit overflow handling. Some algorithms need redesign to fit within Q16.16 precision bounds. Development effort increases compared to using standard floating-point libraries. The benefit is provable reproducibility that supports safety-critical certification requirements. ## Conclusion Cross-platform bit-identity transforms "we believe this is reproducible" into "we can prove this is reproducible." The proof is simple: run the pipeline on different platforms, compare the hashes. If they match, the claim is verified. The certifiable-* ecosystem achieves this through deliberate architectural choices: fixed-point arithmetic, embedded algorithms, explicit serialisation, comprehensive test vectors. None of these choices are exotic. They're just disciplined. Seven pipeline stages. Seven hashes. Identical across platforms. That's the standard for deterministic ML. As with any architectural approach, suitability depends on system requirements, risk classification, and regulatory context. For systems where reproducibility must be proven, not assumed, cross-platform bit-identity is the foundation. --- *Run the verification yourself: clone [certifiable-harness](https://github.com/SpeyTech/certifiable-harness), build on your platform, and compare against the golden references.* --- ## Feistel Shuffle: Deterministic Data Ordering **URL**: https://speytech.com/insights/feistel-shuffle-deterministic/ **Published**: January 20, 2026 20:24 **Topic**: Deterministic Computing **Answers**: How do cycle-walking Feistel networks provide deterministic and fully reproducible data shuffling for ML training pipelines without requiring stored permutation arrays or sequential state, and why does this cryptographic approach guarantee identical sample ordering given the same seed on any platform? **Defines**: Feistel shuffle KEY_CLAIMS: - Shuffling data is fundamental to ML training. - The Feistel shuffle replaces "shuffle with random seed and hope for the best" with "deterministic permutation from first principles." Same seed, same dataset size, same shuffle — guaranteed, across platforms, across time. - A Feistel shuffle uses cycle-walking Feistel networks to generate a deterministic permutation of data indices from a seed value. - The shuffle uses only integer arithmetic operations — XOR, addition, and a hash function — that produce identical results on any C99-conformant platform. - Fisher-Yates requires O(N) memory to store the permutation array and O(N) time to generate it. EVIDENCE: - If you have 1000 training samples, you need a permutation of exactly 1000 elements, not 1024. How cycle-walking Feistel networks can provide reproducible shuffling for ML training Shuffling data is fundamental to ML training. Without shuffling, models learn the order of examples, not their content. Batch composition matters. Epoch ordering matters. But shuffling typically relies on random number generators. Different seeds, different shuffles. Different platforms, potentially different shuffles even with the same seed. For deterministic ML, that's a problem. The Feistel shuffle solves this: a deterministic permutation that looks random but is completely reproducible. ## The Problem with Random Shuffling Consider the standard approach: Fisher-Yates shuffle with a PRNG. ```python import random random.seed(42) random.shuffle(data) ``` This is "deterministic" in the sense that the same seed produces the same shuffle — on the same platform, with the same library version, using the same PRNG implementation. Change any of those, and guarantees disappear. Python's `random` module has changed algorithms between versions. NumPy's shuffle differs from Python's. C's `rand()` is notoriously platform-dependent. For certifiable systems, "it works on my machine with my library version" isn't acceptable. ## Enter the Feistel Network A Feistel network is a cryptographic construction that transforms a block of data through multiple rounds. It's the basis of DES, Blowfish, and other block ciphers. The key property: it's invertible. Every input maps to exactly one output, and you can reverse the process. Applied to shuffling, we use the Feistel network as a permutation generator. Given an index from 0 to N-1, the network produces a permuted index — also from 0 to N-1. Every index maps to a unique output. The permutation is determined entirely by the seed, with no external randomness. ## The Cycle-Walking Extension There's a catch. Feistel networks operate on fixed-size blocks — typically powers of two. If you have 1000 training samples, you need a permutation of exactly 1000 elements, not 1024. Cycle-walking handles this. When the Feistel output falls outside your range, you apply the Feistel function again, "walking" until you land in the valid range. ```c uint32_t ct_feistel_permute(const ct_feistel_t *ctx, uint32_t x) { uint32_t result = x; /* Walk until we land in [0, n) */ do { result = feistel_round(ctx, result); } while (result >= ctx->n); return result; } ``` This always terminates (provably), and the output is always a valid permutation of [0, N). ## The Implementation Here's how [certifiable-data](https://github.com/SpeyTech/certifiable-data) implements the Feistel permutation: ```c typedef struct { uint32_t n; /* Domain size */ uint32_t half_bits; /* Bits per half */ uint32_t mask; /* Mask for half */ uint64_t keys[4]; /* Round keys */ } ct_feistel_t; void ct_feistel_init(ct_feistel_t *ctx, uint32_t n, uint64_t seed) { ctx->n = n; /* Find smallest power of 2 >= n */ uint32_t bits = 1; while ((1u half_bits = (bits + 1) / 2; ctx->mask = (1u half_bits) - 1; /* Derive round keys from seed */ ctx->keys[0] = seed ^ 0x243F6A8885A308D3ULL; ctx->keys[1] = seed ^ 0x13198A2E03707344ULL; ctx->keys[2] = seed ^ 0xA4093822299F31D0ULL; ctx->keys[3] = seed ^ 0x082EFA98EC4E6C89ULL; } ``` The round keys are derived from the seed using constants (first digits of pi, for those curious). Same seed → same keys → same permutation. The core Feistel round: ```c static uint32_t feistel_round(const ct_feistel_t *ctx, uint32_t x) { uint32_t left = x >> ctx->half_bits; uint32_t right = x & ctx->mask; for (int round = 0; round keys[round], ctx->mask); uint32_t new_right = left ^ f; left = right; right = new_right; } return (left half_bits) | right; } static uint32_t round_function(uint32_t x, uint64_t key, uint32_t mask) { uint64_t mixed = x * 0x9E3779B97F4A7C15ULL; mixed ^= key; mixed ^= mixed >> 32; return (uint32_t)(mixed & mask); } ``` Four rounds is sufficient for good diffusion. The round function uses multiplication and XOR — fast, portable, deterministic. ## Why This Matters for ML ### Reproducible Epochs Each epoch shuffles the data differently. With Feistel, you parameterise by epoch: ```c ct_feistel_init(&shuffle, num_samples, seed + epoch); ``` Epoch 0 with seed 42 always produces the same permutation. Epoch 1 produces a different permutation, but equally deterministic. Resume training at epoch 50, and batches are identical to the original run. ### Batch Construction Given the permutation, batch construction is trivial: ```c for (uint32_t i = 0; i = ctx->n); return result; } ``` The inverse uses the same keys in reverse order with the left/right swap reversed. Feistel networks are their own inverse — one of their elegant properties. ## Comparison to Alternatives ### Fisher-Yates - **Pro**: Simple, well-understood - **Con**: Requires storing the full permutation or generating sequentially - **Con**: PRNG-dependent ### Knuth Shuffle Same as Fisher-Yates (they're equivalent algorithms). ### Format-Preserving Encryption (FPE) - **Pro**: Cryptographically strong - **Con**: Typically requires AES, which is overkill for shuffling - **Con**: More complex implementation ### Feistel - **Pro**: Self-contained, no external dependencies - **Pro**: Simple to implement correctly - **Pro**: Invertible by construction - **Pro**: Works for any domain size (with cycle-walking) - **Con**: Slightly slower than direct random shuffle For safety-critical ML, the determinism and simplicity outweigh the minor performance cost. ## Test Vectors For any Feistel implementation to be compliant, these test cases must pass: ```c /* Domain size 100, seed 0 */ ct_feistel_init(&ctx, 100, 0); assert(ct_feistel_permute(&ctx, 0) == 73); assert(ct_feistel_permute(&ctx, 1) == 24); assert(ct_feistel_permute(&ctx, 50) == 91); assert(ct_feistel_permute(&ctx, 99) == 8); /* Bijection check */ bool seen[100] = {false}; for (uint32_t i = 0; i < 100; i++) { uint32_t j = ct_feistel_permute(&ctx, i); assert(j < 100); assert(!seen[j]); seen[j] = true; } ``` If your implementation produces different values, it's not compatible. Cross-platform bit-identity requires exact agreement. ## Practical Considerations ### Domain Size Changes If your dataset size changes (new data added, samples removed), the permutation changes entirely. For incremental training, you may want to fix the domain size and handle growth separately. ### Large Datasets The cycle-walking can require multiple iterations when the domain isn't a power of two. Worst case for n = 2^k + 1 is roughly 2x the iterations. Average case is much better. For billion-element datasets, this is negligible. ### Parallelisation Each index lookup is independent. You can parallelise batch construction trivially — each thread computes its own indices without synchronisation. ## Frequently Asked Questions ### What is a Feistel shuffle for deterministic data ordering? A Feistel shuffle uses cycle-walking Feistel networks to generate a deterministic permutation of data indices from a seed value. Given the same seed, the shuffle produces identical sample ordering on any platform without storing a permutation array, using O(1) memory and O(1) computation per index lookup. ### How does a Feistel shuffle guarantee platform-independent ordering? The shuffle uses only integer arithmetic operations — XOR, addition, and a hash function — that produce identical results on any C99-conformant platform. No floating-point operations, no platform-dependent random number generators, and no stored state beyond the seed. Same seed produces same permutation everywhere. ### Why can't Fisher-Yates shuffle with a fixed seed provide deterministic data ordering? Fisher-Yates requires O(N) memory to store the permutation array and O(N) time to generate it. For large datasets, this memory requirement is prohibitive. Additionally, the shuffle depends on PRNG implementation details that may vary across platforms. Feistel shuffles compute each index independently in O(1) time and O(1) memory. ### What are the trade-offs of Feistel shuffles compared to stored permutation arrays? Feistel shuffles trade computation for memory: each index lookup requires multiple rounds of the Feistel network rather than a single array access. For typical ML training datasets, this overhead is negligible compared to data loading and model computation. The benefit is O(1) memory and guaranteed cross-platform determinism. ## Conclusion The Feistel shuffle replaces "shuffle with random seed and hope for the best" with "deterministic permutation from first principles." Same seed, same dataset size, same shuffle — guaranteed, across platforms, across time. For ML training that must be reproducible, this isn't a minor detail. It's a foundational requirement. When you claim "we can reproduce this training run," the data ordering is part of that claim. The certifiable-* ecosystem uses Feistel shuffling throughout [certifiable-data](https://github.com/SpeyTech/certifiable-data). Combined with the Merkle chain, every batch is cryptographically committed and independently reconstructible. As with any architectural approach, suitability depends on system requirements, risk classification, and regulatory context. For deterministic ML pipelines, Feistel shuffling provides the mathematical foundation for reproducible data ordering. --- *Explore the implementation in [certifiable-data](https://github.com/SpeyTech/certifiable-data) or see the permutation tests for the complete test vector suite.* --- ## Merkle Chains for ML Audit Trails **URL**: https://speytech.com/insights/merkle-chains-ml-audit/ **Published**: January 20, 2026 19:30 **Topic**: Deterministic Computing **Answers**: How do Merkle cryptographic hash chains make individual ML training steps independently verifiable after the fact, and how does chaining gradient computation hashes, weight modification digests, and data provenance records create a tamper-evident audit trail for the entire model development lifecycle? **Defines**: Merkle audit chain KEY_CLAIMS: - "We trained the model on this data with these hyperparameters." That statement is easy to make and difficult to verify. - A Merkle audit chain links sequential operations through cryptographic hashes, making each step independently verifiable and the complete history tamper-evident. - Merkle chains transform "we trained this model" from a claim into evidence. - Merkle chains record each ML training step as a hash-linked entry: gradient computations, weight modifications, and data provenance are individually hashed and chained. - Each chain entry contains the hash of the current operation and the hash of the previous entry. EVIDENCE: - Regulatory Compliance For DO-178C (aerospace), IEC 62304 (medical devices), ISO 26262 (automotive), auditors want evidence that the development process was controlled. - Merkle chains aren't free: Storage: Each step adds ~100 bytes (hashes + step record) Compute: SHA-256 of weights at each step (can be expensive for large models) Complexity: More code, more tests, more things that can go wrong For a 10,000-step training run, you're looking at ~1MB of chain data. - For a 1-million-parameter model (4MB in Q16.16), hashing takes roughly 10ms. - Each chain entry adds a 32-byte SHA-256 hash plus the recorded metadata per training step. How cryptographic hash chains can make every training step verifiable "We trained the model on this data with these hyperparameters." That statement is easy to make and difficult to verify. In most ML pipelines, training is a black box. Data goes in, weights come out. If something goes wrong six months later, good luck reconstructing what actually happened. For safety-critical systems, "trust me" isn't sufficient. Regulators want evidence. Incident investigators want audit trails. Certification bodies want provable claims. Merkle chains provide that evidence. Definition: Merkle Audit Chain A Merkle audit chain links sequential operations through cryptographic hashes, making each step independently verifiable and the complete history tamper-evident. ## The Core Idea A Merkle chain is a sequence of cryptographic hashes where each hash depends on the previous one. Change any step in the sequence, and every subsequent hash changes. It's the same principle that secures blockchain transactions — applied to ML training. For each training step, we compute: ``` h_t = SHA256(h_{t-1} || H(θ_t) || H(B_t) || t) ``` Where: - `h_t` is the hash at step t - `h_{t-1}` is the previous hash - `H(θ_t)` is the hash of the weights after this step - `H(B_t)` is the hash of the batch used in this step - `t` is the step number The chain is cryptographically bound. If someone claims "step 5,000 used batch X," you can verify it. If someone claims "the final weights came from this training run," you can trace the entire history. ## What Gets Committed In [certifiable-training](https://github.com/SpeyTech/certifiable-training), every training step commits: **Weight State (θ_t)** The complete model weights after the update, serialised in canonical form. Canonical means: fixed byte order (little-endian), fixed layout, no padding ambiguity. The same weights always produce the same hash. **Batch Composition (B_t)** Which samples were used, in what order. For a batch of indices [42, 17, 891, 3], we hash the indices themselves. Combined with the deterministic Feistel shuffle, this lets you reconstruct exactly which training examples influenced each step. **Step Number (t)** Prevents replay attacks. You can't take step 5,000's data and claim it was step 3,000. **Previous Hash (h_{t-1})** The chain link. Each hash depends on all previous hashes, creating an immutable history. ## The Genesis Block Every chain needs a starting point. The genesis hash commits the initial state: ``` h_0 = SHA256(H(θ_0) || H(config) || seed) ``` This captures: - Initial weights (random initialisation or pre-trained) - Training configuration (learning rate, batch size, epochs) - Random seed (for deterministic reproduction) From h_0, the entire training run is deterministically specified. Given the same genesis state, any compliant implementation will produce the same sequence of hashes. ## Implementation Here's the core step function from certifiable-training: ```c ct_error_t ct_merkle_step(ct_merkle_ctx_t *ctx, const ct_tensor_t *weights, const uint32_t *batch_indices, uint32_t batch_size, ct_training_step_t *step_out, const ct_fault_flags_t *faults) { /* Check for fault invalidation */ if (ct_has_fault(faults)) { ctx->faulted = true; return CT_ERR_FAULT; } /* Hash current weights */ uint8_t weights_hash[CT_HASH_SIZE]; ct_tensor_hash(weights, weights_hash); /* Hash batch indices */ uint8_t batch_hash[CT_HASH_SIZE]; ct_sha256(batch_indices, batch_size * sizeof(uint32_t), batch_hash); /* Build preimage: prev_hash || weights_hash || batch_hash || step */ uint8_t preimage[CT_HASH_SIZE * 3 + 8]; memcpy(preimage, ctx->current_hash, CT_HASH_SIZE); memcpy(preimage + CT_HASH_SIZE, weights_hash, CT_HASH_SIZE); memcpy(preimage + CT_HASH_SIZE * 2, batch_hash, CT_HASH_SIZE); /* Encode step as little-endian 64-bit */ uint64_t step = ctx->step; for (int i = 0; i > (i * 8)); } /* Compute step hash */ ct_sha256(preimage, sizeof(preimage), ctx->current_hash); ctx->step++; return CT_OK; } ``` The key property: this function is deterministic. Same inputs, same hash. No timestamps, no random nonces, no platform-dependent values. ## Fault Invalidation What happens when something goes wrong during training? An overflow, a division by zero, a NaN that would have been? The chain records it. When a fault flag is set, the Merkle context is marked as "faulted." Subsequent steps can continue (for debugging), but the chain is cryptographically invalidated. This prevents a subtle attack: "the training had some numerical issues, but we fixed them and continued." With fault invalidation, you can't hide problems. The chain either represents a clean run or it doesn't. ## Verification Without Replay The Merkle chain enables two levels of verification: **Hash-Only Verification (Fast)** Given the chain hashes and the claimed final weights, verify that the chain is internally consistent. This doesn't prove the training was correct — it proves the claimed history wasn't tampered with. **Full Replay Verification (Slow)** Re-run the entire training from genesis, comparing hashes at each step. If every hash matches, the training is bit-identical to the claimed history. This is expensive but provides the strongest guarantee. [certifiable-verify](https://github.com/SpeyTech/certifiable-verify) implements both modes. For most audits, hash-only verification is sufficient. For certification or incident investigation, full replay provides cryptographic proof. ## The Checkpoint Problem Training runs can take days. If the machine crashes at step 50,000, you don't want to restart from zero. Checkpoints break the simple chain model — you're resuming from a saved state, not computing continuously. The solution: checkpoints commit to the chain state at the save point. ```c typedef struct { uint64_t step; uint32_t epoch; uint8_t merkle_hash[CT_HASH_SIZE]; uint8_t weights_hash[CT_HASH_SIZE]; uint8_t config_hash[CT_HASH_SIZE]; ct_prng_t prng_state; uint64_t timestamp; /* EXCLUDED from commitment */ uint32_t version; ct_fault_flags_t fault_flags; } ct_checkpoint_t; ``` Note that `timestamp` is excluded from the cryptographic commitment. Timestamps are useful for humans but shouldn't affect determinism — a checkpoint saved at 3pm should be identical to one saved at 3am. ## What This Enables **Incident Investigation** When a deployed model misbehaves, you can trace back: which training run produced this model? What data was used? Were there any numerical faults? **Regulatory Compliance** For DO-178C (aerospace), IEC 62304 (medical devices), ISO 26262 (automotive), auditors want evidence that the development process was controlled. A Merkle chain is that evidence — cryptographically signed, tamper-evident, independently verifiable. **Reproducibility Claims** "Our results are reproducible" is a strong claim. With a Merkle chain, it's a provable claim. Anyone with the genesis state and the chain hashes can verify that your training run is reproducible. **Model Provenance** In a world of fine-tuned models and transfer learning, "where did this model come from?" is increasingly important. The chain provides complete provenance: initial weights → training data → final weights. ## The Cost Merkle chains aren't free: - **Storage**: Each step adds ~100 bytes (hashes + step record) - **Compute**: SHA-256 of weights at each step (can be expensive for large models) - **Complexity**: More code, more tests, more things that can go wrong For a 10,000-step training run, you're looking at ~1MB of chain data. For a million-step run, ~100MB. That's negligible compared to the model weights themselves. The hash computation is more significant. For a 1-million-parameter model (4MB in Q16.16), hashing takes roughly 10ms. For a 1-billion-parameter model, it's 10 seconds per step. That's meaningful overhead. The mitigation: hash only at checkpoint boundaries for large models, with the option for full-step hashing when audit requirements demand it. ## Frequently Asked Questions ### What are Merkle chains for ML audit trails? Merkle chains record each ML training step as a hash-linked entry: gradient computations, weight modifications, and data provenance are individually hashed and chained. This creates a tamper-evident audit trail where any modification to a historical entry invalidates all subsequent hashes in the chain. ### How do Merkle chains make ML training steps independently verifiable? Each chain entry contains the hash of the current operation and the hash of the previous entry. To verify step N, recompute the hash from the recorded inputs and compare it to the stored value. This verification works independently — you can verify any single step without replaying the entire training run. ### Why can't standard ML experiment tracking tools provide the same audit guarantees? Standard experiment tracking tools record metadata — hyperparameters, metrics, timestamps — but do not cryptographically bind computation results to their inputs. Entries can be modified without detection. Merkle chains provide mathematical tamper-evidence: any change to any entry is detectable by any verifier with the chain data. ### What is the storage cost of Merkle chain audit trails for ML training? Each chain entry adds a 32-byte SHA-256 hash plus the recorded metadata per training step. For a training run with millions of steps, this adds tens to hundreds of megabytes. The cost is linear in training steps and negligible compared to model weight storage. Hash computation adds microseconds per step. ## Conclusion Merkle chains transform "we trained this model" from a claim into evidence. Every step is committed. Every batch is recorded. Every weight update is cryptographically bound to its history. For systems that matter — medical devices, autonomous vehicles, aerospace — this audit trail isn't overhead. It's a requirement. When something goes wrong, you need to know what happened. When regulators ask questions, you need provable answers. The certifiable-* ecosystem builds this in from the start. Not as an afterthought, not as a logging feature, but as a fundamental architectural property. As with any architectural approach, suitability depends on system requirements, risk classification, and regulatory context. For systems that must be auditable, Merkle chains provide the foundation. --- *Explore the implementation in [certifiable-training](https://github.com/SpeyTech/certifiable-training) or see [certifiable-verify](https://github.com/SpeyTech/certifiable-verify) for the verification tooling.* --- ## Round-to-Nearest-Even: The Key to Determinism **URL**: https://speytech.com/insights/round-to-nearest-even/ **Published**: January 20, 2026 19:00 **Topic**: Deterministic Computing **Answers**: What is round-to-nearest-even, also known as banker's rounding, why does it eliminate the systematic positive bias that conventional rounding introduces in repeated numerical calculations, and how does consistent application of this IEEE 754 rounding mode enable bit-identical deterministic results across platforms? **Defines**: Round-to-nearest-even KEY_CLAIMS: - Round-to-nearest-even eliminates the systematic bias that conventional rounding introduces. - Round-to-nearest-even rounds halfway values to the nearest even integer, eliminating the systematic positive bias that conventional round-half-up introduces across repeated calculations. - Round-to-Nearest-Even is a small detail with large consequences. - Round-to-nearest-even, also called banker's rounding, rounds midpoint values (exactly 0.5) to the nearest even number rather than always rounding up. - Conventional rounding always rounds 0.5 upward, creating a positive bias that compounds over many operations. EVIDENCE: - The x87 FPU uses 80-bit extended precision internally. - Round-to-nearest-even is unbiased and is the default IEEE 754 rounding mode, making it the correct choice for deterministic fixed-point systems. Why banker's rounding matters for bit-identical machine learning Round-to-nearest-even eliminates the systematic bias that conventional rounding introduces. Most programmers round 2.5 to 3, but this halfway-up convention creates a persistent positive drift that accumulates across thousands of operations in ML inference pipelines. If you said 3, you're thinking like most programmers. If you said 2, you're thinking like someone who needs deterministic systems. Both answers are mathematically valid — and that's exactly the problem. Definition: Round-to-Nearest-Even Round-to-nearest-even rounds halfway values to the nearest even integer, eliminating the systematic positive bias that conventional round-half-up introduces across repeated calculations. ## The Halfway Problem Most rounding methods agree on the easy cases: 2.3 rounds to 2, 2.7 rounds to 3. The disagreement happens at the exact midpoint: 2.5. The "round half up" rule (taught in schools) says 2.5 → 3. Simple, consistent, and subtly biased. Over millions of operations, this bias accumulates. Values drift upward. In safety-critical systems, drift is the enemy. Round-to-Nearest-Even (RNE), also called banker's rounding, takes a different approach: when the value is exactly halfway, round to the nearest *even* number. - 1.5 → 2 (rounds up to even) - 2.5 → 2 (rounds down to even) - 3.5 → 4 (rounds up to even) - 4.5 → 4 (rounds down to even) The bias cancels out. Half the time you round up, half the time down. Over millions of operations, the statistical error approaches zero. ## Why This Matters for Machine Learning Neural network training involves billions of arithmetic operations. Each multiplication, each accumulation, each gradient update requires a rounding decision when you're working in fixed-point arithmetic. Consider a single training step with 1 million weight updates. If each update has even a tiny systematic bias, you're introducing 1 million small errors — all in the same direction. After 10,000 training steps, that's 10 billion biased operations. With RNE, the errors are unbiased. They still exist (quantisation error is unavoidable), but they don't accumulate in one direction. The trained model converges to the same place regardless of whether you're running on x86, ARM, or RISC-V. ## The Implementation Here's how [certifiable-training](https://github.com/SpeyTech/certifiable-training) implements RNE in pure C: ```c int32_t dvm_round_shift_rne(int64_t x, uint32_t shift, ct_fault_flags_t *faults) { if (shift > 62) { faults->domain = 1; return 0; } if (shift == 0) { return dvm_clamp32(x, faults); } int64_t half = 1LL > shift; if (x >= 0) { if (frac > half) { truncated += 1; } else if (frac == half) { /* Exactly halfway: round to even */ if (truncated & 1) { truncated += 1; } } } else { int64_t abs_frac = (-x) & mask; if (abs_frac > half) { truncated -= 1; } else if (abs_frac == half) { /* Exactly halfway: round to even (toward zero if already even) */ if (truncated & 1) { truncated -= 1; } } } return dvm_clamp32(truncated, faults); } ``` The key insight is the `truncated & 1` check. If the integer part is already even, we leave it alone. If it's odd, we bump it to the nearest even value. ## Test Vectors For any RNE implementation to be certifiable, it must pass these exact test vectors (from CT-MATH-001 §8): | Input (Q16.16) | Shift | Expected | Reasoning | |----------------|-------|----------|-----------| | 0x00018000 (1.5) | 16 | 2 | Halfway, 2 is even | | 0x00028000 (2.5) | 16 | 2 | Halfway, 2 is even | | 0x00038000 (3.5) | 16 | 4 | Halfway, 4 is even | | 0x00048000 (4.5) | 16 | 4 | Halfway, 4 is even | | 0x00058000 (5.5) | 16 | 6 | Halfway, 6 is even | | -0x18000 (-1.5) | 16 | -2 | Halfway, -2 is even | | -0x28000 (-2.5) | 16 | -2 | Halfway, -2 is even | | -0x38000 (-3.5) | 16 | -4 | Halfway, -4 is even | If your implementation produces different results for any of these inputs, it's not RNE-compliant — and it won't produce bit-identical results with other compliant implementations. ## The Practical Impact We've verified bit-identity across platforms using these test vectors. The [certifiable-harness](https://github.com/SpeyTech/certifiable-harness) runs the full pipeline — data loading, training, quantisation, inference — and produces identical hashes on: - Google Cloud Debian VM (x86_64) - 11-year-old MacBook (x86_64) - RISC-V validation (in progress) The same seed, the same data, the same hyperparameters → the same trained model, bit-for-bit. Not "close enough." Not "within tolerance." Identical. ## Why Not Just Use Floating Point? IEEE-754 floating point actually mandates RNE as the default rounding mode. So why not use floats? Because "default" doesn't mean "guaranteed." Different compilers, different optimisation levels, different FPU implementations can produce different results. The x87 FPU uses 80-bit extended precision internally. Fused multiply-add operations change the rounding sequence. `-ffast-math` throws all guarantees out the window. Fixed-point with explicit RNE removes the ambiguity. Every operation is defined. Every intermediate result is specified. There's no hidden precision, no compiler freedom, no platform variance. ## The Trade-off RNE adds complexity. The halfway check requires extra logic. The negative number handling is subtle (and easy to get wrong). It's slower than simple truncation. For systems where "close enough" is acceptable, this overhead isn't justified. For systems where reproducibility is mandatory — aerospace, medical devices, autonomous vehicles — the overhead is negligible compared to the cost of non-determinism. ## Frequently Asked Questions ### What is round-to-nearest-even and why does it matter for determinism? Round-to-nearest-even, also called banker's rounding, rounds midpoint values (exactly 0.5) to the nearest even number rather than always rounding up. This eliminates the systematic positive bias that conventional rounding introduces, enabling unbiased accumulation across thousands of operations in deterministic computation chains. ### How does round-to-nearest-even differ from conventional rounding? Conventional rounding always rounds 0.5 upward, creating a positive bias that compounds over many operations. Round-to-nearest-even rounds 0.5 to the nearest even number — 2.5 rounds to 2, 3.5 rounds to 4 — distributing midpoint rounding equally between up and down, producing statistically unbiased results. ### Why doesn't truncation work as a rounding strategy for deterministic systems? Truncation introduces systematic negative bias because it always rounds toward zero. Over thousands of operations in ML training or inference, this bias accumulates and distorts results. Round-to-nearest-even is unbiased and is the default IEEE 754 rounding mode, making it the correct choice for deterministic fixed-point systems. ### What is the implementation cost of round-to-nearest-even in fixed-point arithmetic? Round-to-nearest-even adds one conditional check per rounding operation to detect midpoint values and select the even result. In practice, this adds 1–3 instructions per operation — negligible overhead compared to the multiplication or division being rounded. The [certifiable-training](https://github.com/SpeyTech/certifiable-training) implementation demonstrates the complete approach. ## Conclusion Round-to-Nearest-Even is a small detail with large consequences. It's the difference between "our model training is reproducible" and "our model training is *provably* reproducible." The certifiable-* ecosystem uses RNE throughout: in matrix multiplication, in gradient computation, in activation functions, in loss calculation. Every rounding decision follows the same rule, producing the same result, on every platform. For safety-critical machine learning, that consistency isn't a nice-to-have. It's a requirement. As with any architectural approach, suitability depends on system requirements, risk classification, and regulatory context. For systems that must be certifiable, RNE is the foundation. --- *The certifiable-* ecosystem is open source. Explore the [implementation](https://github.com/SpeyTech/certifiable-training) or read the [CT-MATH-001 specification](https://github.com/SpeyTech/certifiable-training/blob/main/docs/CT-MATH-001.md) for the complete mathematical foundation.* --- ## Fixed-Point Neural Networks: The Math Behind Q16.16 **URL**: https://speytech.com/insights/fixed-point-neural-networks/ **Published**: January 15, 2026 21:30 **Topic**: Safety-Critical AI **Answers**: How does Q16.16 fixed-point integer arithmetic enable fully deterministic neural network inference for safety-critical embedded systems that require guaranteed cross-platform reproducibility, and what are the mathematical foundations, precision trade-offs, dynamic range limitations, and overflow handling strategies for integer-only forward passes? **Defines**: Q16.16 fixed-point arithmetic KEY_CLAIMS: - Neural networks run on floating-point arithmetic. - Q16.16 fixed-point arithmetic represents numbers as 32-bit integers with 16 integer bits and 16 fractional bits, enabling deterministic computation without platform-dependent floating-point variance. - Fixed-point arithmetic trades precision for determinism. - Q16.16 represents numbers as 32-bit integers with 16 fractional bits, using integer multiplication and addition with defined C99 overflow behaviour. - Use saturation arithmetic that clamps results to the representable range rather than wrapping. EVIDENCE: - For systems that require certification under DO-178C, IEC 62304, or ISO 26262, they represent a fundamental barrier. - This article explains the mathematics of Q16.16 fixed-point representation, demonstrates the core operations required for neural network inference, and examines the precision implications for safety-critical AI systems. - Floating-point arithmetic follows the IEEE 754 standard, which specifies representation and basic operations. - The x87 floating-point unit in x86 processors uses 80-bit extended precision for intermediate calculations, even when the source and destination are 32-bit floats. RELATES_TO: - insights/dynamic-memory-safety-critical How integer arithmetic can enable deterministic AI inference for safety-critical systems Neural networks run on floating-point arithmetic. This is so universal that most practitioners never question it. But floating-point has a property that matters enormously in safety-critical systems: it is not deterministic across platforms. The same floating-point calculation can produce different results on x86 versus ARM, on GPU versus CPU, or even between compiler versions. For research and most production systems, these differences are negligible. For systems that require certification under DO-178C, IEC 62304, or ISO 26262, they represent a fundamental barrier. Fixed-point arithmetic offers an alternative. By representing fractional values as scaled integers, fixed-point achieves bit-identical results across all platforms. The trade-off is reduced range and precision compared to floating-point. Understanding this trade-off is essential for evaluating whether fixed-point is appropriate for a given application. This article explains the mathematics of Q16.16 fixed-point representation, demonstrates the core operations required for neural network inference, and examines the precision implications for safety-critical AI systems. Definition: Q16.16 Fixed-Point Arithmetic Q16.16 fixed-point arithmetic represents numbers as 32-bit integers with 16 integer bits and 16 fractional bits, enabling deterministic computation without platform-dependent floating-point variance. ## Why Floating-Point Varies Floating-point arithmetic follows the IEEE 754 standard, which specifies representation and basic operations. However, the standard permits variation in several areas that affect reproducibility. **Intermediate precision.** The x87 floating-point unit in x86 processors uses 80-bit extended precision for intermediate calculations, even when the source and destination are 32-bit floats. ARM processors typically use 32-bit precision throughout. The same sequence of operations can accumulate different rounding errors. **Fused multiply-add.** Modern processors offer FMA instructions that compute `a * b + c` with a single rounding step instead of two. Whether the compiler uses FMA depends on optimisation settings, target architecture, and sometimes the order of operations in source code. FMA produces more accurate results, but different results from separate multiply and add. **Associativity.** Floating-point addition is not associative: `(a + b) + c` may differ from `a + (b + c)`. Compilers that reorder operations for performance can change results. Parallel reduction algorithms that sum values in different orders produce different results. **Transcendental functions.** Functions like `exp()`, `log()`, and `sin()` are not specified bit-exactly by IEEE 754. Different math libraries use different approximation algorithms. For neural network inference, these variations typically produce outputs that differ in the least significant bits. The classification result is usually the same. But "usually the same" is insufficient for systems where certification requires demonstrable reproducibility. ## The Fixed-Point Alternative Fixed-point arithmetic represents fractional values as integers with an implicit scaling factor. The Q16.16 format uses a 32-bit signed integer where: - The upper 16 bits represent the integer part - The lower 16 bits represent the fractional part - The scaling factor is 2^16 = 65536 A value like 3.25 is stored as `3.25 × 65536 = 212992`. The key insight is that all arithmetic operates on integers, using the standard integer ALU that behaves identically on every platform. Design Property: Platform Independence Integer arithmetic produces identical results on all platforms. Fixed-point inherits this property, enabling bit-perfect reproducibility across x86, ARM, RISC-V, and any architecture with standard integer operations. ### Range and Precision Q16.16 provides: | Property | Value | |----------|-------| | Minimum value | -32768.0 | | Maximum value | +32767.99998... | | Resolution | 1/65536 ≈ 0.0000153 | | Decimal precision | ~4.8 significant digits | Compare this to 32-bit floating-point: | Property | Float32 | Q16.16 | |----------|---------|--------| | Range | ±3.4 × 10^38 | ±32768 | | Precision | ~7 significant digits | ~4.8 significant digits | | Deterministic | No | Yes | The reduced range and precision are significant constraints. Neural network weights and activations must be scaled to fit within ±32768, and accumulated rounding errors must be managed carefully. The benefit is certainty: the same input always produces the same output. ## Core Operations Neural network inference requires four fundamental operations: conversion, addition, multiplication, and accumulation. Each has specific implementation requirements in fixed-point. ### Conversion Converting from floating-point to Q16.16 during model quantisation: ```c typedef int32_t fixed_t; #define FX_FRAC_BITS 16 #define FX_SCALE (1 = 0 ? scaled + 0.5f : scaled - 0.5f); } ``` ### Addition and Subtraction Fixed-point values with the same Q format add directly: ```c fixed_t fx_add(fixed_t a, fixed_t b) { return a + b; } fixed_t fx_sub(fixed_t a, fixed_t b) { return a - b; } ``` Overflow is the primary concern. Adding two Q16.16 values near the maximum can overflow the 32-bit representation. For safety-critical systems, saturation arithmetic prevents wrap-around: ```c #define FX_MAX ((fixed_t)0x7FFFFFFF) #define FX_MIN ((fixed_t)0x80000000) fixed_t fx_add_sat(fixed_t a, fixed_t b) { int64_t result = (int64_t)a + (int64_t)b; if (result > FX_MAX) return FX_MAX; if (result > FX_FRAC_BITS); } ``` This operation truncates the lower 16 bits of the 64-bit product. For applications requiring rounding: ```c fixed_t fx_mul_rounded(fixed_t a, fixed_t b) { int64_t product = (int64_t)a * (int64_t)b; // Add 0.5 in the fractional position before shifting product += (1 > FX_FRAC_BITS); } ``` ### Division Division is less common in inference (weights are pre-computed), but when needed: ```c fixed_t fx_div(fixed_t a, fixed_t b) { int64_t dividend = (int64_t)a > FX_FRAC_BITS); } } } ``` The 64-bit accumulator is critical. A matrix multiplication with K=1000 elements could overflow a 32-bit accumulator even if individual products fit. The shift happens once at the end, preserving precision during accumulation. ### Convolution 2D convolution for image processing: ```c void fx_conv2d(const fixed_t* input, const fixed_t* kernel, fixed_t* output, int in_h, int in_w, int k_h, int k_w) { int out_h = in_h - k_h + 1; int out_w = in_w - k_w + 1; for (int oh = 0; oh > FX_FRAC_BITS); } } } ``` ### Activation Functions ReLU is trivial in fixed-point: ```c fixed_t fx_relu(fixed_t x) { return x > 0 ? x : 0; } ``` More complex activations like sigmoid or tanh require lookup tables or polynomial approximations: ```c // Sigmoid approximation using piecewise linear segments fixed_t fx_sigmoid_approx(fixed_t x) { // Saturate for large inputs if (x >= FX_FROM_INT(4)) return FX_FROM_FLOAT(0.9820f); if (x = FX_FROM_INT(-1) && x max_val) max_val = input[ih * in_w + iw + 1]; if (input[(ih + 1) * in_w + iw] > max_val) max_val = input[(ih + 1) * in_w + iw]; if (input[(ih + 1) * in_w + iw + 1] > max_val) max_val = input[(ih + 1) * in_w + iw + 1]; output[oh * out_w + ow] = max_val; } } } ``` ## Precision Analysis The practical question is: does reduced precision affect model accuracy? ### Quantisation Error Converting a trained floating-point model to Q16.16 introduces quantisation error in every weight. For a weight w, the quantised value is: ``` w_q = round(w × 65536) / 65536 ``` The maximum error per weight is ±0.5/65536 ≈ ±7.6 × 10^-6. For a layer with N weights, these errors accumulate. The total error depends on the statistical distribution of weights and the structure of the computation. Empirically, Q16.16 typically maintains classification accuracy within 1-2% of the original floating-point model for common architectures. However, this varies significantly by model and task. Rigorous evaluation on the target application is essential. ### Accumulation Error Each multiplication introduces rounding error when the 64-bit product is shifted back to 32 bits. For a dot product of length K: - K multiplications, each with error up to 1 LSB - One final shift with error up to 1 LSB - Total error bounded by K + 1 LSBs For large K (thousands of weights per neuron), this can become significant. Techniques to manage accumulation error include: 1. **Larger accumulators**: Use 64-bit arithmetic throughout 2. **Block accumulation**: Sum in smaller blocks, normalise between blocks 3. **Kahan summation**: Track and compensate for rounding errors (increases complexity) ### Overflow Prevention The Q16.16 range of ±32768 constrains both weights and activations. Model quantisation must ensure: - All weights fit within the representable range - Activations cannot exceed the range during inference - Accumulated values in matrix operations fit in 64-bit intermediates This typically requires scaling the model. A common approach: 1. Analyse the trained model to find weight and activation ranges 2. Apply per-layer scaling factors to fit within Q16.16 3. Adjust bias terms to compensate for scaling 4. Validate accuracy after quantisation ## Practical Considerations ### Memory Layout Fixed-point values are 32-bit integers. Memory requirements match float32 exactly. There is no memory advantage to Q16.16 over float32, unlike INT8 quantisation. The advantage is computational: fixed-point operations use the integer ALU, which on some embedded processors is faster and more power-efficient than the FPU. More importantly, integer operations are deterministic. ### No Dynamic Allocation Safety-critical systems typically prohibit dynamic memory allocation after initialisation, as discussed in [The Real Cost of Dynamic Memory in Safety-Critical Systems](/insights/dynamic-memory-safety-critical/). The fixed-point implementations shown here use caller-provided buffers: ```c // Caller allocates all buffers fixed_t input[256]; fixed_t kernel[9]; fixed_t output[196]; // Function uses only provided memory fx_conv2d(input, kernel, output, 16, 16, 3, 3); ``` This enables static memory analysis and prevents heap fragmentation, both requirements for DO-178C Level A certification. ### Testing Determinism Verifying bit-exact reproducibility requires testing across platforms: ```c void test_determinism(void) { // Known input fixed_t a = 0x00028000; // 2.5 fixed_t b = 0x00018000; // 1.5 // Expected output (computed once, verified manually) fixed_t expected = 0x0003C000; // 3.75 fixed_t result = fx_mul(a, b); assert(result == expected); // Exact equality, not approximate } ``` These tests must pass on every target platform. Any difference indicates a determinism failure that must be investigated. ## Trade-offs and Limitations Fixed-point Q16.16 is not universally appropriate. Consider these factors: Fixed-Point Strengths Bit-exact reproducibility across platforms No floating-point unit required Predictable execution time (no denormals) Supports static memory analysis Integer ALU may be faster on embedded systems Fixed-Point Limitations Reduced dynamic range (±32768 vs ±10^38) Reduced precision (~4.8 vs ~7 digits) Requires careful overflow management Model must be quantised and validated Some activations need approximation For safety-critical systems requiring certification, the determinism guarantee often outweighs the precision limitations. For research or high-precision applications, floating-point remains the appropriate choice. ## Implementation Reference The [certifiable-inference](https://github.com/SpeyTech/certifiable-inference) project provides a complete implementation of fixed-point neural network inference in C99, including: - Q16.16 arithmetic with saturation - Matrix operations - 2D convolution - Activation functions (ReLU, approximated sigmoid) - Max pooling The implementation passes determinism tests across x86, ARM, and RISC-V platforms. A [live simulator](https://inference.speytech.com/) demonstrates the inference pipeline. ## Frequently Asked Questions ### How does Q16.16 fixed-point arithmetic enable deterministic neural network inference? Q16.16 represents numbers as 32-bit integers with 16 fractional bits, using integer multiplication and addition with defined C99 overflow behaviour. Every operation produces identical results on every conformant platform, eliminating the platform-dependent rounding that makes floating-point inference non-reproducible. ### How do I handle overflow in fixed-point neural network computations? Use saturation arithmetic that clamps results to the representable range rather than wrapping. For multiply operations, use 64-bit intermediate results before shifting back to 32-bit Q16.16 format. Monitor value ranges per layer during development to ensure the dynamic range budget accommodates worst-case activations. ### Why doesn't quantisation to int8 provide the same guarantees as Q16.16? Post-training quantisation to int8 typically uses floating-point scale factors and zero-point offsets that reintroduce platform-dependent behaviour. Q16.16 fixed-point uses purely integer operations throughout — the arithmetic itself is deterministic, not just the storage format. Scale factors in Q16.16 are also fixed-point values. ### What are the precision limitations of Q16.16 for neural network inference? Q16.16 provides approximately 4.8 decimal digits of fractional precision with a range of ±32767. Deep networks with many layers may accumulate quantisation error. Very large or very small values require rescaling. Networks must be designed or adapted to operate within these precision bounds — not all architectures transfer directly from floating-point. ## Conclusion Fixed-point arithmetic trades precision for determinism. The Q16.16 format provides sufficient precision for many neural network applications while guaranteeing bit-identical results across platforms. The mathematics are straightforward: scale values by 65536, use integer arithmetic, and shift results after multiplication. The engineering challenge lies in managing overflow, quantising models appropriately, and validating that reduced precision does not unacceptably degrade accuracy. For systems requiring certification under DO-178C, IEC 62304, or ISO 26262, fixed-point may provide a path that floating-point cannot. The ability to prove that identical inputs produce identical outputs simplifies verification and validation significantly. As with any architectural approach, suitability depends on system requirements, precision constraints, and regulatory context. Fixed-point is not a universal solution, but for safety-critical AI where determinism matters more than dynamic range, it offers a mathematically sound foundation. --- *For a working implementation of these principles, see [certifiable-inference](https://github.com/SpeyTech/certifiable-inference) or try the [live simulator](https://inference.speytech.com/).* --- ## Bit-Perfect Reproducibility: Why It Matters **URL**: https://speytech.com/insights/bit-perfect-reproducibility/ **Published**: January 15, 2026 20:15 **Topic**: Safety-Critical AI **Answers**: What does bit-perfect reproducibility mean for software execution in practice, why does it matter for safety-critical system certification and regulatory compliance, and how do you design, implement, and verify systems that produce identical outputs across different platforms, compilers, and processor architectures? **Defines**: Bit-perfect reproducibility KEY_CLAIMS: - "Reproducible" means different things in different contexts. - Bit-perfect reproducibility is achievable but requires deliberate design. - Bit-perfect reproducibility means a computation produces identical binary output — matching at every bit position — across different platforms, compilers, and runs. - Compute SHA-256 hashes of all intermediate and final outputs on each target platform. - Compilers may reorder floating-point operations, use fused multiply-add instructions, or select different SIMD strategies — all of which change numerical results at the bit level. EVIDENCE: - IEEE 754 floating-point permits variation in several areas: Intermediate precision. x87 FPU uses 80-bit intermediates; ARM uses 32-bit or 64-bit. RELATES_TO: - insights/dynamic-memory-safety-critical - insights/fixed-point-neural-networks What deterministic execution actually means and how to verify it across platforms "Reproducible" means different things in different contexts. In research, it often means "similar results within experimental tolerance." In most production systems, it means "the same classification most of the time." In safety-critical systems, it can mean something far more stringent: identical output, byte for byte, on every execution. This article examines what bit-perfect reproducibility actually requires, why it matters for certification, and how to design systems that achieve it. The techniques apply broadly, but the examples focus on neural network inference where reproducibility failures are particularly common and consequential. ## Levels of Reproducibility It helps to distinguish four levels of reproducibility, each stricter than the last: **Statistical reproducibility.** Results fall within expected variance. Two training runs produce models with similar accuracy. This is the standard for research. **Classification reproducibility.** The same input produces the same classification. The confidence scores may vary, but the final decision is stable. This suffices for many production systems. **Numerical reproducibility.** The same input produces outputs that match within a tolerance (e.g., relative error Design Property: Transportable Verification If a system produces bit-identical outputs across platforms, verification evidence from one platform applies to all platforms. Testing on x86 provides evidence for ARM deployment without re-verification. ## Sources of Non-Reproducibility Achieving bit-perfect reproducibility requires understanding where differences originate. Most stem from a small number of sources. ### Floating-Point Arithmetic IEEE 754 floating-point permits variation in several areas: **Intermediate precision.** x87 FPU uses 80-bit intermediates; ARM uses 32-bit or 64-bit. The same expression produces different rounding. **Operation ordering.** Floating-point addition is not associative. `(a + b) + c` may differ from `a + (b + c)`. Compiler optimisations that reorder operations change results. **Fused operations.** FMA (fused multiply-add) computes `a * b + c` with one rounding instead of two. Whether FMA is used depends on compiler flags, target architecture, and optimisation level. **Transcendental functions.** `sin()`, `exp()`, `log()` are not specified bit-exactly. Different math libraries use different approximations. The solution explored in [Fixed-Point Neural Networks](/insights/fixed-point-neural-networks/) is to avoid floating-point entirely for computation, using fixed-point integer arithmetic that behaves identically on all platforms. ### Hash Table Iteration Many languages implement hash tables with iteration order that depends on memory layout or randomised hash functions: ```python # Python dict iteration order can vary between runs # (though CPython 3.7+ preserves insertion order) for key in my_dict: process(key) # Order may be non-deterministic ``` In C, pointer-based hash tables often iterate in pointer order, which varies with memory allocation: ```c // Dangerous: iteration order depends on pointer values for (entry = table->first; entry; entry = entry->next) { process(entry); // Order is non-deterministic } ``` The solution is deterministic data structures that iterate in a defined order (insertion order, sorted order, or explicitly specified order). ### Threading and Parallelism Concurrent execution introduces non-determinism unless carefully controlled: **Thread scheduling.** The OS decides when threads run. Two threads racing to update shared state may interleave differently on each execution. **Parallel reduction.** Summing an array in parallel typically splits the work across threads. The order of partial sums varies, and with floating-point arithmetic, so does the result. **Lock acquisition order.** When multiple threads contend for locks, acquisition order is non-deterministic. For bit-perfect reproducibility, either avoid parallelism or use deterministic parallel patterns with explicit synchronisation that guarantees the same interleaving on every execution. ### Memory Allocation Dynamic allocation can introduce non-determinism through: **Address-dependent behaviour.** Code that accidentally depends on pointer values (e.g., using pointers as hash keys) behaves differently when allocation returns different addresses. **Allocation order.** Some allocators return memory in different orders depending on heap state, affecting programs that iterate over allocated objects by address. Static allocation, as discussed in [The Real Cost of Dynamic Memory](/insights/dynamic-memory-safety-critical/), eliminates this source of variation. ### System Calls Calls that return environmental information introduce external non-determinism: ```c time_t t = time(NULL); // Different every second int r = rand(); // Different every call (unless seeded) pid_t p = getpid(); // Different every process ``` Bit-perfect reproducibility requires either avoiding these calls or providing deterministic alternatives (e.g., injecting time as an input parameter rather than reading the system clock). ## Designing for Determinism Achieving bit-perfect reproducibility is an architectural decision, not a debugging task. It requires choosing deterministic alternatives for each potential source of variation. ### Pure Functions The foundation is pure functions: outputs depend only on inputs, with no side effects or external state access. ```c // Pure: output depends only on inputs int add(int a, int b) { return a + b; } // Impure: output depends on external state int add_with_timestamp(int a, int b) { return a + b + time(NULL); // Non-deterministic } ``` Pure functions compose deterministically. A pipeline of pure functions is itself pure. Testing pure functions is straightforward: supply inputs, check outputs. ### Explicit State Where state is necessary, make it explicit and contained: ```c typedef struct { fixed_t weights[MAX_WEIGHTS]; fixed_t biases[MAX_BIASES]; uint32_t rng_state; // Explicit RNG state, not global } model_state_t; void infer(const model_state_t* state, const fixed_t* input, fixed_t* output) { // All state is explicit in parameters // No global variables, no system calls } ``` Explicit state enables reproducibility by controlling all inputs to the computation. ### Deterministic Algorithms Some algorithms are inherently non-deterministic; others have deterministic and non-deterministic variants. Choose deliberately: | Operation | Non-deterministic | Deterministic | |-----------|-------------------|---------------| | Sorting equal elements | Quicksort (unstable) | Mergesort (stable) | | Hash table iteration | Address order | Insertion or key order | | Parallel reduction | Thread-arrival order | Fixed tree reduction | | Random sampling | System RNG | Seeded PRNG | The deterministic variant may be slower or use more memory. For safety-critical systems, the trade-off usually favours determinism. ### Fixed-Point Arithmetic As detailed in [Fixed-Point Neural Networks](/insights/fixed-point-neural-networks/), integer arithmetic is deterministic across platforms: ```c // Non-deterministic: floating-point float result = a * b + c; // FMA? Intermediate precision? // Deterministic: fixed-point int64_t product = (int64_t)a * (int64_t)b; int32_t result = (int32_t)((product >> 16) + c); ``` The integer operations produce identical results on x86, ARM, RISC-V, and any other architecture with standard integer arithmetic. ## Verifying Determinism Design enables determinism; testing verifies it. Verification requires running the same computation on multiple platforms and comparing results bit-for-bit. ### Cross-Platform Testing The gold standard is identical binaries (where possible) or identical source compiled for each target: ```bash # Compile for each platform make ARCH=x86_64 make ARCH=aarch64 make ARCH=riscv64 # Run identical tests ./test_x86_64 > output_x86.bin ./test_aarch64 > output_arm.bin ./test_riscv64 > output_riscv.bin # Compare byte-for-byte diff output_x86.bin output_arm.bin diff output_x86.bin output_riscv.bin ``` Any difference indicates a determinism failure. The test should produce no output if all platforms match. ### Hash-Based Verification For large outputs, compare hashes rather than raw bytes: ```c void test_determinism(void) { fixed_t input[INPUT_SIZE]; fixed_t output[OUTPUT_SIZE]; // Known test input load_test_vector(input); // Run inference inference(input, output); // Compute hash uint8_t hash[32]; sha256(output, sizeof(output), hash); // Compare to expected hash (computed once, verified across platforms) const uint8_t expected[32] = { 0x3a, 0x7f, ... }; assert(memcmp(hash, expected, 32) == 0); } ``` If the hash matches the expected value, the output is bit-identical. If it differs, something has changed. ### Regression Testing Determinism tests should run on every build to catch regressions: ```yaml # CI configuration test_determinism: matrix: platform: [x86_64, aarch64, riscv64] steps: - compile: make ARCH=$platform - run: ./determinism_tests - verify: diff output.bin golden/output.bin ``` Golden outputs are generated once and stored in version control. Any change to the output indicates either a bug or an intentional change that requires updating the golden files. ### Fuzzing for Determinism Random input testing can find edge cases where determinism breaks: ```c void fuzz_determinism(int iterations) { for (int i = 0; i < iterations; i++) { // Generate random input (seeded for reproducibility) fixed_t input[INPUT_SIZE]; generate_random_input(input, seed + i); // Run twice fixed_t output1[OUTPUT_SIZE]; fixed_t output2[OUTPUT_SIZE]; inference(input, output1); inference(input, output2); // Must match exactly assert(memcmp(output1, output2, sizeof(output1)) == 0); } } ``` This catches cases where internal state leaks between invocations or where certain input patterns trigger non-deterministic code paths. ## Common Pitfalls Even systems designed for determinism can fail through subtle issues. ### Uninitialised Memory Reading uninitialised memory produces undefined values: ```c fixed_t buffer[SIZE]; // buffer contains garbage - uninitialised process(buffer); // Non-deterministic! ``` Always initialise memory explicitly: ```c fixed_t buffer[SIZE] = {0}; // Zero-initialised // or memset(buffer, 0, sizeof(buffer)); ``` ### Padding Bytes Struct padding may contain garbage: ```c typedef struct { int8_t a; // 3 bytes padding int32_t b; } padded_t; padded_t x; x.a = 1; x.b = 2; // Padding bytes are uninitialised hash(&x, sizeof(x)); // Hash includes garbage padding! ``` Zero the entire struct before use, or hash only the meaningful fields. ### Compiler Optimisations Aggressive optimisation can reorder floating-point operations: ```c // Source code float sum = a + b + c + d; // Compiler may emit float sum = (a + b) + (c + d); // Different rounding! ``` For floating-point code, use `-ffp-contract=off` and similar flags to disable operation fusion. For fixed-point code, this is not a concern since integer operations are not reordered in ways that change results. ### Library Differences Even deterministic code can produce different results if linked against different libraries: ```c // If libc differs between platforms, results may differ qsort(array, n, sizeof(int), compare); // Stable? Ordering of equal elements? ``` Either use libraries with guaranteed behaviour, or implement critical functions directly. ## Practical Considerations ### Performance Trade-offs Deterministic alternatives are sometimes slower: | Pattern | Non-deterministic | Deterministic | Overhead | |---------|-------------------|---------------|----------| | Parallel sum | Thread-order reduction | Fixed tree | ~10-20% | | Hash iteration | Pointer order | Sorted order | O(n log n) | | Memory layout | Allocator-dependent | Static/fixed | Minimal | | Floating-point | Hardware FMA | Software emulation | 2-5x | For safety-critical systems, the overhead is typically acceptable. Correctness and auditability outweigh raw performance. ### Scope of Determinism Not everything needs to be deterministic. A system can have: - Deterministic inference (same input → same output) - Non-deterministic logging (timestamps, which don't affect computation) - Non-deterministic scheduling (order of independent operations) The key is that non-determinism must not affect the auditable computation path. ### Versioning Bit-perfect reproducibility is relative to a specific version. Changing the code changes the outputs. Version management must track: - Source code version - Compiler version - Library versions - Target architecture Reproducibility claims are valid only within a specific configuration. Changing any component may change outputs. ## Implementation Reference The [certifiable-inference](https://github.com/SpeyTech/certifiable-inference) project demonstrates bit-perfect reproducibility: - Fixed-point arithmetic throughout - No floating-point in computation paths - Static allocation only - Deterministic algorithms - Cross-platform verification tests The test suite includes golden outputs verified across x86, ARM, and RISC-V. Any platform difference causes test failure. A [live simulator](https://inference.speytech.com/) demonstrates the deterministic inference pipeline interactively. ## Frequently Asked Questions ### What is bit-perfect reproducibility in software execution? Bit-perfect reproducibility means a computation produces identical binary output — matching at every bit position — across different platforms, compilers, and runs. This property is achieved through fixed-point arithmetic, static allocation, deterministic scheduling, and elimination of all platform-dependent behaviour. ### How do I verify bit-perfect reproducibility across platforms? Compute SHA-256 hashes of all intermediate and final outputs on each target platform. If hashes match across x86, ARM, and other architectures using different compilers and optimisation levels, the execution is bit-perfect. The [certifiable-harness](https://github.com/SpeyTech/certifiable-harness) provides automated cross-platform verification against golden references. ### Why doesn't compiler optimisation preserve bit-perfect output? Compilers may reorder floating-point operations, use fused multiply-add instructions, or select different SIMD strategies — all of which change numerical results at the bit level. Fixed-point integer arithmetic avoids this because integer operations have defined behaviour under C99 regardless of optimisation level. ### What are the practical costs of achieving bit-perfect reproducibility? Fixed-point arithmetic constrains dynamic range compared to floating-point. Static allocation requires upfront memory budgeting. Deterministic scheduling may impose performance overhead. Development requires more discipline, and fewer off-the-shelf libraries support these constraints. The trade-off is justified when certification or audit requirements demand reproducible execution. ## Conclusion Bit-perfect reproducibility is achievable but requires deliberate design. The primary sources of non-determinism—floating-point arithmetic, hash table iteration, threading, memory allocation, and system calls—each have deterministic alternatives. The cost is reduced flexibility and sometimes reduced performance. The benefit is absolute certainty: the same input produces the same output, every time, on every platform. This enables cryptographic verification, exact replay, and transportable certification evidence. For safety-critical systems, where incident investigation may require reproducing exact behaviour months or years later, bit-perfect reproducibility is not merely convenient—it may be essential. As with any architectural approach, suitability depends on system requirements and verification objectives. Not all systems need bit-perfect reproducibility. But for those that do, achieving it is a matter of engineering discipline, not luck. --- *For a working implementation demonstrating bit-perfect reproducibility across platforms, see [certifiable-inference](https://github.com/SpeyTech/certifiable-inference) or try the [live simulator](https://inference.speytech.com/).* --- ## The Real Cost of Dynamic Memory in Safety-Critical Systems **URL**: https://speytech.com/insights/dynamic-memory-safety-critical/ **Published**: January 15, 2026 19:20 **Topic**: Safety-Critical AI **Answers**: Why is dynamic memory allocation using malloc and free problematic for safety-critical software certification under standards like DO-178C and IEC 62304, and how does static allocation with caller-provided buffers simplify formal verification, eliminate heap fragmentation, and enable bounded resource analysis? **Defines**: Static allocation KEY_CLAIMS: - Dynamic memory allocation is fundamental to modern software. - Static allocation provides all memory through caller-supplied buffers at compile time, eliminating heap fragmentation, allocation failures, and the verification burden of dynamic memory management. - Dynamic memory allocation introduces variability that conflicts with safety-critical certification objectives. - Dynamic allocation introduces heap fragmentation, failure modes, and non-deterministic timing that cannot be statically bounded. - The caller allocates all buffers at compile time or program start and passes them to functions as parameters. EVIDENCE: - Certification standards like DO-178C (aerospace), IEC 62304 (medical devices), and ISO 26262 (automotive) impose requirements that make dynamic allocation difficult to verify and, in the most stringent classifications, effectively prohibited. - If malloc can take 10μs in the best case and 10ms in the worst case, the system must be designed for the 10ms case, wasting capacity in normal operation. - A system with 1MB free might fail to allocate 64KB because no single contiguous region remains. - DO-178C does not explicitly prohibit dynamic allocation, but its objectives create significant barriers at higher Design Assurance Levels (DAL). RELATES_TO: - insights/fixed-point-neural-networks Why malloc is problematic for certification and how static allocation can simplify verification Dynamic memory allocation is fundamental to modern software. Languages and frameworks assume heap access. Data structures grow and shrink as needed. Memory management happens automatically or through simple malloc/free pairs. In safety-critical systems, this flexibility becomes a liability. Certification standards like DO-178C (aerospace), IEC 62304 (medical devices), and ISO 26262 (automotive) impose requirements that make dynamic allocation difficult to verify and, in the most stringent classifications, effectively prohibited. Understanding why requires examining what dynamic allocation actually does at runtime and why those behaviours conflict with certification objectives. This article explores the technical problems with dynamic memory in safety-critical contexts, examines how certification standards address these concerns, and demonstrates static allocation patterns that can satisfy verification requirements for neural network inference. Definition: Static Allocation Static allocation provides all memory through caller-supplied buffers at compile time, eliminating heap fragmentation, allocation failures, and the verification burden of dynamic memory management. ## What Dynamic Allocation Does When code calls `malloc(size)`, the runtime memory allocator must: 1. **Search** for a free block of sufficient size 2. **Split** the block if it's larger than needed (in most implementations) 3. **Update** internal bookkeeping structures 4. **Return** a pointer to the allocated region When code calls `free(ptr)`, the allocator must: 1. **Validate** the pointer (in robust implementations) 2. **Mark** the block as available 3. **Coalesce** adjacent free blocks (in most implementations) 4. **Update** bookkeeping structures These operations have properties that create challenges for safety-critical systems. ### Variable Execution Time The time to complete malloc depends on the current state of the heap. A fresh heap with large contiguous free space satisfies requests quickly. A fragmented heap may require searching through many small blocks before finding one that fits. This variability makes worst-case execution time (WCET) analysis difficult. Safety-critical systems often require bounded timing: the system must respond within a guaranteed deadline. If malloc can take 10μs in the best case and 10ms in the worst case, the system must be designed for the 10ms case, wasting capacity in normal operation. ### Fragmentation Repeated allocation and deallocation of varying sizes fragments the heap. Free memory exists, but in pieces too small to satisfy requests. A system with 1MB free might fail to allocate 64KB because no single contiguous region remains. Fragmentation is non-deterministic. It depends on the exact sequence of allocations and frees, which may depend on input data, timing, or external events. Two runs of the same program with different inputs can produce different fragmentation patterns, causing one to succeed and the other to fail. ### Failure Modes When malloc cannot satisfy a request, it returns NULL. Correct handling of allocation failure is notoriously difficult: ```c // Common pattern - often wrong char* buffer = malloc(size); if (buffer == NULL) { // Now what? // - Return error? (caller must handle) // - Log and continue? (with what buffer?) // - Abort? (acceptable in safety-critical?) } ``` Every allocation site requires failure handling. Every failure handler must be tested. In a system with hundreds of allocation points, this creates a verification burden that grows with code complexity. ### Hidden State The heap is global mutable state shared across the entire program. An allocation in one module affects available memory for all other modules. A memory leak in a rarely-executed path may not manifest until hours or days into operation. This hidden coupling makes reasoning about system behaviour difficult. Two modules that appear independent may interact through heap exhaustion in ways that are hard to predict and harder to test. ## What Certification Standards Require Certification standards address these concerns with varying degrees of strictness. ### DO-178C (Aerospace) DO-178C does not explicitly prohibit dynamic allocation, but its objectives create significant barriers at higher Design Assurance Levels (DAL). **Objective A-5** requires demonstration that the software "does not have unintended functions." Dynamic allocation's dependence on runtime state makes this difficult to show exhaustively. **Objective A-7** requires verification that the software performs its intended functions. If allocation can fail, the failure paths must be verified, including demonstration that the system remains safe when memory is exhausted. For DAL A (catastrophic failure conditions), the verification burden is so high that most projects prohibit dynamic allocation after initialisation as a practical matter. The CAST-21 position paper from certification authorities explicitly addresses dynamic memory, noting that its use "ichever requires specific means to show compliance." ### IEC 62304 (Medical Devices) IEC 62304 Class C (highest safety classification) requires: - **Risk analysis** of each software item - **Verification** that software items meet requirements - **Traceability** from requirements through design to tests Dynamic allocation introduces risks (fragmentation, exhaustion, timing variance) that must be analysed, mitigated, and verified. For life-sustaining systems, the analysis overhead often exceeds the cost of redesigning with static allocation. ### ISO 26262 (Automotive) ISO 26262 Part 6 Table 1 lists "No dynamic objects or variables" as a recommendation for ASIL C and ASIL D systems. While not an absolute prohibition, deviating from recommendations requires documented rationale and alternative measures. The standard's emphasis on deterministic timing and freedom from interference aligns poorly with heap allocation's variable timing and global state. Design Property: Analysability Static allocation enables complete analysis of memory usage at compile time. Maximum memory consumption is known before the software runs, eliminating runtime exhaustion as a failure mode. ## The Static Allocation Alternative Static allocation means all memory is reserved at compile time or during initialisation, with no runtime allocation during normal operation. This approach trades flexibility for analysability. ### Caller-Provided Buffers Instead of functions allocating their own memory, callers provide buffers: ```c // Dynamic allocation pattern result_t* process_data(const input_t* input) { result_t* result = malloc(sizeof(result_t)); if (result == NULL) return NULL; // ... process ... return result; // Caller must free } // Static allocation pattern int process_data(const input_t* input, result_t* result) { // result buffer provided by caller // ... process ... return 0; // Success } ``` The caller controls memory lifetime. The function cannot fail due to allocation. Memory ownership is explicit rather than implicit. ### Fixed-Size Arrays Where dynamic arrays might grow, static allocation uses fixed maximum sizes: ```c // Dynamic pattern typedef struct { float* weights; // malloc'd, size varies int size; } layer_t; // Static pattern #define MAX_WEIGHTS 1024 typedef struct { float weights[MAX_WEIGHTS]; // Fixed at compile time int used; // Actual count in use } layer_t; ``` This wastes memory when actual usage is below the maximum. For safety-critical systems, the trade-off is often acceptable: memory is cheap compared to verification effort. ### Object Pools For systems that genuinely need runtime object creation, pools pre-allocate a fixed number of objects: ```c #define POOL_SIZE 32 typedef struct { message_t messages[POOL_SIZE]; uint8_t available[POOL_SIZE]; // 1 = free, 0 = in use int next_free; } message_pool_t; message_t* pool_acquire(message_pool_t* pool) { for (int i = 0; i next_free + i) % POOL_SIZE; if (pool->available[idx]) { pool->available[idx] = 0; pool->next_free = (idx + 1) % POOL_SIZE; return &pool->messages[idx]; } } return NULL; // Pool exhausted } void pool_release(message_pool_t* pool, message_t* msg) { int idx = msg - pool->messages; pool->available[idx] = 1; } ``` Pool exhaustion is still possible, but the maximum is known statically. Testing can verify behaviour when all objects are in use. There is no fragmentation because all objects are the same size. ## Application to Neural Network Inference Neural network inference is particularly amenable to static allocation because the memory requirements are known at model load time. ### Model Structure A neural network has fixed structure: - Layer count is fixed - Weight dimensions per layer are fixed - Maximum activation sizes between layers are fixed All of this is known when the model is deployed. There is no need for runtime allocation. ### Inference Buffers Inference requires temporary buffers for intermediate activations. Using [fixed-point arithmetic](/insights/fixed-point-neural-networks/) for determinism, the maximum size is determined by the largest layer: ```c // Determined at model compile time #define MAX_ACTIVATION_SIZE 4096 typedef struct { fixed_t weights[MAX_WEIGHTS]; fixed_t biases[MAX_BIASES]; fixed_t activation_a[MAX_ACTIVATION_SIZE]; fixed_t activation_b[MAX_ACTIVATION_SIZE]; } inference_ctx_t; void infer(inference_ctx_t* ctx, const fixed_t* input, fixed_t* output) { // Ping-pong between activation buffers const fixed_t* current = input; fixed_t* next = ctx->activation_a; for (int layer = 0; layer activation_a) ? ctx->activation_b : ctx->activation_a; } memcpy(output, current, OUTPUT_SIZE * sizeof(fixed_t)); } ``` Two activation buffers suffice for any depth network by alternating between them. The maximum size is the largest layer, not the sum of all layers. ### Convolution Buffers 2D convolution can be implemented with static buffers: ```c void fx_conv2d(const fixed_t* input, int in_h, int in_w, const fixed_t* kernel, int k_h, int k_w, fixed_t* output) { int out_h = in_h - k_h + 1; int out_w = in_w - k_w + 1; // No allocation - all pointers provided by caller for (int oh = 0; oh > 16); } } } ``` The function uses only stack variables (loop counters, accumulator) and caller-provided buffers. Stack usage is O(1), predictable and analysable. ## Verification Benefits Static allocation simplifies verification in several ways. ### Memory Usage Analysis With static allocation, maximum memory usage is computable at compile time: ``` Total RAM = sizeof(inference_ctx_t) + sizeof(input_buffer) + sizeof(output_buffer) + stack_high_water_mark ``` This total can be compared against available RAM with certainty. There is no "usually enough" or "depends on input." Either the memory fits or it doesn't. ### Stack Analysis Static allocation tools can compute precise stack usage for each function and call path. Combined with static buffers, the total memory footprint is fully characterised without running the code. ### No Exhaustion Testing If memory cannot be exhausted at runtime, exhaustion handling does not require testing. This eliminates a class of difficult-to-reach test cases and associated verification evidence. ### Timing Predictability Without malloc's variable search time, timing analysis becomes tractable. Loop bounds are known. Memory access patterns are predictable. WCET can be computed or measured with confidence. ## Trade-offs Static allocation is not without costs. Static Allocation Benefits Compile-time memory analysis No fragmentation No exhaustion during operation Predictable timing Simplified verification Static Allocation Costs Memory sized for worst case Maximum sizes must be known in advance Less flexible data structures May require architectural changes Not suitable for all applications For applications where input sizes vary enormously (text processing, general-purpose computing), static allocation may be impractical. For embedded inference with known model dimensions, the constraints are typically acceptable. ## Implementation Patterns ### Initialisation-Time Allocation Some systems permit allocation during initialisation but not during operation: ```c typedef struct { fixed_t* weights; fixed_t* activations; int initialised; } runtime_ctx_t; int runtime_init(runtime_ctx_t* ctx, const model_config_t* cfg) { // Allocation permitted here ctx->weights = malloc(cfg->weight_bytes); ctx->activations = malloc(cfg->activation_bytes); if (!ctx->weights || !ctx->activations) { free(ctx->weights); free(ctx->activations); return -1; // Initialisation failure is recoverable } ctx->initialised = 1; return 0; } int runtime_infer(runtime_ctx_t* ctx, const fixed_t* in, fixed_t* out) { // No allocation here - operation phase assert(ctx->initialised); // ... inference using pre-allocated buffers ... return 0; } ``` This pattern separates startup (where failure is recoverable) from operation (where allocation failure could be catastrophic). Certification focuses on demonstrating that no allocation occurs after initialisation. ### Compile-Time Configuration For maximum analysability, buffer sizes can be compile-time constants: ```c // config.h - generated from model analysis #define INPUT_SIZE 784 #define HIDDEN_SIZE 256 #define OUTPUT_SIZE 10 #define MAX_ACTIVATION MAX(INPUT_SIZE, MAX(HIDDEN_SIZE, OUTPUT_SIZE)) // inference.c static fixed_t g_activation_a[MAX_ACTIVATION]; static fixed_t g_activation_b[MAX_ACTIVATION]; ``` The sizes are visible in the source. Static analysis tools can compute total memory without execution. Changes to the model require recompilation, but the memory contract is explicit. ## Practical Considerations ### Memory Overhead Static allocation typically uses more memory than dynamic allocation would for the same workload. The overhead is the difference between worst-case and average-case usage. For neural network inference, the overhead is often modest. Layer sizes don't vary at runtime; they're fixed by the model architecture. The "worst case" is every case. ### Code Portability Static allocation patterns require larger buffers to be passed through call chains. This can make APIs more verbose: ```c // Dynamic style - cleaner API image_t* resize(const image_t* src, int new_w, int new_h); // Static style - explicit buffers int resize(const image_t* src, image_t* dst, int new_w, int new_h, uint8_t* scratch, size_t scratch_size); ``` The verbosity is the cost of explicitness. For safety-critical code, explicit memory management is typically preferred despite the syntactic overhead. ### Legacy Integration Existing codebases may assume dynamic allocation. Migration to static allocation can require significant refactoring. For new safety-critical projects, designing for static allocation from the start is substantially easier than retrofitting. ## Implementation Reference The [certifiable-inference](https://github.com/SpeyTech/certifiable-inference) project demonstrates static allocation throughout: - All buffers provided by callers - No malloc after initialisation - Fixed-size structures with compile-time dimensions - O(1) stack usage in all operations The implementation is suitable for environments where dynamic allocation is prohibited and provides a reference for teams designing their own safety-critical inference engines. ## Frequently Asked Questions ### Why is dynamic memory allocation problematic for safety-critical software? Dynamic allocation introduces heap fragmentation, failure modes, and non-deterministic timing that cannot be statically bounded. Safety standards like DO-178C and IEC 62304 require evidence of worst-case resource usage, which dynamic allocation cannot provide without extensive analysis. ### How does static allocation with caller-provided buffers work? The caller allocates all buffers at compile time or program start and passes them to functions as parameters. Functions operate within provided buffers without allocating or freeing memory. This makes memory usage visible, bounded, and analysable at design time — every byte is accounted for before execution begins. ### Why can't memory pools or custom allocators solve the dynamic allocation problem? Memory pools reduce fragmentation but still introduce allocation failure modes and non-deterministic timing when the pool is exhausted or fragmented. Custom allocators add complexity that must itself be verified. Static allocation eliminates the entire category of allocation-related failures rather than mitigating them with additional mechanisms. ### What are the practical constraints of static allocation for neural network inference? All buffer sizes must be known at compile time, requiring upfront analysis of maximum tensor dimensions, intermediate computation sizes, and activation memory. Variable-length inputs require worst-case allocation. Memory usage may be higher than dynamic allocation for variable workloads, but is guaranteed bounded and analysable. ## Conclusion Dynamic memory allocation introduces variability that conflicts with safety-critical certification objectives. Timing varies with heap state. Fragmentation can cause late-life failures. Exhaustion handling creates verification burden. Static allocation eliminates these concerns by moving memory decisions to compile time. The cost is reduced flexibility and potential memory overhead. For applications with known memory requirements, like neural network inference with fixed model dimensions, the trade-off typically favours static allocation. Certification standards increasingly recognise this trade-off. While few explicitly prohibit dynamic allocation, the verification burden it creates pushes safety-critical projects toward static patterns. Understanding why helps engineers make informed architectural decisions early in development, when the cost of change is lowest. As with any architectural approach, suitability depends on system requirements, memory constraints, and regulatory context. Static allocation is not universally appropriate, but for safety-critical AI where certification is required, it offers a verification-friendly foundation. --- *For a working implementation of static allocation patterns for neural network inference, see [certifiable-inference](https://github.com/SpeyTech/certifiable-inference) or try the [live simulator](https://inference.speytech.com/).* --- ## From Proofs to Code: Mathematical Transcription in C **URL**: https://speytech.com/insights/mathematical-proofs-to-code/ **Published**: January 12, 2026 23:25 **Topic**: Formal Methods **Answers**: How do you faithfully translate mathematical proofs and formal specifications into deterministic C implementations using contracts, preconditions, and postconditions as verification anchors, and what systematic methodology prevents semantic divergence and specification drift between the mathematical proof and the resulting code? KEY_CLAIMS: - Software engineers learn early that implementation differs from specification. - Mathematical transcription offers a systematic approach to closing the gap between specification and implementation in safety-critical systems. - Map each mathematical proposition to a precondition or postcondition in the C implementation. - Contracts encode the mathematical properties directly as executable assertions in the source code. - Code review relies on human attention, which degrades with complexity and over time. EVIDENCE: - Standards like DO-178C, ISO 26262, and IEC 62304 all demand evidence that implementations correctly realize their requirements. - DO-178C Level A, for instance, requires that safety requirements be traceable to design and implementation. - For systems requiring DO-178C Level A or similar certification, proof-based transcription provides clear traceability from requirements through verification. - For organizations developing safety-critical software under standards like DO-178C or ISO 26262, proof-based transcription provides a path to the evidence and traceability those standards require. How mathematical contracts become deterministic implementations ## The Gap Between Mathematics and Implementation Software engineers learn early that implementation differs from specification. Requirements written in natural language get interpreted, approximated, and sometimes misunderstood during coding. Even when requirements are precise, the translation to code introduces opportunities for divergence. In safety-critical systems, this gap represents risk. When software controls flight surfaces, medical devices, or autonomous vehicles, the question "does the code match the specification?" isn't academic—it's a certification requirement. Standards like DO-178C, ISO 26262, and IEC 62304 all demand evidence that implementations correctly realize their requirements. One approach to closing this gap is mathematical transcription: the practice of expressing requirements as formal proofs, then translating those proofs mechanically into code. When done properly, the code becomes a direct representation of proven mathematical properties rather than an interpretation of natural language requirements. ## What Mathematical Transcription Is Not Before describing the approach, it helps to clarify what we're not discussing. This is not automated code generation from formal specifications, though such tools exist. Systems like Coq's extraction facility or SPARK's proof-carrying code can generate implementations from high-level specifications. These are powerful approaches, particularly for purely functional code or systems where the target language matches the specification language well. This is also not traditional "design by contract" in the sense Eiffel popularized, where preconditions and postconditions are runtime checks added to existing code. While contracts are central to our approach, we're describing something more fundamental: using mathematical proofs to determine what the code should be, not just how to verify it afterward. What we're describing is a methodology where mathematical analysis precedes and directs implementation. The proof comes first, the struct design follows from the proof, and the code follows from the struct design. Each step is a mechanical translation of the previous one. ## Stage 1: Mathematical Analysis The process begins with a question: what are we trying to accomplish, stated mathematically? Consider a simple monitoring function that should trigger an alert when a value exceeds a threshold. In natural language: "Monitor a value and alert when it crosses the threshold." Simple enough, but this leaves critical questions unanswered: What is the domain of valid values? What happens at boundary conditions? What if the value equals the threshold exactly? What are the timing requirements? Can the value change during evaluation? Mathematical analysis makes these implicit assumptions explicit: ``` Let v ∈ ℕ be the monitored value, where 0 ≤ v value threshold value >= m->threshold) { m->triggered = 1; } /* Postcondition: alert state correctly reflects comparison */ assert((m->value >= m->threshold) == (m->triggered == 1)); } ``` The assertions are not defensive programming—they're the mechanized form of our mathematical requirements. The preconditions ensure inputs satisfy our proof's assumptions. The postcondition verifies the implementation matches the proven logic. The core logic (`if (m->value >= m->threshold)`) is the direct C translation of our mathematical alert condition (v ≥ t). There's no interpretation, no approximation—just transcription. ## Why This Works for Safety-Critical Systems This approach addresses specific challenges in safety-critical software development. ### Verification Tractability When code is a direct transcription of proofs, verification becomes checking transcription accuracy rather than reasoning about complex implementation logic. Reviewers can compare the code against the proof term by term, confirming that each mathematical requirement has a corresponding code representation. This makes manual review more effective and automated verification more tractable. Tools like Frama-C, SPARK, or TLA+ can verify that implementations satisfy their specifications because the gap between specification and implementation is minimal. ### Certification Evidence Safety standards require evidence that implementations correctly realize requirements. When the implementation process is "prove, then transcribe," the mathematical proof itself serves as certification evidence. DO-178C Level A, for instance, requires that safety requirements be traceable to design and implementation. When struct fields trace directly to proof elements, and code traces directly to proof logic, this traceability is inherent rather than documented after the fact. ### Maintenance Clarity Software changes over time. When modifications are needed, the mathematical proof provides the definitive specification of what the code is supposed to do. Engineers making changes can first update the proof to reflect new requirements, then update the struct and code to match. This inverts the typical maintenance process where engineers read existing code, infer its intent, make modifications, and hope they haven't broken invariants. With proof-first development, invariants are explicit and breaking them requires conscious proof modifications. ## Properties Preserved Through Transcription The transcription process is designed to preserve specific properties from proof to implementation: Design Property: Bounds Preservation Type choices in the struct design enforce the bounds defined in the mathematical proof, such that values cannot exist outside their proven domains. By choosing `uint32_t` with explicit bounds checking, we guarantee that values cannot violate the mathematical assumptions. The type system participates in maintaining proof properties. ### Totality Mathematical proofs operate on total functions—functions defined for all inputs in their domain. Partial functions, which are undefined for some inputs, introduce complexity and risk. The transcription process preserves totality by ensuring all code paths are defined. The `if` statement in our example handles both cases: value below threshold (no action) and value at or above threshold (set triggered flag). There are no missing cases, no undefined behavior. ### Determinism Proofs assume deterministic evaluation: given identical inputs, the function produces identical outputs. The transcription preserves this by avoiding sources of nondeterminism. No dependency on system state beyond the monitored struct. No reliance on timing, no global variables, no hidden state. The function is pure: its behavior depends only on its inputs and affects only its outputs. ## Practical Example: State Machine Transitions The approach scales beyond simple monitors to more complex systems. Consider a state machine with proven transition conditions: ``` States: S = {IDLE, ACTIVE, ERROR} Transitions proven valid: IDLE → ACTIVE when condition C1 holds ACTIVE → IDLE when condition C2 holds ACTIVE → ERROR when condition C3 holds ERROR → IDLE when reset() called ``` The struct represents this exactly: ```c typedef enum { STATE_IDLE, STATE_ACTIVE, STATE_ERROR } state_t; typedef struct { state_t current_state; uint32_t tick_count; /* For C1, C2, C3 evaluation */ uint8_t error_detected; /* For C3 */ } fsm_t; ``` And transitions transcribe the proven logic: ```c void fsm_transition(fsm_t* fsm) { assert(fsm != NULL); switch (fsm->current_state) { case STATE_IDLE: if (condition_c1(fsm)) { fsm->current_state = STATE_ACTIVE; } break; case STATE_ACTIVE: if (condition_c3(fsm)) { fsm->current_state = STATE_ERROR; } else if (condition_c2(fsm)) { fsm->current_state = STATE_IDLE; } break; case STATE_ERROR: /* Only reset() can exit ERROR state */ break; } } ``` The code structure mirrors the mathematical transition rules. Each proven transition has exactly one corresponding code path. No transitions occur that weren't proven valid. ## Testing as Proof Validation When code is transcribed from proofs, testing serves a different purpose than in conventional development. Traditional testing explores implementation behavior to find defects. Proof-based testing validates that transcription was performed correctly. Test cases come directly from proof properties: ```c /* Test: boundary condition from proof */ void test_threshold_boundary(void) { monitor_t m = { .value = 100, .threshold = 100, .triggered = 0 }; monitor_check(&m); assert(m.triggered == 1); /* v ≥ t should trigger */ } /* Test: totality - below threshold case */ void test_below_threshold(void) { monitor_t m = { .value = 99, .threshold = 100, .triggered = 0 }; monitor_check(&m); assert(m.triggered == 0); /* v < t should not trigger */ } ``` These aren't arbitrary test cases chosen to exercise code paths. They're mechanized checks of the mathematical properties we proved. If a test fails, either the transcription was incorrect or the proof was incomplete. ## Where Formal Verification Tools Enter Mathematical transcription can proceed without automated tools—it's fundamentally a human activity of careful translation. However, formal verification tools can validate that transcription was performed correctly. Tools like Frama-C with its WP plugin allow expressing the mathematical proof as ACSL annotations, then proving the C implementation satisfies them. The process becomes: 1. Write mathematical proof 2. Design struct from proof 3. Transcribe to C implementation 4. Express proof as ACSL annotations 5. Use WP to verify implementation matches annotations The tool doesn't replace the human insight of creating the proof or designing the struct. It validates that the mechanical transcription step was performed correctly. Similarly, SPARK for Ada provides a framework where the language itself enforces many proof properties through its type system and runtime checks. The transcription process adapts to leverage language capabilities—Ada's strong typing preserves more proof properties automatically than C requires us to enforce manually. ## Real-World Application Patterns Organizations using proof-based transcription typically follow certain patterns: ### Safety Kernels In safety-critical systems, a small "safety kernel" is often proven formally while surrounding functionality uses conventional development. The kernel handles critical functions like mode management, watchdog timing, or health monitoring. These components are small enough that complete mathematical treatment is tractable. The [c-from-scratch educational course](https://github.com/SpeyTech/c-from-scratch) demonstrates this pattern by building a heartbeat monitor using the prove-first methodology. The resulting code is approximately 200 lines, small enough for complete formal treatment. ### Incremental Adoption Rather than requiring all code to follow proof-based transcription, teams often start with the most critical components. A voting algorithm, a critical state machine, or a safety interlock gets the full mathematical treatment. Less critical code uses conventional practices. This allows teams to gain experience with the methodology while limiting the investment. As the approach proves valuable, it expands to additional components. ### Certification-Driven Development For systems requiring DO-178C Level A or similar certification, proof-based transcription provides clear traceability from requirements through verification. Each certification deliverable maps to a specific artifact: requirements become mathematical proofs, design becomes struct definitions, implementation becomes transcribed code, and verification becomes proof validation. ## Limitations and Practical Considerations Mathematical transcription has clear benefits for safety-critical systems, but also limitations. The approach works best for systems where behavior can be characterized mathematically. Control logic, state machines, monitoring functions, and algorithms map well to mathematical specification. Interactions with hardware, timing-dependent behavior, or systems with emergent properties are more challenging. The methodology requires engineers comfortable with mathematical reasoning. Not every programming problem needs proof-first development, and not every engineer finds the approach natural. Organizations adopting this approach must invest in training and accept that some problems resist mathematical characterization. Finally, proof-based transcription doesn't eliminate all defects. The proof might be incorrect, the transcription might introduce errors, or the requirements themselves might be wrong. What it does provide is a systematic approach to reducing the gap between specification and implementation. ## Integration with Deterministic Platforms Proof-based transcription naturally aligns with deterministic execution platforms. When proofs assume deterministic behavior, implementing on platforms that guarantee determinism preserves proof properties through execution. The [Murray Deterministic Computing Platform (MDCP)](/mdcp/) provides execution semantics that match the assumptions common in mathematical proofs: bounded resources, deterministic scheduling, and reproducible behavior. Code transcribed from proofs runs on MDCP with the same properties the proofs assume. This integration matters for certification. When an implementation is proven correct under certain execution assumptions, those assumptions must hold in the deployed system. Deterministic platforms make those assumptions explicit and verifiable. ## Frequently Asked Questions ### How do you translate mathematical proofs into deterministic C code? Map each mathematical proposition to a precondition or postcondition in the C implementation. Each proof step becomes a function with contracts that mirror the mathematical argument. The transcription preserves proof structure: lemmas become helper functions, theorems become top-level functions, and each contract verifies the corresponding mathematical property. ### How do contracts prevent semantic drift between proofs and code? Contracts encode the mathematical properties directly as executable assertions in the source code. If the implementation diverges from the specification, the contract check fails. This creates a continuous verification loop — the code cannot silently drift from its mathematical foundation because the foundation is embedded as enforceable constraints. ### Why can't code review alone prevent divergence between specification and implementation? Code review relies on human attention, which degrades with complexity and over time. Mathematical properties expressed in prose are ambiguous and difficult to verify against code. Machine-checked contracts are precise, exhaustive, and verified on every execution — they catch divergence that human review misses, especially in maintenance and refactoring. ### What are the limitations of mathematical transcription in C? Some mathematical properties cannot be expressed as runtime assertions, including undecidable and infinite-sequence properties. The C type system is less expressive than formal proof systems. Practical transcription focuses on the verifiable subset of mathematical properties. ## Conclusion Mathematical transcription offers a systematic approach to closing the gap between specification and implementation in safety-critical systems. By proving properties first, designing structs to represent those properties, and transcribing the proven logic to code, we create implementations that are traceable to their requirements by construction. The approach is not suitable for all software. It requires mathematical characterization of requirements, engineers comfortable with formal reasoning, and acceptance that upfront proof effort exceeds initial coding time. For systems where certification matters, where errors have severe consequences, or where long-term maintainability justifies upfront investment, the benefits can justify the cost. The key insight is treating implementation as a mechanical process rather than a creative one. Once the mathematics is worked out, the code practically writes itself. What remains is careful transcription and systematic validation that the transcription preserves the proven properties. As with any architectural approach, suitability depends on system requirements, risk classification, and regulatory context. For organizations developing safety-critical software under standards like DO-178C or ISO 26262, proof-based transcription provides a path to the evidence and traceability those standards require. --- ## The Hidden Cost of Non-Determinism **URL**: https://speytech.com/insights/nondeterminism-cost-debugging/ **Published**: January 12, 2026 19:50 **Topic**: Business Case **Answers**: What is the true financial cost of non-deterministic software defects like race conditions, Heisenbugs, and timing-dependent failures, and how does the fundamental inability to reliably reproduce these defects under controlled conditions impact engineering budgets, project schedules, and total ownership cost? KEY_CLAIMS: - Note: The cost estimates and financial figures discussed in this article are indicative based on industry patterns and published research. - The hidden cost of nondeterminism represents a significant but often unmeasured drain on software development economics, particularly in safety-critical domains. - Non-determinism multiplies debugging costs because failures cannot be reliably reproduced, investigated, or confirmed fixed. - Deterministic architecture converts non-reproducible failures into reproducible ones, reducing mean time to diagnosis. - Better testing tools improve detection but do not eliminate the root cause. EVIDENCE: - In aerospace or automotive contexts governed by standards like DO-178C or ISO 26262, nondeterministic behavior creates certification risk. - IEC 62304 Class C medical device software faces similar challenges. - An organization pursuing DO-178C Level A certification might plan for a 24-month certification timeline. - For a mid-sized aerospace supplier with a DO-178C Level A component, each quarter of certification delay might represent opportunity cost in the range of several million in delayed revenue, based on typical product pricing and market dynamics. RELATES_TO: - insights/debugging-economics Understanding the financial impact of debugging race conditions and Heisenbugs Note: The cost estimates and financial figures discussed in this article are indicative based on industry patterns and published research. Actual costs vary significantly depending on organization size, domain, system complexity, and development practices. These figures should not be used as the basis for specific investment decisions without conducting organization-specific analysis. ## The Iceberg Problem Non-deterministic defects consume disproportionate engineering time and budget. A CFO reviewing a software project sees line items for development, testing, and deployment—but not the hidden cost beneath the surface: the weeks lost to race conditions, Heisenbugs, and timing-dependent failures that resist conventional debugging approaches. Nondeterministic bugs, often called Heisenbugs, are defects whose behavior changes or disappears when you attempt to study them. They arise from race conditions, timing dependencies, uninitialized variables, and other sources of execution variability. Unlike deterministic bugs that can be reliably reproduced and fixed, these elusive defects can consume weeks or months of senior engineering time. The financial impact is rarely captured in project accounting. Organizations track "development costs" and "testing costs" but seldom isolate the specific overhead attributable to nondeterministic behavior. Yet this hidden cost can be substantial enough to affect project ROI, market timing, and competitive position. ## Understanding the Cost Structure The economics of nondeterministic debugging differs fundamentally from conventional defect resolution. A typical deterministic bug might follow this pattern: discover the issue, reproduce it reliably, identify the root cause, implement a fix, verify the correction. Total time: hours to days. A nondeterministic defect follows a very different trajectory. ### Investigation Time Multiplication When engineers encounter a Heisenbug, the first challenge is simply determining that they're dealing with nondeterministic behavior rather than environmental factors or user error. This triage phase can consume significant time as teams attempt various reproduction strategies. Once identified as nondeterministic, the debugging process becomes probabilistic. An engineer might spend days attempting to reproduce a race condition that manifests only under specific timing circumstances. Adding logging to understand the issue may alter the timing enough that the bug disappears, a phenomenon that can lead to false confidence that the problem has been resolved. Research on debugging effectiveness suggests that nondeterministic defects can require three to ten times more investigation effort than comparable deterministic issues. This multiplier reflects not just direct debugging time but also the cognitive overhead of reasoning about multiple possible execution paths and the frustration of working with unreliable reproduction. ### Context Switching Overhead Heisenbugs rarely follow a linear debugging path. An engineer begins investigating, hits a reproduction failure, switches to other work, then returns when the bug resurfaces. Each context switch carries cognitive overhead as the engineer re-establishes mental models of the code, the suspected failure mode, and the debugging strategy. In organizations with multiple ongoing projects, nondeterministic issues can pull senior engineers away from planned work repeatedly as bugs resurface in production or testing environments. The opportunity cost of this disruption compounds the direct debugging time cost. ### Verification Challenges Once a fix is implemented for a nondeterministic defect, verification becomes problematic. How do you confirm that a race condition has been eliminated? Running the test suite once and seeing success proves little when the original issue manifested intermittently. Teams often resort to stress testing, running the same scenarios hundreds or thousands of times to gain statistical confidence. This verification burden adds time to the fix-deploy cycle and requires additional infrastructure for reliable stress testing environments. ## Domain-Specific Cost Amplification The financial impact of nondeterministic debugging varies by domain, with safety-critical systems experiencing particularly severe cost amplification. ### Aerospace and Automotive Systems In aerospace or automotive contexts governed by standards like DO-178C or ISO 26262, nondeterministic behavior creates certification risk. A bug that cannot be reliably reproduced is difficult to analyze for safety implications. The investigation must not only identify the root cause but also demonstrate that all related scenarios have been addressed. Certification timelines in these domains can extend by months when nondeterministic issues arise late in development. Given that certification delays typically cost organizations in the range of hundreds of thousands to millions per month in delayed revenue and continued development expenses, even a single stubborn Heisenbug can have substantial financial implications. ### Medical Device Development IEC 62304 Class C medical device software faces similar challenges. Post-market incidents involving nondeterministic behavior can trigger regulatory actions, field corrections, and potential litigation exposure. The cost of a single post-deployment Heisenbug in a medical device context can exceed the entire development budget when you factor in investigation, regulatory response, field updates, and potential liability. ### Financial Trading Systems In high-frequency trading or transaction processing systems, nondeterministic behavior can have immediate P&L impact. A race condition that causes order mispricing or double execution represents both direct financial loss and regulatory exposure. The cost of such issues is measured not in engineering hours but in trading losses and potential regulatory penalties. ## The Certification Timeline Impact One of the least visible but most significant cost impacts of nondeterminism appears in the certification and regulatory approval process for safety-critical systems. Certification bodies require evidence that systems behave correctly under all operational conditions. When nondeterministic behavior is present, collecting this evidence becomes challenging. Test results that vary between runs undermine confidence and can lead to requests for additional testing, architectural changes, or enhanced monitoring. An organization pursuing DO-178C Level A certification might plan for a 24-month certification timeline. If nondeterministic issues emerge during verification and validation, that timeline can extend to 30 or 36 months. The financial impact of this extension includes continued development expenses, delayed market entry, and competitive disadvantage. For a mid-sized aerospace supplier with a DO-178C Level A component, each quarter of certification delay might represent opportunity cost in the range of several million in delayed revenue, based on typical product pricing and market dynamics. This far exceeds the direct cost of the engineering time spent debugging the nondeterministic issues themselves. ## Hidden Costs in Team Productivity Beyond direct debugging time, nondeterministic issues affect team productivity in subtle ways that rarely appear in project accounting. ### Morale and Retention Senior engineers working on Heisenbugs describe the experience as uniquely frustrating. The lack of reliable reproduction makes progress difficult to measure, and the probabilistic nature of verification means that apparent solutions may prove illusory. This frustration affects morale and can contribute to retention challenges in teams working on systems with frequent nondeterministic issues. Recruiting costs for senior embedded engineers or safety-critical developers can range from tens of thousands to over $100,000 per position when you factor in recruiting fees, relocation, and productivity ramp-up time. If nondeterministic debugging contributes to turnover of even one senior engineer per year, the hidden cost becomes significant. ### Technical Debt Accumulation Teams facing pressing nondeterministic issues often take shortcuts. Rather than resolving the root cause, they might add defensive code, implement workarounds, or adjust timing assumptions to reduce symptom frequency. These quick fixes add technical debt that compounds over time. Later refactoring to remove these workarounds and address underlying architectural issues can consume substantial effort. Organizations may carry this technical debt for years, accepting degraded system performance or maintainability because the cost of properly addressing the underlying nondeterminism seems prohibitive. ## Measurement and Visibility Challenges One reason nondeterminism costs remain hidden is the difficulty of measurement. Traditional project accounting captures development phases, feature implementation, and testing cycles. It doesn't distinguish between time spent implementing planned functionality and time spent investigating Heisenbugs. Some organizations attempting to quantify this cost use time-tracking categories that separate "defect investigation" from "development," but this still doesn't capture the full picture. The context switching overhead, opportunity cost of delays, and technical debt accumulation rarely show up in direct cost accounting. ### Establishing Baseline Metrics Organizations serious about understanding nondeterminism costs can establish metrics tracking reproduction time, investigation duration, and verification cycles for different defect categories. Over time, these metrics can reveal patterns showing which system components or architectural approaches correlate with high nondeterminism costs. A simple starting point: track "time to reliable reproduction" for each defect. Issues requiring more than a few hours to reproduce reliably should be flagged for analysis. Patterns in these flags can indicate architectural areas requiring attention. ## Deterministic Architecture as a Cost Mitigation Strategy Deterministic computing platforms address nondeterminism costs by eliminating variability in execution. When a system produces identical results for identical inputs, several cost categories decrease: Investigation time reduces because bugs can be reliably reproduced. An engineer encountering an issue can capture the input conditions and replay the exact execution path to understand what happened. Verification costs decrease because a test that passes once validates the fix comprehensively rather than providing statistical confidence. Teams can verify corrections quickly rather than running stress tests. Certification timelines can be compressed because evidence collection becomes more straightforward. Test logs represent reproducible facts about system behavior rather than samples from a probability distribution. The [debugging economics article](/insights/debugging-economics/) explores the technical mechanisms through which deterministic execution enables faster defect resolution. The financial benefit stems from reducing the investigation time multiplier from potentially 5-10× down to roughly 1-2× relative to comparable deterministic issues. ## ROI Considerations for Architectural Change Adopting deterministic architecture requires upfront investment. Development practices must change, teams need training, and some systems may require refactoring to eliminate sources of nondeterminism. CFOs evaluating such investments should consider both direct costs and opportunity costs. The direct costs are relatively bounded: training expenses, potential tooling changes, and engineering time for architectural modifications. These might range from tens of thousands to hundreds of thousands depending on organization size and system complexity. The opportunity costs can be more significant. If deterministic architecture enables faster certification, earlier market entry, or reduced field support costs, the financial benefit may substantially exceed the direct implementation cost. However, these benefits are inherently uncertain and depend on factors like regulatory environment, competitive dynamics, and product lifecycle. ### Decision Framework Organizations can approach this decision systematically by estimating current nondeterminism costs, projecting potential reduction from deterministic architecture, and comparing against implementation costs: First, analyze historical data on defect resolution time, certification timeline extensions, and field support incidents attributable to nondeterministic behavior. This establishes a baseline cost. Second, project the potential reduction in these costs if investigation time multipliers decrease and certification evidence collection becomes more tractable. Make conservative assumptions about improvement magnitude. Third, estimate the implementation cost including training, architectural changes, and any productivity impact during transition. The comparison provides a basis for evaluating whether the investment makes financial sense in the specific organizational context. ## Risk-Adjusted Perspective The financial analysis of nondeterminism costs should also consider risk scenarios. While most Heisenbugs represent costly debugging time, some can trigger catastrophic outcomes in safety-critical contexts. High-profile incidents in aerospace and automotive domains, while typically involving multiple contributing factors, have sometimes included components where timing-dependent behavior complicated investigation or contributed to failure modes. The financial impact of such incidents extends beyond immediate costs to include regulatory scrutiny, market reputation damage, and potential litigation exposure. From a CFO perspective, investing in deterministic architecture can be viewed partly as risk mitigation. Even if the expected value calculation based on average debugging costs doesn't strongly favor the investment, the tail risk reduction may justify it in domains where system failures carry severe consequences. ## Practical Implementation Path For organizations considering deterministic architecture to address nondeterminism costs, a phased approach can manage both financial risk and implementation complexity. Starting with new safety-critical components rather than retrofitting entire systems limits initial investment while still capturing benefits where they matter most. As teams gain experience and measurement validates the cost reduction, the approach can expand to additional system areas. This incremental strategy allows financial performance to be tracked and investment decisions to be adjusted based on actual results rather than projections. Early wins in certification timeline compression or debugging efficiency can justify broader adoption. The [Murray Deterministic Computing Platform (MDCP)](/mdcp/) demonstrates this approach by providing deterministic kernels that can host critical functions while integrating with existing system architectures. Similarly, [CardioCore](/cardiocore/) shows application in medical device contexts where both certification timeline and post-market risk justify the architectural investment. ## Frequently Asked Questions ### What is the hidden cost of non-determinism in software systems? Non-determinism multiplies debugging costs because failures cannot be reliably reproduced, investigated, or confirmed fixed. Race conditions, timing-dependent bugs, and Heisenbugs consume disproportionate engineering time — often 5–10× more than equivalent deterministic defects — because most effort goes to reproduction rather than root cause analysis. ### How does deterministic architecture reduce total cost of ownership? Deterministic architecture converts non-reproducible failures into reproducible ones, reducing mean time to diagnosis. Test results are reliable on first execution without statistical re-runs. Regression testing confirms fixes definitively. These properties compound over the system lifecycle, reducing long-term maintenance costs significantly. ### Why doesn't investing in better testing tools solve non-determinism costs? Better testing tools improve detection but do not eliminate the root cause. Non-deterministic systems can pass tests through lucky timing and fail in production through unlucky timing. The testing tool cannot make the system behave consistently — only architectural determinism guarantees that test results predict production behaviour. ### What is the practical implementation path toward deterministic architecture? Start by identifying non-deterministic components causing the most debugging time and replace them incrementally. Each step reduces the non-determinism surface and delivers immediate debugging cost savings. ## Conclusion The hidden cost of nondeterminism represents a significant but often unmeasured drain on software development economics, particularly in safety-critical domains. These costs appear in prolonged debugging cycles, extended certification timelines, accumulated technical debt, and opportunity costs from delayed market entry. For CFOs and engineering leadership evaluating architectural investments, understanding these hidden costs provides important context. While deterministic architecture requires upfront investment, the potential for reducing investigation time multipliers, compressing certification timelines, and mitigating field support costs can represent substantial financial benefit. The key is measurement. Organizations that begin tracking reproduction time, investigation duration, and certification delays attributable to nondeterministic behavior can make data-driven decisions about architectural approaches. Those that fail to measure these costs may continue spending far more on Heisenbug investigation than they realize, while missing opportunities for cost reduction through architectural choices. As with any architectural approach, suitability depends on system requirements, risk classification, and regulatory context. The financial case for deterministic architecture strengthens in domains where certification timelines matter, where post-deployment defects carry high costs, and where engineering time is a limiting factor in development velocity. --- ## ISO 26262 and ASIL-D: The Role of Determinism **URL**: https://speytech.com/insights/iso-26262-asil-d-determinism/ **Published**: January 12, 2026 19:20 **Topic**: Certification **Answers**: What does ISO 26262 ASIL-D classification require for automotive functional safety in systems like airbags and braking, and how does deterministic execution architecture specifically support the diagnostic coverage, fault tolerance, and systematic verification requirements at the highest safety integrity level? KEY_CLAIMS: - Note: This article discusses architectural approaches that can support ISO 26262 compliance. - ASIL-D is the highest automotive safety integrity level, requiring 99% or greater diagnostic coverage, hardware fault tolerance, and systematic verification of all safety-critical functions. - Deterministic execution ensures identical behaviour under identical conditions, enabling exhaustive testing of diagnostic coverage claims. - ASIL-D demands evidence that safety mechanisms detect faults with quantified coverage. - Deterministic scheduling imposes overhead compared to fully dynamic approaches. EVIDENCE: - Note: This article discusses architectural approaches that can support ISO 26262 compliance. - ISO 26262 ASIL-D represents the highest automotive safety integrity level. - This variability introduces specific risks during the ISO 26262 certification process. - ISO 26262 determines requirements for validation, verification, and confirmation measures to ensure a sufficient and acceptable level of safety being achieved. How deterministic architecture can support automotive functional safety certification Note: This article discusses architectural approaches that can support ISO 26262 compliance. It does not provide legal, regulatory, or certification advice. Actual certification outcomes depend on system context, implementation details, assessor interpretation, and comprehensive safety analysis. Organizations pursuing certification should work directly with qualified functional safety consultants and certification bodies. ## The ASIL-D Challenge ISO 26262 ASIL-D represents the highest automotive safety integrity level. Systems like airbags, anti-lock brakes, and power steering require ASIL-D classification because their failure risks are potentially fatal. Deterministic execution architecture can simplify compliance with these demanding requirements. ASIL classification is determined through Hazard Analysis and Risk Assessment (HARA), evaluating three factors: Severity of potential injury, Exposure to operational conditions where the hazard could occur, and Controllability by the driver to prevent harm. A combination of the most severe ratings across these factors results in ASIL D classification. The challenge facing automotive safety engineers is straightforward: ASIL D requires the highest level of assurance that dependent safety goals are sufficient and have been achieved. This assurance must be demonstrated through rigorous verification, validation, and evidence generation throughout the development lifecycle. ## Where Nondeterminism Creates Certification Risk Traditional automotive E/E architectures face a fundamental challenge during certification: the behavior of nondeterministic systems can vary between executions, even with identical inputs. This variability introduces specific risks during the ISO 26262 certification process. ### Verification Complexity The standard specifies safety requirements that are more rigorous at higher ASIL levels in order to achieve the required lower likelihood of dangerous failures. When system behavior includes nondeterministic elements such as thread scheduling variations, interrupt timing dependencies, or floating-point optimization differences, verification becomes challenging. Consider a critical safety function that must respond within defined timing bounds. In a nondeterministic system, the actual response time may vary based on scheduler decisions, cache states, or interrupt patterns. Demonstrating that the system meets its timing requirements under all possible execution paths becomes an evidence problem: how do you prove consistent behavior when the system itself doesn't behave consistently? ### Evidence Generation Challenges ISO 26262 determines requirements for validation, verification, and confirmation measures to ensure a sufficient and acceptable level of safety being achieved. These measures depend fundamentally on the ability to collect meaningful evidence about system behavior. In nondeterministic systems, test results may vary between runs. A test that passes in one execution might fail in another, not because the system changed, but because the underlying execution path differed. This phenomenon, known as flaky testing, undermines confidence in the verification process and makes it difficult to demonstrate that safety requirements have been met consistently. ### Post-Incident Analysis Requirements ISO 26262 uses a risk-based approach where hazards are assessed and safety measures are defined to avoid or control systematic failures and to detect or control random hardware failures or mitigate their effects. When an incident occurs during testing or field operation, understanding what happened requires the ability to reconstruct the exact sequence of events. Nondeterministic systems make reconstruction challenging. If you cannot reliably reproduce the conditions that led to a failure, you cannot definitively determine whether the failure resulted from a systematic error in the design or from an environmental factor. This ambiguity creates risk during certification assessments. ## How Deterministic Architecture Can Support Certification Deterministic computing platforms are designed to produce bit-identical results for identical inputs, eliminating execution path variability. This architectural property can support several aspects of the ISO 26262 certification process. Design Property: Execution Reproducibility Under defined conditions, a deterministic system executing the same input sequence produces identical outputs and identical internal state transitions, enabling precise verification of safety requirements. ### Verification Benefits With deterministic execution, verification testing becomes more tractable. A test that validates a safety function's behavior represents not just one execution path, but all execution paths for that input sequence. This property can reduce the verification burden by eliminating the need to account for scheduling variations, cache state differences, and other sources of nondeterministic behavior. For timing analysis, deterministic systems provide clearer bounds. Worst-case execution time analysis becomes more precise when the scheduler behavior is deterministic and when there are no hidden variables affecting execution timing. ### Evidence Quality Deterministic platforms can generate higher-quality evidence for certification assessments. Test logs from deterministic systems represent reproducible facts about system behavior rather than samples from a distribution of possible behaviors. When an assessor reviews verification evidence, deterministic execution provides stronger assurance that the tested behavior matches the deployed behavior. ISO 26262 highly recommends the use of semi-formal modeling languages for ASIL D designs, with executable validation using either prototyping or simulation being mandatory. Deterministic execution supports this requirement by ensuring that simulation results directly correspond to actual system behavior. ### Incident Investigation When issues arise during development or field operation, deterministic systems enable precise reconstruction of events. Given the same initial state and input sequence, the system will traverse the same execution path, allowing engineers to understand exactly what happened and why. This capability supports root cause analysis and helps distinguish between systematic design errors and environmental factors. ## Architectural Considerations for Determinism Supporting ISO 26262 certification through deterministic architecture requires attention to several design elements. ### Deterministic Scheduling The scheduler must make consistent decisions based on defined priority schemes rather than incorporating timing-dependent or random elements. Fixed-priority scheduling with well-defined preemption rules provides predictable behavior that can be analyzed and verified. ### Elimination of Hidden State Sources of nondeterminism such as uninitialized variables, timing-dependent race conditions, or hardware-dependent cache behavior must be addressed at the architectural level. The system should expose all relevant state explicitly so that verification tools can reason about system behavior comprehensively. ### Bounded Execution Paths All system operations should have defined completion bounds. Unbounded loops, unlimited retry mechanisms, or timing-dependent polling introduce variability that complicates verification. Deterministic architectures typically enforce resource bounds that make all execution paths analyzable. ### Formal Verification Support For ASIL D, ISO 26262 highly recommends semi-formal methods. Deterministic systems are more amenable to formal verification techniques because their behavior can be modeled completely. The absence of nondeterministic elements means that model checking and theorem proving tools can provide stronger guarantees about system properties. ## Integration with Safety Mechanisms Deterministic architecture is designed to complement rather than replace traditional safety mechanisms required by ISO 26262. The standard defines requirements for hardware and software safety mechanisms at the system level. Deterministic execution can enhance these mechanisms. For example, watchdog timers become more reliable when system timing is predictable. Redundancy and voting schemes produce more meaningful results when comparing outputs from deterministically-executed functions. Diagnostic routines can detect anomalies more accurately when normal behavior is consistent. The [Murray Deterministic Computing Platform (MDCP)](/mdcp/) demonstrates this integration approach by providing deterministic kernels that can host safety-critical functions while maintaining compatibility with ISO 26262 verification requirements. Similarly, [CardioCore](/cardiocore/) shows how deterministic principles apply to medical device certification under related standards like IEC 62304. ## Real-World Application Patterns Organizations pursuing ASIL D certification while leveraging deterministic architecture typically follow certain patterns: ### Incremental Adoption Rather than requiring full system determinism, teams often start by making safety-critical functions deterministic while accepting nondeterministic behavior in non-safety-critical components. This approach allows them to gain certification benefits where they matter most while managing development complexity. ### Evidence-First Development With deterministic execution enabling precise evidence generation, development processes can emphasize evidence collection from the start. Every test run produces reproducible evidence that can directly support certification documentation. ### Continuous Verification The reproducibility properties of deterministic systems support continuous integration and verification. Automated test suites can run with confidence that passing results represent genuine safety requirement satisfaction rather than fortunate scheduling outcomes. ## Limitations and Trade-offs Deterministic architecture is designed to support certification, not guarantee it. Several considerations remain: The standard evaluates entire systems, not just computation platforms. Even with deterministic execution, factors such as sensor quality, actuator response characteristics, hardware reliability, and system integration all influence certification outcomes. Determinism adds design constraints. Systems must be architected to avoid nondeterministic patterns, which may require different approaches than conventional embedded development. This can affect development timelines and team training requirements. ISO 26262 uses a risk-based approach where assessors evaluate whether implemented measures adequately address identified hazards. Assessor interpretation plays a significant role, and different certification bodies may have varying perspectives on the value of deterministic architecture in meeting standard requirements. ## Frequently Asked Questions ### What does ISO 26262 ASIL-D require for automotive software? ASIL-D is the highest automotive safety integrity level, requiring 99% or greater diagnostic coverage, hardware fault tolerance, and systematic verification of all safety-critical functions. It applies to systems whose failure directly endangers life, such as braking, steering, and airbag deployment. ### How does deterministic execution support ASIL-D diagnostic coverage requirements? Deterministic execution ensures identical behaviour under identical conditions, enabling exhaustive testing of diagnostic coverage claims. When execution timing and outputs are reproducible, every fault detection mechanism can be verified systematically rather than tested probabilistically across timing permutations. ### Why can't probabilistic testing satisfy ASIL-D verification requirements? ASIL-D demands evidence that safety mechanisms detect faults with quantified coverage. Non-deterministic systems require statistical sampling across timing permutations, making exhaustive coverage claims difficult to justify. Deterministic systems reduce the verification space to the set of distinct inputs rather than inputs multiplied by timing variations. ### What are the limitations of deterministic architecture for ASIL-D systems? Deterministic scheduling imposes overhead compared to fully dynamic approaches. Constrained dynamic range from fixed-point arithmetic requires careful budgeting per computation stage. Integration with existing automotive stacks built on conventional RTOS designs may require significant architectural adaptation at the platform level. ## Strategic Perspective For organizations developing ASIL D automotive systems, deterministic architecture represents a design choice that can address specific certification challenges. It does not eliminate the need for rigorous safety engineering, comprehensive hazard analysis, or robust testing practices. Rather, it provides architectural support for these activities by making system behavior more predictable and verifiable. The decision to pursue deterministic architecture should be based on system requirements, development constraints, and certification strategy. Organizations should evaluate whether the verification benefits and evidence quality improvements align with their specific safety goals and regulatory context. As with any architectural approach, suitability depends on system requirements, risk classification, and regulatory context. Teams should work with qualified functional safety consultants to determine whether deterministic architecture supports their certification objectives. --- ## What Docker Actually Guarantees About Consistency **URL**: https://speytech.com/insights/docker-hidden-cost/ **Published**: January 12, 2026 18:30 **Topic**: Systems Architecture **Answers**: What does Docker container technology actually guarantee about runtime environment consistency, what important consistency problems does containerisation fundamentally not solve at the computational level, and why might shipping large container images to avoid inconsistency be addressing the wrong root cause? KEY_CLAIMS: - Update (January 17, 2026): Based on feedback from Jan Tymiński and others, several clarifications have been added to distinguish deployment consistency from execution determinism, and to better acknowledge Docker's orchestration benefits. - Docker solved deployment inconsistency through containment: wrap your application in an environment, and ship the whole thing. - Docker guarantees filesystem and dependency consistency — the same packages, libraries, and configuration files are present in every container instance. - Non-determinism in software comes from computational sources: floating-point platform variance, thread scheduling order, hash map iteration, and memory allocation patterns. - Containers add unnecessary overhead for deterministic applications, resource-constrained devices, certification-required systems, and high-frequency deployments. EVIDENCE: - Update (January 17, 2026): Based on feedback from Jan Tymiński and others, several clarifications have been added to distinguish deployment consistency from execution determinism, and to better acknowledge Docker's orchestration benefits. - A Python web service might ship 450MB: the application code, Python runtime, system libraries, and a Debian or Alpine base image. - Of those 450MB, how much is actually your code? - The Baseline module—a statistical anomaly detector—compiles to a 27KB static binary. Why shipping 450MB to avoid inconsistency may be solving the wrong problem Update (January 17, 2026): Based on feedback from Jan Tymiński and others, several clarifications have been added to distinguish deployment consistency from execution determinism, and to better acknowledge Docker's orchestration benefits. The core thesis remains unchanged. Docker solved a real problem. Before containers, deploying software meant hoping the production environment matched development. Library versions drifted. System configurations diverged. "Works on my machine" became a punchline because it happened constantly. Containers fixed this by shipping everything: application, dependencies, libraries, and a slice of the operating system. If the container works in testing, it works in production, because production receives the same bytes. This is a genuine engineering achievement. It has made deployment dramatically more reliable for millions of applications. But it's worth examining what Docker actually guarantees—and what it doesn't—because the answer reveals a hidden cost that many teams never consider. ## What Docker Guarantees Docker guarantees filesystem consistency. When you build an image, you capture a specific state: these files, with these contents, at these paths. When you run the image, you get that filesystem. The application sees the same libraries, the same configuration files, the same directory structure, regardless of the host. This eliminates an entire class of deployment failures. No more "missing libssl" errors. No more "wrong Python version" surprises. No more configuration drift between staging and production. Docker also provides process isolation. Your container gets its own process namespace, network namespace, and (optionally) resource limits. Other processes on the host cannot interfere with your files or memory. These guarantees are valuable. They are also the full extent of what containers provide at the deployment layer. ## What Docker Does Not Guarantee Docker does not guarantee deterministic execution. The same container, given the same inputs, may produce different outputs on different runs. This is not a bug in Docker—it's a fundamental limitation of what filesystem consistency can achieve. **Important distinction:** Docker solves *deployment* consistency (the application starts in the same state across environments). It does not solve *execution* determinism (the application executes identically given the same inputs). These are different problems at different layers of the stack. A static binary also doesn't guarantee execution determinism unless the code itself is written deterministically. The difference is that Docker solves deployment problems, while deterministic code design solves execution problems. Consider a container running a multi-threaded application. The threads are scheduled by the host kernel, not by Docker. The order of thread execution depends on CPU load, interrupt timing, and scheduler decisions that vary from moment to moment. Two runs of the same container, with the same inputs, may interleave threads differently and produce different results. Consider a container that calls `gettimeofday()` or reads `/dev/urandom`. The values returned depend on the host system's state at the moment of the call. The container filesystem is identical; the execution is not. Consider a container that allocates memory with `malloc()`. The addresses returned depend on the host's memory layout, ASLR settings, and prior allocations. Code that accidentally depends on pointer ordering will behave differently across runs. Docker guarantees that your code will *start* in the same state. It does not guarantee that your code will *execute* the same way or *finish* in the same state. ## The 450MB Question A typical Docker image for a modest application weighs hundreds of megabytes. A Python web service might ship 450MB: the application code, Python runtime, system libraries, and a Debian or Alpine base image. Of those 450MB, how much is actually *your* code? Often, less than one percent. The application itself might be a few hundred kilobytes. The rest is infrastructure: someone else's code, someone else's configuration, someone else's decisions about how to structure a Linux filesystem. This inversion—shipping 16,000 times more code than you wrote—is the hidden cost of the Docker approach. You're not shipping your application. You're shipping an entire operating system environment, frozen at a point in time, because your application cannot be trusted to run consistently without it. This comparison is deliberately rhetorical to highlight the cost difference. In practice: - Optimized containers (multi-stage builds, Alpine/scratch base) can be 10-50MB - Static binaries with realistic dependencies can be 5-20MB - The ratio changes, but the principle remains: Docker packages environment, static binaries eliminate environmental dependencies Both approaches have contexts where they're optimal. The point is not "Docker is bad" but "understand what you're trading." The question is: why can't your application run without this packaging? ## Inconsistency Has a Source Software behaves inconsistently across environments for specific, identifiable reasons: | Source | Docker Helps? | Why? | |--------|---------------|------| | Dynamic linking | ✅ | Ships consistent library versions | | Configuration files | ✅ | Ships consistent config files | | System calls (time, random) | ❌ | Not a deployment problem - needs code changes | | Non-deterministic algorithms | ❌ | Not a deployment problem - needs code changes | | Thread scheduling | ❌ | Kernel-level, outside Docker's scope | **Dynamic linking.** Your code calls functions in shared libraries. Different library versions implement those functions differently. The fix: ship the library (Docker's approach) or eliminate the dependency (static linking). **Configuration files.** Your code reads settings from files that differ between environments. The fix: ship the files (Docker's approach) or embed configuration in the binary. **System calls with environmental dependencies.** Your code asks the operating system for information—time, randomness, process IDs—that varies by host. The fix: there is no filesystem fix. Docker cannot help here—this requires code-level changes. **Non-deterministic algorithms.** Your code uses hash tables with random iteration order, threading with undefined interleaving, or memory allocation with unpredictable addresses. The fix: there is no container fix. The non-determinism is in your code. Docker addresses the first two sources by brute force: ship everything, and the filesystem becomes consistent. But it cannot address the latter three, because they are not filesystem problems. They are execution problems that require different solutions. ## The Deterministic Alternative What if, instead of shipping an environment that tolerates inconsistent code, you wrote code that executes consistently? The [c-from-scratch](https://github.com/SpeyTech/c-from-scratch) project demonstrates this approach. The Baseline module—a statistical anomaly detector—compiles to a 27KB static binary. It has no dynamic library dependencies. It reads no configuration files. It makes no system calls except through a narrow POSIX interface (read, write, basic file operations). This binary produces identical output on: - A developer's MacBook - A Raspberry Pi running Raspbian - An x86 server running RHEL - A CI runner in GitHub Actions - A Docker container (if you really want one) The consistency does not come from shipping a consistent environment. It comes from writing code that does not depend on environmental details. The POSIX interface is the same everywhere. The binary carries its own logic. Given the same input file, it produces the same output file, byte for byte, regardless of where it runs. ## What Determinism Requires Writing deterministic code is not free. It requires discipline in several areas: **Static linking.** Dependencies are compiled into the binary, not resolved at runtime. This increases binary size (though rarely to container scale) and requires recompilation for security updates. The tradeoff: you know exactly what code will execute. **No environmental queries.** The code does not ask "what time is it?" or "give me a random number" unless those values are provided as explicit inputs. This makes testing easier—inputs are controlled—but requires architectural changes if your current design assumes ambient access to time or randomness. **Deterministic algorithms.** Hash tables use stable iteration order. Floating-point operations are ordered consistently. Threading, if present, uses explicit synchronisation that produces the same interleaving on every run. This is the hardest requirement—it touches algorithmic choices throughout the codebase. **Narrow system interface.** The code interacts with the operating system through a minimal, well-defined interface. POSIX provides this: open, read, write, close. The less you ask of the OS, the less can vary between hosts. These requirements are achievable. They are not even unusual in certain domains. Safety-critical systems—avionics, medical devices, automotive controllers—routinely meet them because certification demands reproducible behaviour. The techniques exist; they're simply not applied to most software because most software doesn't need them. ## When Containers Make Sense To be clear: Docker is not wrong. Containers are the right solution for many, perhaps most, deployment scenarios. If your application genuinely requires a complex runtime—Python with specific package versions, Node.js with native extensions, Java with particular JVM flags—containers package that complexity efficiently. The alternative (documenting and reproducing the environment manually) is error-prone and tedious. If your deployment target is heterogeneous—some hosts run Ubuntu, others CentOS, others Amazon Linux—containers provide a common abstraction. Your application sees the same filesystem regardless of the underlying host distribution. If your team lacks control over the deployment environment—you're shipping to customer data centres, or running in a managed platform like Kubernetes—containers are the interface that platform expects. If your application's non-determinism is acceptable—most web services don't need bit-identical reproducibility—then Docker's guarantees are sufficient, and its costs are reasonable. Additionally, container orchestration platforms (Kubernetes, ECS, Cloud Run) provide operational benefits that go beyond deployment consistency: - Automatic scaling and load balancing - Rolling updates and rollbacks - Health checks and self-healing - Service discovery and networking - Resource isolation and multi-tenancy These operational benefits often justify containers even for applications that could run as static binaries. The infrastructure value exceeds the deployment value. ## When Containers Are Overhead But there are cases where containers add cost without adding value: **Deterministic applications.** If your code already produces identical results across environments, the container is packaging megabytes of redundant insurance. A static binary does not need an environmental safety blanket. **Resource-constrained deployments.** Edge devices, embedded systems, and IoT devices often lack the storage and memory for container runtimes. A static binary runs directly; a container requires infrastructure. **Certification-required systems.** Safety-critical domains require evidence of exactly what code executes. A container image contains thousands of packages, each a potential audit target. A static binary contains your code and nothing else. The certification surface area differs by orders of magnitude. **High-frequency deployments.** If you deploy hundreds of times per day, container image transfer becomes a bottleneck. A small binary transfers in milliseconds; a large image takes minutes over slow links. **Debugging production issues.** When a container behaves differently in production than in testing—despite identical images—the problem is non-determinism in your code or environment. The container obscured this; it did not prevent it. ## The Real Question Key Insight The debate is not "containers versus no containers." It's "where does consistency come from?" Docker's answer: consistency comes from packaging. Ship the environment, and the environment will be consistent. The deterministic answer: consistency comes from code. Write code that does not depend on environmental details, and the environment becomes irrelevant. Both approaches work. Both have costs. Docker's cost is visible in image sizes, transfer times, and registry bills. Determinism's cost is invisible in engineering discipline, architectural constraints, and upfront design effort. The question is which cost you'd rather pay—and whether you're paying Docker's cost because you need to, or because you never considered the alternative. ## Shipping a Bet A colleague once described Docker images as "shipping a bet that nothing upstream breaks." The image captures a moment: these library versions work together today. But libraries are maintained by other people, with other priorities, on other timelines. When a CVE arrives for a transitive dependency four layers deep in your container, you rebuild the image—and pray that the new versions still work together. Usually they do. Sometimes they don't, and you spend days debugging incompatibilities that your code did not introduce. The deterministic approach does not eliminate this risk entirely. Static binaries still depend on some system calls, and operating systems still receive updates. But the surface area is radically smaller. You depend on POSIX semantics, not on the internal implementation of libfoo version 2.3.4-ubuntu7. Smaller bets are easier to win. ## Frequently Asked Questions ### What does Docker actually guarantee about runtime consistency? Docker guarantees filesystem and dependency consistency — the same packages, libraries, and configuration files are present in every container instance. Docker does not guarantee computational determinism: floating-point behaviour, thread scheduling, memory layout, and timing still vary across the host hardware running the container. ### Why doesn't Docker solve non-deterministic software behaviour? Non-determinism in software comes from computational sources: floating-point platform variance, thread scheduling order, hash map iteration, and memory allocation patterns. Docker packages the environment but does not control the execution semantics. If the code is non-deterministic on bare metal, it remains non-deterministic inside a container. ### When is a container unnecessary overhead for deployment? Containers add unnecessary overhead for deterministic applications, resource-constrained devices, certification-required systems, and high-frequency deployments. ### What are the trade-offs between Docker images and static binaries? Docker images provide dependency isolation at the cost of size, transfer time, and audit complexity. Static binaries contain only the application code, transfer in milliseconds, and have a minimal certification surface. Docker excels for complex dependency trees; static binaries excel when determinism and auditability are primary requirements. ## Conclusion Docker solved deployment inconsistency through containment: wrap your application in an environment, and ship the whole thing. This works. It has transformed how software is deployed, making reliable delivery accessible to teams that previously struggled with environmental chaos. But containment is not the only solution. Elimination is another. If your code does not depend on environmental details—if the same binary produces the same output on any POSIX system—then the environment does not need to be shipped. The consistency is in the code, not the container. It's worth noting that containers and deterministic code are not mutually exclusive. You can ship a deterministically-designed application in a container to get both deployment consistency AND execution determinism. The question is whether you need the container layer for your specific use case, or whether simpler deployment (static binary, systemd service, etc.) suffices. The 450MB container and the 27KB binary both represent answers to the question "how do we deploy reliably?" One ships everything to avoid thinking about dependencies. The other thinks carefully about dependencies to avoid shipping everything. Neither is universally correct. But if you've only considered the first approach, it may be worth examining the second. The discipline required to write deterministic code pays dividends beyond deployment: testability, debuggability, reproducibility, and certifiability. The hidden cost of consistent environments is the assumption that your code requires them. Sometimes it does. Sometimes—with care and discipline—it doesn't. As with any architectural approach, suitability depends on system requirements, deployment constraints, and team capabilities. But the next time you wait for a large image to transfer, it's worth asking: what, exactly, am I shipping? --- *Thanks to [Jan Tymiński](https://www.linkedin.com/in/jantyminski/) for thoughtful feedback that improved the clarity of this article's distinction between deployment and execution layers.* --- ## The Zero-Variance Problem: When Mathematics Meets Machines **URL**: https://speytech.com/insights/zero-variance-problem/ **Published**: January 11, 2026 22:50 **Topic**: Formal Methods **Answers**: What is the zero-variance problem in statistical monitoring and anomaly detection systems, why does perfect consistency in input data create mathematically undefined division-by-zero failures in standard deviation and z-score calculations, and how should safety-critical systems detect and handle this subtle edge case? **Defines**: Zero-variance problem KEY_CLAIMS: - Note: This article discusses numerical edge cases in statistical monitoring. - The zero-variance problem illustrates a general truth: mathematics describes ideal relationships, while machines compute with finite precision under real-world constraints. - The zero-variance problem occurs when all observed values in a monitoring window are identical, producing a standard deviation of exactly zero. - Detect zero variance explicitly before computing z-scores by checking whether the variance is below a defined epsilon threshold. - Adding epsilon avoids the crash but produces misleadingly large z-scores for any input that differs even trivially from the constant value. EVIDENCE: - A system might flag a 101-millisecond heartbeat (after a run of 100s) as a catastrophic anomaly because (101 - 100) / 0.0001 = 10,000 standard deviations. - For IEEE 754 double-precision floating point, machine epsilon is approximately 2.2 × 10⁻¹⁶. RELATES_TO: - insights/fsm-composition - insights/statistics-as-state-transitions Why perfect consistency creates impossible calculations—and how to handle it Note: This article discusses numerical edge cases in statistical monitoring. Specific implementations require validation appropriate to their deployment context. Every programmer learns to check for division by zero. It's the canonical example of defensive coding—the operation that crashes programs, corrupts calculations, and appears in every introductory textbook. Yet in statistical monitoring systems, this simple edge case manifests in a form that is both mathematically subtle and practically dangerous: the zero-variance problem. The issue arises in anomaly detection. To determine whether an observation is unusual, we often compute how many standard deviations it lies from the mean—the z-score. The formula is elegant: z = (x − μ) / σ. But when variance is zero, standard deviation σ is also zero, and the formula demands division by nothing. This is not a theoretical curiosity. It occurs in real systems, under realistic conditions, with consequences that range from crashed processes to silent failures to incorrect safety decisions. ## When Variance Vanishes Zero variance sounds impossible. Surely real-world data has some variability? But the conditions that produce it are surprisingly common. **Identical observations.** A system that heartbeats every 100 milliseconds with perfect regularity will produce a sequence: 100, 100, 100, 100, 100. The mean is 100. The variance is 0. When the first anomalous value arrives—say, 150 milliseconds—the z-score calculation divides by zero. **Insufficient data.** With a single observation, variance is undefined (or zero, depending on the formula). A monitoring system that has seen only one heartbeat cannot compute meaningful statistics. Yet the second heartbeat will arrive, and the system must respond. **Numerical underflow.** Even when true variance is positive, floating-point arithmetic can produce zero. If observations are very close together relative to machine precision, accumulated rounding errors can collapse variance to exactly 0.0. The mathematics says variance is tiny; the computer says it's nothing. **Clamped or quantised inputs.** Sensors with limited resolution, systems that round to integers, or processes that saturate at limits can produce streams of identical values. A temperature sensor stuck at its maximum reading reports the same value indefinitely. Variance: zero. Each of these scenarios is realistic. Each produces the same computational crisis: a formula that mathematics defines perfectly, but machines cannot evaluate. ## Why It Matters for Safety In ordinary software, division by zero produces an exception, a crash, or a special value like infinity or NaN. The failure is visible. Someone notices. In safety-critical monitoring, the failure modes are worse. Consider an anomaly detector protecting a cardiac rhythm monitor. The detector computes z-scores on inter-beat intervals. During a period of perfect regularity—a healthy, stable rhythm—variance approaches zero. Then an arrhythmia occurs. The interval changes dramatically. The detector should flag this as a severe anomaly. Instead, it divides by zero. What happens next depends on the implementation: - **Crash.** The monitoring process terminates. The patient is unprotected until someone restarts it. - **NaN propagation.** The z-score becomes NaN, which propagates through subsequent calculations. Comparisons with NaN return false. The anomaly is never detected. - **Infinity.** The z-score becomes positive infinity. If the threshold check uses greater-than comparison, infinity exceeds any threshold, triggering a perpetual alarm. If it uses floating-point equality, infinity may not match expected values, causing silent failure. - **Undefined behaviour.** In languages like C, integer division by zero is undefined. The program may do anything—continue with garbage values, crash, or corrupt memory. None of these outcomes is acceptable. The zero-variance problem transforms a period of perfect health—stable, regular operation—into a vulnerability that manifests precisely when anomalies occur. ## The Mathematical Reality The z-score formula assumes a population with positive variance. When variance is zero, every observation equals the mean. In this degenerate case, the concept of "standard deviations from the mean" is meaningless—there is no scale against which to measure deviation. This is not a flaw in the mathematics. It is a boundary condition where the statistical model does not apply. The formula z = (x − μ) / σ is valid when σ > 0. When σ = 0, we are outside the domain of the function. Mathematicians handle this by stating preconditions: "Let σ > 0." Programmers do not have this luxury. The input arrives regardless of whether it satisfies preconditions. The code must respond. ## Three Inadequate Solutions Before examining what works, consider what doesn't. **Assume it won't happen.** This is the most common approach, and the most dangerous. Developers reason that real data always has some variance, so the edge case is theoretical. This assumption holds until it doesn't—typically in production, under load, with consequences. **Add a small epsilon.** Replace σ with σ + ε to avoid exact zero. This creates a different problem: the choice of ε is arbitrary, and small ε values produce enormous z-scores from tiny deviations. A system might flag a 101-millisecond heartbeat (after a run of 100s) as a catastrophic anomaly because (101 - 100) / 0.0001 = 10,000 standard deviations. **Clamp the z-score.** Compute the z-score normally, then clamp results to some maximum value. This hides the symptom without addressing the cause. The z-score of 10,000 becomes 10 (or whatever the clamp), but the underlying numerical instability remains. Different observations produce the same clamped output, losing information. Each of these approaches either ignores the problem or patches it without understanding. They lead to systems that appear to work but fail under specific, reproducible conditions. ## A Principled Solution: Epistemic Honesty The correct approach is epistemic honesty: acknowledge when the calculation is not meaningful, and represent that explicitly in the output. Design Property: Guarded Computation A statistical calculation should return its result only when the computation is valid. When preconditions are not met, it should return a distinct status indicating insufficient information. In practice, this means the z-score function returns two things: a validity flag and a value. The value is meaningful only when the flag indicates success. ```c typedef struct { bool valid; double z; } zscore_result_t; zscore_result_t compute_zscore(double x, double mu, double variance) { zscore_result_t result; if (variance threshold → STABLE (if z-score normal) - variance > threshold → DEVIATION (if z-score abnormal) - variance ≤ threshold → LEARNING (stay, insufficient data) STABLE: - z-score exceeds threshold → DEVIATION - variance drops to zero → LEARNING (revert, lost statistical basis) DEVIATION: - z-score returns to normal → STABLE - variance drops to zero → LEARNING (revert) ``` The transition "variance drops to zero → LEARNING" handles the case where a previously variable signal becomes constant. The system does not crash or produce garbage; it acknowledges that it has lost the ability to make statistical judgments and reverts to learning mode. This is a total function in the technical sense: every input has a defined response. The zero-variance case is not an exception to be caught but a state to be handled. ## The EPSILON Question The guard condition uses `variance EPSILON) INV-ZV3: (variance drops below EPSILON) → (next_state == LEARNING) ``` These invariants can be verified through contract tests and fuzz testing. The c-from-scratch Baseline module includes tests that specifically target the zero-variance boundary: - Sequences of identical values - Sequences where variance decreases to zero over time - Sequences that alternate between zero and non-zero variance - Boundary cases at exactly EPSILON Fuzz testing with random sequences confirms that the invariants hold regardless of input patterns. The system never divides by zero, never produces NaN, and never crashes—because the edge case is handled by design, not by accident. ## Beyond Z-Scores The zero-variance problem is an instance of a broader pattern: mathematical formulas that are undefined at boundary conditions. Other examples in monitoring systems include: - **Logarithms of zero or negative values** — log-based metrics fail when the input is non-positive - **Ratios with zero denominators** — efficiency metrics, rates, and percentages all divide - **Inverse operations at singularities** — matrix inversion fails for singular matrices The solution pattern is the same: guard the computation, return validity information, and design the state machine to handle the "insufficient data" case explicitly. This is not defensive programming in the sense of catching errors; it is honest programming in the sense of representing what the computation can and cannot tell us. ## Frequently Asked Questions ### What is the zero-variance problem in statistical monitoring? The zero-variance problem occurs when all observed values in a monitoring window are identical, producing a standard deviation of exactly zero. Any z-score calculation then divides by zero, creating an undefined result that crashes or produces garbage output in anomaly detection systems that lack explicit guards. ### How should safety-critical systems handle zero variance? Detect zero variance explicitly before computing z-scores by checking whether the variance is below a defined epsilon threshold. When variance is zero, the system should enter a distinct state — such as CONSTANT — rather than attempting division. This state indicates that the input is stable but anomaly detection is mathematically undefined. ### Why doesn't adding a small epsilon to the denominator properly solve zero variance? Adding epsilon avoids the crash but produces misleadingly large z-scores for any input that differs even trivially from the constant value. A genuine anomaly and a negligible measurement fluctuation receive similar extreme z-scores, undermining the statistical validity of the detection. Explicit state handling is the correct architectural response. ### What are the compositional implications of zero variance in state machines? When a heartbeat monitor feeds inter-arrival times to a baseline monitor, zero variance in heartbeat timing means the baseline monitor cannot compute meaningful anomaly scores. The composition must propagate the zero-variance state explicitly — the downstream monitor must know that its upstream is in a CONSTANT state, not simply receiving unusually stable data. ## Conclusion The zero-variance problem illustrates a general truth: mathematics describes ideal relationships, while machines compute with finite precision under real-world constraints. The gap between mathematical elegance and computational reality is where bugs live. The z-score formula z = (x − μ) / σ is mathematically perfect. It is also computationally incomplete—it does not specify behaviour when σ = 0. That specification is the programmer's responsibility. The principled solution is not to avoid the edge case or to patch it with arbitrary constants. It is to acknowledge it explicitly: when variance is insufficient, the z-score cannot be computed, and this fact should be represented in the output. State machines that consume this output should have explicit states for "insufficient information" and transitions that handle the boundary. This approach aligns with the broader philosophy of the [c-from-scratch](https://github.com/SpeyTech/c-from-scratch) project: make the mathematics explicit, handle all cases, and let the code reflect what we actually know. When we know nothing—when variance is zero—the code should say so. As with any architectural approach, suitability depends on system requirements, risk classification, and numerical context. But for safety-critical monitoring where silent failures are unacceptable, epistemic honesty is not optional. The zero-variance problem is not an edge case to be dismissed; it is a boundary condition to be respected. --- ## Composition Without Compromise: Connecting FSMs **URL**: https://speytech.com/insights/fsm-composition/ **Published**: January 11, 2026 22:22 **Topic**: Formal Methods **Answers**: How do you compose multiple individually verified finite state machines into a larger system that is also verified, without losing the correctness guarantees that each component satisfies in isolation, and what specific composition patterns preserve safety invariants across component interaction boundaries? **Defines**: FSM composition KEY_CLAIMS: - Note: This article discusses architectural patterns for composing finite state machines. - The composition problem is real: connecting verified components does not automatically yield a verified system. - Define a mapping table that maps the product of component states to composed system states, deliberately collapsing the full product space into meaningful distinctions. - Composition maps the product space to a smaller set of meaningful system states. - Component testing verifies individual behaviour but not interaction effects. EVIDENCE: - Standards like IEC 62304 and DO-178C emphasise modular design, traceability, and verification evidence. RELATES_TO: - insights/cryptographic-proof-execution - insights/heartbeats-state-machines - insights/iec-62304-class-c - insights/statistics-as-state-transitions - insights/zero-variance-problem How verified components combine to create verified systems Note: This article discusses architectural patterns for composing finite state machines. While these principles inform safety-critical design, specific implementations require verification appropriate to their regulatory context. The promise of modular software is straightforward: build small, verified components, then combine them into larger systems. The reality is often disappointing. Components that work correctly in isolation interact in unexpected ways. Properties that held individually disappear when modules connect. The system becomes less than the sum of its parts. This failure mode is not inevitable. When components are designed with composition in mind—when their properties are structural rather than incidental—the resulting systems can inherit guarantees from their constituent parts. The key lies in understanding what makes composition safe. ## The Composition Problem Consider two well-tested modules: a heartbeat detector that tracks whether a system is alive, and a statistical baseline that monitors for timing anomalies. Each works correctly in isolation. Each has passing tests and verified invariants. Now connect them. The heartbeat detector outputs inter-arrival times; the baseline detector consumes them. What properties does the combination have? The honest answer, for most software, is "unclear." The modules were designed independently. Their interaction creates a new system with emergent behaviour that neither module anticipated. Edge cases multiply. Timing dependencies appear. The composition may work, but you cannot know without testing every possible interaction—a combinatorial impossibility. This uncertainty is the composition problem: connecting verified components does not automatically yield a verified system. ## Why Most Composition Fails The composition problem has deep roots. Most software modules are designed for convenience rather than composability. They carry implicit assumptions about their environment: that inputs will arrive in certain orders, that global state will be initialised, that timing constraints will be met. These assumptions work when a human orchestrates the modules carefully. They fail when modules are combined mechanically. Consider a module that caches its last result for efficiency. In isolation, this optimisation is invisible—the module returns correct outputs. But when composed with another module that expects fresh computation on every call, the cached values create subtle errors. The caching assumption (that results can be reused) conflicts with the freshness assumption (that each call triggers new computation). Neither module is wrong; their assumptions are simply incompatible. More formally, the problem is that modules have hidden state and hidden dependencies. They reach outside their defined interfaces to touch shared resources, timing mechanisms, or implicit contracts. These hidden channels create coupling that composition cannot see and therefore cannot verify. ## Three Properties That Enable Safe Composition The [c-from-scratch](https://github.com/SpeyTech/c-from-scratch) project takes a different approach. Every module is designed from the start with three properties that, together, enable composition without compromise. Design Property: Closure A module is closed if it depends only on its explicit inputs and internal state. No global variables. No hidden channels. No ambient dependencies. Closure eliminates hidden coupling. A closed module can be reasoned about in isolation because there is nothing outside its interface that affects its behaviour. What you pass in, and what it contains, is all there is. Design Property: Totality A module is total if it handles every possible input. No undefined behaviour. No assumptions about what inputs are "valid." Every state and every input has a defined response. Totality eliminates edge-case failures. A total module cannot be surprised by unexpected inputs because it has a response to everything. When modules are composed, the output of one becomes the input of another—and that input is handled, regardless of what it contains. Design Property: Determinism A module is deterministic if the same state and input always produce the same next state and output. No randomness. No timing dependencies. No non-determinism. Determinism eliminates interaction surprises. When you compose deterministic modules, the composite is also deterministic. The same sequence of inputs will always produce the same sequence of outputs, making the system testable and reproducible. These three properties are not optional features. They are the mathematical requirements for composition that preserves guarantees. ## A Concrete Example: The Timing Health Monitor The c-from-scratch course builds toward a composed system: the Timing Health Monitor. It combines two FSMs—Pulse (for heartbeat detection) and Baseline (for anomaly detection)—into a single system that answers: "Is this process alive and behaving normally?" ### The Pulse Component The Pulse FSM tracks liveness using three states (as explored in [Heartbeats and State Machines](/insights/heartbeats-state-machines/)): ``` Pulse States: { UNKNOWN, ALIVE, DEAD } Pulse Inputs: { BEAT, TIMEOUT } ``` When a heartbeat arrives, Pulse transitions toward ALIVE. When too much time passes without a beat, Pulse transitions toward DEAD. The module outputs inter-arrival times (Δt) between consecutive heartbeats—this becomes the input to the next module. ### The Baseline Component The Baseline FSM monitors those inter-arrival times using exponential moving averages (see [Statistics as State Transitions](/insights/statistics-as-state-transitions/)): ``` Baseline States: { LEARNING, STABLE, DEVIATION } Baseline Inputs: { Δt (timing value) } ``` During the LEARNING phase, Baseline accumulates statistics. Once sufficient data exists, it transitions to STABLE. If subsequent values deviate significantly from the established baseline, it transitions to DEVIATION. ### The Composition The composed Timing Health Monitor has four states: ``` Timing States: { INITIALIZING, HEALTHY, UNHEALTHY, DEAD } ``` The mapping from component states to composed state is a pure function: | Pulse | Baseline | → Timing | |-------|----------|----------| | DEAD | (any) | DEAD | | UNKNOWN | (any) | INITIALIZING | | ALIVE | LEARNING | INITIALIZING | | ALIVE | STABLE | HEALTHY | | ALIVE | DEVIATION | UNHEALTHY | This mapping has important properties. DEAD is absorbing—once the heartbeat is lost, nothing else matters. HEALTHY requires both existence evidence (ALIVE) and statistical evidence (STABLE). The composed state reflects a conjunction of component knowledge. ## Why This Composition Works The composition works because both Pulse and Baseline satisfy closure, totality, and determinism. Let's trace why. **Closure is preserved** because the composed system's state is simply the pair of component states. There is no additional hidden state, no global variables, no ambient dependencies. The composition function (the mapping table) is itself closed—it depends only on its inputs. **Totality is preserved** because the mapping table is complete. Every possible combination of Pulse state and Baseline state has a defined Timing state. When Pulse produces an unexpected state, the composition handles it. When Baseline produces an unexpected state, the composition handles it. The domain is the Cartesian product of component domains, and every element of that product has a defined output. **Determinism is preserved** because the composition function is deterministic and both components are deterministic. Given the same component states, the mapping always produces the same composed state. Given the same inputs to each component, they always produce the same next states. Therefore, given the same initial state and input sequence, the composed system always produces the same final state. This is not an accident. It is the direct consequence of designing components with these properties from the start. ## The Composition Function At each step, the composed system executes a straightforward algorithm: ``` timing_step(state, event, timestamp): 1. Compute Δt if we have a previous heartbeat 2. Feed event/timestamp to Pulse → Pulse updates its state → Pulse produces ALIVE/DEAD/UNKNOWN 3. If Δt is available, feed to Baseline → Baseline updates its statistics → Baseline produces LEARNING/STABLE/DEVIATION 4. Map component states to composed state → Apply the mapping table → Return INITIALIZING/HEALTHY/UNHEALTHY/DEAD ``` The order matters: data flows from event through Pulse (which produces Δt) through Baseline (which consumes Δt) to the final state. This order is determined by the data dependencies, not arbitrary convention. ## What Composition Buys You When composition preserves properties, several engineering benefits follow. **Component-level verification transfers to the system.** The invariants tested on Pulse and Baseline individually continue to hold in the composed system. If Pulse has an invariant "DEAD state is entered only after ALIVE was observed," that invariant holds in the composition. You verify components once; the verification extends. **Debugging becomes tractable.** When the composed system misbehaves, you can trace the failure to a specific component. Was the timing anomaly due to Pulse misclassifying a timeout, or Baseline miscalculating the z-score? The closed boundaries between components let you isolate faults. **System behaviour is reproducible.** Given an initial state and an input sequence, you can replay the exact behaviour. This supports post-incident analysis, regression testing, and certification evidence. See [Cryptographic Execution Tracing](/insights/cryptographic-proof-execution/) for how this property enables audit trails. **Complexity remains manageable.** The composed system has 4 states, not 3 × 3 = 9. The mapping table deliberately collapses the product space into meaningful distinctions. You reason about HEALTHY or UNHEALTHY, not about the twelve possible state combinations. ## The Algebra of Composition There is a deeper structure here. Closed, total, deterministic FSMs form a category in the mathematical sense. The objects are FSMs; the morphisms are well-typed connections between them. Composition is associative: (A ∘ B) ∘ C = A ∘ (B ∘ C). There is an identity FSM that passes inputs unchanged. This algebraic structure means you can compose arbitrarily. Build Pulse and Baseline into Timing. Compose Timing with another FSM that handles recovery. Compose that with an FSM that manages logging. At each stage, the properties are preserved, and the composed system remains closed, total, and deterministic. This is why the title says "without compromise." You do not sacrifice verification for modularity or modularity for verification. The properties are additive, not contradictory. ## Practical Implementation The c-from-scratch course implements this composition in pure C, following the [Math → Structs → Code methodology](/insights/statistics-as-state-transitions/). The composed structure contains the component structures: ```c typedef struct { pulse_t pulse; baseline_t baseline; timing_state_t state; } timing_t; ``` The step function implements the algorithm described above, with explicit error handling for edge cases like division by zero (see [The Zero-Variance Problem](/insights/zero-variance-problem/) for why this matters). Every function maintains the three properties: - All inputs come through parameters; all outputs go through returns or output pointers - Every input combination is handled, including invalid inputs - Given the same state and input, the same output is produced Contract tests verify these properties, not just happy-path behaviour. Fuzz testing with random input sequences confirms the invariants hold under conditions the developer did not imagine. ## Implications for Safety-Critical Systems This compositional approach aligns with regulatory requirements for safety-critical software. Standards like [IEC 62304](/insights/iec-62304-class-c/) and DO-178C emphasise modular design, traceability, and verification evidence. A system composed of verified components, with a verified composition, provides exactly the evidence these standards require. The [CardioCore](/cardiocore/) kernel applies these principles to cardiac rhythm monitoring. The [MDCP](/mdcp/) platform extends them to multi-core determinism. In both cases, the mathematical foundation—closed, total, deterministic FSMs that compose safely—is what enables certification-ready designs. ## Frequently Asked Questions ### How do you compose multiple verified finite state machines into a larger system? Define a mapping table that maps the product of component states to composed system states, deliberately collapsing the full product space into meaningful distinctions. Component invariants transfer to the composition — properties verified on individual FSMs hold in the composed system without re-verification. ### How does FSM composition reduce system state complexity? Composition maps the product space to a smaller set of meaningful system states. Two three-state components produce a 3×3 = 9 state product, but the composition table maps these to four meaningful states (HEALTHY, DEGRADED, CRITICAL, FAILED). Engineers reason about four states, not nine combinations. ### Why doesn't independent testing of FSM components guarantee correct composition? Component testing verifies individual behaviour but not interaction effects. Composition requires explicit mapping between component state combinations and system-level states. Without a defined mapping table, ambiguous state combinations produce undefined system behaviour. The mapping table is itself a specification that must be verified. ### What are the trade-offs of FSM composition for safety-critical systems? Composition preserves component verification at the cost of design-time effort to define and verify the mapping table. The mapping must cover all state combinations including transient states during transitions. For systems with many components, the product space grows multiplicatively, requiring careful state collapsing to keep the composed system tractable. ## Conclusion The composition problem is real: connecting verified components does not automatically yield a verified system. But it is solvable, when components are designed with composition in mind. The key is structural: modules must be closed (no hidden dependencies), total (handle all inputs), and deterministic (same inputs produce same outputs). When components satisfy these properties, their composition inherits them. Verification extends from parts to whole. This is not a theoretical nicety. It is a practical requirement for systems that must be trusted. When a pacemaker monitors cardiac rhythm, or an autonomous vehicle tracks its environment, or a satellite maintains its attitude, the composed system must work correctly—not just its individual pieces. The [c-from-scratch](https://github.com/SpeyTech/c-from-scratch) project teaches this approach from first principles: define the mathematics, transcribe to data structures, implement the step function, verify with contracts. The Timing Health Monitor is a concrete example of composition done right. As with any architectural approach, suitability depends on system requirements, risk classification, and regulatory context. But for systems where correctness matters—where "probably works" is insufficient—composition without compromise is not optional. It is the engineering discipline that makes verification tractable. --- ## Why Your ML Model Gives Different Results Every Tuesday **URL**: https://speytech.com/insights/ml-nondeterminism-problem/ **Published**: January 09, 2026 21:20 **Topic**: Deterministic Computing **Answers**: What are the hidden sources of non-determinism in machine learning training and inference pipelines that cause models to produce different numerical results across runs, and why do floating-point accumulation order, thread scheduling, hash map iteration, and memory allocation patterns affect reproducibility? KEY_CLAIMS: - Floating-point accumulation order, thread scheduling in parallel reductions, hash map iteration order, memory allocation patterns, and random seed management all introduce non-determinism. - Certification requires proving that the deployed model matches the tested model. - Random seeds control explicit randomness but do not address implicit non-determinism from floating-point ordering and thread scheduling. - Every computation must use fixed-point arithmetic, deterministic data ordering, sequential reductions, and static memory allocation. EVIDENCE: - This is the reality of machine learning in 2026. - Certification Requirements DO-178C (aerospace software) requires traceability from requirements to code to test evidence. - IEC 62304 (medical device software) requires documented software development processes. - ISO 26262 (automotive functional safety) requires systematic approaches to avoid unreasonable risk. The hidden sources of non-determinism in machine learning, and why they matter more than you think You train a model on Monday. Validation accuracy: 94.2%. Satisfied, you go home. Tuesday morning, a colleague re-runs the same training script, same data, same hyperparameters. Validation accuracy: 93.8%. "That's within normal variance," everyone agrees. You deploy Monday's model. Six months later, during an audit, someone asks: "Can you reproduce this model?" You run the original script. Validation accuracy: 94.1%. Close, but the weights are different. The predictions on edge cases are different. The model you're auditing isn't the model you deployed. This isn't a story about sloppy engineering. This is the reality of machine learning in 2026. And for safety-critical applications—autonomous vehicles, medical devices, aerospace systems—it's becoming a serious problem. ## The Myth of Random Seeds The standard advice is simple: "Set your random seed for reproducibility." ```python import torch torch.manual_seed(42) np.random.seed(42) random.seed(42) ``` This creates a comforting illusion. The same seed should produce the same sequence of "random" numbers, which should produce the same weight initialisation, the same batch ordering, the same dropout masks—and therefore the same trained model. Except it doesn't. Setting the seed is necessary but nowhere near sufficient. There are at least seven sources of non-determinism that seeds don't control, and most ML practitioners encounter them without realising it. ## Source 1: Floating-Point Ordering Consider a simple sum: `a + b + c + d` In exact arithmetic, the order doesn't matter. In floating-point arithmetic, it absolutely does: ``` (a + b) + (c + d) ≠ ((a + c) + b) + d ``` The differences are tiny—perhaps the 15th decimal place. But neural networks perform billions of these operations during training. Tiny errors accumulate. By the end of training, weights can differ meaningfully. Modern GPUs make this worse. To maximise throughput, they process operations in parallel and accumulate results in non-deterministic order. The same operation on the same GPU can produce different results on different runs—not because of randomness, but because of scheduling variations at the microsecond level. ## Source 2: GPU Non-Determinism NVIDIA's cuDNN library—the backbone of deep learning on GPUs—uses algorithms that are non-deterministic by default. Operations like convolution and pooling have multiple valid implementation strategies. cuDNN selects between them based on runtime profiling, cache state, and GPU occupancy. You can force deterministic mode: ```python torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False ``` But this comes with a 10-30% performance penalty. Most teams disable it for training speed, accepting non-reproducibility as the cost. ## Source 3: Data Loading Parallelism Modern training pipelines load data in parallel: ```python DataLoader(dataset, num_workers=8, shuffle=True) ``` With multiple workers, the order in which batches arrive depends on operating system scheduling, disk I/O timing, and CPU load. The shuffle happens correctly, but the precise sequence of batches varies between runs. "But I set shuffle=True with a seed!" Yes, and the shuffle itself is reproducible. But which worker finishes first? That's determined by factors outside your control. ## Source 4: Batch Normalisation Statistics Batch normalisation layers compute running statistics during training: ``` running_mean = momentum * running_mean + (1 - momentum) * batch_mean ``` These statistics depend on the exact sequence of batches seen. If batch ordering varies (Source 3), running statistics vary. At inference time, the model behaves differently because its normalisation parameters are different. ## Source 5: Dropout and Stochastic Layers Dropout masks are generated from the random state. If anything perturbs that state—a different batch order, a parallel data loading race, even a print statement that triggers formatting code using random numbers—the dropout masks change. The same applies to any stochastic layer: variational layers, noise injection, stochastic depth. Each is a potential divergence point. ## Source 6: Hardware Differences Train on an A100 GPU. Deploy on a T4. Even with deterministic flags enabled, different GPU architectures have different floating-point implementations. Results will differ. Train on GPU. Run inference on CPU. The differences can be even larger—different instruction sets, different SIMD widths, different handling of denormals. "But the differences are tiny!" Yes. And "tiny" can mean a different classification on edge cases. In medical imaging, an edge case might be a tumour. ## Source 7: Library Versions PyTorch 2.0 changed the default random number generator algorithm. Models trained with PyTorch 1.x cannot be exactly reproduced with PyTorch 2.x—even with identical seeds. The "same" seed produces different numbers. cuDNN updates routinely change which algorithms are selected. CUDA versions affect floating-point behaviour. Even NumPy has changed its random number generation across versions. The model you trained 18 months ago, with pinned library versions? Good luck recreating that environment exactly. ## Why This Matters Now For research and commercial ML, non-reproducibility is an inconvenience. You run experiments multiple times and report averages. You accept some variance in production model quality. For safety-critical applications, non-reproducibility is a fundamental obstacle. **Certification Requirements** DO-178C (aerospace software) requires traceability from requirements to code to test evidence. If the same training process produces different models, which model are you certifying? Can you prove that the deployed model is the one you tested? IEC 62304 (medical device software) requires documented software development processes. If training is non-deterministic, how do you document what the process produced? How do you respond when a regulator asks to reproduce a result? ISO 26262 (automotive functional safety) requires systematic approaches to avoid unreasonable risk. How do you argue that your ML component is safe if you cannot reproduce its development? **The EU AI Act** The EU AI Act, coming into force progressively through 2025-2027, mandates technical documentation demonstrating how AI systems were developed. High-risk systems—including those in medical devices, vehicles, and critical infrastructure—require particularly rigorous documentation. Article 11 requires documentation of "the design specifications of the system, in particular the general logic of the AI system and of the algorithms." Article 12 requires "automatic recording of events" enabling tracing of the system's operation. Non-deterministic training makes both requirements difficult to satisfy. How do you document the logic of a model whose weights depend on GPU scheduling? How do you trace operation when you cannot reproduce the artefact? **Audit and Liability** When an autonomous vehicle causes an accident, lawyers will ask: "Show us the exact model that made this decision, and prove how it was trained." When a diagnostic AI misses a cancer, regulators will ask: "Reproduce the training process and show us that the deployed model matches your validation results." If you cannot reproduce training exactly, you cannot answer these questions definitively. You're left arguing that the model was "probably similar" to what you tested. That's not a strong legal position. ## The Gap The machine learning community has made extraordinary progress on model architectures, training techniques, and deployment infrastructure. Reproducibility has received comparatively little attention. This creates a gap: ML capabilities are racing ahead, while ML auditability remains stuck. The models get more powerful; the ability to certify them does not keep pace. For non-safety applications, this gap is acceptable. For safety-critical applications, it's becoming a blocker. Companies are building increasingly capable AI systems that they cannot certify for deployment in regulated environments. The question is not whether deterministic ML is desirable. It obviously is. The question is whether it's achievable. ## The Path Forward Every source of non-determinism listed above has a solution. The solutions are not trivial, but they exist. Floating-point ordering can be controlled through careful algorithm design—fixed accumulation orders, Kahan summation, or integer-based computation for critical paths. GPU non-determinism can be eliminated by avoiding non-deterministic operations or implementing deterministic alternatives. Data loading parallelism can be made deterministic through careful synchronisation and pre-computed batch orderings. Batch normalisation can use deterministic running statistics or be replaced with alternatives like layer normalisation. Dropout can use pre-computed masks derived from cryptographic hash functions rather than stateful random number generators. Hardware differences can be minimised through fixed-point arithmetic or careful floating-point discipline. Library dependencies can be controlled through rigorous environment management and, ultimately, through purpose-built frameworks that don't share codepaths with non-deterministic implementations. None of this is easy. All of it is possible. The result is ML training where: - Same data + same seed = identical model - Every weight is traceable to its initialisation and training history - Training can be replayed for audit or debugging - Certification evidence is reproducible This is what deterministic machine learning looks like. Not "mostly reproducible." Not "reproducible within tolerance." Bit-for-bit identical, on any hardware, years later. ## Implications If deterministic ML is achievable, several implications follow: **Certification becomes tractable.** You can train a model, validate it, and certify the specific artefact you validated. Reproduce it for audit. Demonstrate compliance with documentation requirements. **Debugging becomes possible.** When a model misbehaves, you can replay training to the exact step where problematic behaviour emerged. Step through the learning process. Identify causal factors. **Liability becomes manageable.** You can prove what model was deployed. Reproduce its development. Answer regulatory questions definitively rather than probabilistically. **Development becomes faster.** No more "run it five times to see if the result is real." Train once, evaluate once, trust the result. The safety-critical AI market is constrained not by model capability but by certification capability. Deterministic ML removes that constraint. ## Frequently Asked Questions ### What are the hidden sources of non-determinism in ML pipelines? Floating-point accumulation order, thread scheduling in parallel reductions, hash map iteration order, memory allocation patterns, and random seed management all introduce non-determinism. Any one of these causes different numerical results across runs, and standard ML frameworks contain all of them simultaneously. ### How does non-determinism prevent ML model certification? Certification requires proving that the deployed model matches the tested model. If training produces different weights each run, the certified artefact cannot be reproduced for audit. If inference produces different outputs for identical inputs, the behaviour tested during validation does not represent production behaviour. Certification requires reproducibility. ### Why can't setting random seeds make ML pipelines fully deterministic? Random seeds control explicit randomness but do not address implicit non-determinism from floating-point ordering and thread scheduling. These implicit sources persist even with fixed seeds across all explicit random operations. ### What does a fully deterministic ML pipeline require? Every computation must use fixed-point arithmetic, deterministic data ordering, sequential reductions, and static memory allocation. The entire pipeline — data through training through inference — must be free of platform-dependent behaviour. ## The Question This article has described a problem. Solutions exist. The technology to build deterministic ML frameworks is available today. The question for anyone building AI for safety-critical applications: how much longer can you afford to deploy systems you cannot reproduce? --- *SpeyTech develops deterministic computing infrastructure for safety-critical systems. Our deterministic ML and RL frameworks achieve bit-perfect reproducibility across hardware platforms. Patents GB2521625.0 and GB2522369.4. For technical discussions, contact william@fstopify.com.* --- ## Closure, Totality, and the Algebra of Safe Systems **URL**: https://speytech.com/insights/closure-totality-algebra/ **Published**: January 08, 2026 21:20 **Topic**: Formal Methods **Answers**: What are the mathematical properties of closure, totality, and algebraic composition in the context of safety-critical software design, and how do these three properties determine whether a system fails safely with a controlled shutdown or fails silently with an undetected malfunction? **Defines**: Closure and totality KEY_CLAIMS: - Note: This article discusses mathematical properties relevant to safety-critical system design. - Closure, totality, and boundedness are not just theoretical properties—they are practical design constraints that determine whether systems fail safe or fail silent. - Closure guarantees that every operation on valid states produces another valid state — the system cannot escape its defined state space. - A system with closure cannot reach an undefined state through any sequence of valid operations. - Defensive programming adds runtime checks for known error cases but cannot prove completeness — there may always be an unchecked path. EVIDENCE: - Standards like IEC 62304 for medical devices require evidence that software behaves predictably under all conditions. RELATES_TO: - insights/ema-vs-sma-monitoring - insights/heartbeats-state-machines - insights/iec-62304-class-c - insights/statistics-as-state-transitions Why three mathematical properties can determine whether your system fails safe or fails silent Note: This article discusses mathematical properties relevant to safety-critical system design. Actual safety implementations require rigorous verification, domain expertise, and regulatory approval. This is not engineering guidance for specific applications. Three mathematical properties determine whether a safety-critical system fails safe or fails silent. Closure, totality, and algebraic composition govern the difference between a controlled shutdown and an undetected malfunction—yet most engineers never explicitly consider them. These properties are closure, totality, and boundedness. Together, they form a kind of algebra for reasoning about system safety. Understanding them transforms safety engineering from intuition and testing into something closer to proof. ## The Problem with "Mostly Works" Consider a function that calculates a running average. It works correctly for typical inputs. But what happens when: - The input is NaN or infinity? - The function is called recursively by an interrupt handler? - Memory pressure causes the historical buffer to fail allocation? - The counter overflows after months of continuous operation? Each of these represents an edge case that "mostly works" code ignores. In a web application, such failures might cause a page refresh. In a pacemaker, they could cause silence—the most dangerous failure mode of all. The traditional response is defensive programming: add checks, handle exceptions, write more tests. But this approach is fundamentally reactive. We're patching holes as we discover them, never confident we've found them all. Design Property: Enumerable Failure Modes A system with closure, totality, and boundedness has failure modes that can be enumerated at design time, not discovered in production. ## Property 1: Closure A system is **closed** if its next state depends only on its current state and current input—nothing else. Formally: St+1 = f(St, xt) This seems obvious until you catalogue what violates it: - **Global variables** — state depends on values modified elsewhere - **History buffers** — state depends on arbitrarily old inputs - **System calls** — state depends on OS scheduler, file system, network - **Timestamps** — state depends on wall-clock time - **Random numbers** — state depends on entropy source A closed system has no hidden inputs. Every dependency is explicit in the state vector. This means behaviour is reproducible: given the same initial state and input sequence, the system produces identical outputs every time. Why does this matter for safety? Because reproducibility enables diagnosis. When a closed system fails, you can replay the exact sequence that caused the failure. When a non-closed system fails, you're left wondering what hidden variable was different this time. ``` Closed system: State = (counter, accumulator, fault_flag) Input = observation Next state = deterministic function of state + input Non-closed system: State = (counter, accumulator, fault_flag, ???) Input = observation + time + thread state + heap layout + ... Next state = ¯\_(ツ)_/¯ ``` ### Achieving Closure Closure is a design constraint, not a runtime property. You achieve it by: 1. **Embedding configuration at initialisation** — don't read config files during operation 2. **Eliminating buffers** — use streaming algorithms that maintain fixed-size state 3. **Removing system dependencies** — no clocks, no file I/O, no network calls in core logic 4. **Making all inputs explicit** — if something affects output, it must be a parameter The [EMA vs SMA analysis](/insights/ema-vs-sma-monitoring/) demonstrates this concretely: exponential moving averages maintain closure (fixed state size) while simple moving averages violate it (unbounded history buffer). ## Property 2: Totality A function is **total** if it produces a valid output for every possible input. The opposite—a partial function—is undefined for some inputs. Most software is partial. Division is undefined when the denominator is zero. Array access is undefined when the index is out of bounds. Pointer dereference is undefined when the pointer is null. These "undefined behaviours" are gaps in the function's domain where anything can happen. In safety-critical systems, partial functions are silent failure modes. The function doesn't return an error—it simply doesn't return a meaningful result. Or it corrupts memory. Or it hangs. The caller has no way to know something went wrong. Partial Function Undefined for some inputs May crash, hang, or corrupt Caller cannot detect failure Requires defensive checks everywhere Total Function Defined for all inputs Returns valid result or explicit error Failure is always signalled Safety properties are composable ### Achieving Totality Totality requires explicitly handling every input case: ```c hb_result_t hb_step(hb_fsm_t *m, hb_input_t input) { hb_result_t result = { .state = HB_FAULT }; // Handle invalid state if (m == NULL) { return result; // Total: null input handled } // Handle reentrancy if (m->in_step) { m->fault_reentry = 1; m->state = HB_FAULT; return result; // Total: reentrant call handled } m->in_step = 1; // Handle invalid input if (input != HB_BEAT && input != HB_TIMEOUT) { m->fault_input = 1; m->state = HB_FAULT; m->in_step = 0; return result; // Total: unknown input handled } // Normal processing... // Every path returns a valid result m->in_step = 0; return result; } ``` Notice the pattern: every possible input has an explicit handling path. There are no gaps where behaviour is undefined. The function is total over its entire domain. For floating-point inputs, totality requires explicit handling of special values: ```c if (!isfinite(value)) { m->fault_fp = 1; m->state = FAULT_STATE; return error_result; // Total: NaN and Inf handled } ``` ## Property 3: Boundedness A system is **bounded** if it uses constant memory and constant time, regardless of input history or operational duration. - **O(1) memory**: State size is fixed at design time - **O(1) time**: Each step completes in bounded cycles Boundedness rules out: - **Dynamic allocation** — malloc can fail, fragment, or exhaust - **Recursion** — stack depth depends on input - **Variable-length loops** — iteration count depends on data - **Growing buffers** — memory usage increases over time Why does boundedness matter? Because unbounded resource usage is a time bomb. A system that allocates memory on each event will eventually exhaust available memory. A system with recursion depth dependent on input can overflow the stack. These failures might take months to manifest—long after testing is complete. Design Property: Time-Independent Safety A bounded system's safety properties hold on day one and day one thousand. No accumulation of state can cause delayed failure. ### Achieving Boundedness Boundedness is achieved through algorithm selection and implementation discipline: 1. **Use streaming algorithms** — EMA instead of SMA, Welford's instead of batch variance 2. **Pre-allocate everything** — all memory reserved at initialisation 3. **Fixed iteration bounds** — loops have constant maximum iterations 4. **Tail-call elimination or iteration** — no recursive algorithms The state machine pattern naturally supports boundedness. An FSM with n states and m transitions uses O(1) memory and processes each input in O(1) time, regardless of how many inputs it has processed historically. ## The Algebra of Composition The power of these properties emerges when composing systems. If module A and module B are both closed, total, and bounded, then their composition A → B is also closed, total, and bounded. This compositional guarantee is rare in software engineering. Usually, combining correct components can produce incorrect systems due to emergent interactions. But closure, totality, and boundedness are preserved under composition. ``` Module A: closed, total, bounded Module B: closed, total, bounded A → B composition: - Closed: output of A depends only on A's state + input input of B is output of A therefore B's state depends only on B's state + A's output composition is closed ✓ - Total: A produces valid output for all inputs B produces valid output for all inputs (including A's outputs) composition is total ✓ - Bounded: A uses O(1) memory and time B uses O(1) memory and time composition uses O(1) + O(1) = O(1) ✓ ``` This is why the [c-from-scratch](https://github.com/SpeyTech/c-from-scratch) methodology emphasises these properties at the module level. Each module—the heartbeat detector, the baseline monitor, the anomaly classifier—is independently closed, total, and bounded. Composition then inherits these properties automatically. ## Determinism as a Consequence When a system has closure, totality, and boundedness, determinism follows as a consequence: - **Closure** ensures no hidden inputs affect behaviour - **Totality** ensures every input produces a defined output - **Boundedness** ensures resource usage cannot cause variable behaviour Given identical initial states and input sequences, such a system produces identical outputs. This reproducibility is the foundation of testability, debuggability, and certifiability. The relationship to safety certification frameworks becomes clear. Standards like [IEC 62304](/insights/iec-62304-class-c/) for medical devices require evidence that software behaves predictably under all conditions. A system with closure, totality, and boundedness provides exactly this evidence—not through exhaustive testing, but through structural properties that can be verified by inspection. ## Practical Implications These three properties impose constraints that feel restrictive at first: - No global state - No dynamic allocation - No partial functions - No unbounded loops - No system calls in core logic But these constraints are clarifying, not limiting. They force explicit design decisions that would otherwise be implicit (and often wrong). They make failure modes enumerable rather than discoverable. They transform "I think it works" into "I can show it works." The trade-off is design effort. Achieving closure, totality, and boundedness requires thinking carefully about every input, every state transition, every resource allocation. This effort is front-loaded—spent during design rather than during debugging. For safety-critical systems, this trade-off is favourable. The cost of careful design is measured in engineering hours. The cost of silent failure is measured in lives. ## Frequently Asked Questions ### What are closure and totality in safety-critical software design? Closure guarantees that every operation on valid states produces another valid state — the system cannot escape its defined state space. Totality guarantees that every valid input has a defined output — no input produces undefined behaviour. Together, they ensure the system fails safely with controlled responses rather than silently malfunctioning. ### How do closure and totality determine whether a system fails safely? A system with closure cannot reach an undefined state through any sequence of valid operations. A system with totality handles every possible input, including malformed or unexpected ones. Without both properties, there exist input sequences that drive the system into undefined behaviour where failure mode is unpredictable. ### Why doesn't defensive programming provide the same guarantees as algebraic closure? Defensive programming adds runtime checks for known error cases but cannot prove completeness — there may always be an unchecked path. Algebraic closure is a structural property of the type system and state machine design: the architecture makes invalid states unrepresentable, eliminating the category of errors rather than catching them individually. ### What are the practical trade-offs of designing for closure and totality? Designing for closure and totality requires upfront investment in type design, state machine specification, and formal property verification. The constraint space must be fully enumerated, which adds design effort. The return is provable safety properties that persist through maintenance and evolution — the system cannot be accidentally weakened by future changes. ## Conclusion Closure, totality, and boundedness are not just theoretical properties—they are practical design constraints that determine whether systems fail safe or fail silent. - **Closure** ensures reproducibility: same inputs, same outputs, every time - **Totality** ensures explicit failure: no undefined behaviour, no silent corruption - **Boundedness** ensures temporal stability: safety properties that hold indefinitely Together, they form an algebra for reasoning about safety. Systems built on these foundations can be composed confidently, tested meaningfully, and certified with evidence rather than hope. The [Heartbeats and State Machines](/insights/heartbeats-state-machines/) article demonstrates these properties in a concrete liveness detector. The [Statistics as State Transitions](/insights/statistics-as-state-transitions/) article shows how streaming algorithms achieve closure and boundedness. These are not abstract concepts—they are engineering techniques that produce systems worthy of trust. As with any architectural approach, suitability depends on system requirements, risk classification, and regulatory context. But for systems where silent failure is unacceptable, these three properties offer a path from intuition to confidence. --- ## Heartbeats and State Machines: Proving Existence in Time **URL**: https://speytech.com/insights/heartbeats-state-machines/ **Published**: January 08, 2026 17:40 **Topic**: Formal Methods **Answers**: How can deterministic finite state machines model liveness detection heartbeat monitoring with formally verifiable temporal properties, and why is proving that a subsystem is still running and responsive as important in safety-critical systems as verifying what computations it is performing? **Defines**: Heartbeat monitoring KEY_CLAIMS: - Note: This article discusses architectural patterns for liveness detection. - Liveness detection—proving that something exists in time—is a foundational problem in safety-critical systems. - Heartbeat monitoring uses a deterministic FSM to prove that a subsystem is alive and responsive by tracking inter-arrival times of periodic signals. - Simple timeouts have two states: responding or not. - Counter-based watchdogs lack formal state semantics and cannot distinguish slow, intermittent, and stopped systems. EVIDENCE: - This approach supports regulatory frameworks like IEC 62304 for medical devices, where evidence of correctness is a certification requirement. RELATES_TO: - insights/iec-62304-class-c - insights/statistics-as-state-transitions How deterministic finite state machines can model liveness detection with verifiable properties Note: This article discusses architectural patterns for liveness detection. Actual medical device implementations require rigorous verification and regulatory approval. This is not medical device design guidance. Liveness detection proves a subsystem is still running and responsive. A pacemaker must verify the heart is beating. A flight controller must confirm sensor subsystems remain responsive. A distributed system must detect node failures before they cascade. Deterministic finite state machines can model these heartbeat protocols with formally verifiable temporal properties. This fundamental problem—proving existence in time—appears deceptively simple. Yet naive implementations routinely fail in ways that compromise safety. The solution lies in treating liveness detection not as a timing hack, but as a formal state machine with provable properties. ## The Liveness Problem Consider a subsystem that should emit periodic signals. How do we know it's still alive? The naive approach: check if we received a signal "recently." But this raises immediate questions. How recent is recent? What happens during the first few seconds before we have enough data? What if signals arrive slightly late due to scheduling jitter? What if a single spurious signal masks an underlying failure? Each question reveals a hidden assumption. Each assumption represents a potential failure mode in production. Design Property: Existence Uncertainty Between observations, existence is uncertain. A liveness detector must distinguish between "confirmed alive," "confirmed dead," and "insufficient evidence to determine." This three-valued logic is not a limitation—it's intellectual honesty. Systems that collapse uncertainty into binary alive/dead decisions are implicitly making assumptions about timing, reliability, and failure modes that may not hold. ## Modelling Heartbeats as State Transitions Rather than tracking timestamps, we can model liveness detection as a finite state machine (FSM). The key insight: state encodes *what we know*, and transitions encode *how evidence changes knowledge*. Define three states: - **INIT**: Insufficient observations to determine liveness - **OK**: Evidence supports the system is alive - **FAULT**: Evidence indicates the system has stopped And two inputs: - **BEAT**: A heartbeat signal was received - **TIMEOUT**: Sufficient time passed without a signal The state transition function becomes: ``` δ(INIT, BEAT) → OK // First evidence of life δ(INIT, TIMEOUT) → INIT // Can't fault what we haven't confirmed δ(OK, BEAT) → OK // Continued evidence δ(OK, TIMEOUT) → FAULT // Silence after confirmed activity δ(FAULT, BEAT) → FAULT // Dead systems stay dead (sticky fault) δ(FAULT, TIMEOUT)→ FAULT // Fault is terminal without reset ``` This FSM exhibits several important properties by construction. ## Property 1: No False Positives During Learning The INIT state provides a learning period where the detector cannot fault. This is not a grace period based on wall-clock time—it's a formal requirement that we observe at least one heartbeat before we can claim silence is meaningful. ``` INV-1: (state == FAULT) → (n_beats > 0) ``` A system cannot be declared dead if we never confirmed it was alive. This invariant is enforced by the transition function: there is no path from INIT to FAULT. ## Property 2: Sticky Faults Once a fault is detected, the FSM remains in FAULT regardless of subsequent inputs. This is a deliberate design choice for safety-critical applications. ``` INV-2: (state == FAULT at time t) → (state == FAULT at time t+1) ``` Why make faults sticky? In safety-critical contexts, a detected failure should trigger investigation, not be silently recovered. A pacemaker that detects cardiac arrest should not quietly resume normal operation if the heart starts beating again—it should alert and require explicit clinical intervention. The only exit from FAULT is an explicit reset operation, which represents a deliberate human decision that the fault has been addressed. ## Property 3: Bounded Memory and Time The FSM requires exactly two pieces of state: the current state (3 possible values) and a beat counter. No timestamps. No buffers. No history. ``` Memory: O(1) Time per step: O(1) ``` This is not merely efficient—it's a safety property. Unbounded memory means unbounded failure modes. A buffer overflow in a heartbeat detector could be catastrophic in an implantable device. ## The Mathematics of Timing But wait—how do we generate TIMEOUT inputs without tracking time? The answer is to separate concerns. The FSM handles state transitions. A separate *tick* mechanism handles timing. On each tick (a regular polling interval), we check: has a beat arrived since the last tick? If not, and enough ticks have passed, we generate a TIMEOUT input. ``` tick_step: if beat_received_this_tick: fsm_step(BEAT) ticks_since_beat = 0 else: ticks_since_beat += 1 if ticks_since_beat >= max_ticks: fsm_step(TIMEOUT) ``` The `max_ticks` parameter encodes the timing tolerance. But notice: the FSM itself knows nothing about time. It only knows about the sequence of BEAT and TIMEOUT events. This separation means the FSM's correctness properties are independent of the specific timing configuration. ## From Theory to Code The translation from mathematical model to C is direct. The FSM becomes a struct: ```c typedef struct { hb_state_t state; // INIT, OK, FAULT uint32_t n_beats; // Observation counter uint32_t ticks; // Ticks since last beat uint8_t fault_flag; // Sticky fault indicator uint8_t in_step; // Reentrancy guard } hb_fsm_t; ``` The transition function becomes a switch statement that directly transcribes the mathematical δ: ```c hb_result_t hb_step(hb_fsm_t *m, hb_input_t input) { // Reentrancy guard if (m->in_step) { m->fault_flag = 1; m->state = HB_FAULT; return (hb_result_t){ .state = HB_FAULT }; } m->in_step = 1; // State transitions switch (m->state) { case HB_INIT: if (input == HB_BEAT) { m->state = HB_OK; m->n_beats++; } // TIMEOUT in INIT: stay in INIT break; case HB_OK: if (input == HB_BEAT) { m->n_beats++; m->ticks = 0; } else { // TIMEOUT m->state = HB_FAULT; m->fault_flag = 1; } break; case HB_FAULT: // Sticky: no transitions out break; } m->in_step = 0; return (hb_result_t){ .state = m->state }; } ``` This is not code that implements a specification—it *is* the specification, transcribed into a different notation. Every line traces to a mathematical statement. Every invariant can be checked after every step. ## Testing Contracts, Not Coverage Traditional testing asks: "Did I execute every line?" Contract testing asks: "Did I verify every guarantee?" For the heartbeat FSM, we define explicit contracts: - **CONTRACT-1 (No False Early Fault)**: The FSM cannot transition to FAULT without first visiting OK - **CONTRACT-2 (Sticky Fault)**: Once in FAULT, no input sequence exits FAULT - **CONTRACT-3 (Liveness Detection)**: A sequence of BEAT inputs keeps the FSM in OK - **CONTRACT-4 (Fault Detection)**: TIMEOUT after OK transitions to FAULT Each contract has a corresponding test that verifies the guarantee holds. Fuzz testing with 100,000 random input sequences confirms invariants hold under arbitrary conditions—not just the happy paths a developer imagined. ## Composition: Where Heartbeats Meet Baselines The real power of this approach emerges in composition. The heartbeat FSM outputs inter-arrival times—the duration between successive beats. These durations become inputs to a statistical baseline detector (explored in [Statistics as State Transitions](/insights/statistics-as-state-transitions/)). ``` Event → Heartbeat FSM → Δt → Baseline FSM → Anomaly? ``` Each FSM maintains its own contracts. The composition inherits guarantees from both: the heartbeat FSM provides liveness detection; the baseline FSM provides anomaly detection on timing patterns. Together, they answer: "Is the system alive, and is it behaving normally?" This modular composition is only possible because each component is closed (no hidden dependencies), total (handles all inputs), and deterministic (reproducible behaviour). These properties, established mathematically and enforced in code, enable systems that support certification, audit, and verification processes. ## Implications for Safety-Critical Design The heartbeat pattern illustrates a broader principle: safety-critical systems benefit from modelling behaviour as explicit state machines with formal properties. This approach supports regulatory frameworks like [IEC 62304](/insights/iec-62304-class-c/) for medical devices, where evidence of correctness is a certification requirement. A well-documented FSM with proven invariants provides exactly the kind of auditable evidence that regulators expect for Class C software. More importantly, it provides *engineering* confidence. When a pacemaker's liveness detector is a three-state FSM with five invariants, all verified by contract tests, the failure modes are enumerable. When it's a tangle of timestamps and heuristics, the failure modes are limited only by imagination. ## Frequently Asked Questions ### What is heartbeat monitoring with finite state machines? Heartbeat monitoring uses a deterministic FSM to prove that a subsystem is alive and responsive by tracking inter-arrival times of periodic signals. The FSM transitions between states (INIT, ALIVE, SUSPECT, DEAD) based on timing contracts, providing formal liveness guarantees rather than ad-hoc timeout checks. ### How do state machine heartbeats differ from simple timeout monitors? Simple timeouts have two states: responding or not. FSM heartbeats add intermediate states — a SUSPECT state requires two consecutive missed heartbeats before declaring DEAD, eliminating single-event false positives. Each transition has formal preconditions, postconditions, and testable contracts. ### Why doesn't a simple counter-based watchdog provide sufficient liveness detection? Counter-based watchdogs lack formal state semantics and cannot distinguish slow, intermittent, and stopped systems. FSM heartbeats model these as distinct states with different recovery actions, making the monitoring system's behaviour verifiable and certifiable. ### What are the limitations of FSM-based heartbeat monitoring? FSM heartbeats detect timing failures but not content failures — a subsystem can send heartbeats while producing incorrect results. The FSM cannot detect Byzantine failures where the subsystem actively lies about its state. Heartbeat monitoring must be composed with output validation for complete health assessment. ## Conclusion Liveness detection—proving that something exists in time—is a foundational problem in safety-critical systems. By modelling heartbeat detection as a deterministic finite state machine, we transform an intuitive timing check into a formal system with provable properties. The key insights are structural: separate timing generation from state logic; use three-valued states that acknowledge uncertainty; make faults sticky to require explicit recovery; verify contracts rather than coverage. This approach is explored in detail in the [c-from-scratch](https://github.com/SpeyTech/c-from-scratch) educational project, where the Pulse module implements a complete heartbeat detector with full contract testing. The mathematical rigour transfers: what you prove on paper, you transcribe into code, and you verify through tests. As with any architectural approach, suitability depends on system requirements, risk classification, and regulatory context. But for systems where knowing something is *still there* is as critical as knowing what it's *doing*, the state machine approach offers a path from intuition to proof. --- ## IEC 62304 Class C: Medical Device Software Requirements **URL**: https://speytech.com/insights/iec-62304-class-c/ **Published**: January 08, 2026 17:15 **Topic**: Medical Devices **Answers**: What does IEC 62304 Class C safety classification require for medical device software like pacemaker firmware and insulin pump controllers, and how can deterministic architecture with static allocation, fixed-point arithmetic, and formal traceability support compliance with these most stringent requirements? KEY_CLAIMS: - Note: This article discusses general principles of IEC 62304 compliance. - IEC 62304 Class C represents the highest bar for medical device software development. - IEC 62304 Class C applies to software that can cause death or serious injury, requiring full lifecycle verification. - Deterministic execution with static allocation and fixed-point arithmetic simplifies verification by eliminating non-deterministic failure modes. - Conventional RTOS designs introduce dynamic memory allocation, preemptive thread scheduling, and non-deterministic timing — each requiring extensive analysis to demonstrate safety. EVIDENCE: - Note: This article discusses general principles of IEC 62304 compliance. - IEC 62304 defines the lifecycle requirements for medical device software. - IEC 62304 Section 5 specifies software development process requirements. - IEC 62304 requires documenting software architecture with sufficient detail to support verification. RELATES_TO: - insights/do178c-certification - insights/implantable-device-litigation How deterministic architecture can support the most stringent safety classification for medical device software Note: This article discusses general principles of IEC 62304 compliance. Actual certification requirements depend on specific device classifications, regulatory jurisdictions, and notified body interpretations. This is not legal or regulatory advice. IEC 62304 defines the lifecycle requirements for medical device software. Among its classifications, Class C represents the highest level of rigour—software where failure could result in death or serious injury. Pacemaker firmware. Insulin pump controllers. Ventilator software. For manufacturers developing Class C software, the standard imposes requirements that many conventional architectures struggle to meet. Deterministic execution isn't mandated by the standard, but it can provide architectural properties that directly support compliance evidence. ## Understanding the Classification System IEC 62304 classifies software based on the severity of harm that could result from failure: Class A No injury or damage to health possible Basic documentation requirements Unit testing optional Example: Patient record display Class B Non-serious injury possible Unit-level verification required Architecture documentation required Example: Diagnostic imaging display Class C Death or serious injury possible Full lifecycle documentation required Detailed design verification required Example: Implantable cardiac devices The jump from Class B to Class C is significant. It's not merely more documentation—it's a fundamentally different evidence burden. You must demonstrate not just that the software works, but that you understand *why* it works, and that this understanding is traceable through every development artefact. ## The Class C Evidence Requirements IEC 62304 Section 5 specifies software development process requirements. For Class C, key requirements include: **Software Architecture (5.3)**: The architecture must be documented with sufficient detail to support verification. This includes identifying software items, their interfaces, and the data flows between them. **Detailed Design (5.4)**: Each software unit must be specified in detail sufficient to enable correct implementation and verification. The design must address how the unit contributes to the overall safety requirements. **Software Unit Verification (5.5)**: Each unit must be verified against its detailed design. The verification must demonstrate correct implementation of the design and absence of unintended functionality. **Integration Testing (5.6)**: Software items must be tested in combination to verify that they function correctly together and that interfaces operate as specified. **System Testing (5.7)**: The complete software system must be tested to verify that it meets all specified requirements. The standard requires *traceability* throughout: from requirements to architecture, from architecture to detailed design, from design to implementation, from implementation to verification. Any gap in this chain becomes a compliance finding. ## Where Conventional Architectures Struggle Traditional embedded software architectures face several challenges in Class C compliance: ### Non-Deterministic Behaviour When software exhibits different timing or sequencing depending on runtime conditions, verification becomes probabilistic rather than exhaustive. A test that passes 10,000 times might fail on execution 10,001 due to a timing window that only opens under specific load conditions. For Class C devices, this creates an uncomfortable question: how many test executions are enough? The honest answer is that no number is sufficient if the underlying behaviour is non-deterministic. You're sampling from a space you cannot fully characterise. ### Implicit State Operating systems and middleware often maintain internal state that affects application behaviour but isn't visible to the application developer. Thread scheduling decisions, interrupt priorities, memory allocation patterns—all can influence execution in ways that are difficult to document and verify. IEC 62304 requires documenting software architecture with sufficient detail to support verification. When significant behaviour is determined by implicit state in platform components, this documentation requirement becomes challenging to satisfy. ### Interface Complexity Complex inter-component interfaces create verification challenges. If component A can call component B in 47 different ways, and component B can be in 23 different states, the interface has over 1,000 potential interaction scenarios. Testing all of them may be impractical; documenting all of them is certainly tedious. This complexity tends to compound. Systems built from complex components with complex interfaces exhibit combinatorial explosion in their verification requirements. ## How Deterministic Architecture Supports Compliance Deterministic execution provides architectural properties that can directly address these challenges: ### Reproducible Behaviour Design Property: Reproducibility Given identical inputs and initial state, a deterministic system produces identical outputs and final state—enabling exhaustive verification of observed behaviour. When behaviour is reproducible, testing becomes definitive rather than statistical. A test that passes demonstrates correct behaviour for that input scenario. The verification record shows what the system *does*, not what it *probably* does. This property directly supports IEC 62304's verification requirements. Evidence of correct behaviour is concrete and repeatable. ### Explicit State Deterministic architectures typically make all state explicit and inspectable. There is no hidden scheduler state, no implicit priority inheritance, no background garbage collection. The system state at any moment can be captured, examined, and restored. For documentation purposes, this means the architecture description can be complete. Every state variable, every state transition, every possible configuration is enumerable. There are no "it depends on runtime conditions" qualifications. ### Minimal Interfaces Deterministic designs tend toward minimal, well-defined interfaces. Components communicate through explicit channels with specified protocols. The tick-based execution model, for example, provides a single synchronisation primitive: the tick boundary. Fewer interface scenarios mean fewer test cases, fewer documentation pages, and fewer opportunities for unexpected interactions. The verification burden scales linearly with functionality rather than combinatorially with interface complexity. ## Mapping to IEC 62304 Requirements Specific standard requirements that deterministic architecture can support: | Requirement | How Determinism Helps | |-------------|----------------------| | 5.3.2 - Develop architecture to support hazard control | Reproducible behaviour enables verification of hazard controls | | 5.3.6 - Verify architecture supports requirements | Complete state documentation enables traceability | | 5.4.2 - Develop detailed design from architecture | Explicit interfaces simplify unit-level design | | 5.5.3 - Verify software units | Deterministic units have definitive test results | | 5.6.3 - Verify integration | Reproducible timing eliminates integration test flakiness | | 5.7.2 - Verify software system | System-level tests are repeatable and conclusive | The pattern is consistent: where the standard requires evidence of correct behaviour, deterministic execution provides evidence that is concrete rather than statistical, complete rather than sampled. ## The Software Problem Report Challenge IEC 62304 Section 9 addresses software problem resolution. When anomalies are discovered, they must be evaluated, documented, and resolved. For Class C software, this includes evaluating whether the problem affects safety. Non-deterministic bugs present a particular challenge: they may be difficult to reproduce, difficult to diagnose, and difficult to verify as resolved. A problem report stating "intermittent crash under high load" can consume weeks of engineering time with no definitive resolution. Deterministic architectures can reduce this burden. When bugs are reproducible, they can be captured as failing test cases. When fixes are applied, the test case demonstrates resolution. The problem report lifecycle becomes tractable. This matters for more than engineering efficiency. Regulatory reviewers examine problem reports. A history of intermittent issues with uncertain resolutions suggests an architecture that resists verification. A history of reproducible issues with demonstrated fixes suggests an architecture under control. ## Post-Market Surveillance Implications Class C devices require post-market surveillance under the Medical Device Regulation (MDR) in Europe and similar requirements elsewhere. When field issues occur, manufacturers must investigate, assess safety impact, and potentially issue field safety corrective actions. The investigation phase benefits significantly from reproducibility. If device logs capture sufficient state, and device behaviour is deterministic, then field issues can potentially be reproduced in the laboratory. The root cause analysis has concrete evidence to work with. For non-deterministic systems, field issue investigation often relies on statistical analysis of failure patterns across the installed base. This can identify correlations but rarely provides mechanistic understanding. Regulatory authorities increasingly expect more than correlation. ## The Certification Timeline Factor While not a compliance requirement per se, certification timeline affects commercial viability. Devices that spend years in regulatory review face market timing risks and extended capital requirements. Deterministic architectures can support faster certification through: **Reduced verification iterations**: Tests that pass consistently don't require re-runs to build confidence. **Cleaner audit findings**: Clear traceability and complete documentation reduce audit queries. **Faster problem resolution**: Reproducible issues reach root cause faster. **Reusable evidence**: Platform components verified once can support multiple device applications. These factors are difficult to quantify precisely, but the pattern observed in practice suggests that verifiable architectures reach market faster than their conventional counterparts—sometimes significantly faster. ## Practical Considerations Adopting deterministic architecture for Class C development involves trade-offs: **Development approach**: Deterministic designs require discipline. The freedom to spawn threads or allocate memory dynamically is constrained. Some developers find this restrictive. **Performance characteristics**: Deterministic scheduling can impose overhead compared to fully dynamic approaches. For compute-intensive applications, this overhead must be evaluated. **Platform availability**: Deterministic execution platforms are less common than conventional RTOS options. Toolchain and ecosystem maturity varies. **Team expertise**: Designing for determinism requires specific skills that may not be present in teams experienced with conventional embedded development. These constraints are real and should be evaluated against the compliance benefits for any specific project. ## Frequently Asked Questions ### What does IEC 62304 Class C require for medical device software? IEC 62304 Class C applies to software that can cause death or serious injury, requiring full lifecycle verification. This is the most stringent classification for medical device software. ### How does deterministic architecture support IEC 62304 Class C compliance? Deterministic execution with static allocation and fixed-point arithmetic simplifies verification by eliminating non-deterministic failure modes. Tests that pass consistently do not require re-runs to build confidence. Reproducible issues reach root cause faster. Clear traceability and complete documentation reduce audit queries from assessors. ### Why doesn't a conventional RTOS simplify IEC 62304 certification? Conventional RTOS designs introduce dynamic memory allocation, preemptive thread scheduling, and non-deterministic timing — each requiring extensive analysis to demonstrate safety. These architectural properties increase the verification surface area and create failure modes that are difficult to reproduce during testing or audit. ### What are the trade-offs of deterministic architecture for medical devices? Deterministic designs constrain development freedom: no dynamic memory, no thread spawning, restricted scheduling. Some developers find this restrictive. Performance overhead from deterministic scheduling must be evaluated for compute-intensive applications. Platform availability and toolchain maturity for deterministic execution environments are more limited than conventional RTOS options. ## Conclusion IEC 62304 Class C represents the highest bar for medical device software development. The standard's requirements for traceability, verification, and documented understanding of system behaviour create challenges that conventional architectures struggle to address efficiently. Deterministic execution provides architectural properties—reproducibility, explicit state, minimal interfaces—that can directly support compliance evidence. The result is potentially faster certification, more tractable problem resolution, and stronger audit performance. For manufacturers developing the next generation of safety-critical medical devices, the architecture decision deserves careful consideration. The standard doesn't mandate determinism, but determinism can make the standard's requirements substantially easier to meet. --- *As with any architectural approach, suitability depends on system requirements, risk classification, and regulatory context. Medical device development involves numerous factors beyond software architecture, and regulatory strategy should be developed in consultation with qualified regulatory affairs professionals.* ## Further Reading - [CardioCore™ Medical Kernel](/cardiocore/) — Deterministic platform designed for IEC 62304 alignment - [Reproducibility and Post-Incident Analysis in Implantable Cardiac Devices](/insights/implantable-device-litigation/) — Legal and regulatory implications - [DO-178C Level A Certification](/insights/do178c-certification/) — Parallel requirements in aerospace --- ## Statistics as State Transitions **URL**: https://speytech.com/insights/statistics-as-state-transitions/ **Published**: January 7, 2026 21:00 **Topic**: Formal Methods **Answers**: How can deterministic finite state machines provide a fully reproducible computational foundation for statistical anomaly detection in safety-critical runtime monitoring systems, and what specific advantages does modelling statistical computations as explicit verifiable state transitions offer over conventional probabilistic detection approaches? **Defines**: Statistics as state transitions KEY_CLAIMS: - Statistics and state machines rarely appear in the same sentence. - Deterministic finite state machines model statistical computations as explicit state transitions with verifiable contracts. - Safety standards like DO-178C and IEC 62304 require evidence of correct behaviour. - Conventional statistical libraries use platform-dependent floating-point arithmetic and lack explicit handling for edge cases. - State machine monitors detect anomalies relative to learned baselines but cannot classify root causes. EVIDENCE: - The reframing from "statistical monitoring" to "state machine with contracts" has practical implications: Certification evidence: Safety standards like DO-178C and IEC 62304 require evidence of correct behaviour. - Safety standards like DO-178C and IEC 62304 require evidence of correct behaviour. RELATES_TO: - insights/ema-vs-sma-monitoring - insights/semantic-security-monitoring How finite state machines can provide a deterministic foundation for anomaly detection Statistics and state machines rarely appear in the same sentence. Statistics belongs to the world of probability distributions, confidence intervals, and hypothesis testing. State machines belong to the world of formal verification, protocol design, and hardware controllers. But what if statistical monitoring could be reframed as state transitions? What if anomaly detection wasn't a probabilistic judgement call, but a deterministic function from input to state? This reframing isn't just theoretical elegance. It's the foundation for building monitoring systems that can be verified, tested, and certified—properties that matter when the system being monitored is safety-critical. ## The Problem with Statistical Monitoring Traditional anomaly detection treats statistics as an oracle. You feed it data, it returns a judgement: normal or abnormal, with perhaps a confidence score attached. The internal state is opaque. The decision boundary is learned, not specified. The behaviour under edge cases is undefined. This works adequately for many applications. For safety-critical systems, it creates fundamental problems: **Non-reproducibility**: Run the same detector twice on the same data, and you may get different results—especially if the detector uses adaptive thresholds or online learning with floating-point accumulation errors. **Unbounded state**: Many statistical methods require unbounded history. A sliding window of N observations requires O(N) memory. Store-everything approaches grow without limit. **Opaque transitions**: When the system moves from "normal" to "alert", what exactly triggered the transition? In a learned model, the answer may be "a complex combination of 47 features weighted by coefficients from last Tuesday's training run." **Unverifiable contracts**: What are the formal guarantees? Under what conditions will the detector definitely fire? Under what conditions will it definitely not fire? For most statistical systems, these questions have no precise answers. ## The State Machine Reframing A finite state machine (FSM) has three components: a set of states, a transition function, and an initial state. Given the current state and an input, the transition function deterministically produces the next state. The insight is that statistical monitoring can be cast in exactly this form: ``` State: S = (μ, σ², n, q) Input: x ∈ ℝ (a single observation) Transition: S' = f(S, x) ``` Where: - μ is the running mean (exponentially weighted) - σ² is the running variance (exponentially weighted) - n is the observation count - q is the discrete state: LEARNING, STABLE, or DEVIATION The transition function f is completely deterministic. Given the same state S and input x, it produces exactly the same next state S'. No randomness. No hidden variables. No dependence on history beyond what's encoded in the state. Design Property: Closure The state Sₜ₊₁ = f(Sₜ, xₜ) is fully determined by the previous state and current observation. No external history is required. This property—closure—is what makes the system a valid state machine rather than a statistical approximation wearing FSM clothing. ## The EMA Foundation The key to achieving closure is the Exponential Moving Average (EMA). Unlike a Simple Moving Average (SMA) which requires a buffer of N previous values, the EMA computes the new mean from just the previous mean and the current observation: ``` μₜ = α·xₜ + (1 - α)·μₜ₋₁ ``` This single equation delivers several properties simultaneously: **O(1) memory**: Store one value (μ), not N values. **O(1) computation**: One multiply, one add—not a sum over N elements. **Spike resistance**: A single outlier of magnitude M can shift the mean by at most α·M. With α = 0.1, even a massive spike has bounded impact. **Recency weighting**: Recent observations influence the mean more than ancient ones, which is usually what anomaly detection requires. The same exponential structure extends to variance: ``` σₜ² = α·(xₜ - μₜ₋₁)² + (1 - α)·σₜ₋₁² ``` Note the careful ordering: the deviation uses the *previous* mean, not the updated mean. This prevents the current observation from influencing its own anomaly score. ## State Transitions as Contracts With mean and variance tracked, anomaly detection becomes a z-score calculation: ``` z = |xₜ - μₜ₋₁| / σₜ ``` The z-score answers: "How can deterministic finite state machines provide a fully reproducible computational foundation for statistical anomaly detection in safety-critical runtime monitoring systems, and what specific advantages does modelling statistical computations as explicit verifiable state transitions offer over conventional probabilistic detection approaches?" A z-score of 3 indicates an observation that would occur roughly 0.3% of the time under a normal distribution. The state machine's discrete state q transitions based on this z-score: ``` LEARNING → STABLE when n ≥ min_samples and σ² > ε STABLE → DEVIATION when z > threshold DEVIATION → STABLE when z ≤ threshold ``` These transitions are not heuristics. They're contracts that can be tested: **CONTRACT-1 (Convergence)**: For stationary input, μₜ converges to the true mean E[X]. **CONTRACT-2 (Sensitivity)**: Deviations from the mean can be detected within O(1/α) observations. **CONTRACT-3 (Stability)**: The false positive rate is bounded by P(|Z| > threshold) for the underlying distribution. **CONTRACT-4 (Spike Resistance)**: A single outlier M shifts the mean by at most α·M. Each contract is a theorem about the system's behaviour. Each can be verified through testing or formal proof. ## Why This Matters for Safety-Critical Systems The reframing from "statistical monitoring" to "state machine with contracts" has practical implications: **Certification evidence**: Safety standards like DO-178C and IEC 62304 require evidence of correct behaviour. A state machine with proven contracts provides exactly that evidence. A machine learning model with "good accuracy on the test set" does not. **Reproducible debugging**: When an anomaly is detected (or missed), the entire state history can be reconstructed. Given the initial state and the input sequence, the final state is mathematically determined. **Bounded resource usage**: O(1) memory and O(1) computation per step means the monitor can run on constrained embedded systems—exactly where safety-critical monitoring is often needed. **Compositional reasoning**: State machines compose. A heartbeat monitor (detecting existence in time) can feed its inter-arrival times to a baseline monitor (detecting normality in value). The composition is itself a state machine with well-defined properties. ## The Implementation Reality Theory is necessary but not sufficient. Real implementations must handle cases that pure mathematics ignores: **Division by zero**: The z-score calculation divides by σ. When variance is zero (or numerically indistinguishable from zero), this is undefined. Real implementations need an explicit guard: ```c if (variance <= EPSILON) { z = 0.0; // Cannot compute meaningful z-score } else { z = fabs(x - mu) / sqrt(variance); } ``` **Floating-point accumulation**: Even deterministic calculations can accumulate error over millions of observations. The implementation must either bound execution length or use numerical techniques that limit drift. **State initialisation**: What's "normal" before we've seen any data? The LEARNING state exists precisely to handle this—the system must accumulate sufficient evidence before making judgements. These aren't bugs to work around. They're the reality of finite machines computing with finite precision. A proper implementation addresses them explicitly rather than hoping they don't occur. ## Frequently Asked Questions ### How do state machines provide deterministic statistical monitoring? Deterministic finite state machines model statistical computations as explicit state transitions with verifiable contracts. Each update follows a defined path through states (LEARNING, ACTIVE, CONSTANT, ALERT) using purely integer or fixed-point arithmetic, producing identical anomaly detection results for identical input sequences across all platforms. ### How does modelling statistics as state transitions support certification? Safety standards like DO-178C and IEC 62304 require evidence of correct behaviour. A state machine with proven contracts — bounded memory, bounded influence, spike resistance — provides exactly this evidence. Each contract is a testable invariant, unlike ML models where correctness evidence is statistical rather than formal. ### Why can't conventional statistical libraries provide the same guarantees? Conventional statistical libraries use platform-dependent floating-point arithmetic and lack explicit handling for edge cases. State machine implementations bound resource usage to O(1) memory and O(1) computation per step with deterministic arithmetic throughout. ### What are the limitations of state machine statistical monitoring? State machine monitors detect anomalies relative to learned baselines but cannot classify root causes. They require a learning period before producing meaningful alerts. Complex multi-variate anomaly patterns may require composed state machines with carefully managed interaction boundaries, increasing design complexity for sophisticated detection requirements. ## From Monitoring to Composition The real power of the state machine framing emerges in composition. Consider a pipeline: ``` events → Pulse → Δt → Baseline → deviation? ``` Pulse (from Module 1 of c-from-scratch) detects heartbeat events and outputs inter-arrival times. Baseline monitors those times for anomalies. The result: timing anomaly detection without manually configured thresholds. Both components are closed, total, deterministic FSMs. Their composition is also a closed, total, deterministic FSM. The properties proved for each component extend to the composition. This is modular verification: prove components correct, compose them, and know the composition inherits correctness. It's the same principle that makes well-designed software systems tractable. --- *As with any architectural approach, suitability depends on system requirements and monitoring context. The FSM framing assumes that anomaly detection can be expressed as state transitions over scalar observations—an assumption that holds for many monitoring scenarios but should be validated for specific use cases.* ## Further Reading - [Why EMA Beats SMA for Safety-Critical Monitoring](/insights/ema-vs-sma-monitoring/) — Mathematical foundations - [c-from-scratch Module 2: Baseline](https://github.com/SpeyTech/c-from-scratch) — Working implementation - [Semantic Security Monitoring in Deterministic Systems](/insights/semantic-security-monitoring/) — Extending the pattern to security observability --- ## Why EMA Beats SMA for Safety-Critical Monitoring **URL**: https://speytech.com/insights/ema-vs-sma-monitoring/ **Published**: January 7, 2026 **Topic**: Systems Architecture **Answers**: Why are exponential moving averages mathematically superior to simple moving averages for safety-critical anomaly detection and real-time runtime monitoring, and what specific mathematical properties of EMA including O(1) memory usage, bounded state size, and recency weighting make it preferable for deterministic systems? **Defines**: Exponential moving average KEY_CLAIMS: - Exponential moving averages outperform simple moving averages for safety-critical monitoring. - An exponential moving average is a recursive filter that weights recent observations more heavily, requiring O(1) memory and bounded state for deterministic anomaly detection. - Simple Moving Average is a pedagogical tool—useful for explaining concepts, unsuitable for production systems where determinism matters. - EMA uses O(1) memory regardless of history length, while SMA requires O(N) storage for its sliding window. - Alpha controls the trade-off between responsiveness and stability. How exponential moving averages provide the mathematical properties that safety-critical systems require Exponential moving averages outperform simple moving averages for safety-critical monitoring. EMA requires O(1) memory, weights recent observations more heavily, and produces bounded deterministic state—properties that SMA cannot provide. Yet most engineers reach for SMA first because it appears in every statistics textbook. But for systems where determinism, bounded memory, and mathematical closure matter, SMA has fundamental problems that make it unsuitable. The Exponential Moving Average (EMA) isn't just an alternative—it's the only form that satisfies the contracts safety-critical systems require. This insight emerged from developing the Baseline module for [c-from-scratch](https://github.com/SpeyTech/c-from-scratch), an open-source educational project teaching deterministic C programming. The mathematical analysis has broader implications for anyone building monitoring systems in constrained environments. Definition: Exponential Moving Average An exponential moving average is a recursive filter that weights recent observations more heavily, requiring O(1) memory and bounded state for deterministic anomaly detection. ## The Hidden Assumptions of SMA A Simple Moving Average over N samples is defined as: ``` μₜ = (1/N) · Σ xₖ for k = t-N+1 to t ``` This looks clean on paper. In practice, it requires: - **A buffer of N previous values** — memory that grows with window size - **Knowledge of buffer fill state** — behaviour differs during startup - **Shifting operations** — oldest value must be removed as new value enters These aren't implementation details. They're fundamental properties that violate the contracts deterministic systems need. ## Five Properties That Matter For safety-critical monitoring, we need a system that is: 1. **Closed** — State at time t depends only on state at t-1 and current input 2. **Bounded** — Memory usage is O(1), independent of observation count 3. **Deterministic** — Same inputs always produce same outputs 4. **Spike-resistant** — No single input can corrupt the baseline 5. **Recoverable** — System can resume from any saved state Let's evaluate both approaches against these properties. Simple Moving Average Closure: ❌ Depends on N past samples Memory: ❌ Requires buffer of size N Determinism: ❌ Behaviour varies with buffer fill Spike resistance: ❌ One outlier corrupts N steps C-friendly: ❌ Requires shifting buffers Exponential Moving Average Closure: ✓ Depends only on μₜ₋₁ and xₜ Memory: ✓ O(1) — single value Determinism: ✓ Pure recurrence relation Spike resistance: ✓ Bounded influence per input C-friendly: ✓ One multiply + one add SMA fails on every property that matters. This isn't a matter of preference—it's a matter of mathematical suitability. ## The EMA Recurrence The Exponential Moving Average is defined as: ``` μₜ = α·xₜ + (1 − α)·μₜ₋₁ ``` Where 0 Design Property: Closure The state Sₜ = f(Sₜ₋₁, xₜ) is fully determined by the previous state and current observation. No external history is required. ## Implementation in Pure C The EMA update translates directly to C: ```c typedef struct { double mean; double variance; uint32_t count; baseline_state_t state; } baseline_t; void baseline_update(baseline_t *b, double x, double alpha) { double deviation = x - b->mean; b->mean = alpha * x + (1.0 - alpha) * b->mean; b->variance = alpha * (deviation * deviation) + (1.0 - alpha) * b->variance; b->count++; // State transition logic if (b->count >= MIN_SAMPLES && b->variance > EPSILON) { double sigma = sqrt(b->variance); double z = fabs(deviation) / sigma; b->state = (z > THRESHOLD) ? DEVIATION : STABLE; } } ``` No allocations. No buffers. No dependencies. Just arithmetic that a microcontroller can execute in microseconds. ## Practical Applications This pattern applies wherever you need anomaly detection with deterministic properties: **Embedded systems**: Heartbeat monitoring, sensor validation, watchdog triggers. Memory constraints make SMA impractical; EMA fits in registers. **DevOps/SRE**: Latency monitoring, error rate tracking, capacity planning. The bounded spike influence prevents alert storms from single bad measurements. **Financial systems**: Transaction monitoring, fraud detection. Deterministic behaviour supports audit requirements. **Medical devices**: Vital sign monitoring, dosage tracking. The mathematical properties support regulatory evidence for certification. ## Frequently Asked Questions ### Why is EMA better than SMA for safety-critical monitoring? EMA uses O(1) memory regardless of history length, while SMA requires O(N) storage for its sliding window. EMA's recency weighting responds faster to genuine changes while its bounded spike influence prevents single outliers from dominating the calculation. ### How do I choose the smoothing factor alpha for EMA in monitoring? Alpha controls the trade-off between responsiveness and stability. Smaller alpha (0.01–0.05) produces stable baselines resistant to noise, suitable for slow-changing metrics. Larger alpha (0.1–0.3) responds quickly to genuine changes, suitable for detecting rapid anomalies. Validate against historical data with known anomalies to calibrate the threshold. ### Why can't SMA be used on memory-constrained embedded systems? SMA requires storing the entire window of N previous values to compute the running average, consuming O(N) memory. On constrained embedded systems — pacemakers, sensor nodes, watchdog controllers — this memory is unavailable. EMA stores only the current average and alpha parameter, fitting in two registers regardless of monitoring duration. ### What are the limitations of EMA for anomaly detection? EMA cannot detect patterns within the history — only the current weighted average and its trend. It responds more slowly to gradual drift than windowed approaches. The choice of alpha is fixed at design time, creating a single trade-off between responsiveness and noise rejection that cannot adapt to changing conditions without external logic. ## Conclusion Simple Moving Average is a pedagogical tool—useful for explaining concepts, unsuitable for production systems where determinism matters. Exponential Moving Average provides the mathematical properties that safety-critical monitoring requires: closure, bounded memory, deterministic behaviour, spike resistance, and recoverability. These aren't incremental improvements; they're categorical differences that determine whether a system can be certified, verified, and trusted. The implementation is trivial. The mathematics is elegant. The properties are exactly what we need. For the complete derivation and working C implementation, see [c-from-scratch Module 2: Baseline](https://github.com/SpeyTech/c-from-scratch) on GitHub. Key Takeaway EMA isn't an optimisation of SMA—it's the only form that satisfies the contracts safety-critical systems require: closure, bounded memory, determinism, spike resistance, and recoverability. As with any architectural approach, suitability depends on system requirements and the specific monitoring context. EMA assumes that recent observations are more relevant than distant ones—an assumption that holds for most anomaly detection scenarios but should be validated for your use case. --- ## Semantic Security Monitoring in Deterministic Systems **URL**: https://speytech.com/insights/semantic-security-monitoring/ **Published**: January 07, 2026 **Topic**: Safety Engineering **Answers**: How does semantic security monitoring in deterministic computing systems differ fundamentally from traditional statistical threshold-based security detection approaches, and how can structured domain-aware observability combined with cryptographic audit trails actively support both real-time incident investigation and subsequent post-incident regulatory compliance? KEY_CLAIMS: - Note: This article discusses general principles of security observability in deterministic architectures. - Semantic security monitoring evaluates security events against structured domain-aware rules rather than statistical thresholds. - Statistical monitoring triggers alerts when metrics cross thresholds, generating false positives from benign anomalies and missing attacks that stay within thresholds. - Statistical monitors produce probabilistic confidence scores that vary with training data and model updates. - Semantic monitors may be less effective at identifying previously unknown attack patterns that do not match defined rules. EVIDENCE: - This distinction matters because regulatory frameworks like DO-178C, IEC 62304, and ISO 26262 increasingly emphasise end-to-end evidence chains. - Several certification frameworks include requirements that semantic monitoring may help address: DO-178C (aerospace software): Emphasises traceability from requirements through implementation to test evidence. - IEC 62304 (medical device software): Requires documented software development processes with defined inputs and outputs at each stage. - ISO 26262 (automotive functional safety): Addresses diagnostic coverage and fault detection capabilities. How structured observability can support incident investigation and regulatory compliance Note: This article discusses general principles of security observability in deterministic architectures. Actual implementation requirements depend on specific regulatory frameworks, threat models, and system context. The concepts presented here are indicative of architectural patterns rather than prescriptive specifications. ## The Observability Challenge in Safety-Critical Systems Traditional security monitoring tools are designed for environments where "good enough" detection suffices. They sample logs, use statistical thresholds, and accept a baseline of false positives as operational noise. For commercial web applications, this trade-off is reasonable. For safety-critical systems—medical devices, aerospace avionics, industrial control systems—this approach can introduce risks that may be difficult to quantify. When a monitoring system itself exhibits non-deterministic behaviour, investigators face a fundamental question: did the anomaly originate in the monitored system, or in the observer? This distinction matters because regulatory frameworks like DO-178C, IEC 62304, and ISO 26262 increasingly emphasise end-to-end evidence chains. A certification authority reviewing an incident wants to understand not just what happened, but how the monitoring infrastructure itself can be trusted to report accurately. ## Semantic vs. Statistical Approaches Statistical Monitoring Threshold-based anomaly detection Probabilistic alerting with tunable sensitivity Pattern matching against known signatures Sampling to manage data volumes Semantic Monitoring State-machine driven event classification Deterministic rule evaluation Relationship-aware context correlation Complete event capture with structured retention The distinction is not that one approach is inherently superior—each serves different requirements. Statistical methods can excel at identifying novel attack patterns through behavioural analysis. Semantic methods can provide the reproducibility that regulatory review processes often require. In this context, "semantic" means that monitoring decisions are derived from explicit system models—states, relationships, and transitions—rather than inferred statistically from aggregate behaviour. For systems where an auditor may need to reconstruct precisely why a particular alert fired (or failed to fire), semantic approaches offer certain advantages. The monitoring logic becomes auditable code rather than trained weights or adaptive thresholds. ## Determinism as a Design Constraint Design Property: Observational Reproducibility Given identical input sequences and initial state, a deterministic monitor is designed to produce identical output sequences—supporting independent verification of monitoring conclusions. This property has practical implications for incident response. When investigating a security event months or years after occurrence, teams can potentially replay the original log sequence through the monitoring logic and verify that current conclusions match historical alerts. The monitor's behaviour becomes a function of its inputs rather than hidden state accumulated over time. This approach may also simplify certain aspects of certification. Rather than arguing that a statistical model "usually" detects particular threat classes, teams can demonstrate specific input-output relationships through structured test suites. ## Architecture Patterns for Semantic Monitoring A semantic security monitor typically comprises several coordinated components: **Event Normalisation Layer**: Raw system events (authentication attempts, file operations, network connections, process lifecycle) are transformed into a canonical representation. This layer abstracts platform-specific formats while preserving semantic content. **Relationship Engine**: Events are correlated based on explicit relationships—user sessions, process trees, network flows. Rather than statistical co-occurrence, relationships are defined through deterministic rules that can be inspected and verified. **State Machine Evaluator**: Security policies are expressed as finite state machines with well-defined transitions. An event either triggers a transition or it does not—there is no probability attached to the evaluation. **Evidence Generator**: When policies trigger, the monitor produces structured evidence packages containing the event sequence, rule chain, and relevant context. These packages are designed to support both automated response and human investigation. An evidence package might include: - Canonicalised events E₁…Eₙ in the causal chain - The exact rule identifiers evaluated and their outcomes - The state transition path taken through the policy automaton - Timestamps with causal ordering constraints - Context snapshots (user session, process ancestry, network flow) This structure differs from traditional logging in a key respect: the evidence package is self-contained and reproducible. An auditor can verify the alert by replaying the event sequence through the same rule set—without access to the original system or surrounding log context. ``` Event Flow: Raw → Normalise → Correlate → Evaluate → Evidence Each stage: - Accepts defined input schema - Produces defined output schema - Maintains no hidden state between invocations - Can be tested in isolation ``` ## Integration with Deterministic Platforms When semantic monitoring runs atop a deterministic execution platform, additional properties may become available. Consider a medical device running on an architecture like MDCP (Multi-Domain Coordination Protocol). The platform's kernel-level determinism can mean that not only the monitoring logic, but the execution environment itself, exhibits reproducible behaviour. An investigator reviewing an incident has potential access to: - The exact sequence of system calls and their timing - Memory state at defined checkpoints - Inter-process communication patterns - Hardware interaction logs Combined with semantic monitoring, this creates what might be called "total system observability"—the ability to potentially reconstruct system behaviour with high fidelity rather than inferring it from sampled telemetry. For regulatory contexts, this level of observability may support more efficient certification processes. This does not eliminate the need for statistical testing or safety analysis, but can reduce ambiguity during incident review and compliance audits. Rather than extensive statistical testing to establish confidence intervals, teams can potentially complement probabilistic evidence with exhaustive analysis of the state space actually exercised. ## Practical Considerations Semantic monitoring is not without trade-offs: **Computational overhead**: Deterministic evaluation of every event can require more resources than sampling-based approaches. For high-throughput systems, this may necessitate careful capacity planning. **Rule maintenance**: Explicit policy rules must be maintained as threat landscapes evolve. This requires ongoing security engineering effort, though the rules themselves become auditable assets. **Novel threat detection**: Semantic monitors may be less effective at identifying previously unknown attack patterns that don't match defined rules. Defence-in-depth strategies often combine semantic monitoring with complementary statistical approaches. **Integration complexity**: Retrofitting semantic monitoring to existing systems can require significant architecture changes. Greenfield deployments may find adoption more straightforward. ## Regulatory Alignment Considerations Several certification frameworks include requirements that semantic monitoring may help address: **DO-178C** (aerospace software): Emphasises traceability from requirements through implementation to test evidence. Semantic monitors with deterministic rule evaluation can produce traceable evidence chains. **IEC 62304** (medical device software): Requires documented software development processes with defined inputs and outputs at each stage. Monitoring systems with explicit state machines can align with these process requirements. **ISO 26262** (automotive functional safety): Addresses diagnostic coverage and fault detection capabilities. Deterministic monitoring logic can support analysis of diagnostic coverage achievable under defined conditions. These frameworks do not mandate any particular monitoring approach. However, the emphasis on evidence, traceability, and reproducibility in modern safety standards may favour architectural patterns that exhibit these properties by design. ## Looking Forward As safety-critical systems become more connected and complex, the role of security monitoring in certification contexts is likely to grow. Regulatory bodies are increasingly interested in cybersecurity as a safety concern, not merely a commercial risk. Semantic monitoring represents one approach to addressing this convergence. By treating security observability as an engineering discipline with defined properties rather than a best-effort operational function, organisations may be better positioned to demonstrate compliance and investigate incidents effectively. The architectural investment required is non-trivial. For systems where regulatory approval timelines and incident investigation capabilities represent strategic concerns, that investment may yield returns through faster certification cycles and more defensible security postures. ## Frequently Asked Questions ### What is semantic security monitoring in deterministic systems? Semantic security monitoring evaluates security events against structured domain-aware rules rather than statistical thresholds. Each event is classified using explicit policy logic with cryptographic audit trails, enabling both real-time incident detection and post-incident forensic analysis with deterministic reproducibility. ### How does semantic monitoring differ from statistical threshold-based detection? Statistical monitoring triggers alerts when metrics cross thresholds, generating false positives from benign anomalies and missing attacks that stay within thresholds. Semantic monitoring evaluates event meaning against domain-specific rules, reducing false positives and detecting attacks that exploit the gap between threshold and intent. ### Why can't statistical security monitoring provide deterministic audit evidence? Statistical monitors produce probabilistic confidence scores that vary with training data and model updates. Semantic monitors with deterministic rule evaluation produce identical assessments for identical inputs, creating reproducible audit trails that support regulatory evidence requirements under DO-178C, IEC 62304, and ISO 26262. ### What are the limitations of semantic security monitoring? Semantic monitors may be less effective at identifying previously unknown attack patterns that do not match defined rules. Rule maintenance requires ongoing security engineering effort as threat landscapes evolve. Computational overhead from deterministic evaluation of every event can require more resources than sampling-based approaches in high-throughput systems. ## Further Reading - [MDCP Architecture Overview](/mdcp/) — Deterministic execution platform design - [C-Sentinel Project](/open-source/) — Open source semantic security monitor - [Certification Considerations for Connected Devices](/insights/) — Regulatory landscape analysis --- Semantic security monitoring treats observability as an engineering discipline. The architectural investment is non-trivial, but for systems where certification timelines and incident investigation capabilities are strategic concerns, structured observability may yield faster approval cycles. As with any architectural approach, suitability depends on system requirements, risk classification, and regulatory context. --- ## MDCP vs. Conventional RTOS **URL**: https://speytech.com/insights/mdcp-vs-conventional-rtos/ **Published**: January 5, 2026 **Topic**: Technical Comparison **Answers**: How does the Murray Deterministic Computing Platform compare both technically and economically against widely used conventional real-time operating systems like VxWorks, QNX Neutrino, and FreeRTOS for safety-critical applications that require provably deterministic execution, simplified certification evidence, and reduced verification cost? KEY_CLAIMS: - A detailed technical and economic comparison of the Murray Deterministic Computing Platform against industry-standard real-time operating systems including VxWorks, QNX Neutrino, and FreeRTOS. - MDCP uses tick-based deterministic scheduling where task execution order is fixed and reproducible, whereas conventional RTOS designs use preemptive priority-based scheduling with non-deterministic timing. - Choose MDCP when certification cost is a primary concern or when bit-perfect reproducibility is required across platforms. - Conventional RTOS kernels contain preemptive scheduling, dynamic memory, and interrupt-driven concurrency — each introducing non-deterministic paths that must be exhaustively tested for certification. - MDCP constrains development flexibility: tasks must fit within tick budgets, dynamic memory is not available, and scheduling is cooperative rather than preemptive. EVIDENCE: - The MDCP platform achieves a ~46KB kernel footprint compared to 100-200KB for conventional RTOS solutions. - This smaller codebase can translate into certification savings, given typical costs of ~$1,000-$2,000 per source line of code for DO-178C Level A certification. - Typical DO-178C Level A certification timelines may compress meaningfully when execution is reproducible. Side-by-side comparison of MDCP deterministic platform against VxWorks, QNX, FreeRTOS, and conventional real-time operating systems A detailed technical and economic comparison of the Murray Deterministic Computing Platform against industry-standard real-time operating systems including VxWorks, QNX Neutrino, and FreeRTOS. Note: Cost and timeline figures are indicative estimates based on publicly discussed certification programs and industry benchmarks; actual results vary by system scope, regulatory context, and organisational factors. ## Quick Comparison Summary | Feature | MDCP | VxWorks | QNX Neutrino | FreeRTOS | |---------|------|---------|--------------|----------| | **Deterministic Execution** | ✓ Native | Not natively supported | Not natively supported | Not natively supported | | **Multi-Core Determinism** | ✓ Lock-free | Lock-based | Lock-based | SMP limited | | **Deterministic Replay** | ✓ Byte-identical | Not supported by design | Not supported by design | Not supported by design | | **Kernel Size** | ~46KB | ~200KB | ~100KB | ~50KB (basic) | | **DO-178C Level A Cert Cost** | Indicative: $2-6M | Indicative: $15-30M | Indicative: $10-20M | Indicative: $5-10M | | **Avg Debug Cost (Heisenbug)** | Indicative: $1-4K | Indicative: $10-64K | Indicative: $10-64K | Indicative: $10-64K | | **Race Conditions** | Designed to eliminate | Possible | Possible | Possible | | **Runtime Safety Guardrails** | ✓ PBAS-6 native | Application layer | Application layer | Limited | ## Economic Impact Analysis ### Certification Cost Savings (Indicative Range) The MDCP platform achieves a ~46KB kernel footprint compared to 100-200KB for conventional RTOS solutions. This smaller codebase can translate into certification savings, given typical costs of ~$1,000-$2,000 per source line of code for DO-178C Level A certification. ### Substantial Debug Cost Reduction Potential Deterministic replay capability can materially improve Heisenbug debugging by enabling reproducible root cause analysis. Debug time can potentially drop from 48-190 hours to 5-14 hours per issue. For projects encountering significant timing-related bugs, this represents meaningful potential savings at scale. ### Reduced Time-to-Market Potential Determinism can accelerate the verification phase. Typical DO-178C Level A certification timelines may compress meaningfully when execution is reproducible. In competitive markets, this acceleration can represent material commercial impact in time-sensitive markets. ## Technical Deep Dive ### Deterministic Execution **MDCP Approach:** - Tick-based state transitions at discrete boundaries - Event-based architecture reduces shared memory dependencies - Deterministic scheduling engine (DSE) for core assignment - Cryptographic hashing supports verification of reproducible replay **Conventional RTOS Approach:** - Preemptive priority-based scheduling - Thread execution order depends on timing - Shared memory requires locks/mutexes - Identical inputs can produce different outputs The fundamental difference is architectural: MDCP is designed to produce reproducible, bit-identical results under defined conditions given identical initial state and input sequence. Conventional RTOS face challenges providing this level of reproducibility due to timing-dependent scheduling decisions. ### Multi-Core Coordination **MDCP Approach:** - Lock-free coordination via event ordering - No mutexes, spinlocks, or memory barriers required - Designed to scale efficiently to 8-16 cores - Designed to avoid deadlock and priority inversion risks inherent in lock-based designs **Conventional RTOS Approach:** - Heavy reliance on locks for coordination - Lock contention can degrade performance - Scaling challenges beyond 4-8 cores - Deadlock and priority inversion possible MDCP's MycoEco kernel is designed to achieve deterministic parallel execution without the synchronization primitives that introduce non-determinism in conventional systems. ### Debugging & Verification **MDCP Approach:** - Deterministic replay from execution traces - Reduced test cases needed per code path (deterministic coverage) - Bugs are designed to reproduce consistently under replay conditions - Root cause analysis potentially reduced to hours rather than days **Conventional RTOS Approach:** - Replay not possible (timing-dependent) - 10-100x test cases often needed for coverage - Heisenbugs can disappear when observed - Speculative debugging can take 48-190 hours This difference can fundamentally change the economics of safety-critical software development. When bugs reproduce reliably, debugging becomes engineering rather than archaeology. ## When to Choose MDCP ### Particularly Well-Suited For - Safety-critical systems targeting DO-178C, ISO 26262, or IEC 61508 certification - Applications where reproducibility is valuable (aerospace, medical, autonomous vehicles) - Multi-core systems benefiting from deterministic coordination - Programs where debugging cost and certification timeline are important constraints ### Consider Alternatives When - Legacy codebase with heavy POSIX dependencies - Non-safety-critical consumer applications (certification overhead may not be justified) - Existing vendor relationships with proprietary tool dependencies ## Frequently Asked Questions ### How does MDCP differ from conventional RTOS designs like VxWorks and QNX? MDCP uses tick-based deterministic scheduling where task execution order is fixed and reproducible, whereas conventional RTOS designs use preemptive priority-based scheduling with non-deterministic timing. MDCP eliminates race conditions, priority inversions, and scheduling-dependent behaviour by design rather than through defensive programming. ### When should I choose MDCP over a conventional RTOS? Choose MDCP when certification cost is a primary concern or when bit-perfect reproducibility is required across platforms. MDCP is designed for safety-critical systems where provable determinism reduces verification cost. ### Why can't conventional RTOS achieve the same certification cost as MDCP? Conventional RTOS kernels contain preemptive scheduling, dynamic memory, and interrupt-driven concurrency — each introducing non-deterministic paths that must be exhaustively tested for certification. MDCP eliminates these paths architecturally, reducing the verification surface area by orders of magnitude compared to testing all timing permutations. ### What are the limitations of MDCP compared to conventional RTOS? MDCP constrains development flexibility: tasks must fit within tick budgets, dynamic memory is not available, and scheduling is cooperative rather than preemptive. Real-time responsiveness is bounded by tick duration. Some workloads with highly variable execution times may require architectural adaptation to fit the deterministic model. ## Next Steps Ready to see deterministic execution in action? Explore our interactive tick scheduler demo or dive deeper into the mathematics of deterministic scheduling. For detailed technical specifications and validation data, request access to the full technical brief under NDA. --- ## NVIDIA ASIL-B to ASIL-D: The Determinism Question **URL**: https://speytech.com/insights/nvidia-asil-determinism/ **Published**: December 24, 2025 **Topic**: Autonomous Systems **Answers**: What does NVIDIA's achievement of ASIL-B Linux kernel certification mean for the autonomous vehicle industry, and what additional architectural considerations specifically around deterministic execution and temporal isolation are needed to progress from ASIL-B to ASIL-D for Level 4 and Level 5 autonomy? KEY_CLAIMS: - On December 23, 2025, NVIDIA announced a significant milestone: portions of their Linux kernel work have achieved ASIL-B certification for automotive safety-critical systems. - Multiple architectural approaches serve different automotive safety levels. - NVIDIA's ASIL-B certification validates the Linux kernel for automotive safety applications up to the second-highest integrity level. - ASIL-D requires higher diagnostic coverage, stricter fault tolerance, and deterministic execution guarantees beyond what general-purpose operating systems typically provide. - General-purpose kernels contain millions of lines of code with non-deterministic scheduling, exceeding practical ASIL-D verification scope. EVIDENCE: - On December 23, 2025, NVIDIA announced a significant milestone: portions of their Linux kernel work have achieved ASIL-B certification for automotive safety-critical systems. - Tick-Based Scheduling All decisions occur at discrete tick boundaries (typically 1ms). NVIDIA's achievement is impressive — and it clarifies the architectural considerations for Level 4/5 autonomy On December 23, 2025, NVIDIA announced a significant milestone: portions of their Linux kernel work have achieved ASIL-B certification for automotive safety-critical systems. This represents years of engineering effort and positions NVIDIA as a serious player in the autonomous vehicle market. This achievement also clarifies an important industry question: **what architectural approaches best support ASIL-D certification for Level 4/5 autonomous vehicles?** ## NVIDIA's Achievement: Context and Significance NVIDIA's ASIL-B certification covers specific Linux kernel components used in their DRIVE automotive computing platform. This is genuinely impressive work—certifying *any* portion of the Linux kernel to automotive safety standards requires extraordinary discipline. The certification likely covers: - Memory management subsystems - Scheduling components - Device drivers for automotive peripherals - Real-time extensions (PREEMPT_RT patches) - Safety monitoring frameworks **Why this matters:** The automotive industry is standardizing on Linux for infotainment, instrument clusters, and increasingly for ADAS (Advanced Driver Assistance Systems). NVIDIA's certification demonstrates that Linux *can* meet automotive safety requirements—at least at ASIL-B. ## The ASIL Hierarchy: What Separates B from D ISO 26262 defines four ASIL (Automotive Safety Integrity Level) classifications: **ASIL-A:** Low injury risk (e.g., rear lighting systems) **ASIL-B:** Medium injury risk (e.g., brake lights, ADAS warnings) **ASIL-C:** High injury risk (e.g., airbag deployment, ABS) **ASIL-D:** Highest injury risk (e.g., steering, braking, full autonomy) The jump from ASIL-B to ASIL-D represents a substantial increase in certification rigour: # ASIL Certification Requirements Comparison ASIL-B Requirements: ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ - Software unit testing: 80%+ coverage - Integration testing: Functional coverage - Hazard analysis: Moderate rigor - Documentation: Comprehensive - Verification: Independent review - Estimated cost: Indicative £10-20M ASIL-D Requirements: ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ - Software unit testing: 100% coverage - Integration testing: 100% MC/DC coverage - Hazard analysis: Exhaustive FMEA - Documentation: Complete traceability - Verification: Independent V&V team - Formal methods: Recommended for critical paths - Hardware/software co-verification - Estimated cost: Indicative £30-80M+ **The key consideration:** ASIL-D places strong emphasis on **provable correctness** and exhaustive failure mode analysis. For large, general-purpose systems, meeting these requirements introduces substantial technical and economic challenges. ## Architectural Considerations for ASIL-D General-purpose operating systems like Linux are optimised for throughput, flexibility, and broad hardware support. These design goals can create challenges when targeting ASIL-D certification: ### 1. Scheduling Determinism Linux's Completely Fair Scheduler (CFS) is designed for throughput and fairness, not determinism. Scheduling decisions depend on: - System load (variable) - Priority inheritance (complex state) - CPU affinity masks (runtime configuration) - Interrupt latency (hardware-dependent) **Consideration:** Bounding worst-case execution time (WCET) can be challenging in systems with timing-dependent scheduling. ### 2. Concurrency and Synchronisation Large kernels typically manage concurrency through synchronisation primitives. Even with PREEMPT_RT patches: - Spinlocks introduce timing variability - RCU (Read-Copy-Update) has variable grace periods - Memory allocation timing varies with system state - IRQ handling introduces timing variability **Consideration:** Guaranteeing identical execution sequences across all operating conditions becomes difficult to demonstrate. ### 3. Code Size and Certification Scope The Linux kernel exceeds 30 million lines of code. ASIL-D encourages: - High code coverage in testing - Formal verification of critical paths - Complete traceability from requirements to implementation - Exhaustive hazard analysis **Consideration:** Certification cost and timeline scale with codebase size and complexity. ## Why ASIL-D Matters for Autonomous Vehicles Level 4/5 autonomous vehicles make safety-critical decisions: - Emergency braking at highway speeds - Lane changes in dense traffic - Navigation through pedestrian-heavy areas - Fail-safe transitions when sensors fail **These functions typically require ASIL-D certification.** Regulators worldwide (NHTSA, UNECE, China's MIIT) are increasingly examining these requirements. Understanding the architectural implications early can help inform design decisions. Note: Cost, timeline, and regulatory outcomes discussed in this article are indicative estimates based on public industry discussions and certification programs. Actual results vary significantly by system architecture, deployment scope, and regulatory jurisdiction. ## The Deterministic Execution Approach Deterministic kernels take a different architectural approach: **reproducibility by design**. ### Architecture Comparison General-Purpose Kernel (e.g., Linux with PREEMPT_RT) Large codebase (30M+ lines) Throughput-optimised scheduler Relies on runtime synchronisation WCET: Challenging to bound precisely Replay: Difficult due to timing dependencies Well-suited for: ASIL-A/B applications Deterministic Kernel (e.g., MDCP) Minimal codebase (~46KB) Tick-based deterministic execution Designed to avoid race conditions by construction WCET: Amenable to static analysis Replay: Supported by design Designed for: ASIL-D certification pathways ### How Deterministic Execution Supports ASIL-D **1. Tick-Based Scheduling** All decisions occur at discrete tick boundaries (typically 1ms). Given identical inputs and initial state, execution is designed to produce identical outputs. **2. Concurrency Model** Single-threaded execution per tick reduces the synchronisation complexity that can make exhaustive analysis difficult. **3. Replay Capability** Given initial state Σ₀ and event sequence E₁..Eₙ, final state Σₙ is designed to be reproducible: ``` Replay(Σ₀, E₁..Eₙ) → Σₙ (reproducible under defined conditions) ``` This can support: - Systematic testing of failure scenarios - Post-incident reconstruction - Formal verification of safety properties - Stronger evidence for regulatory review **4. WCET Analysis** Deterministic execution models are generally more amenable to static analysis for computing worst-case execution time bounds. ## Comparative Economics Note: The following cost estimates are indicative and based on publicly discussed certification programs. Actual costs depend heavily on system scope, existing infrastructure, and regulatory context. # Autonomous Vehicle Program: Indicative Cost Factors GENERAL-PURPOSE KERNEL APPROACH: ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ASIL-B certification: £15-30M (indicative) ASIL-D extension: Substantial additional investment Timeline: Multi-year effort Post-deployment considerations: - Incident investigation complexity (timing-dependent) - Regulatory review cycles - Insurance and liability factors DETERMINISTIC KERNEL APPROACH: ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ASIL-D certification: Potentially £2-6M (indicative) Timeline: Potentially 12-24 months Post-deployment considerations: - Incident investigation (replay-assisted) - Regulatory review (reproducibility evidence) - Insurance (demonstrable safety properties) Different architectures present different cost/benefit profiles depending on safety requirements and deployment context. ## Complementary Architectures NVIDIA's ASIL-B Linux kernel and deterministic kernels like MDCP can be complementary technologies for different safety tiers: **Linux (ASIL-B):** - Infotainment systems - HMI (Human-Machine Interface) - ADAS Level 2/3 features - Navigation and connectivity - Cost-effective for general computing workloads **Deterministic Kernels (ASIL-D pathway):** - Autonomous driving controller - Steering and braking actuation - Sensor fusion and decision-making - Safety monitoring and failsafe - Designed for Level 4/5 autonomy requirements A combined architecture might leverage both: - Linux handles rich UI and connectivity - Deterministic kernel handles safety-critical control - Hypervisor ensures isolation - Combined solution addresses different regulatory tiers ## The Path Forward NVIDIA's work validates that Linux can meet automotive safety standards at ASIL-B. This is valuable for the significant portion of automotive software that operates at this safety level. For functions that require ASIL-D—the code that makes safety-critical decisions—**deterministic execution models offer architectural advantages** that can simplify the path to certification. The reproducibility, traceability, and bounded execution characteristics align well with ASIL-D requirements. **NVIDIA's achievement moves the industry forward.** It clarifies where general-purpose kernels excel and where alternative architectures may offer advantages for the highest safety levels. ## Frequently Asked Questions ### What does NVIDIA's ASIL-B Linux kernel certification mean for autonomous vehicles? NVIDIA's ASIL-B certification validates the Linux kernel for automotive safety applications up to the second-highest integrity level. This enables Linux-based software stacks for infotainment, telemetry, and non-critical perception tasks in production vehicles while establishing a compliance baseline the industry can build upon. ### How do you progress from ASIL-B to ASIL-D for autonomous driving? ASIL-D requires higher diagnostic coverage, stricter fault tolerance, and deterministic execution guarantees beyond what general-purpose operating systems typically provide. Complementary architectures using deterministic kernels for the highest-criticality functions alongside Linux for lower-criticality tasks can address the gap through architectural partitioning. ### Why can't a general-purpose OS kernel achieve ASIL-D certification? General-purpose kernels contain millions of lines of code with non-deterministic scheduling, exceeding practical ASIL-D verification scope. The architecture prioritises flexibility and performance over the deterministic guarantees ASIL-D demands. ### What are the limitations of partitioned ASIL-B and ASIL-D architectures? Partitioned architectures require strict isolation between safety levels, adding integration complexity and communication overhead. The hypervisor or partitioning layer itself must be certified to the highest level. Inter-partition communication latency may affect real-time performance for time-critical control functions. ## Conclusion Multiple architectural approaches serve different automotive safety levels. - **NVIDIA's ASIL-B Linux work** demonstrates that general-purpose kernels can meet automotive safety standards and provides a strong foundation for ADAS and infotainment. - **Deterministic execution platforms** offer architectural characteristics that can simplify ASIL-D certification for safety-critical autonomous functions. These approaches are complementary. The organisations that understand where each architecture fits best will be well-positioned as the industry evolves toward higher levels of autonomy. The technology landscape is maturing. The architectural choices made today will shape the certification outcomes of tomorrow. --- ## Cryptographic Execution Tracing and Evidentiary Integrity **URL**: https://speytech.com/insights/cryptographic-proof-execution/ **Published**: December 23, 2025 **Topic**: Deterministic Computing **Answers**: How can cryptographic execution tracing using hash chains and tamper-evident sealed audit logs strengthen post-incident forensic analysis in safety-critical software systems where regulatory and legal proceedings require provable evidence, and what role does deterministic execution play in preserving evidentiary integrity? **Defines**: Cryptographic execution tracing KEY_CLAIMS: - Note: The following discussion references publicly reported incidents to illustrate investigation challenges. - Cryptographic execution tracing strengthens post-incident analysis for safety-critical software. - Cryptographic execution tracing records each computation step as a hash-chained entry in a tamper-evident audit log. - Conventional logs record events but cannot prove completeness or detect tampering. - Traditional logs lack tamper-evidence — entries can be modified, deleted, or inserted without detection. EVIDENCE: - Spacecraft anomalies: The NASA Mars Climate Orbiter loss in 1999 involved a units conversion issue. - The practical impact depends on tracing granularity — per-tick tracing in a 1ms tick system adds less than 0.1% overhead, while per-instruction tracing would be prohibitive. How deterministic systems with cryptographic sealing can strengthen post-incident analysis Note: The following discussion references publicly reported incidents to illustrate investigation challenges. These are complex events with multiple contributing factors; the intent is to explore how execution traceability relates to post-incident analysis, not to assign causation. Safety-critical software failures expose a fundamental forensic challenge: reconstructing exactly what the software did before an incident. Conventional logging captures fragments, but cryptographic execution tracing can provide tamper-evident, verifiable records of every state transition. Flight data recorders capture sensor readings and control surface positions. System logs record events and state changes. But the internal software state—variable values, conditional branches taken, the exact sequence of function calls—may not be fully captured. This can lead to extended investigation timelines as engineers attempt to reconstruct probable execution paths through simulation and analysis. This is an evidentiary challenge that affects many domains: when software-controlled systems fail in safety-critical contexts, the ability to provide strong evidence of execution history can significantly influence investigation timelines, liability discussions, and regulatory outcomes. ## Investigation Challenges in Safety-Critical Failures Several well-documented cases illustrate how execution uncertainty can extend investigation complexity: **Aviation incidents**: Major aviation investigations have highlighted the challenge of reconstructing software decision sequences from flight data alone. When internal software state isn't fully captured, investigators may rely on simulation and code analysis to develop probable execution scenarios, a process that can extend timelines and leave some questions unresolved. **Spacecraft anomalies**: The NASA Mars Climate Orbiter loss in 1999 involved a units conversion issue. Post-failure analysis required reconstructing the exact sequence of calculations that led to the trajectory error. Without complete execution traces, investigators relied on software inspection and simulation to develop their findings. **Medical device investigations**: Software-related medical device issues can be challenging to investigate when failures cannot be reliably reproduced. This has contributed to situations where broader product actions are taken when specific root causes are difficult to isolate. In cases like these, limited execution traceability has been associated with: - **Extended investigation timelines** - **Increased uncertainty in root cause determination** - **Broader regulatory responses** when specific failures are difficult to isolate - **Prolonged liability discussions** when technical evidence is ambiguous ## Limitations of Traditional Logging Conventional system logs can have limitations for post-incident analysis: ### 1. Selective Capture Traditional logging captures selected events—function calls, state changes, error conditions—but typically not complete execution state. The gaps between logged events can leave room for uncertainty about intermediate computations. A typical system log might record: ``` [timestamp] Sensor reading: 74.5° [timestamp] Command issued: -2.5° ``` But what happened between these events? Which conditional branches were taken? What were the intermediate calculations? Without complete state capture, reconstruction may require inference. ### 2. Integrity Considerations Log files are typically mutable. In adversarial contexts or when system corruption occurs, questions about log integrity can complicate analysis. ### 3. Timing Dependencies In systems with race conditions or timing dependencies, similar log entries might correspond to different execution paths. Traditional logs may not capture the scheduler state, interrupt timing, or memory ordering that influenced which path was actually taken. ### 4. Storage Trade-offs High-fidelity logging of complete execution state would generate substantial data volumes. Practical systems log selectively, but every omission is a potential gap in the evidentiary record. ## Cryptographic Hash Chains: Strengthening Execution Evidence Deterministic execution combined with cryptographic hash chaining offers an approach to address some of these limitations. The core concept: **deterministic execution + hash chaining = tamper-evident execution traces**. ### How It Works At each tick boundary, a cryptographic hash is computed from the complete system state: ``` State(t₀) → hash₀ = SHA-256(State(t₀)) State(t₁) → hash₁ = SHA-256(State(t₁) || hash₀) State(t₂) → hash₂ = SHA-256(State(t₂) || hash₁) ... State(tₙ) → hashₙ = SHA-256(State(tₙ) || hashₙ₋₁) ``` Each hash is computed from: 1. **Current state**: Memory, registers, program counter 2. **Previous hash**: Cryptographically linking to prior history 3. **Input events**: Any external inputs received at this tick The resulting hash chain has an important property: **modification to any state in the chain is designed to invalidate subsequent hashes during verification**, making tampering detectable. ### Cryptographic Assurance The strength of this approach relies on the collision resistance properties of SHA-256. Under widely accepted cryptographic assumptions, finding a modified state that produces the same hash is computationally infeasible with current technology. This provides strong evidence of execution integrity, though like all cryptographic systems, it operates within the bounds of current threat models and implementation correctness. ## MDCK: Deterministic Cryptography Kernel MDCP's MDCK (Murray Deterministic Cryptography Kernel) implements cryptographic sealing with several design considerations: ### Bounded Computation Cryptographic operations are designed to complete within deterministic time bounds. MDCK uses constant-time implementations of SHA-256 that execute in consistent clock cycles regardless of input data, preserving determinism while providing cryptographic capabilities. ### Incremental Hashing Rather than hashing the entire system state at each tick, MDCK uses incremental approaches: - **State delta compression**: Only changed memory regions are hashed - **Merkle tree structure**: Large states are organized as Merkle trees, allowing partial updates - **Rolling hashes**: Efficient recomputation when small portions of state change This can reduce the computational overhead of cryptographic sealing, making it more practical for embedded systems. ### Storage Optimisation Complete execution traces can be large. MDCK provides configurable retention: - **Safety-critical sections**: Full trace retention with intermediate states - **Non-critical sections**: Periodic checkpoints with hash chains between checkpoints - **Post-incident**: Automatic extraction and archival of relevant execution windows Design Property: Tamper Detection Given a cryptographically sealed execution trace (State₀, hash₀), ..., (Stateₙ, hashₙ), modification to any Stateᵢ is designed to be detectable by recomputing the hash chain and comparing with the stored hashₙ, under standard cryptographic assumptions. ## Potential Evidentiary Implications Cryptographically sealed execution traces may influence post-incident analysis in several ways: ### Evidentiary Considerations Cryptographic evidence is increasingly recognised in various legal and regulatory contexts. The specific admissibility and weight given to such evidence depends on jurisdiction, chain-of-custody documentation, and other factors. However, tamper-evident execution traces may provide stronger evidentiary foundations than traditional logs in some contexts. ### Analysis Efficiency With cryptographically sealed traces: - **Reconstruction may be simplified**: Execution traces can provide direct evidence rather than requiring simulation-based reconstruction - **Ambiguity may be reduced**: State transitions are documented rather than inferred - **Focus can shift**: Technical analysis can focus on understanding behaviour rather than establishing what happened ### Risk Management Considerations Insurance and regulatory bodies may view systems with stronger execution traceability favourably, though specific implications depend on context: Traditional Logging Investigation may require extensive reconstruction Ambiguity can extend liability discussions Root cause isolation can be challenging Broader product actions may be needed when issues are hard to isolate Cryptographic Execution Tracing Execution history can be verified directly Stronger evidence may support faster resolution Specific failure modes may be more readily identifiable Targeted responses may be possible when root cause is clear Note: Legal, insurance, and regulatory outcomes depend on many factors beyond execution traceability. The implications discussed here are illustrative of potential benefits rather than guaranteed outcomes. ## Illustrative Applications ### Aerospace **Scenario**: Engine control software detects an anomaly and reduces thrust. Was this correct behaviour given sensor inputs? **With traditional logging**: Investigation may require simulation and analysis to reconstruct the decision process, with potential for differing expert interpretations. **With cryptographic execution tracing**: Hash chain can verify that given specific sensor inputs, the control law computed the recorded output. The execution path is documented rather than reconstructed. ### Medical Devices **Scenario**: A medical device delivers an unexpected output. Was this configuration error, hardware fault, or software behaviour? **With traditional logging**: Device logs may show commands but not the complete decision process. Broader product actions may be taken when specific root cause is uncertain. **With cryptographic execution tracing**: Execution trace can show sensor readings, algorithm computations, and output commands, potentially enabling more targeted root cause identification. ### Autonomous Systems **Scenario**: An autonomous system fails to respond as expected. Which subsystem was responsible? **With traditional logging**: Multiple failure modes might explain the outcome, requiring extensive analysis to narrow possibilities. **With cryptographic execution tracing**: Hash chain can document the state of each subsystem, potentially enabling faster isolation of the specific failure point. ## Performance Considerations The overhead of cryptographic sealing can be modest with appropriate implementation: **Computational cost**: SHA-256 hashing at 1000 ticks/second adds approximately 2-3% CPU overhead on modern embedded processors (measured in internal testing on ARM Cortex-A53; actual overhead varies by hardware and configuration). **Storage cost**: With delta compression and Merkle trees, execution traces can be compressed significantly. Specific storage requirements depend on system complexity and retention policy. **Determinism preservation**: Constant-time cryptographic implementations are designed to avoid introducing timing variability that could affect deterministic replay. ## Frequently Asked Questions ### What is cryptographic execution tracing? Cryptographic execution tracing records each computation step as a hash-chained entry in a tamper-evident audit log. Each hash depends on the previous hash, creating a chain where any modification to historical entries invalidates all subsequent hashes, providing mathematical evidence of execution integrity. ### How does cryptographic tracing differ from conventional logging? Conventional logs record events but cannot prove completeness or detect tampering. Cryptographic hash chains make any gap, insertion, or modification mathematically detectable. The chain also proves execution order, whereas conventional logs only record timestamps that can be manipulated or drift across systems. ### Why can't traditional logging provide legally defensible execution evidence? Traditional logs lack tamper-evidence — entries can be modified, deleted, or inserted without detection. In legal and regulatory proceedings, the opposing party can challenge log integrity. Cryptographic hash chains provide mathematical proof that the recorded execution sequence has not been altered since creation. ### What are the performance costs of cryptographic execution tracing? Hash computation adds overhead per traced operation, typically microseconds for SHA-256 on modern hardware. The practical impact depends on tracing granularity — per-tick tracing in a 1ms tick system adds less than 0.1% overhead, while per-instruction tracing would be prohibitive. Storage costs scale linearly with trace length. ## Conclusion Cryptographic execution tracing strengthens post-incident analysis for safety-critical software. The ability to provide tamper-evident evidence of exact execution paths becomes increasingly valuable as software controls more critical systems. Cryptographic execution tracing represents one architectural approach that can strengthen post-incident analysis: - **From reconstruction to verification**: Execution traces can be checked rather than reconstructed - **From inference to evidence**: State transitions are documented rather than inferred - **From ambiguity to clarity**: Specific execution paths can be identified rather than debated This approach does not eliminate all uncertainty, nor is it appropriate for every system. The value depends on the risk profile, regulatory context, and investigation requirements of specific applications. For safety-critical systems where post-incident clarity matters, deterministic execution with cryptographic sealing offers an architectural approach that can materially strengthen evidentiary support and enable more efficient investigation processes. As with any architectural approach, suitability depends on system requirements, risk classification, and the specific regulatory and legal context in which the system operates. --- ## Reproducibility and the Economics of Debugging **URL**: https://speytech.com/insights/debugging-economics/ **Published**: December 23, 2025 **Topic**: Engineering Economics **Answers**: What is the financial and schedule impact of non-deterministic software bugs on engineering programmes, how does the inability to reliably reproduce failures like race conditions and Heisenbugs amplify debugging costs, and what does the Ariane 5 disaster teach about reproducibility economics? KEY_CLAIMS: - On June 4, 1996, the Ariane 5 rocket—Europe's flagship launch vehicle—exploded 37 seconds after liftoff. - The accumulated evidence suggests that reproducibility can significantly alter the cost structure of debugging in complex systems. - Non-reproducible bugs like race conditions and Heisenbugs can consume orders of magnitude more engineering time than deterministic defects. - Deterministic execution makes every failure reproducible by definition — given the same inputs, the system produces the same behaviour. - Logging and monitoring capture symptoms after the fact but cannot reproduce the execution path that caused the failure. EVIDENCE: - On June 4, 1996, the Ariane 5 rocket—Europe's flagship launch vehicle—exploded 37 seconds after liftoff. - The cause: a software bug that had existed in the Ariane 4 codebase for years but only manifested under Ariane 5's different flight profile. - The bug was a 64-bit floating point number being converted to a 16-bit signed integer without proper range checking. - Under Ariane 5's faster acceleration, it did. How non-deterministic execution can amplify engineering cost and schedule risk On June 4, 1996, the Ariane 5 rocket—Europe's flagship launch vehicle—exploded 37 seconds after liftoff. The $370 million rocket and its $500 million payload were destroyed. The cause: a software bug that had existed in the Ariane 4 codebase for years but only manifested under Ariane 5's different flight profile. The bug was a 64-bit floating point number being converted to a 16-bit signed integer without proper range checking. Under Ariane 4's trajectory, the value never exceeded the integer's range. Under Ariane 5's faster acceleration, it did. The overflow triggered an exception, which propagated through backup systems, causing total flight control failure. Here's the economics puzzle: **Why wasn't this caught in testing?** Because it was difficult to reproduce in the test environment. The exact timing, sensor values, and flight profile that triggered the bug didn't occur during ground testing. Engineers ran thousands of simulations. The bug never manifested. Until it did—catastrophically—during the first production flight. This illustrates a recurring pattern in complex systems: **bugs that are difficult to reproduce often incur disproportionately higher investigation and resolution costs**. ## The Cost Structure of Non-Reproducible Bugs Industry surveys suggest that software debugging consumes 35-50% of total development time. For safety-critical systems, it can exceed 60%. But not all debugging effort is equal. ### Reproducible Bugs: The Baseline A reproducible bug follows a relatively predictable cost curve: 1. **Detection** (1-2 hours): Bug report filed with reproduction steps 2. **Localization** (2-8 hours): Engineer traces execution to identify root cause 3. **Fix** (2-4 hours): Code change to address root cause 4. **Verification** (2-4 hours): Test that fix resolves the issue 5. **Total: 7-18 hours** at $200-300/hour fully loaded = **$1,400-$5,400 per bug** (indicative) This is manageable. The engineer has a clear path: reproduce the bug, inspect state, identify the fault, fix it, verify the fix works. ### Non-Reproducible Bugs: The Cost Amplifier A Heisenbug—a bug that disappears when you try to observe it—has a markedly different cost profile: 1. **Detection** (1-2 hours): Bug report filed, often with incomplete reproduction steps 2. **Attempted reproduction** (8-40 hours): Engineers try to recreate conditions that trigger the bug 3. **Speculative debugging** (20-80 hours): Without reproduction, engineers add logging, insert breakpoints, modify code—each change potentially altering the timing that caused the bug 4. **Exploratory fixes** (10-40 hours): Engineers implement fixes based on hypothesis, which may or may not address the root cause 5. **Regression testing** (10-30 hours): After each exploratory fix, extensive testing to check if the bug reappears 6. **Escalation** (5-20 hours): Senior engineers or external consultants brought in when initial attempts fail 7. **Total: 54-212 hours** = **$10,800-$63,600 per bug** (indicative) **Observed cost impact:** Frequently several-fold higher than comparable reproducible defects. And this assumes the bug is eventually fixed. In practice: - A significant percentage of Heisenbugs are never definitively resolved; teams implement workarounds or accept residual risk - Many "fixes" address symptoms rather than root causes, potentially leading to related issues later - Some bugs recur in production despite being marked "fixed" in development Note: Cost figures throughout this article are indicative estimates based on published industry discussions and engineering surveys. Actual costs vary significantly by organisation, system complexity, and development context. ### The Opportunity Cost Beyond direct engineering hours, non-reproducible bugs can impose opportunity costs: **Delayed features**: Engineers debugging may not be available for new capabilities. Extended debugging efforts can delay feature delivery. **Schedule risk**: Non-reproducible bugs create uncertainty. Programs may add schedule margin to account for debugging overruns, potentially delaying market entry. **Team dynamics**: Hunting Heisenbugs can be frustrating. Engineers may spend extended periods on low-progress work, which can affect productivity. **Technical debt**: Exploratory fixes often add code complexity. Workarounds for non-reproducible bugs can accumulate, making the codebase harder to maintain. ## Why Non-Determinism Can Amplify Debug Cost Non-reproducible bugs are expensive because **reproducibility is a foundational requirement for applying hypothesis-driven debugging methods reliably**. ### The Scientific Method and Reproduction Effective debugging typically follows hypothesis-driven investigation: 1. **Reproduce** the failure 2. **Hypothesize** a cause 3. **Test** the hypothesis (add instrumentation, modify code) 4. **Verify** the fix resolves the issue Each step benefits from reproduction. Without it: - Verifying hypotheses becomes difficult - Testing whether fixes work becomes uncertain - Distinguishing signal from noise becomes challenging Engineers may resort to: - **Code inspection**: Reading thousands of lines hoping to spot the bug - **Broad debugging**: Making multiple changes simultaneously, hoping one helps - **Heuristic fixes**: "This pattern often causes problems, so let's change it" None of these approaches provide high confidence. The bug might be fixed. Or it might manifest differently. Or it might still exist but not have occurred in recent tests. ### Race Conditions: A Common Challenge Race conditions—bugs caused by timing-dependent execution order—are among the most common and challenging Heisenbugs. Example: Two threads access shared memory without proper synchronization. Thread A reads a value. Thread B modifies it. Thread A uses the now-stale value. Depending on scheduler timing, this can cause: - Corrupted data structures - Incorrect calculations - System crashes - Security vulnerabilities In development, engineers run the code thousands of times. It usually works. Occasionally it fails—but when they add logging to diagnose the failure, the logging changes timing and the bug may disappear. The Heisenberg principle in action: observation can alter the phenomenon. ## A Deterministic Replay Approach Deterministic execution addresses the reproduction challenge directly. Given identical initial state and input sequence, execution is designed to be reproducible. Bugs are less likely to disappear when observed. They can reproduce more consistently. ### How Replay Works 1. **Checkpoint** system state at tick boundaries 2. **Record** all external inputs (sensor data, user commands, network packets) 3. **On failure**, save checkpoint + input sequence 4. **Replay** from checkpoint with identical inputs → designed to produce identical execution → same failure Engineers gain reproducibility: - Bug can manifest consistently on replay - Can add detailed logging without altering execution timing - Can step through code with debugger without timing changes - Can verify fixes more confidently—if replay no longer fails, evidence that bug is addressed ### The Potential Cost Impact Deterministic replay can change debugging economics: Traditional Debugging (Non-Reproducible Bug) Attempted reproduction: 8-40 hours Speculative debugging: 20-80 hours Exploratory fixes: 10-40 hours Regression testing: 10-30 hours Total: 48-190 hours (indicative) Deterministic Replay Approach Reproduction: Near-instant (replay from checkpoint) Root cause analysis: 2-8 hours Fix implementation: 2-4 hours Verification: 1-2 hours (replay confirms fix) Total: 5-14 hours (indicative) **Indicative per-bug impact:** Often an order-of-magnitude reduction in engineering effort when replay is available, based on reported case studies. ## Illustrative Case Studies The following scenarios illustrate how reproducibility can affect debugging economics in different domains. ### Case Study 1: Autonomous Vehicle Perception **Scenario**: Perception system occasionally misclassifies objects. Bug occurs infrequently during testing. Safety-relevant—requires investigation before production. **Traditional debugging approach**: - Extensive test driving attempting to trigger the bug - Code inspection and hypothesis testing - Multiple exploratory fixes - Additional regression testing - **Significant engineering investment with residual uncertainty** **Deterministic replay approach**: - Capture sensor data and system state when bug occurs - Replay from checkpoint → bug reproduces consistently - Root cause identified: floating point precision issue under specific conditions - Fix implemented and verified through replay - **Substantially reduced investigation time with higher confidence in fix** ### Case Study 2: Medical Device Firmware **Scenario**: Medical device occasionally exhibits unexpected behaviour. Occurs rarely. Requires investigation for regulatory approval. **Traditional debugging**: - Extensive simulation and physical testing to reproduce - Analysis of interrupt handling and timing - Multiple exploratory fixes with safety testing after each - Additional documentation for regulatory review due to uncertainty - **Extended timeline with residual concerns** **Deterministic replay**: - Record execution state when issue occurs - Replay in lab → reproduces consistently - Root cause identified: timing-dependent interrupt handling - Fix verified through extensive replay testing - **Reduced investigation time with stronger evidence for regulatory review** ### Case Study 3: Avionics System **Scenario**: Flight control system experiences transient fault. Occurred once in extensive flight hours. Requires investigation. **Traditional debugging**: - Extensive simulation and hardware-in-loop testing - Analysis of sensor fusion and control algorithms - Multiple firmware revisions with flight testing - Extended regulatory review due to uncertainty - **Substantial cost and schedule impact** **Deterministic replay**: - Flight data recorder captured execution trace - Replay in lab → fault reproduces - Root cause identified: sensor data timing dependency - Fix verified through extensive scenario replay - Potentially accelerated regulatory review due to reproducible evidence - **Reduced overall investigation and certification timeline** ## Schedule and Time-to-Market Considerations Beyond direct debugging costs, non-reproducible bugs can affect product schedules. ### Schedule Uncertainty A single Heisenbug can introduce schedule uncertainty: 1. **Discovery timing**: Heisenbugs often appear during integration or system testing when multiple components interact—close to scheduled release. 2. **Unpredictable resolution**: Teams may struggle to estimate how long a Heisenbug will take to resolve. Schedule risk compounds. 3. **Regression considerations**: Each exploratory fix might require extensive re-testing, adding time to the schedule. 4. **Certification implications**: For safety-critical systems, unresolved transient faults can complicate certification discussions. ### The Value of Reduced Uncertainty Time-to-market can have significant financial implications: **Aerospace**: Program delays can affect revenue timing, continued development costs, and competitive positioning. **Automotive**: Vehicle launch timing affects market share, model year alignment, and tooling costs. **Medical devices**: Approval timing affects clinical trial costs, competitive positioning, and opportunity costs. Deterministic debugging can help reduce schedule uncertainty by: - Shortening investigation cycles - Reducing uncertainty around defect resolution timelines - Potentially supporting more efficient certification discussions ## Implementation Considerations Adopting deterministic replay requires platform support: ### Technical Requirements **Tick-based execution**: State transitions occur at discrete tick boundaries, enabling checkpoint/replay. **Event recording**: External inputs (sensors, user commands, network data) recorded at tick granularity. **State capture**: System state serializable for checkpointing—typically 1-10MB per checkpoint depending on application complexity. **Storage**: Recording infrastructure for execution traces. Modern systems can store hours of detailed traces. ### Operational Integration **Development workflow**: Engineers replay failures in debuggers with full symbol information, stepping through execution with high fidelity. **Continuous integration**: Automated tests can capture execution traces. Failed tests include replay data, enabling reproduction. **Field diagnostics**: Production systems can record execution traces. Field issues can be analyzed in lab via replay. **Regulatory submissions**: Execution traces can provide objective evidence of system behavior for certification discussions. ## Potential Benefits Organizations that adopt deterministic debugging may gain advantages in several areas: ### 1. Development Efficiency Reduced debugging time can accelerate: - Feature delivery (less time investigating defects) - Integration cycles (fewer integration issues) - Release confidence (higher certainty in quality) ### 2. Product Quality Deterministic replay can enable: - Root cause fixes rather than symptomatic patches - More comprehensive test coverage (replay enables testing of rare conditions) - Higher confidence in production reliability ### 3. Total Cost of Ownership Engineering cost reductions can compound over product lifecycles: - Initial development savings - Maintenance efficiency - Reduced field support escalations ### 4. Regulatory Efficiency Certification discussions may benefit from deterministic systems: - Reproducible evidence can support approval discussions - Potentially reduced test case requirements - Stronger evidence for fix verification ## Frequently Asked Questions ### What is the economic cost of non-reproducible software bugs? Non-reproducible bugs like race conditions and Heisenbugs can consume orders of magnitude more engineering time than deterministic defects. The Ariane 5 disaster cost approximately $370 million for a software failure that could not be reproduced in the original test environment. Engineering teams typically spend 30–70% of debugging time on reproduction alone. ### How does deterministic execution reduce debugging costs? Deterministic execution makes every failure reproducible by definition — given the same inputs, the system produces the same behaviour. Engineers replay failures in debuggers with full symbol information, stepping through execution with high fidelity. This eliminates the most expensive phase of debugging: attempting to reproduce the conditions that triggered the defect. ### Why can't better logging and monitoring replace deterministic architecture for debugging? Logging and monitoring capture symptoms after the fact but cannot reproduce the execution path that caused the failure. Non-deterministic bugs may not recur under monitoring conditions. Deterministic architecture guarantees that captured inputs reproduce the exact failure, converting debugging from hypothesis testing to direct observation. ### What are the limitations of deterministic debugging approaches? Deterministic replay requires recording infrastructure for all external inputs. Storage scales with execution trace length. The approach works best for computational bugs and is less effective for failures caused by external system interactions, network partitions, or hardware faults that cannot be deterministically replayed. ## Conclusion The accumulated evidence suggests that reproducibility can significantly alter the cost structure of debugging in complex systems. For organisations developing safety-critical or highly concurrent software, deterministic replay represents a structural approach for reducing investigation cost, schedule risk, and post-deployment uncertainty. The Ariane 5 incident—and numerous similar cases across industries—illustrate the potential consequences when bugs are difficult to reproduce. While deterministic execution is not the only approach to improving debugging economics, it addresses one of the fundamental challenges: the ability to reliably reproduce and investigate failures. For teams building systems where debugging cost and schedule predictability matter, understanding how execution determinism affects these economics can help inform architectural decisions early in the development process. --- ## The Mathematics of Deterministic Scheduling **URL**: https://speytech.com/insights/deterministic-scheduling/ **Published**: December 23, 2025 **Topic**: Formal Methods **Answers**: How does tick-based deterministic scheduling work at the fundamental computational level to eliminate all timing variance between successive runs, and why does replacing preemptive multitasking with fixed-cycle cooperative execution remove the timing-dependent non-determinism that makes safety-critical systems difficult to verify? **Defines**: Tick-based scheduling KEY_CLAIMS: - Non-determinism introduces significant challenges in safety-critical systems. - Deterministic scheduling through tick-based execution represents a shift in how concurrent systems can be reasoned about. - Tick-based deterministic scheduling divides execution into fixed-duration time slots where each task runs in a predetermined order without preemption. - By executing tasks in a fixed order within each tick, deterministic scheduling removes race conditions, priority inversions, and timing-dependent interleavings. - Preemptive schedulers interrupt tasks based on priorities and timing, creating execution orderings that vary between runs. How tick-based execution addresses non-determinism at the fundamental level of computation t t₀ t₁ t₂ t₃ t₄ S₀ S₁ S₂ S₃ S₄ δ(S₀,i₁) δ(S₁,i₂) δ(S₂,i₃) δ(S₃,i₄) DISCRETE TIME STATE MACHINE Each state transition occurs at a discrete tick boundary Non-determinism introduces significant challenges in safety-critical systems. When execution order depends on timing variation, hardware concurrency, or scheduler behavior, reproducing failures can become difficult. This complicates post-incident analysis, certification evidence, and long-term liability management. The fundamental challenge is that conventional computing treats time as continuous. Interrupts arrive at arbitrary moments. Thread schedulers make opportunistic decisions based on dynamic load. Memory operations complete in variable clock cycles. The result: identical inputs can produce different outputs, and debugging can become archaeological guesswork rather than systematic deduction. MDCP addresses this class of challenges through tick-based deterministic scheduling—a mathematical approach that makes time discrete and execution reproducible under defined conditions. ## The Formal Foundation At its core, deterministic scheduling is an application of discrete mathematics to computing systems. We model computation as a deterministic finite automaton (DFA) where state transitions occur only at discrete time boundaries called *ticks*. Definition: Tick-Based State Machine A tick-based system is a 5-tuple (S, Σ, δ, s₀, T) where S is a finite set of states, Σ is the input alphabet, δ: S × Σ → S is the transition function, s₀ ∈ S is the initial state, and T is a monotonically increasing sequence of discrete time values {t₀, t₁, t₂, ...} at which transitions occur. This formalization captures the core design principle: given an initial state s₀ and a sequence of inputs i₁, i₂, ..., iₙ arriving at ticks t₁, t₂, ..., tₙ, the final state is computed as: # State evolution under tick-based scheduling s(t₁) = δ(s₀, i₁) s(t₂) = δ(s(t₁), i₂) = δ(δ(s₀, i₁), i₂) ... s(tₙ) = δ(δ(...δ(s₀, i₁)...), iₙ) Because δ is a function (not a relation), the state evolution is mathematically determined by initial state and input sequence. This structure avoids many common sources of race conditions, scheduler-induced variability, and timing-dependent behavior. ## Addressing Sources of Non-Determinism Conventional systems can suffer from multiple sources of non-determinism. Tick-based scheduling is designed to address each one: ### Interrupt Timing In conventional systems, interrupts can arrive at any point during instruction execution. The exact moment an interrupt fires affects register state, memory contents, and subsequent execution flow. Two executions with identical inputs may diverge based on interrupt timing alone. Under tick-based scheduling, interrupts are **not processed immediately**. Instead, they are queued and processed at the next tick boundary. This transforms asynchronous events into synchronous state transitions, making interrupt effects reproducible at the granularity of ticks rather than dependent on sub-instruction timing. ### Thread Scheduler Decisions Conventional thread schedulers make dynamic decisions based on CPU load, priorities, time quantum expiration, and other runtime factors. The same program with identical inputs may schedule threads differently on different runs, producing different interleavings and potentially different results. Tick-based scheduling replaces priority-based preemptive scheduling with deterministic round-robin scheduling at tick boundaries. Each thread executes until it yields or the tick expires. Thread switches occur only at deterministic points. Given the same initial state and input sequence, thread execution order is designed to be reproducible across runs. CONVENTIONAL SCHEDULING T1 T2 T1 T2 Variable timing, preemption at arbitrary points TICK-BASED SCHEDULING T1 T2 T1 Transitions only at tick boundaries—deterministic ordering Thread scheduling comparison: variable vs. tick-aligned ### Memory Ordering Modern CPUs and compilers reorder memory operations for performance. Without careful use of memory barriers, different executions may observe memory operations in different orders, even with identical instruction sequences. This is particularly relevant in multi-core systems where cache coherency protocols introduce additional variability. MDCP addresses memory ordering through its tick-based architecture. The architecture enforces deterministic memory visibility at tick boundaries, ensuring memory state is consistent and reproducible between ticks. The MycoEco kernel is designed to ensure that all cores observe memory operations in a deterministic order. ## Practical Implications The mathematical structure of tick-based scheduling translates to practical engineering benefits: Debugging Record initial state and input sequence Replay execution reproducibly across supported configurations Time-travel debugging with high fidelity Root cause analysis grounded in reproducible execution evidence Testing Test cases designed to execute reproducibly Reduced flaky tests from timing dependencies Coverage metrics that are reproducible Regression testing with higher confidence Certification Supports reproducible execution traces for DO-178C evidence Aligns with ISO 26262 ASIL D reproducibility expectations Formal verification becomes more tractable Certification evidence grounded in reproducible behavior Post-Incident Analysis Supports execution replay for incident investigation Cryptographic verification of recorded state sequences Stronger evidence for root cause determination Can reduce ambiguity in technical investigations ## Performance Considerations A common question about tick-based scheduling is performance: "Won't forcing all operations to tick boundaries reduce throughput?" The answer involves trade-offs. Yes, tick-based scheduling adds latency—operations must wait for the next tick boundary. But this trades small, bounded latency for improved reproducibility and reduced debugging uncertainty. When a single non-reproducible bug can consume weeks of engineering time and delay certification, the microsecond-level latency can be a worthwhile trade-off for appropriate use cases. Moreover, MDCP's architecture includes optimizations that minimize tick overhead. The MycoEco kernel uses lock-free data structures that allow concurrent operations within ticks. The tick granularity is configurable—safety-critical sections can use fine-grained ticks (1µs) while less critical sections use coarser ticks (100µs) to reduce overhead. ## Frequently Asked Questions ### What is tick-based deterministic scheduling? Tick-based deterministic scheduling divides execution into fixed-duration time slots where each task runs in a predetermined order without preemption. Every tick produces identical task execution regardless of external timing — eliminating the scheduling-dependent non-determinism that makes safety-critical verification difficult. ### How does deterministic scheduling eliminate timing-dependent bugs? By executing tasks in a fixed order within each tick, deterministic scheduling removes race conditions, priority inversions, and timing-dependent interleavings. The system behaves identically whether running under heavy load or idle conditions, making every execution path testable and reproducible. ### Why can't preemptive multitasking provide the same guarantees as tick-based scheduling? Preemptive schedulers interrupt tasks based on priorities and timing, creating execution orderings that vary between runs. The number of possible interleavings grows combinatorially with task count, making exhaustive testing impractical. Tick-based scheduling constrains execution to a single deterministic ordering that can be verified completely. ### What are the performance trade-offs of tick-based scheduling? Tick-based scheduling imposes fixed overhead per tick boundary and may underutilise CPU when tasks complete early within their allocated slots. Tasks must be designed to fit within tick budgets, which requires WCET analysis. The trade-off is predictable worst-case performance rather than optimised average-case performance. ## Conclusion Deterministic scheduling through tick-based execution represents a shift in how concurrent systems can be reasoned about. By treating time as discrete rather than continuous, certain sources of execution variability become constrained, making reproducibility and analysis more tractable. This approach does not eliminate all complexity, nor is it appropriate for every system. However, for safety-critical domains where reproducibility, traceability, and bounded execution behavior are central requirements, tick-based deterministic scheduling provides a mathematically grounded foundation. As systems grow more autonomous and certification requirements evolve, architectural choices that support reproducible execution may play an increasingly important role in enabling reliable verification, investigation, and long-term system confidence. --- ## DO-178C: Deterministic Execution Cuts Certification Cost **URL**: https://speytech.com/insights/do178c-certification/ **Published**: December 23, 2025 **Topic**: Safety Certification **Answers**: How can deterministic execution architecture using tick-based scheduling and a minimal formally verified code footprint substantially reduce the overall cost, engineering effort, and certification timeline of DO-178C Level A aerospace software certification compared to building on conventional real-time operating systems? **Defines**: DO-178C certification KEY_CLAIMS: - Note: Cost and timeline figures in this article are indicative estimates based on published industry benchmarks and certification program discussions. - DO-178C Level A is the highest aerospace software assurance level, requiring MC/DC structural coverage, complete requirements traceability, and deterministic execution evidence for flight-critical systems. - DO-178C Level A certification is the standard for aviation software safety, but it requires substantial verification effort. - Deterministic execution with tick-based scheduling produces identical behaviour across runs, reducing the number of test cases needed to demonstrate compliance. - Compare the verification surface area: lines of code requiring MC/DC coverage, number of scheduling-dependent test paths, and traceability items from requirements to test evidence. EVIDENCE: - DO-178C Level A—the highest software safety standard for commercial aviation—requires objective evidence of correct behaviour under all conditions. - DO-178C "Software Considerations in Airborne Systems and Equipment Certification" is the FAA-recognised standard for avionics software. - DO-178C defines five levels of software criticality: Level A (Catastrophic): Failure may cause death or loss of aircraft. - DO-178C defines 71 objectives that must be satisfied for Level A certification. How tick-based architecture and minimal code footprint can reduce certification effort and timelines in aerospace programs Note: Cost and timeline figures in this article are indicative estimates based on published industry benchmarks and certification program discussions. Actual costs vary significantly by system scope, regulatory context, and organisational factors. Recent high-profile recertification programs in aviation have highlighted the verification challenges inherent in complex software systems. When certification authorities require extensive evidence that software will behave predictably under all conditions, the verification burden can become substantial. The technical challenge often isn't writing correct code—it's **demonstrating** that the code will behave correctly. With conventional software systems where execution can depend on timing, scheduler decisions, and concurrent interactions, demonstrating correctness may require extensive testing across many possible execution scenarios. DO-178C Level A—the highest software safety standard for commercial aviation—requires objective evidence of correct behaviour under all conditions. Industry estimates suggest that achieving this standard for conventional systems can cost tens of millions of dollars and take 18-36 months. The effort scales with code size and the complexity of verifying timing-dependent behaviour. Tick-based deterministic execution offers an architectural approach that can change this trade space. Definition: DO-178C Level A Certification DO-178C Level A is the highest aerospace software assurance level, requiring MC/DC structural coverage, complete requirements traceability, and deterministic execution evidence for flight-critical systems. ## Understanding DO-178C Level A DO-178C "Software Considerations in Airborne Systems and Equipment Certification" is the FAA-recognised standard for avionics software. Level A applies to software whose failure could cause catastrophic events—loss of aircraft control, structural failure, multiple fatalities. ### The Five Software Levels DO-178C defines five levels of software criticality: **Level A (Catastrophic)**: Failure may cause death or loss of aircraft. Examples: flight control computers, engine control systems. **Level B (Hazardous)**: Failure may cause serious injury or major aircraft damage. Examples: auto-throttle, weather radar. **Level C (Major)**: Failure may cause passenger discomfort or inconvenience. Examples: in-flight entertainment, cabin lighting. **Level D (Minor)**: Failure has minimal impact. Examples: crew scheduling systems. **Level E (No Effect)**: Failure has no safety impact. Level A software faces the most stringent requirements. Every line of code must be traced to requirements. Every requirement must have test cases. Every possible execution path must be analysed. The verification burden is substantial. ### The Certification Objectives DO-178C defines 71 objectives that must be satisfied for Level A certification. Key objectives include: **Structural Coverage Analysis (DO-178C §6.4.4)**: Demonstrate that testing exercises every statement, every branch, and every condition in the code. For systems with timing-dependent behaviour, achieving complete coverage may require testing with different timing scenarios and configurations. **Requirements-Based Testing (DO-178C §6.4.2)**: Every software requirement must have corresponding test cases that verify correct behaviour. When software behaviour can vary with timing, test cases may need to account for these variations. **Robustness Testing (DO-178C §6.4.3)**: Verify software behaves correctly under abnormal conditions—invalid inputs, resource exhaustion, hardware failures. Systems with timing dependencies may need to test these conditions across various timing scenarios. **Dead Code Analysis (DO-178C §6.4.4.2)**: Demonstrate that no executable code exists that cannot be reached during normal operation. In systems where code reachability depends on scheduler decisions, this analysis can be complex. **Traceability (DO-178C §6.3)**: Bidirectional tracing from high-level requirements down to object code and test cases. Every code path must trace to a requirement; every requirement must trace to test verification. Each objective represents significant engineering effort. Industry estimates suggest Level A certification typically costs in the range of tens of millions of dollars, with timelines of 18-36 months from code freeze to certification approval. ## Challenges with Conventional Approaches The primary challenge in DO-178C certification often isn't writing correct code—it's **demonstrating** correctness. Conventional RTOS-based systems can face several verification challenges: ### 1. Timing-Dependent Execution Most real-time operating systems use preemptive priority-based scheduling. Thread execution order can depend on: - Priority levels (which may change dynamically) - Time quantum expiration - Interrupt timing - Lock acquisition order - CPU load and resource availability This means **similar inputs may produce different execution paths** depending on timing. Achieving structural coverage may require testing across many timing permutations. Industry discussions suggest that accounting for timing-dependent behaviour can significantly increase test case counts—potentially by an order of magnitude or more for complex systems. ### 2. Code Size Considerations Modern RTOS implementations vary in size: - Larger kernels: 100-200KB - Mid-range kernels: 50-100KB - Minimal kernels: under 50KB DO-178C certification effort tends to scale with code size. Industry benchmarks suggest costs in the range of $1,000-$2,000 per source line of code for Level A certification, though this varies significantly by context. ### 3. Concurrency Complexity Multi-threaded systems introduce considerations around race conditions, deadlocks, and priority inversion. DO-178C may require analysis of: - Possible thread interleavings - Lock acquisition orders - Interrupt timing interactions - Shared resource access patterns Analysis of concurrent systems can be complex, and most certification efforts rely on extensive testing. Conventional RTOS Certification Considerations Timing-dependent thread scheduling Larger kernel footprint Complex concurrency analysis Potentially large test case counts Extended timelines common Deterministic Platform Considerations Deterministic tick-based scheduling Minimal kernel footprint Reduced concurrency complexity Potentially reduced test case counts May support shorter timelines ## How Deterministic Execution Can Simplify Certification Tick-based deterministic execution is designed to address several certification challenges: ### Objective 1: Structural Coverage **Conventional approach**: Test with varying timing, priorities, and loads to exercise code paths. Each path may require multiple test cases with different timing scenarios. **Deterministic approach**: Given initial state and input sequence, execution path is designed to be reproducible. This can reduce the number of distinct timing-dependent test cases needed for coverage. **Potential impact**: Can reduce test case count for timing-dependent scenarios. ### Objective 2: Requirements-Based Testing **Conventional approach**: Requirements specify behaviour ("system shall respond within 100ms"), but actual response time may vary with scheduler state. Test cases may need to verify behaviour across timing distributions. **Deterministic approach**: Requirements can map to tick counts ("system shall respond within N ticks"). Test cases can verify reproducible behaviour rather than statistical properties. **Potential impact**: Can reduce timing-dependent test failures and regression testing burden. ### Objective 3: Robustness Testing **Conventional approach**: Test abnormal conditions across possible timing scenarios. A timeout condition might behave differently depending on when it occurs relative to other processing. **Deterministic approach**: Abnormal conditions are events processed at tick boundaries. Behaviour is designed to be reproducible regardless of when the condition occurs. **Potential impact**: Robustness testing can become more reproducible. ### Objective 4: Dead Code Analysis **Conventional approach**: Demonstrate code unreachability across possible scheduler states and timing conditions. May require complex static analysis. **Deterministic approach**: Code reachability is designed to be deterministic. Static analysis tools can have clearer information about which paths can execute. **Potential impact**: Can simplify dead code analysis. ### Objective 5: Traceability **Conventional approach**: Trace requirements to test cases that verify behaviour across timing variations. **Deterministic approach**: Trace requirements to test cases that verify reproducible behaviour. **Potential impact**: Can simplify traceability documentation and review. ## The Code Size Factor Beyond determinism, minimal code footprint can reduce certification effort. ### MDCP Platform Size - **MDMK kernel** (multi-core deterministic scheduling): ~26KB - **PBAS-6 kernel** (safety guardrails): ~20KB - **Combined platform core**: ~46KB This is substantially smaller than many conventional RTOS implementations. ### Certification Effort Scaling DO-178C Level A certification effort tends to scale with source lines of code (SLOC). While exact costs vary significantly: ``` Smaller platform footprint → Fewer lines to verify → Reduced documentation volume → Potentially faster authority review → Lower overall certification effort ``` This potential cost reduction can apply across programs. Minimising platform size can maximise the return on certification investment. ### Why Smaller Code Can Help Smaller code can mean: **Fewer review cycles**: Certification authorities review all code and documentation. Smaller codebases may enable faster reviews. **Less documentation**: DO-178C requires extensive documentation. Documentation volume tends to scale with code size. **Reduced regression scope**: When issues are found during certification, fixes trigger regression analysis. Smaller codebases may have fewer interactions to analyse. ## PBAS-6 Integration: Safety by Design The PBAS-6 (Progressive Bounded Autonomous Systems) kernel provides runtime safety capabilities that can map to DO-178C safety requirements. ### Safety Envelopes as Certification Evidence PBAS-6 enforces safety envelopes—runtime bounds on system state: - Control authority limits - Rate-of-change limits - Resource utilisation bounds - Escalation triggers for approaching boundaries These envelopes can provide **runtime verification** that complements compile-time verification. DO-178C §6.3.4 requires "evidence of absence of unintended functions." PBAS-6 guardrails can provide continuous evidence that the system remains within safe operating bounds. ### Escalation States as Safety Modes PBAS-6 defines progressive escalation: ``` NOMINAL → WARNING → CAUTION → ALERT → CRITICAL ``` Each escalation level corresponds to reduced control authority and increased conservatism. This can map to DO-178C requirements for: - Fault detection and handling (§6.3.3.c) - System safety assessment (§6.2) - Failure conditions analysis (§2.2.2) The deterministic nature of escalation—same inputs designed to produce reproducible escalation decisions—can simplify verification. ### Potential for Multi-Domain Certification PBAS-6's small footprint may make it economically viable to pursue certification across multiple domains: - **DO-178C Level A**: Aviation - **ISO 26262 ASIL D**: Automotive - **IEC 62304 Class C**: Medical devices - **IEC 61508 SIL 4**: Industrial control Each standard has similar requirements but different terminology. Small size can make multi-standard certification more tractable. ## Timeline Considerations Beyond cost, deterministic execution may accelerate certification timelines. ### Conventional Certification Timeline Typical DO-178C Level A timeline for RTOS-based system: 1. **Planning (3-6 months)**: Software planning documents, standards selection, tool qualification plans 2. **Development (6-12 months)**: Coding, unit testing, integration testing 3. **Verification (9-15 months)**: Requirements-based testing, structural coverage, robustness testing 4. **Certification review (3-6 months)**: Authority review, defect resolution, regression testing 5. **Total: 21-39 months** (indicative) The verification phase often dominates. Timing-dependent behaviour can extend verification because: - Tests with timing sensitivity may need re-running - Coverage gaps may require additional test cases - Timing-dependent issues may require extensive debugging - Regression testing may restart with each fix ### Potential Timeline with Deterministic Execution With tick-based deterministic execution, some of these factors may be reduced: - Fewer timing-dependent test variations - More reproducible test results - Deterministic replay for debugging - Smaller codebase for review **Potential savings**: Several months in verification and review phases, though actual results depend on many factors. ## Industry Precedents While deterministic platforms for DO-178C are still emerging, the certification benefits of small, simple kernels are well-established: **seL4 microkernel**: The formally verified seL4 kernel is ~12KB. Its formal verification demonstrated that small, well-designed kernels can achieve strong assurance properties. **Separation kernels**: Several separation kernels have achieved DO-178B/C certification with relatively small footprints. Their simple architectures have supported certification timelines shorter than typical RTOS certification. **Space systems**: NASA's JPL uses stripped-down kernels for spacecraft. Small size enables exhaustive testing within mission schedules and budgets. The pattern is consistent: **smaller code + simpler architecture tends to support faster, more tractable certification**. ## Regulatory Context Certification authorities increasingly recognise deterministic execution as a factor in software verification: **FAA Advisory Circular 20-115D**: Discusses "deterministic behaviour" as a factor in software complexity assessment. Deterministic systems may receive lower complexity ratings, potentially reducing verification burden. **EASA Certification Memorandum**: Acknowledges that "predictable, repeatable execution simplifies verification" and suggests this may support reduced test case requirements for deterministic systems. **DO-333**: "Formal Methods Supplement to DO-178C" explicitly supports formal verification, which benefits from deterministic semantics. Tick-based execution can provide a foundation for formal methods. Regulatory guidance increasingly recognises architectures that simplify verification. ## Strategic Considerations In aerospace, certification capability is strategically important. Programs that can achieve Level A certification more efficiently may benefit from: **Earlier market entry**: Faster certification can enable earlier service entry **Reduced program risk**: More predictable certification reduces schedule uncertainty **Technology differentiation**: Deterministic platforms may enable capabilities that would be more costly to certify with conventional approaches For organisations developing safety-critical systems, pre-certified deterministic platforms can represent significant avoided certification effort. ## Frequently Asked Questions ### How does deterministic execution reduce DO-178C certification cost? Deterministic execution with tick-based scheduling produces identical behaviour across runs, reducing the number of test cases needed to demonstrate compliance. Smaller, formally verifiable codebases require less structural coverage analysis, fewer review cycles, and simpler traceability matrices — all of which are major cost drivers in Level A certification. ### How do I estimate the certification effort reduction from deterministic architecture? Compare the verification surface area: lines of code requiring MC/DC coverage, number of scheduling-dependent test paths, and traceability items from requirements to test evidence. Deterministic architectures with minimal codebases can reduce each of these by an order of magnitude compared to conventional RTOS approaches, though actual results depend on application complexity. ### Why can't conventional RTOS approaches achieve the same certification savings? Conventional RTOS kernels contain preemptive scheduling, dynamic memory management, and interrupt-driven concurrency — each introducing non-deterministic execution paths that require exhaustive testing. Every scheduling permutation is a potential certification test case. Deterministic architectures eliminate these paths rather than testing all of them. ### What regulatory precedents support deterministic approaches for DO-178C? FAA Advisory Circular 20-115D discusses deterministic behaviour as a factor in software complexity assessment. EASA Certification Memoranda acknowledge that predictable, repeatable execution simplifies verification. DO-333 explicitly supports formal verification, which benefits from deterministic semantics where formal methods can prove properties rather than testing for them. ## Conclusion DO-178C Level A certification is the standard for aviation software safety, but it requires substantial verification effort. Conventional approaches face challenges from timing-dependent execution, larger code footprints, and complex concurrency analysis. Tick-based deterministic execution offers an architectural approach that can alter the certification trade-offs: - **Determinism can reduce timing variability**, potentially reducing test case counts for timing-dependent scenarios - **Smaller code footprint** can reduce documentation and review effort - **Simplified concurrency model** can reduce analysis complexity - **PBAS-6 guardrails** can provide runtime safety verification - **Timeline reduction** may add significant program value For aerospace organisations facing certification challenges and compressed development schedules, deterministic platforms represent an architectural approach worth evaluating. The potential benefits in certification effort, timeline, and verification tractability can be material. As with any architectural approach, suitability depends on system requirements, regulatory context, and organisational factors. Early engagement with certification authorities is recommended when evaluating novel architectural approaches for safety-critical systems. --- ## Post-Incident Analysis in Implantable Cardiac Devices **URL**: https://speytech.com/insights/implantable-device-litigation/ **Published**: December 23, 2025 **Topic**: Medical Devices **Answers**: How does deterministic execution traceability and bit-perfect computational replay capability influence post-incident investigation methodology, expert witness technical analysis, liability determination, and regulatory enforcement outcomes in cases where implantable cardiac devices like pacemakers are involved in patient harm or unexpected death? KEY_CLAIMS: - Note: The following scenario is illustrative and representative of patterns observed in publicly reported medical device litigation. - The medical device industry faces ongoing challenges related to software reproducibility. - Deterministic execution with bit-perfect replay enables investigators to reconstruct the exact computational state at the time of an incident. - Design execution tracing into the firmware from the start with tick-granularity input recording and cryptographic hash chains. - Conventional logs capture commands and outputs but not the complete decision process between them. EVIDENCE: - All device decisions occur at discrete tick boundaries (typically 1ms intervals for cardiac devices). How execution traceability can influence investigation, liability, and regulatory outcomes Note: The following scenario is illustrative and representative of patterns observed in publicly reported medical device litigation. It does not refer to any specific case or manufacturer. Implantable cardiac device failures expose a critical gap in execution traceability. A patient dies several days after pacemaker implantation. The autopsy indicates cardiac arrest. The device logs show "normal operation." The manufacturer's position is that the device functioned correctly. The family's expert witness contends that the logs are incomplete and potentially insufficient for conclusive analysis. Such cases can extend for years. Legal costs can reach several million pounds. Jury verdicts or settlements may reach substantial amounts. Appeals can add additional years to resolution. The challenge: **definitive determination of what actually occurred may remain elusive**. This pattern is not uncommon. It reflects a recurring challenge when deploying complex, timing-dependent software in life-critical implantable devices. Industry estimates suggest that litigation, recalls, and related costs in this space may reach hundreds of millions of pounds annually across major manufacturers. ## The Reproducibility Challenge Modern implantable cardiac devices—pacemakers, implantable cardioverter-defibrillators (ICDs), cardiac resynchronization therapy (CRT) devices—run sophisticated embedded software. This software makes thousands of decisions per day: - When to pace (deliver electrical stimulus) - How much energy to deliver - Whether to defibrillate - How to interpret sensor data - When to log events - How to manage battery power In conventional implementations, these decisions can depend on: - **Interrupt timing** from sensors and timers - **Scheduler decisions** about which tasks run when - **Memory access patterns** that vary with system load - **Timing-dependent interactions** between concurrent processes This means that **similar patient conditions may produce different device behaviors** depending on timing, system state, and execution history. When a device-related adverse event occurs, reconstructing exactly what happened can be challenging. ### Litigation Patterns Medical device litigation often follows recognisable patterns: **Phase 1: The Incident** (Day 0) - Patient experiences adverse event (arrhythmia, cardiac arrest, device-related issue) - Device logs retrieved (if patient survives) or extracted post-mortem - Logs may show: "Device operated within normal parameters" **Phase 2: Expert Analysis** (Months 1-12) - Plaintiff's expert may argue: "The logs are incomplete or insufficient" - Defendant's expert may argue: "The logs show proper function" - Neither side may be able to definitively establish device state at moment of failure - Discovery may demand device source code, test procedures, validation data **Phase 3: Extended Litigation** (Years 1-5) - Engineers testify about device behavior under "similar" conditions - Simulator-based attempts to recreate incidents can be limited by timing-dependent variability - Juries may decide based on probability assessments rather than definitive evidence - Settlement or verdict costs vary widely **Phase 4: Regulatory Considerations** (Years 2-10) - Regulators may mandate design changes - Class actions or recalls may occur (costs can be substantial) - Reputational effects may impact market position - Insurance costs may increase Industry-wide costs are difficult to quantify precisely, but publicly reported cases suggest material financial exposure across major manufacturers. ## Limitations of Conventional Logging Device manufacturers log events extensively. A typical pacemaker generates records of: - Heartbeat detections - Pacing decisions - Battery voltage - Lead impedance - Arrhythmia episodes - Parameter changes However, conventional logging has limitations for post-incident analysis: ### 1. Sampling Rather Than Complete Capture Logs capture **samples** of device state, not complete execution traces. Between logged events, many software decisions occur. If an issue arises between samples, root cause may be difficult to observe. ### 2. Timing Uncertainty Event timestamps depend on system clock, which can drift with temperature, battery voltage, and crystal oscillator variations. Events logged "simultaneously" may have occurred in different orders. Reconstructing causal chains can be challenging. ### 3. Incomplete State Logs capture what developers anticipated would be important. If an issue involves an unlogged variable or edge case, evidence may not exist. This can complicate post-incident analysis. ### 4. Potential Data Issues After device failure (battery depletion, memory issues, electromagnetic interference), logs may be partial or corrupted. Complete log integrity may be difficult to establish definitively. ### 5. Reproducibility Limitations Most significantly: **even with complete logs, execution may be difficult to reproduce**. Simulator runs with similar inputs may produce different outputs due to timing variations. Claims about device behavior can be difficult to verify conclusively. Conventional Pacemaker Logging Event sampling (may be incomplete) Timing can be uncertain Limited state capture Potential data integrity issues after failure Reproduction can be challenging Expert testimony often required Litigation timelines can extend for years Deterministic Kernel Approach (e.g., CardioCore) Designed for complete execution tracing Tick-based timing for consistency Full state capture at boundaries Cryptographic tamper-detection Designed to support reproducible replay Can reduce reliance on testimony May significantly reduce investigation time ## A Deterministic Approach: CardioCore CardioCore is designed to address reproducibility challenges through deterministic kernel architecture. The goal is execution that can be replayed with consistent results. ### Tick-Based Execution All device decisions occur at discrete **tick boundaries** (typically 1ms intervals for cardiac devices). Sensor inputs, pacing decisions, and state transitions are synchronised to ticks. This approach is designed to reduce timing variability: - Interrupts are processed at tick boundaries (not immediately) - Tasks execute in deterministic order each tick - The architecture is designed to reduce race conditions - Replay is designed to produce consistent execution across supported configurations ### Complete State Capture At each tick, CardioCore is designed to capture: - **Input state**: sensor values (ECG, accelerometer, battery voltage) - **Decision state**: algorithm parameters, thresholds, mode settings - **Output state**: pacing commands, defibrillation decisions - **Internal state**: timers, counters, state machines This creates an **execution trace** from which any tick can potentially be reconstructed. ### Cryptographic Attestation Each tick's state is hashed with SHA-256. Hash chains are designed to support: - **Completeness detection**: Missing ticks can be identified - **Integrity verification**: Modified logs are designed to be detectable - **Temporal ordering**: Event sequence is cryptographically bound In post-incident analysis, this can provide: 1. Device execution trace (initial state + input sequence) 2. Cryptographic hash chain (supports trace completeness verification) 3. Replay capability (enables independent verification) Independent experts can potentially **replay execution** and verify consistent results. This can help narrow the scope of technical disputes. ### Replay Verification CardioCore includes replay capability: 1. Load initial device state (at implantation or programming) 2. Apply recorded input sequence (sensor data, patient commands) 3. Execute deterministically (tick-based state transitions) 4. Compare outputs against recorded execution **Potential result**: Stronger evidence regarding device behavior at time of incident. Reproducible execution evidence can significantly reduce ambiguity in technical investigations, potentially accelerating resolution regardless of outcome. ## CardioCore Validation: Test Results CardioCore has been validated through comprehensive automated testing demonstrating deterministic execution, safety integration, and replay verification in controlled test environments. ### Integration Test Results A full 5-phase integration test demonstrates critical capabilities: ``` # CardioCore Integration Demo - 500 Tick Execution CardioCore™ Deterministic Medical Kernel PHASE 1: Kernel + DSE Scheduler [0] Sensing - priority=1, period=1 [1] Pacing - priority=2, period=10 [2] Monitor - priority=10, period=100 PHASE 2: Audit Log (Hash-Chained) Max entries: 1024 Initial hash: 484a383b... EXECUTION: 500 Ticks Tick 100: hash=e13188d3... Tick 200: hash=2b61245e... Tick 300: hash=7521bcb2... Tick 400: hash=a0679525... Tick 500: hash=fd184f65... DETERMINISM VERIFICATION Run 1: fd184f65ffb63b49... Run 2: fd184f65ffb63b49... Result: VERIFIED ✓ STATISTICS Safety checks: 50 | Vetoes: 0 Audit entries: 1055 Hash chain: VERIFIED ✓ All 5 phases complete ✓ Replay(Σ₀, L, t) = Σₜ verified ``` ### What These Results Demonstrate **Reproducible Execution**: Two independent runs with identical initial state and input sequence produced identical final state hashes. This provides evidence that execution is reproducible under test conditions. **Complete Audit Trail**: 1,055 events logged across 500 ticks with cryptographic hash chain verification. Sensing events, pacing decisions, and safety checks are recorded with tamper-detection capability. **Safety Integration**: VITA-SB safety layer performed 50 checks with 50 modifications (safety constraints applied). Zero vetoes indicates normal operation within safety boundaries during testing. **Replay Capability**: The system can restart from initial state Σ₀, apply recorded event log L, and reach identical final state Σₜ. This supports incident reconstruction capability. ### Test Coverage CardioCore includes comprehensive automated test suites: ``` # CardioCore Test Suite Unit Tests: test_kernel.c - Core kernel functionality test_log.c - Audit log and hash chains test_state.c - State transitions test_replay.c - Replay engine verification test_safety.c - VITA-SB safety layer test_hash.c - Cryptographic hash functions Integration Tests: demo_integration.c - Full 5-phase integration demo_basic.c - Basic pacing scenarios All tests: PASSING ✓ ``` This validation demonstrates CardioCore as a **proof-of-concept deterministic kernel** with reproducibility verification under controlled test conditions. Production deployment and medical device certification would be completed by the acquiring organisation. ## Illustrative Impact Comparison **The following scenario illustrates potential differences in investigation approaches:** **Patient**: 72-year-old with ICD implanted for ventricular tachycardia **Incident**: Device delivered shock during rhythm that patient's cardiologist questions **Outcome**: Patient survived but experienced distress ### Conventional Investigation Approach **Potential Timeline**: - **Months 1-6**: Device interrogation, log analysis, expert engagement - **Months 7-18**: Discovery (source code, test data, similar incidents) - **Months 19-36**: Expert analysis, simulator attempts, technical discussions - **Months 37-48**: Trial preparation, proceedings, resolution - **Months 49-60**: Potential appeals, final settlement **Potential costs**: Can reach several million pounds including legal fees, expert witnesses, and settlement/verdict. **Challenge**: Questions may remain about precise root cause. ### Deterministic Kernel Approach **Potential Timeline**: - **Weeks 1-2**: Device trace retrieved (complete execution record) - **Weeks 2-3**: Independent expert replays execution, verifies reproducibly - **Weeks 3-4**: Replay analysis identifies specific algorithm behavior - **Weeks 4-6**: Parties have clearer technical basis for resolution **Potential costs**: May be substantially reduced due to faster, clearer technical analysis. **Potential outcome**: Root cause more readily identifiable. Clearer basis for resolution regardless of liability determination. Note: Timeline and cost comparisons are illustrative and based on general industry patterns. Actual outcomes depend on case specifics, jurisdiction, and many other factors. ## Regulatory Considerations Beyond post-incident analysis, deterministic execution may provide regulatory advantages: ### IEC 62304 Alignment IEC 62304 (Medical Device Software Lifecycle) emphasises: - Complete traceability from requirements to implementation - Verification that software behaves as specified - Analysis of failure modes Deterministic kernels can support: - **Traceability**: Execution maps to requirements in reproducible fashion - **Verification**: Replay can demonstrate specified behavior - **Failure mode analysis**: Replay enables systematic edge case testing This may support FDA/MHRA submissions and reduce post-market surveillance burden. ### Post-Market Surveillance Regulators require ongoing monitoring of device performance in real-world use. With deterministic execution: - **Incident analysis**: Field issues may be reproducible in lab settings - **Trend detection**: Patterns may emerge from analysis of fleet data - **Response capability**: Firmware updates can potentially be validated against historical traces This may reduce recall risk and support patient safety outcomes. ### Clinical Trial Efficiency Device trials require demonstrating safety and efficacy. Deterministic execution may enable: - **Reproducible endpoints**: Trial results potentially verifiable by replay - **Accelerated analysis**: Deterministic traces may enable automated analysis - **Regulatory confidence**: Reviewers may be able to independently verify claims This could potentially reduce trial timelines, though actual impact depends on regulatory acceptance and specific trial design. ## Economic Considerations for Device Manufacturers Adopting deterministic kernels may produce financial benefits across several areas: **Litigation costs**: Faster, clearer technical analysis may reduce legal expenses and settlement amounts. **Recall costs**: Deterministic firmware updates may be validatable without full device replacement in some scenarios. **Regulatory timelines**: Improved traceability and reproducibility may support faster approvals. **Insurance**: Demonstrable reproducibility may support more favorable risk assessments. **Market position**: Differentiation on safety and traceability may provide competitive advantages. Note: Economic impacts are indicative and depend on organisation size, product portfolio, regulatory context, and many other factors. Actual results will vary. ## Implementation Considerations Transitioning to deterministic kernels involves several factors: ### Hardware Compatibility CardioCore is designed to support standard medical device hardware: - ARM Cortex-M series (M0+, M3, M4, M7) - Low-power operation (minimal overhead) - Small memory footprint (CardioCore demonstrates that deterministic execution is practical and deployable for implantable cardiac devices. For manufacturers evaluating architectural approaches for next-generation devices, understanding how execution reproducibility affects investigation, liability, and regulatory outcomes can help inform design decisions. As the industry continues to evolve, architectural choices that support reproducible execution may play an increasingly important role in enabling reliable verification, investigation, and long-term confidence in implantable medical device software. --- ## The MycoEco Kernel: Lock-Free Determinism at Scale **URL**: https://speytech.com/insights/mycoeco-kernel/ **Published**: December 23, 2025 **Topic**: Systems Architecture **Answers**: How does the MycoEco kernel achieve deterministic multi-core concurrent execution without using locks, mutexes, or any blocking synchronisation primitives, and what specific event-based architecture patterns enable lock-free parallel processing across multiple processor cores while maintaining bit-identical reproducibility between separate runs? KEY_CLAIMS: - The MycoEco kernel achieves deterministic multi-core execution without locks. - MycoEco demonstrates that deterministic, lock-free multi-core execution is achievable within a compact, certifiable kernel architecture. - MycoEco is a deterministic multi-core kernel that achieves lock-free concurrent execution using event-based architecture instead of locks, mutexes, or blocking synchronisation primitives. - MycoEco replaces shared-memory concurrency with event-based message passing between cores. - Locks introduce timing-dependent behaviour: thread acquisition order varies between runs depending on scheduling, cache state, and contention. EVIDENCE: - The implementation exists, passes 46 automated tests including multi-core determinism verification, and runs in under 256KB of kernel space. - Worst-case execution time (WCET): Can be analysed statically from the event handlers and maximum event counts This design supports certification to standards like DO-178C Level A and ISO 26262 ASIL D, which require demonstrable worst-case timing bounds. - The entire kernel—multi-core scheduling, event management, replay capability, cryptographic hashing, PBAS-6 guardrails—fits in under 256KB of memory. - For comparison: Linux kernel: ~30MB (minimal configuration) FreeRTOS: ~10KB (but without deterministic multi-core, crypto, or guardrails) seL4 (microkernel): ~12KB (but without multi-core determinism) MycoEco achieves substantial functionality in a compact footprint. How event-based architecture enables deterministic multi-core execution without locks The MycoEco kernel achieves deterministic multi-core execution without locks. Conventional wisdom assumes deterministic execution requires serialisation, and serialisation limits multi-core performance. The MycoEco architecture disproves this assumption using event-based coordination that eliminates mutexes and barriers while maintaining bit-identical reproducibility across runs. This assumption has shaped the design of many operating systems. Most general-purpose systems use schedulers optimised for throughput, with reproducibility as a secondary concern. Safety-critical systems have often accepted performance trade-offs from heavy locking or limited their use of multi-core capabilities. The MycoEco kernel demonstrates an alternative architectural approach. Through event-based architecture and deterministic scheduling, MycoEco achieves **lock-free deterministic execution across multiple cores**. No mutexes. No spinlocks. No barriers. Just deterministic coordination that scales. This isn't theoretical. The implementation exists, passes 46 automated tests including multi-core determinism verification, and runs in under 256KB of kernel space. ## The Lock Trade-offs To understand MycoEco's approach, it helps to understand why conventional systems use locks. ### Race Conditions in Shared Memory Multi-core processors share memory. When two cores try to modify the same memory location simultaneously, the result depends on timing—which core's write happens last. This is a **race condition**, and it makes execution non-deterministic. The traditional solution: locks. Core A acquires a mutex, modifies the shared data, releases the mutex. Core B waits. This ensures only one core accesses shared data at a time, addressing the race condition. But locks introduce well-known trade-offs: **Performance considerations**: Cores spend time waiting rather than computing. With N cores, adding more cores can yield diminishing returns as contention increases. **Priority inversion**: A low-priority thread holding a lock can block high-priority threads, complicating real-time guarantees. **Deadlock risk**: Locks taken in different orders can deadlock, requiring careful prevention schemes. **Composability challenges**: Lock-based code doesn't always compose cleanly—combining two lock-free modules can create potential deadlocks. For safety-critical systems: **locks do not inherently guarantee reproducible execution order**. Lock acquisition order can still depend on timing. Thread A might acquire the lock first in one execution, Thread B in another. The execution is serialised but not necessarily deterministic. ### The Conventional Trade-off Many systems have been designed under assumptions that prioritise either determinism or scalability: - **Option 1**: Use locks, accept performance trade-offs and potential timing variability - **Option 2**: Go lock-free, accept non-determinism from race conditions Safety-critical systems have often chosen Option 1. High-performance systems have often chosen Option 2. Achieving both determinism and performance has been considered challenging. MycoEco explores a different point in this design space. ## Event-Based Architecture: The Key Insight MycoEco's approach is based on recognising that **determinism doesn't require serialisation—it requires deterministic ordering**. Instead of preventing cores from executing simultaneously, MycoEco is designed to ensure that when they do execute simultaneously, the result is deterministic. The key is replacing shared memory communication with event-based communication. ### Events as First-Class Primitives In MycoEco, cores don't share memory. They communicate through **events**. An event is a self-contained message containing: - **Tick number**: When it should be processed - **Source core**: Which core generated it - **Payload**: Data being communicated - **Deterministic hash**: Cryptographic fingerprint for integrity verification Events are immutable once created. They flow through the system in deterministic order, processed at tick boundaries. Design Property: Event Determinism Given a deterministic initial state and a deterministic event ordering, the execution on N cores is designed to produce an identical final state regardless of the relative timing of core execution. This is the fundamental insight. Determinism doesn't require cores to execute in lockstep. It requires that **events be processed in deterministic order**, and that **each event's effect be deterministic**. ### The Deterministic Scheduling Engine (DSE) MycoEco's DSE implements deterministic event ordering without locks. At each tick: 1. **Event collection**: All cores submit events for the current tick 2. **Deterministic sorting**: Events are ordered by a deterministic function (tick number, source core, event hash) 3. **Slot assignment**: Each event is assigned to a processing slot 4. **Parallel execution**: Cores execute their assigned events in parallel The critical property: **slot assignment is deterministic**. Given the same set of events, the DSE always assigns them to the same slots. This means: - Core A always processes the same events in the same order - Core B always processes the same events in the same order - The relative timing of A and B doesn't matter—only the deterministic assignment No locks. No waiting. Just deterministic coordination. ## Replay: Verification of Determinism A key test of a deterministic system is **replay**: can you reproduce execution consistently? MycoEco's test suite includes multi-core replay verification: ``` [Replay Tests (Determinism Verification)] replay_checkpoint... PASS replay_determinism... PASS replay_from_checkpoint... PASS replay_multicore_determinism... PASS ``` These tests verify: **Single-core replay**: Execute a sequence of operations, checkpoint state, replay from checkpoint → identical final state **Multi-core replay**: Execute on 4 cores, checkpoint, replay on different hardware → byte-identical final state **Checkpoint-restart**: Stop execution mid-tick, save complete state, restart on different cores → execution continues identically The `replay_multicore_determinism` test provides strong internal verification. It runs identical workloads on multiple cores, checksums the final state, then replays the execution and verifies the checksum matches. This test has passed consistently in internal testing across different hardware configurations. Traditional multi-threaded systems typically cannot pass this test reliably. Running the same program twice may produce different thread interleavings, different memory access patterns, different final states. With MycoEco, the final state is designed to be determined by the initial state and event sequence. ## Biological Inspiration: Mycelial Networks The name "MycoEco" draws from mycology—the study of fungal networks. Mycelium exhibits emergent coordination without central control: - **Decentralised decision-making**: No single "master" node coordinates the network - **Event propagation**: Chemical signals propagate through the network deterministically - **Resource allocation**: Nutrients flow to where they're needed without explicit orchestration - **Fault tolerance**: The network adapts when parts are damaged MycoEco mirrors these properties: **No master core**: Each core is equal. There's no master that serialises operations. **Event propagation**: Events flow through the kernel like chemical signals through mycelium—deterministically, without central coordination. **Load balancing**: The DSE distributes events across cores based on deterministic assignment, naturally balancing load. **Resilience**: If a core fails, events can be reassigned to surviving cores. The system adapts without violating determinism. This biological metaphor reflects a fundamental architectural principle: **emergent order from deterministic rules, not imposed order from central control**. ## Performance Characteristics Lock-free determinism sounds promising in theory, but how does it scale in practice? Note: Performance figures are indicative and depend on workload characteristics, event rates, and hardware configuration. ### Overhead Analysis MycoEco adds three sources of overhead compared to non-deterministic execution: 1. **Event construction** (~50 CPU cycles per event, indicative) 2. **Deterministic sorting** (O(N log N) where N = events per tick) 3. **Digest computation** (cryptographic hashing for verification) Combined, these add approximately 2-5% overhead compared to an equivalent non-deterministic system in internal testing. This is substantially less than lock-based approaches, which can incur 20-40% overhead from contention and context switching in high-contention scenarios. ### Scaling Properties Traditional locked systems can show diminishing returns beyond a certain core count. Adding more cores increases contention, potentially causing throughput to plateau or decrease. MycoEco is designed to show positive scaling up to the point where event sorting becomes the bottleneck. With typical workloads ( Mutex-Based Systems (High Contention) 2-4 cores: Moderate efficiency 8+ cores: Efficiency can decline with contention Worst case: Deadlock or livelock possible Timing: Can be difficult to bound MycoEco (Event-Based) 2-4 cores: Typically high efficiency observed 8-16 cores: Efficiency generally maintained Worst case: Deterministic degradation Timing: Designed to be bounded The key difference: MycoEco's performance is designed to be **predictable**. Worst-case execution time can be bounded. With locks, worst-case can be difficult to bound if contention patterns vary. ## Real-Time Considerations Safety-critical systems require hard real-time guarantees: operations must complete within bounded time. Locks can complicate this through priority inversion and variable blocking times. MycoEco is designed to provide deterministic timing: **Bounded event processing**: Each event processes in time determined by the event handler **Bounded sorting**: Event sorting takes O(N log N) where N is bounded by the maximum events per tick **No priority inversion**: Events execute in deterministic order. No low-priority event can block high-priority execution through lock contention. **Worst-case execution time (WCET)**: Can be analysed statically from the event handlers and maximum event counts This design supports certification to standards like DO-178C Level A and ISO 26262 ASIL D, which require demonstrable worst-case timing bounds. ## PBAS-6 Guardrails: Safety Envelopes MycoEco integrates PBAS-6 (Progressive Bounded Autonomous Systems) guardrails that enforce safety envelopes during execution. These are runtime checks designed to ensure the system remains within safety constraints. At each tick, PBAS-6 checks: - **State validity**: Is the system state within safe bounds? - **Event safety**: Do pending events violate safety constraints? - **Escalation triggers**: Has the system approached constraint boundaries? If a violation is detected, PBAS-6 **escalates** to a safer operating mode: ``` NOMINAL → Normal operation WARNING → Approaching constraint boundary CAUTION → Within safety margin ALERT → Immediate action required CRITICAL → Emergency shutdown initiated ``` The test suite verifies these guardrails: ``` [Envelope (PBAS-6 Guardrails) Tests] envelope_initial... PASS envelope_check... PASS envelope_escalation... PASS guard_state_string... PASS ``` This integration means MycoEco doesn't just provide deterministic execution—it provides **safe deterministic execution** with runtime verification. ## Kernel Size: Under 256KB One of MycoEco's notable properties is its size. The entire kernel—multi-core scheduling, event management, replay capability, cryptographic hashing, PBAS-6 guardrails—fits in under 256KB of memory. ``` [ABI Tests] abi_event_size... PASS abi_envelope_size... PASS abi_kernel_under_256k... PASS ``` For comparison: - **Linux kernel**: ~30MB (minimal configuration) - **FreeRTOS**: ~10KB (but without deterministic multi-core, crypto, or guardrails) - **seL4 (microkernel)**: ~12KB (but without multi-core determinism) MycoEco achieves substantial functionality in a compact footprint. This makes it viable for: - Aerospace applications with strict memory budgets - Medical devices where certification effort scales with code size - Automotive ECUs with limited flash memory - IoT devices requiring deterministic behaviour ## The Certification Consideration Safety certification (DO-178C, ISO 26262, IEC 62304) requires significant effort. Effort tends to scale with: - **Lines of code** (more code = more testing) - **Complexity** (locks and race conditions require extensive analysis) - **Timing variability** (may require probabilistic analysis and larger test suites) MycoEco's architecture can address all three: **Small codebase**: Under 256KB means fewer lines to verify **Simpler semantics**: Event-based architecture can be easier to reason about than lock-based concurrency **Deterministic execution**: Can reduce or constrain classes of timing-related failure modes that require probabilistic analysis This architectural approach may support reduced certification effort compared to conventional RTOS with locks, though actual impact depends on specific system requirements and regulatory context. ## Architectural Implications Many existing systems have been designed under assumptions that prioritise either determinism or scalability. MycoEco demonstrates that these goals need not be mutually exclusive. This has potential implications for several domains: **Autonomous systems**: Can potentially achieve real-time performance with deterministic guarantees, supporting certification of control systems. **Medical devices**: Can leverage multi-core processors while maintaining the determinism that supports regulatory approval. **Aerospace**: Can use commercial multi-core processors in safety-critical avionics while maintaining determinism. **Industrial control**: Can pursue both high performance and high safety integrity levels. ## Frequently Asked Questions ### What is the MycoEco kernel? MycoEco is a deterministic multi-core kernel that achieves lock-free concurrent execution using event-based architecture instead of locks, mutexes, or blocking synchronisation primitives. Its codebase is under 256KB, enabling exhaustive verification for safety-critical deployments across aerospace, medical, and automotive domains. ### How does MycoEco achieve lock-free determinism across multiple cores? MycoEco replaces shared-memory concurrency with event-based message passing between cores. Each core processes events in a deterministic order defined by the scheduler, eliminating data races and lock contention. The same input sequence produces identical execution across runs regardless of hardware timing variations. ### Why can't lock-based concurrency provide the same determinism guarantees? Locks introduce timing-dependent behaviour: thread acquisition order varies between runs depending on scheduling, cache state, and contention. This creates non-deterministic execution paths that grow combinatorially with thread count. Event-based architectures define a fixed processing order, making all execution paths deterministic and testable. ### What are the trade-offs of the MycoEco kernel architecture? Event-based architecture can impose communication overhead compared to direct shared-memory access. The programming model requires restructuring algorithms to use message passing rather than shared state. However, the small codebase simplifies verification, and deterministic execution can reduce or constrain classes of timing-related failures that would otherwise require probabilistic analysis. ## Conclusion MycoEco demonstrates that deterministic, lock-free multi-core execution is achievable within a compact, certifiable kernel architecture. Through event-based architecture, deterministic scheduling, and lock-free coordination, MycoEco provides: - **Deterministic execution** across multiple cores - **Replay capability** for execution verification - **Bounded real-time** characteristics - **Safety envelopes** via PBAS-6 integration - **Minimal footprint** (< 256KB) - **Certification-friendly** architecture The test suite passes 46 tests including multi-core replay verification. The kernel scales efficiently within its design parameters. The architecture supports certification to high safety standards. For organisations building safety-critical systems, MycoEco provides an additional architectural option when balancing performance, predictability, and verification effort. Internal test output summarises the result of deterministic multi-core replay verification: ``` Deterministic multi-core execution verified under test conditions. ``` --- # Technical Articles — AI Architecture Production AI systems, MLOps patterns, and certifiable ML. ## Incident Reconstruction: Beyond It Worked Yesterday **URL**: https://speytech.com/ai-architecture/incident-reconstruction-determinism/ **Published**: January 26, 2026 22:00 **Topic**: AI Architecture **Answers**: How does deterministic execution architecture with bit-perfect replay capability, cryptographic execution tracing through hash chains, and tamper-evident sealed audit logs transform incident reconstruction and root cause analysis in safety-critical systems from conventional log-based guesswork into rigorous and repeatable computational forensics? **Defines**: Deterministic incident reconstruction KEY_CLAIMS: - An autonomous vehicle strikes a pedestrian. - Incident investigation in non-deterministic systems is fundamentally limited. - Deterministic incident reconstruction replays the exact computation that occurred during a safety-critical incident using recorded inputs and verified software. - Bit-perfect replay eliminates the ambiguity of conventional investigation where multiple failure modes might explain observed behaviour. - Conventional logs capture selected events at selected granularity, leaving gaps between recorded states. EVIDENCE: - Safety standards increasingly require demonstrable reconstruction capability: DO-178C (aerospace): Requires that software behaviour be verifiable. - IEC 62304 (medical devices): Requires traceability from requirements through implementation to testing. - ISO 26262 (automotive): Requires evidence of safety. RELATES_TO: - ai-architecture/debugging-model-behavior-production - insights/bit-perfect-reproducibility - insights/cryptographic-proof-execution - insights/implantable-device-litigation How bit-perfect replay, execution tracing, and sealed audit logs transform incident response from guesswork to forensics An autonomous vehicle strikes a pedestrian. A medical device delivers the wrong dose. A trading algorithm loses millions in seconds. In each case, investigators need to answer: What exactly happened? What was the system's state? What inputs did it receive? What decision did it make, and why? For non-deterministic systems, these questions often have no definitive answers. The system cannot be replayed. The state cannot be reconstructed. The best investigators can offer is "we think this probably happened." For deterministic systems with proper audit trails, every question has a precise answer, cryptographically verified and legally defensible. ## The Investigation Problem ### What Investigators Need Post-incident analysis requires reconstructing the exact sequence of events: 1. **Input reconstruction:** What data entered the system? 2. **State reconstruction:** What was the system's internal state at each moment? 3. **Decision reconstruction:** What logic produced the output? 4. **Counterfactual analysis:** Would different inputs have produced different outputs? For safety-critical systems, these aren't academic questions. Regulators demand answers. Liability depends on them. Future safety improvements require understanding what went wrong. ### Why Non-Determinism Defeats Investigation Consider a neural network that misclassified a stop sign: ```python # Somewhere in production output = model.predict(input_image) # output = "speed limit 35" instead of "stop sign" ``` To investigate, you need to answer: Why did the model produce this output? **Problem 1: The model may not be reproducible.** If training used stochastic elements, you can't prove the deployed model matches any specific training run. **Problem 2: Inference may not be reproducible.** If the model uses floating-point with hardware-dependent rounding, the same input might produce different outputs on different machines. **Problem 3: State may not be reconstructible.** If the model has internal state (RNN, attention cache), and that state wasn't logged, you can't know what the model "saw." **Problem 4: Inputs may be incomplete.** If preprocessing was non-deterministic (random cropping, noise injection), you can't reconstruct what the model actually received. The investigation stalls at "we can't reproduce the failure." This is unacceptable for safety-critical systems. ## Deterministic Systems Enable Forensics A deterministic system with proper instrumentation provides complete reconstruction: ### Bit-Perfect Replay If the system is deterministic, you can replay the exact computation: ```c // Recorded incident data incident_record_t incident = load_incident("2026-01-27-14-23-45"); // Reconstruct state at incident time system_t system; system_init(&system, &incident.config); // Replay inputs up to incident for (int i = 0; i timestamp_ns = timestamp; record->sequence_number = log->next_sequence++; record->type = input->type; record->payload_size = sizeof(input_t); memcpy(record->payload, input, sizeof(input_t)); // Extend Merkle chain extend_chain(log, record); } ``` ### State Snapshots Periodic state snapshots enable reconstruction without replaying from the beginning: ```c typedef struct { uint64_t timestamp_ns; uint32_t snapshot_id; uint32_t input_sequence; // Last input processed state_t full_state; // Complete system state uint8_t state_hash[32]; // Hash of serialised state uint8_t chain_hash[32]; // Current Merkle chain position } state_snapshot_t; void take_snapshot(system_t *sys, logger_t *log) { state_snapshot_t snap; snap.timestamp_ns = get_timestamp(); snap.snapshot_id = log->next_snapshot++; snap.input_sequence = log->last_sequence; snap.full_state = sys->state; // Hash the state for integrity verification hash_state(&sys->state, snap.state_hash); // Record current chain position memcpy(snap.chain_hash, log->current_chain_hash, 32); write_snapshot(log, &snap); } ``` To replay to a specific point: 1. Load the nearest preceding snapshot 2. Replay inputs from that snapshot's sequence number ### Decision Traces Every significant decision should be traced: ```c typedef struct { uint64_t timestamp_ns; uint32_t decision_id; decision_type_t type; decision_value_t value; // What inputs influenced this decision uint32_t input_count; input_reference_t inputs[MAX_INPUTS]; // What state influenced this decision state_summary_t state_summary; // The decision logic (which rules fired, which thresholds crossed) uint32_t rule_count; rule_evaluation_t rules[MAX_RULES]; // Hash for integrity uint8_t trace_hash[32]; } decision_trace_t; void trace_decision(logger_t *log, decision_context_t *ctx) { decision_trace_t trace; trace.timestamp_ns = get_timestamp(); trace.decision_id = log->next_decision++; trace.type = ctx->decision_type; trace.value = ctx->decision_value; // Record what influenced this decision trace.input_count = ctx->input_count; for (int i = 0; i input_count; i++) { trace.inputs[i] = ctx->inputs[i]; } // Record relevant state summarise_state(ctx->system_state, &trace.state_summary); // Record which rules evaluated to what trace.rule_count = ctx->rule_count; for (int i = 0; i rule_count; i++) { trace.rules[i] = ctx->rule_evaluations[i]; } // Hash and chain hash_trace(&trace, trace.trace_hash); write_trace(log, &trace); } ``` ## Legal and Regulatory Implications Deterministic reconstruction isn't just technically useful - it has legal weight. ### Admissibility For evidence to be admissible in court, it must be: - **Authentic:** Proven to be what it claims to be - **Reliable:** Generated by a process known to be accurate - **Complete:** Not selectively edited Cryptographically sealed audit trails satisfy all three: - Chain hashes prove authenticity - Deterministic replay proves reliability - Merkle verification proves completeness ### Liability Determination When an incident occurs, liability often depends on proving what the system knew and when: **Without determinism:** "The system may have detected the obstacle, but we can't prove it." **With determinism:** "The system detected the obstacle at timestamp T₁ and classified it as debris. The classification changed to pedestrian at timestamp T₂, 1.3 seconds before impact." The difference matters enormously in litigation. ### Regulatory Compliance Safety standards increasingly require demonstrable reconstruction capability: **DO-178C (aerospace):** Requires that software behaviour be verifiable. Deterministic replay provides verification. **IEC 62304 (medical devices):** Requires traceability from requirements through implementation to testing. Deterministic audit trails extend traceability to runtime. **ISO 26262 (automotive):** Requires evidence of safety. Deterministic reconstruction provides evidence of what happened and why. For more on medical device implications, see [Reproducibility and Post-Incident Analysis in Implantable Cardiac Devices](/insights/implantable-device-litigation/). ## Production Debugging The same infrastructure that enables incident investigation also improves everyday debugging. ### Reproducing Production Issues The classic debugging nightmare: "It fails in production but works in development." With deterministic systems: ```bash # Export production incident $ export-incident --id 12345 --output incident.dat # Import to development environment $ import-incident incident.dat # Replay with debugging $ replay-debug --breakpoint "decision.confidence < 0.5" Replaying incident 12345... Hit breakpoint at frame 847: decision.confidence = 0.47 (debug) print decision { type: CLASSIFY, value: "unknown", confidence: 0.47, inputs: [frame_847, state_846] } (debug) print inputs[0].features { edge_count: 23, color_histogram: [0.2, 0.3, ...], texture_signature: 0x7a3f... } ``` The production failure is now reproducible in development. Debug at leisure. Fix with confidence. ### Root Cause Analysis Deterministic systems enable systematic root cause analysis: ```bash # Find all incidents with similar characteristics $ incident-search --decision-type CLASSIFY --confidence-below 0.5 Found 17 incidents: 12345: frame 847, confidence 0.47 12298: frame 1203, confidence 0.39 12156: frame 512, confidence 0.44 ... # Analyse common factors $ incident-correlate --incidents 12345,12298,12156,... Common factors: - 94% occurred during low-light conditions - 88% involved partially occluded objects - 76% had high background complexity Recommended investigation: perception model performance in low-light, high-complexity scenarios ``` This transforms debugging from "fix the bug you found" to "find all bugs of this type." ## Frequently Asked Questions ### What is deterministic incident reconstruction? Deterministic incident reconstruction replays the exact computation that occurred during a safety-critical incident using recorded inputs and verified software. Unlike conventional log-based analysis that infers what happened, deterministic replay reproduces the actual execution path with cryptographic verification of correctness. ### How does bit-perfect replay improve root cause analysis? Bit-perfect replay eliminates the ambiguity of conventional investigation where multiple failure modes might explain observed behaviour. Given recorded inputs and the verified software version, the exact state at every computation step is reproduced — not simulated or approximated. Root cause identification becomes verification rather than hypothesis testing. ### Why can't conventional logging provide the same incident reconstruction capability? Conventional logs capture selected events at selected granularity, leaving gaps between recorded states. Investigators must infer the computation between log entries, introducing uncertainty. Deterministic systems with complete input recording can replay the full execution, eliminating inferential gaps and producing cryptographically verifiable evidence. ### What infrastructure does deterministic incident reconstruction require? The system needs deterministic execution architecture, tick-granularity recording of all external inputs, cryptographic hash chains for tamper-evident state tracking, and sufficient storage for execution traces. Modern systems can store hours of detailed traces. The investment is in architecture design, not runtime overhead — recording adds minimal latency. ## Conclusion Incident investigation in non-deterministic systems is fundamentally limited. You can hypothesise what happened, but you cannot prove it. You can guess at causes, but you cannot verify them. You can propose fixes, but you cannot confirm they address the actual problem. Deterministic systems with proper audit infrastructure transform investigation from guesswork to forensics: - **Bit-perfect replay** reconstructs the exact computation - **Sealed audit trails** prove logs haven't been tampered with - **Decision traces** explain not just what happened, but why The infrastructure investment is significant: input logging, state snapshots, decision tracing, Merkle chains. But for safety-critical systems, this investment is essential. When an autonomous vehicle crashes or a medical device malfunctions, "we don't know what happened" is not an acceptable answer. The [certifiable-* ecosystem](https://github.com/SpeyTech) implements these patterns. [Debugging Model Behavior in Production](/ai-architecture/debugging-model-behavior-production/) covers practical debugging strategies. [Bit-Perfect Reproducibility](/insights/bit-perfect-reproducibility/) explains the underlying determinism requirements. "It worked yesterday" is not evidence. Cryptographically sealed replay logs are evidence. Build systems that can prove what happened. --- ## Version Control for Deterministic Systems: Git Isn't Enough **URL**: https://speytech.com/ai-architecture/version-control-deterministic-systems/ **Published**: January 26, 2026 21:15 **Topic**: AI Architecture **Answers**: Why is Git alone insufficient for version control and configuration management in deterministic safety-critical systems requiring formal certification evidence, and how do Merkle chains, cryptographic attestation of build artifacts, and fully reproducible builds provide the tamper-evident evidence trail that standards demand? **Defines**: Merkle chain version control KEY_CLAIMS: - Git is excellent version control. - Cryptographic attestation binds build artifacts to their source through Merkle trees and digital signatures, providing tamper-evident proof that deployed software matches certified source. - Git is necessary but not sufficient for safety-critical systems. - Git tracks source code but cannot verify binary reproducibility, data provenance, or deployment integrity. - Merkle chains provide tamper-evident records of data provenance, training history, build artefacts, and deployment attestation — properties Git does not track. EVIDENCE: - DO-178C Level A software - the kind that can crash an aircraft if it fails - requires: Configuration Management: Every artefact (source, object code, executable, test data) must be identified, controlled, and traceable. - Q16.16 operations produce identical results on any platform. RELATES_TO: - insights/cryptographic-proof-execution - insights/feistel-shuffle-deterministic - insights/merkle-chains-ml-audit How Merkle chains, cryptographic attestation, and reproducible builds satisfy certification evidence requirements Git is excellent version control. It tracks source code changes, enables collaboration, and provides complete history of who changed what and when. But Git tracks *source*. It says nothing about: - Whether the same source produces the same binary - What training data produced a given model - Whether the deployed model matches the trained model - What the system's state was at any historical point For safety-critical systems governed by DO-178C, IEC 62304, or ISO 26262, these gaps are disqualifying. Certification requires traceability from requirements through implementation to deployed artefacts. "Trust me, I committed it" isn't evidence. Definition: Cryptographic Attestation Cryptographic attestation binds build artifacts to their source through Merkle trees and digital signatures, providing tamper-evident proof that deployed software matches certified source. ## What Certification Actually Requires ### DO-178C (Aerospace) DO-178C Level A software - the kind that can crash an aircraft if it fails - requires: **Configuration Management:** Every artefact (source, object code, executable, test data) must be identified, controlled, and traceable. **Traceability:** Requirements trace to design, design traces to code, code traces to tests, tests trace to results. Bidirectionally. **Reproducibility:** Given the same inputs (source, compiler, configuration), the build process must produce the same outputs. Always. **Data Integrity:** Evidence that artefacts haven't been modified since verification. Git provides some of this - commit hashes identify source versions, history shows changes. But Git doesn't verify that yesterday's build produces today's binary. Git doesn't track which dataset trained which model. Git doesn't attest that the deployed binary matches the verified one. ### IEC 62304 (Medical Devices) Class C medical device software - software whose failure could cause death - has similar requirements: **Software Configuration Management:** Identify and control all software items, including documentation, source code, and executables. **Traceability Matrix:** Map between requirements, design, implementation, and verification. **Problem Resolution:** Track every issue from discovery through resolution, with evidence. Again, Git handles source. But a neural network model isn't source code. Training data isn't source code. The relationship between a dataset, a training run, and a resulting model isn't captured in commits. ### ISO 26262 (Automotive) ASIL-D software - the highest automotive safety integrity level - requires: **Configuration Management:** Control of all work products, including code, documentation, and calibration data. **Change Management:** Every change must be authorised, implemented, verified, and recorded. **Baseline Management:** Consistent sets of items that form a release must be identified and controlled. For autonomous vehicles using machine learning, the "calibration data" includes training datasets and model weights. These aren't text files that diff cleanly in Git. ## The ML Pipeline Problem Machine learning makes version control harder because the artefacts are different: ### Training Data A dataset might be: - 100GB of images - Continuously updated from production - Preprocessed through multiple stages - Augmented with synthetic variations Git isn't designed for this. LFS helps with large files but doesn't provide cryptographic integrity verification. DVC tracks data but doesn't create certification-grade audit trails. **What certification needs:** Proof that the exact data used to train model version X was dataset version Y, with cryptographic verification that neither has been modified. ### Training Process A training run involves: - Random initialisation (or does it?) - Stochastic gradient descent with shuffled batches - Hardware-dependent floating-point behaviour - Non-deterministic GPU operations - Hyperparameter choices that may not be recorded Two training runs with "the same" configuration often produce different models. Which one was deployed? Which one was verified? Can you prove it? **What certification needs:** A complete, reproducible record of every training step, with cryptographic proof that the final model is the product of that exact process. ### Model Artefacts A trained model is: - Weights (potentially gigabytes of floating-point numbers) - Architecture definition - Preprocessing configuration - Postprocessing logic - Runtime dependencies These aren't source code. They're binary artefacts that must be tracked, versioned, and verified with the same rigour as source. **What certification needs:** Cryptographic attestation that the deployed model is bit-identical to the verified model, with a chain of custody from training through deployment. ## Merkle Chains: Cryptographic Audit Trails The [certifiable-* ecosystem](https://github.com/SpeyTech) addresses these requirements using Merkle chains - the same cryptographic structure that secures blockchains, but applied to ML pipeline provenance. ### How Merkle Chains Work A Merkle chain is a sequence of cryptographic hashes where each hash includes the previous hash: ``` H₀ = SHA256(initial_state) H₁ = SHA256(H₀ || step_1_data) H₂ = SHA256(H₁ || step_2_data) ... Hₙ = SHA256(Hₙ₋₁ || step_n_data) ``` This creates a tamper-evident chain: - Changing any step invalidates all subsequent hashes - The final hash commits to the entire history - Verification requires only the final hash and the step data ### Applied to ML Pipelines The [certifiable-data](https://github.com/SpeyTech/certifiable-data) project creates Merkle chains for data pipelines: ```c // Each data batch gets a hash that chains to previous batches typedef struct { uint8_t prev_hash[32]; // Previous batch hash uint8_t data_hash[32]; // This batch's content hash uint64_t batch_index; // Monotonic batch number uint64_t timestamp; // Processing timestamp uint8_t chain_hash[32]; // H(prev_hash || data_hash || metadata) } data_provenance_t; ``` When training begins, the initial data state is hashed. Each preprocessing step - normalisation, augmentation, shuffling - extends the chain. The final chain hash commits to the entire data preparation process. ### Training Chains The [certifiable-training](https://github.com/SpeyTech/certifiable-training) project extends this to training: ```c // Each training step extends the Merkle chain typedef struct { uint8_t prev_hash[32]; // Previous step hash uint8_t weights_hash[32]; // Current weights hash uint8_t gradients_hash[32];// This step's gradients uint32_t epoch; uint32_t batch; uint8_t chain_hash[32]; // Commits to entire training history } training_step_t; ``` Every gradient update is recorded. The chain hash after training commits to: - The initial weights - Every batch of training data (via data chain) - Every gradient computation - Every weight update - The final model This isn't logging - it's cryptographic proof. Given the chain, anyone can verify that the final model is the exact product of that training process. ### Deployment Attestation The [certifiable-deploy](https://github.com/SpeyTech/certifiable-deploy) project packages models with cryptographic attestation: ```c // Deployment bundle with attestation typedef struct { uint8_t model_hash[32]; // Hash of model weights uint8_t training_chain[32]; // Final training chain hash uint8_t data_chain[32]; // Final data chain hash uint8_t source_commit[20]; // Git commit of training code uint8_t config_hash[32]; // Hash of all configuration uint8_t bundle_signature[64]; // Ed25519 signature over all above } deployment_attestation_t; ``` The deployment bundle includes: - The model itself - Cryptographic proof of its provenance - Signature from an authorised build system Verification checks that: 1. The model hash matches the bundle contents 2. The training chain is valid 3. The data chain is valid 4. The signature is valid If any check fails, the model is rejected. There's no way to deploy a model without valid provenance. ## Reproducible Builds Cryptographic hashes prove that artefacts haven't changed. But certification also requires *reproducibility* - the ability to recreate artefacts from source. ### The Reproducibility Problem Traditional builds are not reproducible: ```bash $ gcc -O2 main.c -o program $ sha256sum program a1b2c3d4... $ gcc -O2 main.c -o program # Same command, same source $ sha256sum program e5f6g7h8... # Different hash! ``` The difference comes from: - Timestamps embedded in binaries - Non-deterministic compiler optimisations - File ordering in archives - Environment-dependent paths For certification, this is unacceptable. If you can't reproduce the binary, you can't verify it. ### Deterministic Compilation The certifiable-* projects enforce deterministic builds: ```makefile # Reproducible build flags CFLAGS += -fno-guess-branch-probability # Deterministic optimisation CFLAGS += -frandom-seed=fixed # Fixed randomisation seed CFLAGS += -D__DATE__="\"Jan 01 2026\"" # Fixed date CFLAGS += -D__TIME__="\"00:00:00\"" # Fixed time # Reproducible archive creation AR_FLAGS = Dcr # Deterministic mode, no timestamps ``` With these flags, the same source always produces the same binary. The binary hash becomes a verifiable identifier. ### Deterministic Training Neural network training is notoriously non-reproducible. The [certifiable-training](https://github.com/SpeyTech/certifiable-training) approach eliminates non-determinism: **Fixed-point arithmetic:** No floating-point means no hardware-dependent rounding. Q16.16 operations produce identical results on any platform. **Deterministic shuffling:** Feistel-based shuffling with fixed seeds, as described in [The Feistel Shuffle](/insights/feistel-shuffle-deterministic/), provides reproducible data ordering. **Deterministic reduction:** Gradient accumulation uses fixed ordering, eliminating parallel reduction non-determinism. **Explicit random seeds:** All randomness comes from seeded PRNGs with recorded seeds. The result: given the same data, configuration, and seeds, training produces bit-identical models on any platform. ## The Evidence Package Certification auditors don't just want hashes - they want a complete evidence package that demonstrates compliance. ### Requirements Traceability Matrix ``` REQ-001: System shall detect anomalies within 100ms → DESIGN-001: Use EMA-based baseline with O(1) update → CODE: baseline.c:update_monitoring() → TEST: test_baseline.c:test_detection_latency() → RESULT: PASS (avg 2.3ms, max 8.1ms) ``` Git tracks the code. The Merkle chain tracks the test results. Together they provide bidirectional traceability. ### Configuration Baseline A baseline captures the complete state at a release point: ```json { "baseline_id": "v1.2.0", "timestamp": "2026-01-27T10:00:00Z", "components": { "source": { "repository": "speytech/certifiable-inference", "commit": "abc123...", "commit_hash": "sha256:def456..." }, "training_data": { "dataset": "sensor-readings-v3", "chain_hash": "sha256:789abc..." }, "model": { "architecture": "cnn-small", "weights_hash": "sha256:fed987...", "training_chain": "sha256:654321..." }, "binary": { "platform": "arm64-linux", "hash": "sha256:aabbcc..." } }, "attestation": { "signer": "build-system-key-001", "signature": "ed25519:..." } } ``` This baseline is a complete, verifiable snapshot. Given this document, auditors can: - Retrieve the exact source code - Verify the training data provenance - Verify the model provenance - Reproduce the binary - Confirm nothing has been modified ### Change Control Records Every change to a baselined system requires documentation: ```json { "change_id": "CR-2026-001", "baseline_from": "v1.2.0", "baseline_to": "v1.2.1", "description": "Update anomaly threshold from 3.0 to 2.5 sigma", "justification": "Field data shows 3.0 sigma misses 12% of anomalies", "impact_analysis": { "code_changes": ["config.h:ANOMALY_THRESHOLD"], "test_changes": ["test_baseline.c:test_threshold_values"], "documentation_changes": ["user-manual.md:section-4.2"] }, "verification": { "tests_passed": true, "regression_clear": true, "review_approved": "2026-01-26" }, "approval": { "approver": "quality-manager", "date": "2026-01-27", "signature": "ed25519:..." } } ``` This isn't bureaucracy - it's evidence that changes are controlled, reviewed, and verified. The cryptographic signatures make it tamper-evident. ## Practical Implementation ### Directory Structure A certifiable project includes evidence alongside code: ``` project/ ├── src/ # Source code (Git tracked) ├── include/ # Headers (Git tracked) ├── tests/ # Test code (Git tracked) ├── evidence/ # Certification evidence │ ├── requirements/ # Requirements documents │ ├── design/ # Design documents │ ├── traceability/ # RTM and matrices │ ├── test-results/ # Test execution records │ └── baselines/ # Release baselines ├── chains/ # Merkle chain data │ ├── data/ # Data provenance chains │ ├── training/ # Training step chains │ └── builds/ # Build attestations └── releases/ # Signed release packages ``` ### Automated Chain Generation The Merkle chains are generated automatically during pipeline execution: ```c // During data preprocessing void process_batch(batch_t *batch, chain_t *chain) { // Process the data normalize(batch); augment(batch); // Extend the chain uint8_t batch_hash[32]; sha256(batch->data, batch->size, batch_hash); chain_extend(chain, batch_hash); } // During training void training_step(model_t *model, batch_t *batch, chain_t *chain) { // Compute gradients gradient_t grads = compute_gradients(model, batch); // Update weights apply_gradients(model, &grads); // Extend chain with step record step_record_t record = { .weights_hash = hash_weights(model), .gradients_hash = hash_gradients(&grads), .batch_index = batch->index }; chain_extend(chain, &record); } ``` The chain generation is part of normal operation, not a separate audit step. ### Verification Tools The [certifiable-verify](https://github.com/SpeyTech/certifiable-verify) project provides verification tools: ```bash # Verify a deployment bundle $ certify-verify bundle model-v1.2.0.cbf Verifying bundle: model-v1.2.0.cbf Model hash: OK (matches embedded hash) Training chain: OK (2,847 steps verified) Data chain: OK (1,203 batches verified) Signature: OK (signed by build-key-001) Bundle verification: PASSED # Reproduce and verify a build $ certify-rebuild --baseline v1.2.0 --verify Rebuilding from baseline v1.2.0 Fetching source: abc123... Fetching config: def456... Building: arm64-linux Binary hash: sha256:aabbcc... Expected: sha256:aabbcc... Reproduction: MATCHED ``` These tools enable auditors to verify claims independently. ## Integration with Git The Merkle chain approach complements Git rather than replacing it: **Git tracks:** Source code, configuration files, documentation, test code **Chains track:** Data provenance, training history, build artefacts, deployment attestation **Together they provide:** Complete traceability from requirements through deployment The connection points are explicit: ```json { "training_chain_final": "sha256:abc123...", "source_commit": "git:def456...", "link_attestation": "This training chain was produced by code at commit def456..." } ``` ## Frequently Asked Questions ### Why is Git alone insufficient for version control in deterministic safety-critical systems? Git tracks source code but cannot verify binary reproducibility, data provenance, or deployment integrity. Certification requires evidence of all of these properties. ### How do Merkle chains complement Git for safety-critical version control? Merkle chains provide tamper-evident records of data provenance, training history, build artefacts, and deployment attestation — properties Git does not track. Together, Git and Merkle chains provide complete traceability from requirements through source code, training data, model weights, build artefacts, and deployment verification. ### Why can't reproducible builds alone satisfy certification requirements? Reproducible builds verify that the same source produces the same binary, but do not cover data provenance, training reproducibility, or deployment integrity. Certification standards require evidence across the complete lifecycle — from requirements through deployment. Merkle chains capture the stages that reproducible builds miss. ### What are the trade-offs of Merkle chain version control? Merkle chains add hash computation overhead, require chain storage, and increase toolchain complexity. The benefit is cryptographic proof of integrity at every stage — tamper-evident evidence that certification assessors can verify independently. ## Conclusion Git is necessary but not sufficient for safety-critical systems. Source control tracks code changes, but certification requires tracking everything: data, training, builds, and deployments. Merkle chains provide the cryptographic foundation: - Tamper-evident history that proves integrity - Verifiable provenance from data to deployment - Reproducible builds that auditors can check The [certifiable-* ecosystem](https://github.com/SpeyTech) implements these patterns for ML pipelines, as detailed in [Merkle Chains for ML Audit Trails](/insights/merkle-chains-ml-audit/) and [Cryptographic Execution Tracing](/insights/cryptographic-proof-execution/). The overhead is real - generating chains, storing evidence, maintaining baselines all require effort. But for systems where certification is required, this overhead is unavoidable. The choice is between systematic evidence generation and ad-hoc documentation that auditors will reject. For systems that don't require formal certification, the same principles provide value: reproducible builds catch "works on my machine" problems, provenance chains enable debugging, and attestation prevents accidental deployment of wrong artefacts. Git tracks what you wrote. Merkle chains prove what you built. --- ## Testing ML Systems: Beyond Unit Tests and Accuracy Metrics **URL**: https://speytech.com/ai-architecture/ml-testing-systems/ **Published**: January 24, 2026 00:30 **Topic**: AI Architecture **Answers**: What testing strategies go beyond basic unit tests and aggregate accuracy metrics for production machine learning systems, and how do you systematically test for data distribution drift, model degradation over time, infrastructure integration failures, and edge case behaviour in ML pipelines? KEY_CLAIMS: - Production ML testing requires five layers: data validation, unit tests, model validation, integration tests, and production testing. - Validate input data distributions against training baselines using statistical tests at ingestion time. - Accuracy is an aggregate metric that hides performance variance across subgroups, edge cases, and distribution shifts. - ML systems have statistical failure modes where the system functions correctly at the infrastructure level but produces subtly wrong predictions. RELATES_TO: - ai-architecture/ml-graceful-degradation - ai-architecture/ml-observability-blind-spot A practical testing strategy for production machine learning The model passes all tests. Accuracy is 94%. The PR gets approved. Three days later, production is on fire. Predictions are nonsense. Customer complaints flood in. The post-mortem reveals: a feature column changed upstream. The schema was the same. The values were garbage. No test caught it because no test checked for it. ML testing isn't just unit tests and accuracy metrics. Production ML systems fail in ways that traditional software testing doesn't anticipate — data drift, distribution shift, feature corruption, silent model degradation. A comprehensive testing strategy addresses these failure modes at every layer. ## The ML Testing Pyramid Like the traditional testing pyramid, ML testing has layers. Unlike traditional testing, the base isn't unit tests — it's data validation. **Data validation** (base, most tests): Schema checks, distribution validation, drift detection, anomaly flagging. Data problems cause most ML failures. Test data first. **Unit tests**: Preprocessing functions, feature engineering, data transformations. Traditional software tests for the code that touches data. **Model validation**: Performance metrics, slice analysis, fairness checks, regression tests. Does the model behave correctly on known cases? **Integration tests**: End-to-end pipeline tests, API contract tests, latency validation. Does everything work together? **Production testing** (top, fewest but critical): Shadow deployment, canary analysis, A/B testing. Does it work with real traffic? Invest proportionally: most effort at the base, less as you go up. Data tests catch more bugs than model tests. Model tests catch more bugs than integration tests. But you need all layers. ## Layer 1: Data Validation Data validation catches problems before they reach your model. This is where testing effort pays the highest returns. ### Schema Validation The minimum viable data test: does the data have the expected structure? ```python from dataclasses import dataclass from typing import List, Dict, Any, Set import pandas as pd @dataclass class ColumnSchema: name: str dtype: str nullable: bool = False allowed_values: Set[Any] = None min_value: float = None max_value: float = None class SchemaValidator: def __init__(self, schema: List[ColumnSchema]): self.schema = {col.name: col for col in schema} def validate(self, df: pd.DataFrame) -> List[str]: errors = [] # Check for missing columns missing = set(self.schema.keys()) - set(df.columns) if missing: errors.append(f"Missing columns: {missing}") # Check for unexpected columns unexpected = set(df.columns) - set(self.schema.keys()) if unexpected: errors.append(f"Unexpected columns: {unexpected}") # Validate each column for col_name, col_schema in self.schema.items(): if col_name not in df.columns: continue col = df[col_name] # Nullability if not col_schema.nullable and col.isna().any(): null_count = col.isna().sum() errors.append(f"{col_name}: {null_count} null values (not allowed)") # Allowed values (for categoricals) if col_schema.allowed_values: invalid = set(col.dropna().unique()) - col_schema.allowed_values if invalid: errors.append(f"{col_name}: invalid values {invalid}") # Range checks if col_schema.min_value is not None: below_min = (col col_schema.max_value).sum() if above_max: errors.append(f"{col_name}: {above_max} values above {col_schema.max_value}") return errors # Usage schema = [ ColumnSchema("user_id", "int64", nullable=False), ColumnSchema("amount", "float64", nullable=False, min_value=0), ColumnSchema("category", "object", allowed_values={"A", "B", "C"}), ColumnSchema("timestamp", "datetime64[ns]", nullable=False), ] validator = SchemaValidator(schema) errors = validator.validate(incoming_data) if errors: raise DataValidationError(errors) ``` Run schema validation on every data ingestion. Block the pipeline if validation fails. Silent data corruption is worse than a failed pipeline. ### Distribution Validation Schema can be correct while data is garbage. Distribution checks catch semantic problems: ```python import numpy as np from scipy import stats class DistributionValidator: def __init__(self, reference_stats: Dict[str, Dict]): self.reference = reference_stats def validate(self, df: pd.DataFrame, threshold: float = 0.1) -> List[str]: warnings = [] for col_name, ref_stats in self.reference.items(): if col_name not in df.columns: continue col = df[col_name].dropna() # Numeric columns: check mean/std shift if 'mean' in ref_stats: current_mean = col.mean() ref_mean = ref_stats['mean'] ref_std = ref_stats['std'] # Z-score of mean shift if ref_std > 0: z_score = abs(current_mean - ref_mean) / ref_std if z_score > 3: warnings.append( f"{col_name}: mean shifted from {ref_mean:.2f} to {current_mean:.2f} " f"(z={z_score:.1f})" ) # Categorical columns: check distribution shift if 'value_counts' in ref_stats: current_dist = col.value_counts(normalize=True).to_dict() ref_dist = ref_stats['value_counts'] # Simple distribution comparison for value, ref_pct in ref_dist.items(): current_pct = current_dist.get(value, 0) if abs(current_pct - ref_pct) > threshold: warnings.append( f"{col_name}={value}: {ref_pct:.1%} -> {current_pct:.1%}" ) return warnings @classmethod def from_dataframe(cls, df: pd.DataFrame) -> 'DistributionValidator': """Create validator from reference dataframe.""" stats = {} for col in df.columns: if df[col].dtype in ['int64', 'float64']: stats[col] = { 'mean': df[col].mean(), 'std': df[col].std(), 'min': df[col].min(), 'max': df[col].max() } else: stats[col] = { 'value_counts': df[col].value_counts(normalize=True).to_dict() } return cls(stats) ``` Generate reference statistics from known-good training data. Compare incoming data against reference. Alert on significant drift. ### Data Expectations For more sophisticated validation, define expectations declaratively: ```python # Using a Great Expectations-style approach expectations = [ # Column existence {"type": "expect_column_to_exist", "column": "user_id"}, {"type": "expect_column_to_exist", "column": "amount"}, # Type checks {"type": "expect_column_values_to_be_of_type", "column": "amount", "type": "float"}, # Value constraints {"type": "expect_column_values_to_be_between", "column": "amount", "min": 0, "max": 1000000}, {"type": "expect_column_values_to_not_be_null", "column": "user_id"}, # Distribution checks {"type": "expect_column_mean_to_be_between", "column": "amount", "min": 50, "max": 500}, {"type": "expect_column_proportion_of_unique_values_to_be_between", "column": "category", "min": 0.001, "max": 0.1}, # Cardinality {"type": "expect_column_unique_value_count_to_be_between", "column": "category", "min": 3, "max": 10}, ] ``` Declarative expectations serve as documentation and tests simultaneously. They're readable, maintainable, and version-controllable. ## Layer 2: Unit Tests Unit tests cover the code that transforms data: preprocessing, feature engineering, custom layers. ```python import pytest import numpy as np class TestFeatureEngineering: def test_normalize_standard_case(self): result = normalize(50, min_val=0, max_val=100) assert result == 0.5 def test_normalize_edge_cases(self): assert normalize(0, min_val=0, max_val=100) == 0.0 assert normalize(100, min_val=0, max_val=100) == 1.0 def test_normalize_out_of_range(self): # Should clip, not crash assert normalize(150, min_val=0, max_val=100) == 1.0 assert normalize(-50, min_val=0, max_val=100) == 0.0 def test_extract_features_shape(self): transaction = {"amount": 100, "category": "retail", "hour": 14} features = extract_features(transaction) assert features.shape == (128,) assert features.dtype == np.float32 def test_extract_features_deterministic(self): transaction = {"amount": 100, "category": "retail", "hour": 14} f1 = extract_features(transaction) f2 = extract_features(transaction) np.testing.assert_array_equal(f1, f2) def test_extract_features_missing_field(self): transaction = {"amount": 100} # Missing category and hour with pytest.raises(ValueError, match="missing required field"): extract_features(transaction) ``` Property-based testing catches edge cases you didn't think of: ```python from hypothesis import given, strategies as st @given(st.floats(min_value=-1e6, max_value=1e6, allow_nan=False)) def test_normalize_always_returns_valid_range(value): result = normalize(value, min_val=0, max_val=100) assert 0.0 Dict: """Evaluate model performance on a specific data slice.""" mask = slice_fn(X) X_slice = X[mask] y_slice = y[mask] if len(X_slice) == 0: return {"slice": slice_name, "count": 0, "metrics": None} y_pred = model.predict(X_slice) return { "slice": slice_name, "count": len(X_slice), "metrics": { "accuracy": accuracy_score(y_slice, y_pred), "precision": precision_score(y_slice, y_pred, average='weighted'), "recall": recall_score(y_slice, y_pred, average='weighted'), } } # Define critical slices slices = [ ("new_users", lambda X: X["account_age_days"] 1000), ("mobile", lambda X: X["device_type"] == "mobile"), ("international", lambda X: X["country"] != "US"), ] # Evaluate and assert minimums for slice_name, slice_fn in slices: result = evaluate_by_slice(model, X_test, y_test, slice_fn, slice_name) if result["count"] > 100: # Only check slices with enough data assert result["metrics"]["accuracy"] > 0.85, \ f"Accuracy on {slice_name} below threshold: {result['metrics']['accuracy']}" ``` ### Regression Testing Keep a set of known examples with expected predictions. Test that the model still handles them correctly: ```python # regression_cases.json [ { "id": "obvious_fraud_1", "input": {"amount": 9999, "country": "XX", "velocity": 50}, "expected_class": "fraud", "min_confidence": 0.9 }, { "id": "obvious_legitimate_1", "input": {"amount": 25, "country": "US", "velocity": 1}, "expected_class": "legitimate", "min_confidence": 0.8 }, { "id": "edge_case_high_amount_trusted_user", "input": {"amount": 5000, "country": "US", "velocity": 1, "account_age": 3650}, "expected_class": "legitimate", "min_confidence": 0.6 } ] def test_regression_cases(model, cases_file: str): with open(cases_file) as f: cases = json.load(f) failures = [] for case in cases: pred = model.predict_proba(case["input"]) pred_class = model.predict(case["input"]) if pred_class != case["expected_class"]: failures.append(f"{case['id']}: expected {case['expected_class']}, got {pred_class}") elif pred[case["expected_class"]] < case["min_confidence"]: failures.append( f"{case['id']}: confidence {pred[case['expected_class']]:.2f} " f"below threshold {case['min_confidence']}" ) assert not failures, f"Regression failures:\n" + "\n".join(failures) ``` Add cases when you find bugs. The regression suite grows over time, encoding institutional knowledge about edge cases. ### Fairness Checks Test for unintended bias across protected attributes: ```python def test_demographic_parity(model, X, sensitive_attr: str, threshold: float = 0.1): """Check that positive prediction rate is similar across groups.""" predictions = model.predict(X) groups = X[sensitive_attr].unique() positive_rates = {} for group in groups: mask = X[sensitive_attr] == group positive_rates[group] = predictions[mask].mean() max_rate = max(positive_rates.values()) min_rate = min(positive_rates.values()) disparity = max_rate - min_rate assert disparity < threshold, \ f"Demographic disparity {disparity:.2%} exceeds threshold. Rates: {positive_rates}" ``` ## Layer 4: Integration Tests Integration tests verify the full pipeline works end-to-end: ```python def test_inference_pipeline_e2e(): """Test complete inference pipeline with realistic request.""" # Setup client = TestClient(app) sample_request = load_fixture("sample_inference_request.json") # Execute start = time.monotonic() response = client.post("/predict", json=sample_request) latency_ms = (time.monotonic() - start) * 1000 # Verify assert response.status_code == 200 assert "prediction" in response.json() assert "confidence" in response.json() assert 0 <= response.json()["confidence"] <= 1 assert latency_ms < 100, f"Latency {latency_ms}ms exceeds 100ms SLA" def test_training_pipeline_e2e(): """Test complete training pipeline produces valid model.""" # Run training on small dataset result = training_pipeline.run( data_path="test_fixtures/small_training_set.parquet", output_path="/tmp/test_model", epochs=2 ) # Verify outputs assert result.status == "success" assert os.path.exists("/tmp/test_model/model.pt") assert os.path.exists("/tmp/test_model/metrics.json") # Verify model loads and predicts model = load_model("/tmp/test_model") test_input = load_fixture("sample_input.json") prediction = model.predict(test_input) assert prediction is not None ``` ## Layer 5: Production Testing The final layer tests in production, with real traffic. ### Shadow Deployment Run the new model alongside production, compare outputs, don't serve results: ```python class ShadowDeployment: def __init__(self, prod_model, shadow_model, sample_rate: float = 0.1): self.prod = prod_model self.shadow = shadow_model self.sample_rate = sample_rate self.comparisons = [] def predict(self, input_data): # Always get production prediction prod_result = self.prod.predict(input_data) # Conditionally run shadow if random.random() < self.sample_rate: shadow_result = self.shadow.predict(input_data) self.comparisons.append({ "input_hash": hash_input(input_data), "prod": prod_result, "shadow": shadow_result, "match": prod_result == shadow_result }) # Always return production result return prod_result ``` ### Canary Analysis Route small percentage of traffic to new model, monitor for degradation: ```python def analyze_canary(control_metrics: Dict, canary_metrics: Dict, threshold: float = 0.05): """Compare canary against control, return go/no-go decision.""" checks = [] # Error rate comparison error_increase = canary_metrics["error_rate"] - control_metrics["error_rate"] checks.append({ "metric": "error_rate", "control": control_metrics["error_rate"], "canary": canary_metrics["error_rate"], "pass": error_increase < threshold }) # Latency comparison latency_increase = (canary_metrics["p99_latency"] - control_metrics["p99_latency"]) / control_metrics["p99_latency"] checks.append({ "metric": "p99_latency", "control": control_metrics["p99_latency"], "canary": canary_metrics["p99_latency"], "pass": latency_increase < 0.2 # Allow 20% latency increase }) all_passed = all(c["pass"] for c in checks) return {"decision": "proceed" if all_passed else "rollback", "checks": checks} ``` ## Frequently Asked Questions ### What testing strategies go beyond unit tests for production ML systems? Production ML testing requires five layers: data validation, unit tests, model validation, integration tests, and production testing. Each layer catches failure modes the others miss. ### How do I test for data drift in ML pipelines? Validate input data distributions against training baselines using statistical tests at ingestion time. Check schema compliance, value range bounds, null rates, and feature correlation matrices. Automate these checks as pipeline gates that block training or serving when distributions diverge beyond defined thresholds. ### Why doesn't high test accuracy guarantee production ML reliability? Accuracy is an aggregate metric that hides performance variance across subgroups, edge cases, and distribution shifts. A model with 94% overall accuracy may fail completely on a minority subgroup representing 2% of traffic. Integration failures, feature pipeline bugs, and infrastructure issues cause production failures that accuracy metrics never measure. ### What are the limitations of ML testing compared to traditional software testing? ML systems have statistical failure modes where the system functions correctly at the infrastructure level but produces subtly wrong predictions. Ground truth labels may not be available in production. Testing for all input distributions is impossible — testing must be ongoing, not just pre-deployment, with continuous monitoring for behavioural drift. ## The Testing Mindset ML testing isn't a phase — it's continuous. Data changes. Models drift. Production reveals failure modes that tests missed. Build testing into the pipeline: - Data validation on every ingestion - Unit tests on every commit - Model validation on every training run - Integration tests on every deployment - Production testing on every release The goal isn't perfect coverage — it's catching problems before users do. Every production incident should add a test. Over time, your test suite encodes everything you've learned about how your system fails. --- *For more on ML system reliability, see [The Observability Blind Spot](/ai-architecture/ml-observability-blind-spot/) for monitoring production systems, and [Graceful Degradation in ML Systems](/ai-architecture/ml-graceful-degradation/) for handling failures gracefully. For deterministic testing approaches, explore [certifiable-harness](https://github.com/SpeyTech/certifiable-harness).* --- ## Cost Engineering for ML Infrastructure **URL**: https://speytech.com/ai-architecture/ml-cost-engineering/ **Published**: January 24, 2026 00:05 **Topic**: AI Architecture **Answers**: Where does the money actually go in production machine learning infrastructure, which cost categories do engineering teams most commonly misjudge or overlook, and what should teams optimise first when managing compute costs across model training, real-time inference, data storage, and pipeline operations? KEY_CLAIMS: - Note: Cost figures in this article are indicative estimates based on typical cloud pricing patterns. - Storage and idle compute typically dominate ML infrastructure costs, not GPU training runs. - Start by measuring actual GPU utilisation during inference — most serving clusters run well below capacity. - Aggregate cloud spend hides which components drive costs and which are waste. - Eliminate idle resources before optimising active workloads. EVIDENCE: - Cost difference is dramatic: S3 Standard: ~$0.023/GB/month S3 Infrequent Access: ~$0.0125/GB/month S3 Glacier: ~$0.004/GB/month Moving 10TB from Standard to Glacier saves roughly $190/month. RELATES_TO: - ai-architecture/ml-graceful-degradation - ai-architecture/when-you-dont-need-feature-store Where the money goes in ML infrastructure and what to optimise first Note: Cost figures in this article are indicative estimates based on typical cloud pricing patterns. Actual costs vary significantly based on provider, region, commitment level, and workload characteristics. Use these as directional guidance, not precise projections. The conversation usually starts with GPUs. "We need more GPUs." "GPU costs are killing us." "If we had better GPUs, we could train faster." GPUs are expensive. They're also visible — big line items that draw attention. But in most ML infrastructure deployments, GPUs aren't where the money actually goes. Or rather, they're not where the *waste* goes. The biggest cost savings in ML infrastructure rarely come from GPU optimisation. They come from the boring stuff: storage nobody remembers to delete, compute that sits idle, data that crosses network boundaries repeatedly, and operational complexity that requires expensive humans to manage. ## Where Cost Actually Goes A typical ML infrastructure bill breaks down differently than most teams expect: **Storage and data management: 30-40%** Training data, model checkpoints, experiment artifacts, logs, feature stores, vector databases. Data accumulates. Old experiments never get deleted. Checkpoints from failed runs persist forever. That "temporary" dataset from six months ago is still in S3. **Idle and overprovisioned compute: 20-30%** Inference clusters sized for peak load running at 15% utilisation. Development GPU instances left running overnight. Kubernetes clusters with generous resource requests and minimal actual usage. Auto-scaling that scales up eagerly and down reluctantly. **Active compute (including GPUs): 15-25%** The actual work — training runs, inference serving, data processing. The part everyone focuses on. **Network egress: 8-15%** Data moving between regions, between clouds, between services. Every byte that leaves a cloud provider's network costs money. Cross-region replication, API responses, model downloads. **Operational overhead: 5-10%** Monitoring, logging, security scanning, compliance tooling. The infrastructure to manage the infrastructure. The exact percentages vary by organisation, but the pattern is consistent: storage and idle resources typically exceed active compute costs. Yet optimisation efforts focus disproportionately on making training 10% faster rather than eliminating the 25% of compute that does nothing. ## The 80/20 of Cost Optimisation Optimise in order of impact, not visibility. ### 1. Kill Idle Resources The highest-ROI cost optimisation is eliminating resources that aren't doing anything. This sounds obvious. It's also consistently underexecuted. **Find idle compute:** ```python import boto3 from datetime import datetime, timedelta def find_idle_instances(min_cpu_percent: float = 5.0, days: int = 7): """Find EC2 instances with sustained low CPU utilisation.""" ec2 = boto3.client('ec2') cloudwatch = boto3.client('cloudwatch') instances = ec2.describe_instances( Filters=[{'Name': 'instance-state-name', 'Values': ['running']}] ) idle_instances = [] end_time = datetime.utcnow() start_time = end_time - timedelta(days=days) for reservation in instances['Reservations']: for instance in reservation['Instances']: instance_id = instance['InstanceId'] # Get CPU utilisation response = cloudwatch.get_metric_statistics( Namespace='AWS/EC2', MetricName='CPUUtilization', Dimensions=[{'Name': 'InstanceId', 'Value': instance_id}], StartTime=start_time, EndTime=end_time, Period=3600, # Hourly Statistics=['Average'] ) if response['Datapoints']: avg_cpu = sum(d['Average'] for d in response['Datapoints']) / len(response['Datapoints']) if avg_cpu bytes: local_path = os.path.join(self.local_cache, key) # Check local cache first if os.path.exists(local_path): with open(local_path, 'rb') as f: return f.read() # Download from remote data = self._download_remote(key) # Cache locally (with eviction if needed) self._ensure_cache_space(len(data)) os.makedirs(os.path.dirname(local_path), exist_ok=True) with open(local_path, 'wb') as f: f.write(data) return data def _ensure_cache_space(self, needed_bytes: int): """Evict oldest files if cache is full.""" current_size = self._get_cache_size() if current_size + needed_bytes self.checkpoint_interval: self.save_checkpoint() self.last_checkpoint = time.time() return loss def save_checkpoint(self, emergency: bool = False): checkpoint = { 'model_state': self.model.state_dict(), 'optimizer_state': self.optimizer.state_dict(), 'epoch': self.current_epoch, 'step': self.current_step, 'best_metric': self.best_metric } path = f"s3://checkpoints/run-{self.run_id}/step-{self.current_step}.pt" torch.save(checkpoint, path) if emergency: logger.info(f"Emergency checkpoint saved: {path}") ``` **Spot considerations:** - Checkpoint frequently (every 5-10 minutes for long training) - Use instance types with higher spot availability - Implement automatic restart from latest checkpoint - Consider spot fleets across multiple instance types ### 5. Right-Size Before Upgrading The instinct when inference is slow is to get bigger instances. Often the better answer is to use current instances more efficiently. **Batching:** Single-request inference wastes GPU parallelism. Batching multiple requests together amortises overhead and increases throughput. ```python class BatchingInferenceServer: def __init__(self, model, max_batch_size: int = 32, max_wait_ms: int = 50): self.model = model self.max_batch_size = max_batch_size self.max_wait_ms = max_wait_ms self.pending_requests = [] self.lock = threading.Lock() async def predict(self, input_data: dict) -> dict: future = asyncio.Future() with self.lock: self.pending_requests.append((input_data, future)) if len(self.pending_requests) >= self.max_batch_size: self._process_batch() # Wait for result or timeout trigger return await future def _process_batch(self): with self.lock: if not self.pending_requests: return batch = self.pending_requests[:self.max_batch_size] self.pending_requests = self.pending_requests[self.max_batch_size:] # Batch inference inputs = [req[0] for req in batch] results = self.model.predict_batch(inputs) # Resolve futures for (_, future), result in zip(batch, results): future.set_result(result) ``` **Model optimisation:** Before buying bigger GPUs, try: - Quantisation (INT8 inference is 2-4x faster than FP32) - Pruning (remove unnecessary weights) - Distillation (train a smaller model to mimic the large one) - ONNX Runtime or TensorRT optimisation A quantised model on a smaller instance often beats an unoptimised model on a larger instance — at a fraction of the cost. ## The Hidden Cost of Complexity Infrastructure cost isn't just cloud bills. It's also engineering time. A system that requires a dedicated ML platform team to operate costs more than a simpler system that application developers can manage themselves. Kubernetes clusters need care and feeding. Custom training frameworks need maintenance. Bespoke serving infrastructure needs debugging. Before adding infrastructure complexity to solve a cost problem, calculate the total cost including engineering time. Sometimes the answer is "pay the cloud bill and ship features instead." ## Measurement Before Optimisation You can't optimise what you don't measure. Before starting cost optimisation: **Tag everything:** ```python # Apply consistent tags to all resources REQUIRED_TAGS = { 'team': 'ml-platform', 'project': 'recommendation-engine', 'environment': 'production', 'cost-center': 'product-12345' } def create_instance_with_tags(instance_config: dict) -> str: instance_config['TagSpecifications'] = [{ 'ResourceType': 'instance', 'Tags': [{'Key': k, 'Value': v} for k, v in REQUIRED_TAGS.items()] }] return ec2.run_instances(**instance_config) ``` **Allocate costs to teams:** Cloud cost allocation by tag lets you answer "which team is spending the most?" and "which project has runaway costs?" Without this, cost optimisation is organisational guesswork. **Track cost per prediction:** ```python def calculate_cost_per_prediction( monthly_cost: float, monthly_predictions: int ) -> float: """ Simple but useful: what does each prediction cost? Track this over time to see if you're improving. """ return monthly_cost / monthly_predictions if monthly_predictions > 0 else 0 # Example: $10,000/month infrastructure, 50M predictions # Cost per prediction: $0.0002 (0.02 cents) ``` This single metric — cost per prediction — captures the efficiency of your entire ML infrastructure. Track it monthly. Set targets. Celebrate improvements. ## Frequently Asked Questions ### Where does the money actually go in ML infrastructure? Storage and idle compute typically dominate ML infrastructure costs, not GPU training runs. Teams overestimate GPU spend because it appears as large visible line items, while overlooking persistent storage costs, always-on inference servers at low utilisation, data pipeline compute, and logging infrastructure that accumulates continuously. ### How do I reduce ML inference costs without degrading performance? Start by measuring actual GPU utilisation during inference — most serving clusters run well below capacity. Right-size instances to match actual load, implement autoscaling to eliminate idle capacity, use spot instances for fault-tolerant workloads, and batch requests to maximise throughput per GPU-hour before investing in model optimisation. ### Why can't I just track total cloud spend to manage ML costs? Aggregate cloud spend hides which components drive costs and which are waste. Without per-prediction cost attribution, teams optimise visible costs like training GPUs while ignoring invisible costs like redundant data copies, over-provisioned inference clusters, and logging pipelines that store data no one reads. ### What should I optimise first in ML infrastructure costs? Eliminate idle resources before optimising active workloads. Shut down unused development clusters, implement autoscaling for inference, delete redundant data copies, and right-size storage tiers. These changes often reduce total spend by 30–50% without touching model architecture or training pipelines. ## The Optimisation Sequence When cloud bills arrive and leadership asks for cuts, resist the urge to start with GPUs. Instead: 1. **Find and kill idle resources** — immediate savings, zero risk 2. **Implement storage lifecycle** — significant savings, low effort 3. **Reduce egress** — moderate savings, requires architecture awareness 4. **Use spot for training** — good savings, requires checkpoint discipline 5. **Right-size inference** — moderate savings, requires load testing 6. **Optimise models** — variable savings, requires ML expertise 7. **Then consider GPU changes** — often unnecessary if steps 1-6 are done Most organisations can cut ML infrastructure costs 30-50% without touching model architecture or GPU selection. The savings are in the boring stuff — storage policies, idle detection, network topology. Not exciting. Very effective. --- ## Related Reading - [When You Don't Need a Feature Store](/ai-architecture/when-you-dont-need-feature-store/) — Avoiding premature complexity - [Graceful Degradation in ML Systems](/ai-architecture/ml-graceful-degradation/) — Handling cost-driven capacity constraints --- ## State Management in ML Services: Beyond Stateless Inference **URL**: https://speytech.com/ai-architecture/ml-state-management/ **Published**: January 23, 2026 22:00 **Topic**: AI Architecture **Answers**: What architectural patterns handle state management in ML inference services that need to maintain request context, session history, or feature cache state between sequential requests, and when should engineering teams move beyond simple stateless inference to implement stateful model serving patterns? KEY_CLAIMS: - The standard advice for ML serving is simple: keep it stateless. - Stateless inference becomes insufficient when the service needs session context, conversation history, user embeddings, interaction sequences, or online learning updates between requests. - Client-side state suits small payloads with simple consistency requirements. - Sending full context per request increases payload size, network bandwidth, and parsing overhead linearly with history length. - Design for graceful degradation when state is missing — serve a reasonable if suboptimal response without state rather than returning an error. RELATES_TO: - ai-architecture/ml-graceful-degradation - ai-architecture/ml-observability-blind-spot Architectural patterns for ML systems that need to remember The standard advice for ML serving is simple: keep it stateless. Each request contains everything needed. Each response is independent. Scale horizontally by adding replicas. This is good advice — until it isn't. Recommendation systems that ignore what you just clicked. Chatbots that forget your name mid-conversation. Fraud detection that can't see the pattern across transactions. Search that doesn't understand "show me more like that." Real ML systems often need state. Session context, conversation history, user embeddings, interaction patterns, online learning updates. The question isn't whether to have state — it's where to put it and how to manage it. ## When Stateless Isn't Enough Stateless inference works when the input contains all necessary context. For many use cases, it does. Image classification doesn't need to know what images you classified yesterday. Sentiment analysis doesn't care about previous sentences in other documents. But several common patterns require state: ### Conversational Systems "Show me blue ones" only makes sense if the system remembers you were looking at shoes. Conversation context accumulates across turns. Without state, every message needs to include the entire conversation history — possible but inefficient, and it pushes complexity to the client. ### Personalised Recommendations Good recommendations depend on user history. What did they click? What did they buy? What did they ignore? This isn't just "features in, prediction out" — it's continuous state evolution based on feedback. ### Session-Based Behaviour User behaviour within a session differs from behaviour across sessions. A user browsing casually behaves differently than one actively shopping. Session state — time on site, pages visited, cart contents — improves predictions. ### Online Learning Models that update based on feedback need to maintain learned state. Contextual bandits, reinforcement learning, adaptive systems — these require state that evolves with each interaction. ### Multi-Turn Tasks Complex tasks span multiple requests. Document processing with iterative refinement. Multi-step reasoning. Workflows with branching logic. Each step depends on results from previous steps. ## Where State Lives State has to live somewhere. The options differ in latency, durability, and complexity. ### Client-Side State The client sends all necessary state with each request. The server remains stateless. ```python # Client sends conversation history with each request { "session_id": "abc123", "message": "Show me blue ones", "history": [ {"role": "user", "content": "I'm looking for running shoes"}, {"role": "assistant", "content": "I can help with that. Any preferences on brand or price range?"}, {"role": "user", "content": "Under $150, any brand"} ] } ``` **Advantages**: Server stays stateless. Easy to scale. No session affinity required. **Disadvantages**: Payload grows with history. Client must manage state. Can't update state server-side (e.g., computed embeddings). Clients can tamper with state. Client-side state works for short conversations and when you trust the client. It fails for long sessions, sensitive state, or server-computed features. ### In-Memory Server State The server maintains state in memory, keyed by session ID. ```python from collections import defaultdict from threading import Lock from typing import Dict, Any import time class InMemoryStateStore: def __init__(self, ttl_seconds: int = 3600): self.state: Dict[str, Dict[str, Any]] = {} self.timestamps: Dict[str, float] = {} self.ttl = ttl_seconds self.lock = Lock() def get(self, session_id: str) -> Dict[str, Any]: with self.lock: self._evict_expired() return self.state.get(session_id, {}) def set(self, session_id: str, state: Dict[str, Any]): with self.lock: self.state[session_id] = state self.timestamps[session_id] = time.monotonic() def update(self, session_id: str, updates: Dict[str, Any]): with self.lock: if session_id not in self.state: self.state[session_id] = {} self.state[session_id].update(updates) self.timestamps[session_id] = time.monotonic() def _evict_expired(self): now = time.monotonic() expired = [ sid for sid, ts in self.timestamps.items() if now - ts > self.ttl ] for sid in expired: del self.state[sid] del self.timestamps[sid] ``` **Advantages**: Low latency. Simple implementation. No external dependencies. **Disadvantages**: Lost on server restart. Requires session affinity (sticky sessions). Doesn't scale across replicas. Memory pressure under load. In-memory state works for development and single-instance deployments. It fails at scale or when durability matters. ### External State Store State lives in Redis, DynamoDB, or another external store. All server replicas access the same state. ```python import json from typing import Dict, Any, Optional import redis class RedisStateStore: def __init__(self, redis_client: redis.Redis, ttl_seconds: int = 3600): self.redis = redis_client self.ttl = ttl_seconds self.prefix = "ml:session:" def _key(self, session_id: str) -> str: return f"{self.prefix}{session_id}" def get(self, session_id: str) -> Dict[str, Any]: data = self.redis.get(self._key(session_id)) if data: return json.loads(data) return {} def set(self, session_id: str, state: Dict[str, Any]): self.redis.setex( self._key(session_id), self.ttl, json.dumps(state) ) def update(self, session_id: str, updates: Dict[str, Any]): # Get-modify-set with optimistic locking pipe = self.redis.pipeline() key = self._key(session_id) while True: try: pipe.watch(key) current = self.get(session_id) current.update(updates) pipe.multi() pipe.setex(key, self.ttl, json.dumps(current)) pipe.execute() break except redis.WatchError: continue # Retry on conflict def append_to_list(self, session_id: str, field: str, value: Any, max_length: int = 100): """Append to a list field with bounded length.""" key = self._key(session_id) # Use Lua script for atomic append+trim script = """ local current = redis.call('GET', KEYS[1]) local data = current and cjson.decode(current) or {} data[ARGV[1]] = data[ARGV[1]] or {} table.insert(data[ARGV[1]], cjson.decode(ARGV[2])) while #data[ARGV[1]] > tonumber(ARGV[3]) do table.remove(data[ARGV[1]], 1) end redis.call('SETEX', KEYS[1], ARGV[4], cjson.encode(data)) return #data[ARGV[1]] """ self.redis.eval(script, 1, key, field, json.dumps(value), max_length, self.ttl) ``` **Advantages**: Survives restarts. Scales horizontally. Shared across replicas. Rich data structures (Redis lists, sets, sorted sets). **Disadvantages**: Network latency on every access. External dependency. Requires serialization. Consistency considerations. External state is the default choice for production systems. Redis is common for session state; DynamoDB or Cassandra for larger state or higher durability requirements. ### Database-Backed State For state that must survive indefinitely — user profiles, long-term preferences, model feedback — use a proper database. ```python from sqlalchemy import Column, String, JSON, DateTime, create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker from datetime import datetime Base = declarative_base() class UserState(Base): __tablename__ = 'user_state' user_id = Column(String, primary_key=True) preferences = Column(JSON, default={}) embedding = Column(JSON, default=[]) # Store as list, convert to numpy interaction_count = Column(Integer, default=0) last_updated = Column(DateTime, default=datetime.utcnow) class DatabaseStateStore: def __init__(self, connection_string: str): engine = create_engine(connection_string) Base.metadata.create_all(engine) self.Session = sessionmaker(bind=engine) def get_user_state(self, user_id: str) -> Optional[UserState]: session = self.Session() try: return session.query(UserState).filter_by(user_id=user_id).first() finally: session.close() def update_user_embedding(self, user_id: str, new_embedding: list): session = self.Session() try: state = session.query(UserState).filter_by(user_id=user_id).first() if state: state.embedding = new_embedding state.last_updated = datetime.utcnow() else: state = UserState(user_id=user_id, embedding=new_embedding) session.add(state) session.commit() finally: session.close() ``` **Advantages**: Durable. Queryable. Supports complex relationships. Transactional. **Disadvantages**: Higher latency. More complex operations. Schema management. Use databases for state that has long-term value: user profiles, aggregated feedback, learned preferences. Don't use databases for ephemeral session state. ## Architectural Patterns ### Pattern 1: Layered State Different types of state live in different stores, accessed in order of latency: ```python class LayeredStateManager: def __init__(self, memory_store, redis_store, db_store): self.memory = memory_store # Hot session state self.redis = redis_store # Warm session state self.db = db_store # Cold user state def get_context(self, session_id: str, user_id: str) -> dict: context = {} # Layer 1: In-memory session state (conversation history) session_state = self.memory.get(session_id) if session_state: context['history'] = session_state.get('history', []) # Layer 2: Redis session state (computed features) redis_state = self.redis.get(session_id) if redis_state: context['session_embedding'] = redis_state.get('embedding') context['click_history'] = redis_state.get('clicks', []) # Layer 3: Database user state (long-term preferences) user_state = self.db.get_user_state(user_id) if user_state: context['preferences'] = user_state.preferences context['user_embedding'] = user_state.embedding return context ``` This pattern keeps hot data close (in-memory), warm data accessible (Redis), and cold data durable (database). ### Pattern 2: Event Sourcing Instead of storing current state, store the sequence of events that produced it. Reconstruct state by replaying events. ```python from dataclasses import dataclass from typing import List from datetime import datetime @dataclass class Event: session_id: str event_type: str payload: dict timestamp: datetime class EventSourcedState: def __init__(self, event_store): self.events = event_store def append_event(self, session_id: str, event_type: str, payload: dict): event = Event( session_id=session_id, event_type=event_type, payload=payload, timestamp=datetime.utcnow() ) self.events.append(event) def get_state(self, session_id: str) -> dict: events = self.events.get_events(session_id) state = {"history": [], "preferences": {}, "context": None} for event in events: if event.event_type == "message": state["history"].append(event.payload) elif event.event_type == "preference_update": state["preferences"].update(event.payload) elif event.event_type == "context_set": state["context"] = event.payload.get("context") return state ``` **Advantages**: Complete audit trail. Can reconstruct state at any point. Natural fit for ML feedback loops. **Disadvantages**: State reconstruction cost. Storage growth. Complexity. Event sourcing works well for systems where the history itself has value — audit requirements, debugging, replay for analysis. ### Pattern 3: Sticky Sessions with Replication Route all requests for a session to the same server. Replicate state asynchronously for fault tolerance. ```python # Load balancer configuration (conceptual) # Route by session_id hash to consistent server class StickySessionManager: def __init__(self, local_store, replication_queue): self.local = local_store self.replication = replication_queue def update_state(self, session_id: str, state: dict): # Update local immediately self.local.set(session_id, state) # Queue async replication self.replication.put({ "session_id": session_id, "state": state, "timestamp": time.time() }) def get_state(self, session_id: str) -> dict: # Always read from local for lowest latency return self.local.get(session_id) ``` **Advantages**: Lowest latency for reads. Simple consistency model. Server can cache aggressively. **Disadvantages**: Requires session-aware load balancing. Failover complexity. Uneven load distribution. Sticky sessions work when latency is critical and sessions are relatively short-lived. ## The CAP Theorem Applies Stateful ML services face the same distributed systems trade-offs as any other stateful service. You cannot simultaneously guarantee: - **Consistency**: All replicas see the same state - **Availability**: Every request receives a response - **Partition tolerance**: The system continues operating despite network failures For most ML use cases, availability matters more than strict consistency. A recommendation based on slightly stale state is better than no recommendation. A conversation that occasionally loses context is better than a conversation that fails entirely. Design for eventual consistency. Accept that state might be briefly inconsistent across replicas. Use idempotent operations where possible. ## Practical Considerations **State size matters.** Session state should be small — conversation history, recent interactions, computed embeddings. Large state (full user history, large models) belongs in external storage with lazy loading. **TTL everything.** Sessions end. Users leave. State that lingers forever consumes resources forever. Set TTLs on all session state. Archive or delete on expiry. **Instrument state operations.** Track state store latency. Alert on failures. Monitor cache hit rates. State store problems become inference problems. **Plan for state loss.** Despite best efforts, state gets lost — store failures, network partitions, bugs. Design for graceful degradation when state is missing. Can you serve a reasonable (if suboptimal) response without state? **Test stateful behaviour.** Stateful systems have more edge cases. What happens when state is partially corrupted? When the store is slow? When a session spans a server restart? These scenarios need explicit testing. ## Frequently Asked Questions ### When does ML inference need state management beyond stateless serving? Stateless inference becomes insufficient when the service needs session context, conversation history, user embeddings, interaction sequences, or online learning updates between requests. Recommendation systems, chatbots, fraud detection across transaction sequences, and contextual search all require state to deliver accurate predictions. ### How do I choose between client-side, server-side, and external state stores? Client-side state suits small payloads with simple consistency requirements. Server-side state offers lowest read latency but requires session-aware load balancing. External stores like Redis provide shared state across replicas with independent scaling. Choose based on state size, consistency requirements, and failover complexity tolerance. ### Why doesn't embedding all context in every request scale for stateful ML? Sending full context per request increases payload size, network bandwidth, and parsing overhead linearly with history length. For long conversations or large feature histories, request sizes grow to megabytes. External state stores provide O(1) lookups by session ID regardless of history depth. ### What happens when ML session state is lost or corrupted? Design for graceful degradation when state is missing — serve a reasonable if suboptimal response without state rather than returning an error. Set TTLs on all session state to prevent resource leaks. Monitor cache hit rates and state store latency to detect problems before they affect inference quality. ## Choosing Your Approach Start with the simplest approach that meets your requirements: 1. **Stateless** if you can include all context in the request 2. **Client-side state** for short sessions with trusted clients 3. **Redis** for most production session state needs 4. **Database** for durable, long-term user state 5. **Event sourcing** when history and audit matter 6. **Sticky sessions** when latency is critical and sessions are short Don't over-engineer. Many systems that think they need complex state management actually need a Redis instance and thoughtful key design. Add complexity only when simpler approaches demonstrably fail. --- ## Related Reading - [Graceful Degradation in ML Systems](/ai-architecture/ml-graceful-degradation/) — Handling state store failures - [The Observability Blind Spot](/ai-architecture/ml-observability-blind-spot/) — Monitoring stateful services --- ## Graceful Degradation in ML Systems **URL**: https://speytech.com/ai-architecture/ml-graceful-degradation/ **Published**: January 23, 2026 21:14 **Topic**: AI Architecture **Answers**: What are the proven architectural patterns for implementing graceful degradation in production ML inference systems, and how do you design reliable fallback strategies for common failure scenarios when models time out, feature stores become unreachable, memory pressure spikes, or GPU hardware errors occur? KEY_CLAIMS: - Graceful degradation is an architectural pattern where ML services return progressively simpler but still useful responses when primary inference paths fail. - Design a fallback hierarchy with independent failure modes at each level. - Retries amplify failures under resource pressure because the original failure was likely caused by resource exhaustion, memory pressure, or cascading timeouts. - Degraded responses may not satisfy all use cases — a safe default recommendation is better than no recommendation, but may not drive revenue. RELATES_TO: - ai-architecture/debugging-model-behavior-production - ai-architecture/ml-observability-blind-spot - ai-architecture/production-ai-unix-principles Fallback strategies for production inference that fails gracefully instead of failing loudly The model times out. The feature store is unreachable. Memory pressure forces garbage collection mid-inference. The GPU throws a CUDA error. What happens next determines whether your users experience a brief hiccup or a complete outage. Most ML systems have one answer to failure: return an error. HTTP 500, stack trace in the logs, maybe a retry. But production systems that serve real users need a better answer. They need graceful degradation — the ability to provide *something useful* even when the primary path fails. A degraded answer is almost always better than no answer. A safe default is almost always better than an error page. ## Why ML Systems Fail Before designing fallbacks, understand the failure modes. ML inference fails differently than traditional services because it has more moving parts, each with its own failure characteristics. ### Timeout Failures The model takes too long. This is the most common failure in production ML. Causes include: input larger than expected, cold start after scaling, resource contention, or the model simply being too slow for production latency requirements. Timeouts are predictable — you know they'll happen, you just don't know when. Design for them. ### Resource Exhaustion Memory pressure, GPU out of memory, thread pool exhausted, connection pool drained. Resource failures cascade: one component under pressure slows down, causing backpressure on upstream components, which then also fail. Resource exhaustion is often self-inflicted. A traffic spike causes slowdowns, which causes retries, which causes more traffic, which causes more slowdowns. ### Dependency Failures Feature stores, embedding services, preprocessing pipelines, model registries — modern ML systems have many dependencies. Any one of them can fail, and they fail independently. Dependency failures require dependency awareness. You can't fall back gracefully if you don't know what failed. ### Model Failures The model itself can fail: NaN outputs, confidence below threshold, exceptions in custom layers, corrupted weights after a bad deployment. Model failures are often silent — the model returns *something*, but that something is garbage. Model failures need validation. Trust but verify. ### Data Failures Bad input data: missing features, out-of-range values, encoding mismatches, null where not-null was expected. Data failures are caller problems, but they're your responsibility to handle gracefully. ## The Fallback Hierarchy When the primary model can't answer, fall back through progressively simpler alternatives. Each level trades accuracy for availability. ### Level 1: Cached Predictions For requests you've seen before, return the cached answer. Cache hit rates vary wildly by use case — recommendation systems might hit 60%, fraud detection might hit 5% — but any cache hit is a request you don't need to compute. ```python from functools import lru_cache from typing import Optional, Tuple import hashlib import json class PredictionCache: def __init__(self, redis_client, ttl_seconds: int = 3600): self.redis = redis_client self.ttl = ttl_seconds def _cache_key(self, model_version: str, input_data: dict) -> str: # Deterministic key from input input_hash = hashlib.sha256( json.dumps(input_data, sort_keys=True).encode() ).hexdigest()[:16] return f"pred:{model_version}:{input_hash}" def get(self, model_version: str, input_data: dict) -> Optional[dict]: key = self._cache_key(model_version, input_data) cached = self.redis.get(key) if cached: return json.loads(cached) return None def set(self, model_version: str, input_data: dict, prediction: dict): key = self._cache_key(model_version, input_data) self.redis.setex(key, self.ttl, json.dumps(prediction)) ``` Cache considerations: - **Key design**: Include model version. A cached prediction from v2 isn't valid for v3. - **TTL**: Balance freshness against hit rate. Shorter TTL for fast-changing domains. - **Stale-while-revalidate**: Return stale cache while refreshing in the background. ### Level 2: Simplified Model Maintain a lightweight model that trades accuracy for speed and reliability. This might be: - A smaller version of the same architecture (distilled model) - A simpler model type (logistic regression instead of deep learning) - A model with fewer features (dropping expensive-to-compute features) ```python class FallbackModelChain: def __init__(self, primary_model, fallback_model, timeout_ms: int = 100): self.primary = primary_model self.fallback = fallback_model self.timeout_ms = timeout_ms def predict(self, input_data: dict) -> Tuple[dict, str]: """Returns (prediction, source) tuple.""" # Try primary with timeout try: result = self._predict_with_timeout( self.primary, input_data, self.timeout_ms ) return result, "primary" except TimeoutError: logger.warning("primary_model_timeout", timeout_ms=self.timeout_ms) except Exception as e: logger.error("primary_model_error", error_type=type(e).__name__) # Fall back to simplified model try: result = self.fallback.predict(input_data) return result, "fallback" except Exception as e: logger.error("fallback_model_error", error_type=type(e).__name__) raise # Let outer handler deal with it ``` The fallback model should be fast, reliable, and *always available*. Load it eagerly at startup. Keep it in memory. Don't let it share resources with the primary model. ### Level 3: Rule-Based Fallback When models fail, fall back to rules. Rules are fast, predictable, and explainable. They won't be as accurate as your model, but they provide a reasonable answer. ```python class RuleBasedFallback: """Simple rules for fraud detection when models are unavailable.""" def predict(self, transaction: dict) -> dict: score = 0.0 reasons = [] # High amount if transaction.get("amount", 0) > 5000: score += 0.3 reasons.append("high_amount") # New account account_age_days = transaction.get("account_age_days", 0) if account_age_days dict: return self.defaults.get(self.domain, {"source": "safe_default"}) ``` The safe default should never fail. It should have no dependencies, no computation, no I/O. It's a constant that gets returned when everything else is broken. ## Circuit Breakers: Failing Fast When a service is failing, continuing to call it makes things worse. Timeouts pile up, resources get exhausted, and the failure cascades. Circuit breakers prevent this by tracking failure rates and "opening" when failures exceed a threshold. An open circuit fails immediately without calling the underlying service. ```python import time from enum import Enum from threading import Lock class CircuitState(Enum): CLOSED = "closed" # Normal operation OPEN = "open" # Failing fast HALF_OPEN = "half_open" # Testing recovery class CircuitBreaker: def __init__( self, failure_threshold: int = 5, recovery_timeout: float = 30.0, half_open_requests: int = 3 ): self.failure_threshold = failure_threshold self.recovery_timeout = recovery_timeout self.half_open_requests = half_open_requests self.state = CircuitState.CLOSED self.failure_count = 0 self.success_count = 0 self.last_failure_time = 0 self.lock = Lock() def can_execute(self) -> bool: with self.lock: if self.state == CircuitState.CLOSED: return True if self.state == CircuitState.OPEN: # Check if recovery timeout has passed if time.monotonic() - self.last_failure_time > self.recovery_timeout: self.state = CircuitState.HALF_OPEN self.success_count = 0 return True return False if self.state == CircuitState.HALF_OPEN: # Allow limited requests to test recovery return self.success_count = self.half_open_requests: self.state = CircuitState.CLOSED self.failure_count = 0 else: self.failure_count = 0 def record_failure(self): with self.lock: self.failure_count += 1 self.last_failure_time = time.monotonic() if self.state == CircuitState.HALF_OPEN: self.state = CircuitState.OPEN elif self.failure_count >= self.failure_threshold: self.state = CircuitState.OPEN ``` Use separate circuit breakers for each dependency. The feature store might be healthy while the model service is failing. Breaking the circuit on one shouldn't affect the other. ## Putting It Together A production inference endpoint that degrades gracefully: ```python class ResilientPredictor: def __init__(self, config): self.cache = PredictionCache(config.redis_client) self.primary_model = load_model(config.primary_model_path) self.fallback_model = load_model(config.fallback_model_path) self.rules = RuleBasedFallback() self.safe_default = SafeDefault(config.domain) self.circuit_breaker = CircuitBreaker() self.timeout_ms = config.timeout_ms def predict(self, input_data: dict) -> dict: # Level 0: Check cache first cached = self.cache.get(self.primary_model.version, input_data) if cached: return {**cached, "source": "cache"} # Level 1: Try primary model (if circuit allows) if self.circuit_breaker.can_execute(): try: result = self._predict_with_timeout( self.primary_model, input_data, self.timeout_ms ) self.circuit_breaker.record_success() self.cache.set(self.primary_model.version, input_data, result) return {**result, "source": "primary"} except Exception as e: self.circuit_breaker.record_failure() logger.warning("primary_failed", error=str(e)) # Level 2: Try fallback model try: result = self.fallback_model.predict(input_data) return {**result, "source": "fallback"} except Exception as e: logger.warning("fallback_failed", error=str(e)) # Level 3: Try rules try: result = self.rules.predict(input_data) return result except Exception as e: logger.error("rules_failed", error=str(e)) # Level 4: Safe default (should never fail) return self.safe_default.get() ``` Every request gets an answer. The answer might come from the primary model, a cache, a fallback, rules, or a safe default — but it's always an answer. ## Observability for Degradation Track which fallback level served each request. This isn't just operational awareness — it's product signal. ```python # Emit metrics on every prediction metrics.increment("prediction_served", tags={ "source": result.get("source", "unknown"), "model_version": self.primary_model.version }) # Alert when fallback usage exceeds threshold # "More than 10% of requests served by fallback for 5 minutes" ``` A sudden spike in fallback usage indicates a problem even if users aren't complaining. They're getting answers, but not the best answers. That's signal worth investigating. For comprehensive monitoring approaches, see [The Observability Blind Spot](/ai-architecture/ml-observability-blind-spot/) and the [certifiable-monitor](https://github.com/SpeyTech/certifiable-monitor) project for deterministic drift detection. ## Design Principles **Fail fast, recover slow.** Open the circuit quickly when things go wrong. Close it slowly, verifying the service has actually recovered. **Independent fallbacks.** Each fallback level should have independent failure modes. If the fallback model shares a GPU with the primary model, they'll fail together. **Test the fallbacks.** Fallback code paths are rarely exercised in normal operation. Use chaos engineering to verify they work: inject failures, kill dependencies, exhaust resources. **Make degradation visible.** Users might not notice degraded responses, but your team should. Dashboard the fallback rates. Alert on anomalies. **Design for the worst case.** Assume every component will fail simultaneously. What answer do you give then? That's your safe default, and it should be acceptable. ## Frequently Asked Questions ### What is graceful degradation in ML systems? Graceful degradation is an architectural pattern where ML services return progressively simpler but still useful responses when primary inference paths fail. Instead of returning HTTP 500 errors, the system falls back through a hierarchy: cached predictions, simplified models, rule-based defaults, and finally safe static responses. ### How do I design fallback strategies for ML inference failures? Design a fallback hierarchy with independent failure modes at each level. A typical chain: primary model → cached recent prediction → lightweight model → business rules → safe default. Each level must be independently testable, and fallback code paths must be exercised regularly through chaos engineering to verify they actually work. ### Why doesn't a simple retry strategy work for ML system failures? Retries amplify failures under resource pressure because the original failure was likely caused by resource exhaustion, memory pressure, or cascading timeouts. Retrying sends more load to an already overwhelmed system. Circuit breakers that fail fast and redirect to fallback paths recover faster than retry loops. ### What are the limitations of graceful degradation in production ML? Degraded responses may not satisfy all use cases — a safe default recommendation is better than no recommendation, but may not drive revenue. Each fallback level must have independent failure modes; shared infrastructure between primary and fallback paths causes correlated failures. Testing fallback paths requires deliberate chaos engineering investment. ## The Alternative Is Worse Without graceful degradation, ML systems have two modes: working and broken. Users experience either perfect service or error pages. There's no middle ground. With graceful degradation, systems have a spectrum: optimal, degraded-but-functional, minimal-but-safe. Users always get something useful. The system absorbs failures instead of propagating them. Production systems fail. The question is whether they fail gracefully or fail loudly. Graceful degradation turns potential outages into service quality variations — a much better trade-off for everyone involved. --- *For more on production ML reliability, see [Debugging Model Behavior in Production](/ai-architecture/debugging-model-behavior-production/) and [Production AI Systems: What 30 Years of UNIX Taught Me](/ai-architecture/production-ai-unix-principles/).* --- ## The Observability Blind Spot: What ML Metrics Miss **URL**: https://speytech.com/ai-architecture/ml-observability-blind-spot/ **Published**: January 23, 2026 18:00 **Topic**: AI Architecture **Answers**: What critical information about production model health do standard ML monitoring metrics like accuracy, latency, and throughput fail to capture, and how do these observability blind spots allow silent model failures and data drift to go entirely undetected by conventional dashboards? KEY_CLAIMS: - The dashboard shows 94.3% accuracy. - Standard ML metrics measure model quality but miss operational health signals like latency distribution, memory pressure, and input drift. - Alert on user-facing symptoms rather than internal metrics. - Accuracy is a lagging indicator calculated over labelled batches, not a real-time signal. - Add latency percentile tracking, per-worker memory monitoring, input distribution histograms, and prediction confidence monitoring. EVIDENCE: - Production systems page on symptoms, not research metrics. "The model's loss increased by 0.003" is not actionable at 3 AM. "P99 latency exceeded 500ms" is. - A system with P50 of 20ms and P99 of 800ms has a fundamentally different failure mode than one with P50 of 100ms and P99 of 150ms. - Symptom-based: Alert on what users experience. "P99 latency > 500ms for 5 minutes" is actionable. "Model loss increased" is not. - If P99 is normally 180ms with standard deviation of 40ms, alert at 300ms (3 sigma), not 500ms (a nice round number). RELATES_TO: - ai-architecture/ml-observability-gap - ai-architecture/production-ai-unix-principles Why accuracy looks fine while your production system burns The dashboard shows 94.3% accuracy. The model is healthy. Everything is green. Meanwhile, the on-call engineer is dealing with a flood of customer complaints about slow responses. Support tickets mention "the system just hangs." The fraud team reports that decisions are taking so long that transactions are timing out. The model is fine. The system is on fire. This is the observability blind spot: the gap between what ML metrics tell you and what production systems actually need to know. It's a gap that swallows engineering hours, damages customer trust, and makes incident response feel like archaeology. ## The Fundamental Mismatch Research metrics answer research questions. How well does this model generalise? Is it better than the baseline? Should we publish? Production metrics answer operational questions. Is this system healthy right now? Should I wake someone up? What broke? These are different questions. They require different measurements. But most ML systems conflate them, tracking accuracy and loss in production dashboards as if they were operational signals. They're not. Here's why. ### Accuracy Is a Lagging Indicator By the time accuracy degrades measurably, the problem has been affecting users for hours or days. Accuracy requires ground truth labels, which often arrive with significant delay. In fraud detection, you might not know whether a decision was correct for 30 days. In recommendation systems, the feedback loop can take weeks. Worse, accuracy is an aggregate. It tells you nothing about which requests are failing, which users are affected, or which code path is responsible. A 2% accuracy drop could mean a complete failure for one customer segment while everything else works perfectly. Production systems need leading indicators — signals that predict problems before they impact aggregate metrics. ### Loss Doesn't Page Training loss is useful for understanding model behaviour during development. In production, it's noise. A model can have stable loss while timing out on every request. Loss doesn't capture infrastructure failures, network latency, memory pressure, or any of the ways production systems actually break. Production systems page on symptoms, not research metrics. "The model's loss increased by 0.003" is not actionable at 3 AM. "P99 latency exceeded 500ms" is. ## The Four Signals That Actually Matter Production ML observability requires four categories of signals, none of which appear in a typical ML training loop: ### 1. Latency Distribution Not average latency — the distribution. P50 tells you the typical experience. P99 tells you the worst 1% of users. P99.9 tells you whether your system can meet SLAs under load. The gap between P50 and P99 reveals architectural problems. A system with P50 of 20ms and P99 of 800ms has a fundamentally different failure mode than one with P50 of 100ms and P99 of 150ms. The first system works great until it doesn't. The second is consistently mediocre but predictable. ```python # Production-ready latency tracking import time from dataclasses import dataclass from typing import Optional import logging logger = logging.getLogger(__name__) @dataclass class PredictionMetrics: latency_ms: float model_version: str input_size: int cache_hit: bool error: Optional[str] = None def predict_with_metrics(model, input_data) -> tuple: start = time.monotonic() error = None result = None try: result = model.predict(input_data) except Exception as e: error = type(e).__name__ raise finally: latency_ms = (time.monotonic() - start) * 1000 metrics = PredictionMetrics( latency_ms=latency_ms, model_version=model.version, input_size=len(input_data), cache_hit=False, error=error ) # Emit to your metrics system emit_metrics(metrics) # Log for debugging (structured, not printf) logger.info("prediction_complete", extra={ "latency_ms": latency_ms, "model_version": model.version, "status": "error" if error else "success" } ) return result, metrics ``` The key insight: measure at the boundary. Latency inside the model is interesting for optimisation. Latency at the API boundary is what users experience. ### 2. Throughput and Saturation How many requests per second can your system handle? More importantly, how close are you to that limit right now? Saturation is the ratio of current load to maximum capacity. A system at 30% saturation has headroom. A system at 90% saturation is one traffic spike away from degradation. Track throughput at multiple levels: - Requests received (what users are asking for) - Requests processed (what you actually handled) - Requests dropped (what you couldn't handle) The gap between received and processed is your error budget being consumed in real time. ### 3. Error Rate by Category Not all errors are equal. A timeout is different from a validation error is different from a model exception. Production systems need error classification: **Infrastructure errors**: Network timeouts, memory exhaustion, disk full. These are system problems, not model problems. **Input errors**: Invalid data, missing fields, out-of-range values. These are caller problems, possibly indicating upstream issues. **Model errors**: Exceptions during inference, NaN outputs, confidence below threshold. These are model problems. **Business errors**: Prediction made but wrong, caught by downstream validation. These are the errors accuracy measures, but they arrive late. ```python from enum import Enum class ErrorCategory(Enum): INFRASTRUCTURE = "infrastructure" INPUT_VALIDATION = "input_validation" MODEL_INFERENCE = "model_inference" BUSINESS_LOGIC = "business_logic" TIMEOUT = "timeout" def categorise_error(exception: Exception, context: dict) -> ErrorCategory: if isinstance(exception, TimeoutError): return ErrorCategory.TIMEOUT if isinstance(exception, MemoryError): return ErrorCategory.INFRASTRUCTURE if isinstance(exception, ValueError) and "input" in str(exception).lower(): return ErrorCategory.INPUT_VALIDATION if isinstance(exception, (RuntimeError,)) and context.get("in_model", False): return ErrorCategory.MODEL_INFERENCE return ErrorCategory.INFRASTRUCTURE # Default to infra for unknown ``` Alert thresholds should differ by category. A spike in infrastructure errors at 2% might be critical. A spike in input validation errors at 5% might just mean a misbehaving client. ### 4. Data Drift The input distribution in production will differ from training. The question is how much and whether it matters. Population Stability Index (PSI) is a common measure. For a feature, it compares the distribution in a reference period to the current distribution: ```python import numpy as np def calculate_psi(reference: np.ndarray, current: np.ndarray, bins: int = 10) -> float: """ Calculate Population Stability Index between two distributions. PSI 0.25: Significant shift, likely action needed """ # Bin the reference distribution breakpoints = np.percentile(reference, np.linspace(0, 100, bins + 1)) breakpoints[0] = -np.inf breakpoints[-1] = np.inf ref_counts = np.histogram(reference, bins=breakpoints)[0] cur_counts = np.histogram(current, bins=breakpoints)[0] # Convert to proportions, avoiding division by zero ref_pct = (ref_counts + 1) / (len(reference) + bins) cur_pct = (cur_counts + 1) / (len(current) + bins) # PSI formula psi = np.sum((cur_pct - ref_pct) * np.log(cur_pct / ref_pct)) return psi ``` PSI alone doesn't tell you whether drift matters for predictions. A feature could shift dramatically without affecting model output if other features compensate. But PSI is a leading indicator — it tells you something changed before you see accuracy degrade. For a deeper treatment of drift detection in safety-critical contexts, see [certifiable-monitor](https://github.com/SpeyTech/certifiable-monitor), which implements deterministic drift detection with Total Variation distance, Jensen-Shannon divergence, and PSI. ## Structured Logging for ML Systems Metrics tell you what's happening. Logs tell you why. But most ML logging is either absent or useless — either no logs at all, or printf-style strings that can't be queried. Production ML systems need structured logs with consistent fields: ```python import json import logging from datetime import datetime class StructuredLogger: def __init__(self, service_name: str): self.service = service_name self.logger = logging.getLogger(service_name) def log(self, event: str, level: str = "info", **context): record = { "timestamp": datetime.utcnow().isoformat() + "Z", "service": self.service, "event": event, "level": level, **context } getattr(self.logger, level)(json.dumps(record)) # Usage log = StructuredLogger("fraud-model-v3") log.log("prediction_start", request_id="req-8847291", user_id="usr-12345", model_version="v3.2.1", input_features=["amount", "merchant_category", "time_since_last"] ) log.log("prediction_complete", request_id="req-8847291", latency_ms=47.3, prediction=0.73, confidence=0.89, cache_hit=False ) log.log("prediction_error", level="error", request_id="req-8847292", error_type="TimeoutError", error_message="Model inference exceeded 100ms timeout", latency_ms=147.8 ) ``` The key fields for ML systems: - **request_id**: Correlate logs across services - **model_version**: Know which model made which prediction - **latency_ms**: Always track timing - **input_hash**: Reproducibility without storing PII - **prediction + confidence**: What the model actually said - **error_type + error_message**: Categorised, searchable errors With structured logs, incident investigation becomes querying: "Show me all predictions from model v3.2.1 where latency exceeded 200ms in the last hour." Without them, it's grep and prayer. ## Alert Design: Actionable vs. Noise The goal of alerting is to wake someone up when they can do something useful. Most ML alerting fails this test by alerting on research metrics or setting thresholds based on intuition rather than evidence. ### Alerts That Work **Symptom-based**: Alert on what users experience. "P99 latency > 500ms for 5 minutes" is actionable. "Model loss increased" is not. **Threshold from data**: Set thresholds based on historical baselines, not round numbers. If P99 is normally 180ms with standard deviation of 40ms, alert at 300ms (3 sigma), not 500ms (a nice round number). **Rate of change**: Sometimes the trend matters more than the absolute value. "Error rate increased 300% in 10 minutes" is more urgent than "Error rate is 1.5%." **Composite signals**: Combine metrics to reduce noise. Alert when latency is high AND error rate is rising AND throughput is dropping. Any one alone might be noise; together they're a pattern. ### Alerts That Don't Work **Accuracy dropped**: By the time you notice, it's too late. And what are you going to do at 3 AM — retrain? **Loss increased**: See above. Also, loss fluctuates normally. **Any single metric in isolation**: Context matters. High latency during planned load testing isn't an incident. **Threshold violations without duration**: Momentary spikes happen. Require the condition to persist (5 minutes is a common minimum) before alerting. ## The Observability Stack for ML Putting this together, a production ML observability stack needs: **Metrics collection**: Prometheus, Datadog, CloudWatch — tool doesn't matter, consistency does. Emit the four signals (latency, throughput, errors, drift) from every model serving endpoint. **Structured logging**: ELK, Loki, CloudWatch Logs — again, tool doesn't matter. Structure does. JSON with consistent fields, queryable in incident response. **Distributed tracing**: Jaeger, Zipkin, or cloud-native equivalents. ML requests often span services. When inference is slow, is it the model, the feature store, the network, or the downstream consumer? **Dashboards**: One dashboard per service showing the four signals. Research metrics can go on a separate dashboard for the ML team. Operations dashboards show operational metrics. **Alerting**: PagerDuty, Opsgenie, or equivalent. Route alerts based on category — infrastructure errors to platform team, model errors to ML team, business errors to product. ## Frequently Asked Questions ### What do standard ML metrics miss about production model health? Standard ML metrics measure model quality but miss operational health signals like latency distribution, memory pressure, and input drift. A model can show 94% accuracy while production latency causes transaction timeouts and customer complaints. ### How do I design alerts that detect real ML failures without generating noise? Alert on user-facing symptoms rather than internal metrics. Set thresholds from historical baselines, not round numbers. Require conditions to persist for at least five minutes before alerting. Combine multiple signals — high latency AND rising error rate AND dropping throughput together indicate a real incident rather than momentary noise. ### Why doesn't model accuracy monitoring catch production failures? Accuracy is a lagging indicator calculated over labelled batches, not a real-time signal. Production failures manifest as latency spikes, memory exhaustion, feature staleness, or confidence distribution shifts — none of which appear in accuracy metrics. By the time accuracy visibly drops, users have already experienced degraded service for hours or days. ### What metrics should I add first to close the ML observability gap? Add latency percentile tracking, per-worker memory monitoring, input distribution histograms, and prediction confidence monitoring. These four categories catch the majority of silent production failures that accuracy metrics miss entirely. ## The Blind Spot Closed The observability blind spot exists because ML teams optimise for research metrics while production systems fail in operational ways. Closing the gap requires treating ML services as services first, ML second. Accuracy matters for model development. In production, it's a lagging indicator at best. The signals that keep systems healthy are the same signals that keep any service healthy: latency, throughput, errors, and early warning of change. Instrument for operations. Log for debugging. Alert for action. The model can be perfect and the system can still be down. Production observability isn't about watching the model. It's about watching the system that contains the model. --- *For more on production ML infrastructure, see [The Observability Gap in ML Systems](/ai-architecture/ml-observability-gap/) and [Production AI Systems: What 30 Years of UNIX Taught Me](/ai-architecture/production-ai-unix-principles/). For deterministic approaches to drift detection and runtime monitoring, explore [certifiable-monitor](https://github.com/SpeyTech/certifiable-monitor).* --- ## The Certifiable-* Ecosystem: One Deterministic ML Pipeline **URL**: https://speytech.com/ai-architecture/certifiable-ecosystem/ **Published**: January 19, 2026 23:00 **Topic**: AI Architecture **Answers**: What is the certifiable-* ecosystem of eight interconnected C99 projects and how does it provide a complete deterministic ML pipeline with cryptographic provenance chains, fixed-point arithmetic, and static allocation for safety-critical systems that require bit-identical execution across different platforms and compilers? **Defines**: Certifiable-* ecosystem KEY_CLAIMS: - There's a question that blocks AI adoption in safety-critical systems: "Can you prove the model running on deployed hardware is exactly the same as what you tested?" Not "similar". - The certifiable-* ecosystem is a set of eight interconnected C99 projects providing a complete deterministic ML pipeline from data loading through deployment. - Each pipeline stage produces SHA-256 hashes of its outputs. - Existing frameworks rely on floating-point arithmetic, dynamic allocation, and thread scheduling — all sources of platform-dependent non-determinism that prevent bit-identical execution. - The ecosystem constrains model architectures to those expressible in Q16.16 fixed-point arithmetic with static allocation. EVIDENCE: - The certifiable- ecosystem takes a different approach: Every calculation uses 32-bit fixed-point representation: 16 bits for the integer part 16 bits for the fractional part Range: -32768.0 to +32767.99998 No floating-point operations anywhere in the pipeline. - Each stage produces a 32-byte SHA-256 commitment that includes: The stage's own output The previous stage's commitment This creates an unbroken chain from training data to deployed inference: Modify any input, and every downstream commitment changes. - The chain is tamper-evident by construction. certifiable-harness orchestrates all seven stages and compares results against a golden reference: The golden reference is a 368-byte binary containing commitments from all seven stages. - Precision: Q16.16 has less dynamic range than FP32. Eight interlocking C99 projects that make every ML pipeline stage bit-identical and auditable There's a question that blocks AI adoption in safety-critical systems: *"Can you prove the model running on deployed hardware is exactly the same as what you tested?"* Not "similar". Not "statistically equivalent". The *same* — bit for bit, hash for hash, across different platforms, compilers, and architectures. With TensorFlow Lite, PyTorch, or ONNX Runtime, the answer is no. Floating-point arithmetic varies by platform. Hash table iteration order depends on memory allocation. Thread scheduling is inherently non-deterministic. For most applications, that doesn't matter. For aerospace, medical devices, and autonomous vehicles — where certification requires evidence, not assumptions — it's a fundamental barrier. The certifiable-* ecosystem removes that barrier. ## Eight Projects, One Pipeline The ecosystem consists of eight interconnected projects, each handling one stage of the ML pipeline: | Stage | Project | Purpose | Commitment | |-------|---------|---------|------------| | 0 | [certifiable-data](https://github.com/SpeyTech/certifiable-data) | Data pipeline | Merkle root of batches | | 1 | [certifiable-training](https://github.com/SpeyTech/certifiable-training) | Model training | Gradient chain hash | | 2 | [certifiable-quant](https://github.com/SpeyTech/certifiable-quant) | Quantization | Error certificate | | 3 | [certifiable-deploy](https://github.com/SpeyTech/certifiable-deploy) | Deployment packaging | Attestation tree | | 4 | [certifiable-inference](https://github.com/SpeyTech/certifiable-inference) | Forward pass | Predictions hash | | 5 | [certifiable-monitor](https://github.com/SpeyTech/certifiable-monitor) | Runtime monitoring | Ledger digest | | 6 | [certifiable-verify](https://github.com/SpeyTech/certifiable-verify) | Verification | Report hash | | — | [certifiable-harness](https://github.com/SpeyTech/certifiable-harness) | End-to-end orchestration | Golden reference | Every stage produces a cryptographic commitment. Every commitment chains to the next. Break any link, and verification fails. ## The Core Problem: Non-Determinism Traditional ML frameworks aren't designed for determinism. They're optimised for flexibility and performance: **Floating-point variance:** The same model produces different outputs on different CPUs due to FMA (fused multiply-add) availability, SIMD instruction selection, and compiler optimisations. **Memory allocation:** Python dictionaries, hash maps, and sets iterate in order determined by memory layout — which varies between runs. **Threading:** Parallel operations complete in unpredictable order. Reduce operations accumulate floating-point errors differently depending on execution timing. **Dynamic allocation:** malloc() returns different addresses, affecting pointer-based data structures and timing. For consumer applications, these differences are invisible. For certification, they're disqualifying. ## The Solution: Determinism by Design The certifiable-* ecosystem takes a different approach: ### Fixed-Point Arithmetic (Q16.16) Every calculation uses 32-bit fixed-point representation: - 16 bits for the integer part - 16 bits for the fractional part - Range: -32768.0 to +32767.99998 No floating-point operations anywhere in the pipeline. Same inputs produce same outputs on any platform that implements integer arithmetic correctly — which is all of them. ```c /* Q16.16 multiplication with overflow detection */ int32_t q16_mul(int32_t a, int32_t b, q16_fault_t *fault) { int64_t result = (int64_t)a * (int64_t)b; result >>= 16; if (result > Q16_MAX || result overflow = 1; return (result > 0) ? Q16_MAX : Q16_MIN; } return (int32_t)result; } ``` ### Static Allocation No malloc(). All buffers declared at compile time or allocated by the caller: ```c /* Caller provides the buffer */ void ci_forward(const ci_model_t *model, const int32_t *input, int32_t *output, /* Caller-allocated */ int32_t *workspace, /* Caller-allocated */ ci_fault_t *fault); ``` No heap fragmentation. No allocation failures. Bounded memory usage provable at compile time. ### Deterministic Algorithms - **Sorting:** Merge sort (stable, O(n log n) worst case) - **Shuffling:** Feistel network with cycle-walking (deterministic given seed) - **Hashing:** SHA-256 throughout - **Reduction:** Ordered accumulation (no parallel reduce) Every algorithm chosen for determinism first, performance second. ## Cryptographic Provenance Each stage produces a 32-byte SHA-256 commitment that includes: 1. The stage's own output 2. The previous stage's commitment This creates an unbroken chain from training data to deployed inference: ``` M_data = MerkleRoot(batch_hashes) H_train = SHA256(M_data || gradient_chain) H_cert = SHA256(H_train || quantization_certificate) R_attest = SHA256(H_cert || bundle_files) H_pred = SHA256(R_attest || predictions) L_n = SHA256(H_pred || ledger_entries) H_report = SHA256(L_n || verification_results) ``` Modify any input, and every downstream commitment changes. The chain is tamper-evident by construction. ## The Harness: Proving Bit-Identity certifiable-harness orchestrates all seven stages and compares results against a golden reference: ```bash $ ./certifiable-harness --golden reference.golden --output result.json ═══════════════════════════════════════════════════════════════ Certifiable Harness v1.0.0 Platform: x86_64 ═══════════════════════════════════════════════════════════════ [0] data ✓ (OK, 4 µs) [1] training ✓ (OK, 3 µs) [2] quant ✓ (OK, 3 µs) [3] deploy ✓ (OK, 3 µs) [4] inference ✓ (OK, 3 µs) [5] monitor ✓ (OK, 4 µs) [6] verify ✓ (OK, 8 µs) Status: ALL STAGES PASSED ✓ Bit-identical: YES ✓ ═══════════════════════════════════════════════════════════════ ``` The golden reference is a 368-byte binary containing commitments from all seven stages. Run the harness on any platform — if the hashes match, you have mathematical proof of identical execution. ### Verified Cross-Platform The harness has been tested on: | Platform | OS | Compiler | Result | |----------|-----|----------|--------| | x86_64 | Linux (Ubuntu) | GCC 12.2.0 | ✓ Bit-identical | | x86_64 | macOS 11.7 | Apple Clang | ✓ Bit-identical | Different operating systems. Different compilers. Same hashes. ## What's Implemented | Project | Tests | Key Features | |---------|-------|--------------| | certifiable-data | 142 | CSV parsing, Merkle trees, deterministic shuffle | | certifiable-training | 10 suites | Gradient descent, weight updates, chain hashing | | certifiable-quant | 134 | FP32→Q16.16, error bounds, certificates | | certifiable-deploy | 147 | Bundle format, manifest, attestation | | certifiable-inference | 8 suites | Conv2D, pooling, dense layers, activations | | certifiable-monitor | 253 | Drift detection, ledger, policy enforcement | | certifiable-verify | 10 suites | Binding verification, report generation | | certifiable-harness | 4 suites | Orchestration, golden comparison | **Total: 700+ tests across 8 projects.** ## Documentation for Certification Each project includes formal documentation designed for regulatory review: - **MATH-001** — Mathematical specification (definitions, algorithms, proofs) - **STRUCT-001** — Data structure specification (types, layouts, invariants) - **SRS-xxx** — Software requirements (traceable, testable requirements) certifiable-harness alone has 81 traceable requirements across 4 SRS documents. ## Compliance Context The ecosystem is designed to support certification under: | Standard | Domain | Key Requirements | |----------|--------|------------------| | DO-178C Level A | Aerospace | MC/DC coverage, traceability, determinism | | IEC 62304 Class C | Medical devices | Risk management, verification, documentation | | ISO 26262 ASIL-D | Automotive | Fault tolerance, diagnostic coverage | | ISO 21448 (SOTIF) | Automotive AI | Behaviour verification, edge cases | | UL 4600 | Autonomous systems | Safety case, operational design domain | Deterministic execution simplifies verification. If the same inputs always produce the same outputs, testing becomes meaningful. If you can prove cross-platform identity, deployment becomes traceable. ## The Trade-Offs This approach has costs: **Performance:** Fixed-point is slower than optimised floating-point on modern GPUs. The ecosystem is designed for edge deployment where determinism matters more than throughput. **Precision:** Q16.16 has less dynamic range than FP32. For safety-critical applications, bounded precision with known error bounds is often preferable to unbounded precision with unknown variance. **Complexity:** Eight projects is more infrastructure than dropping in TensorFlow Lite. The question is whether that infrastructure is justified by the assurance it provides. **Ecosystem:** No pre-trained models, no model zoo, no community of contributors (yet). You're building from scratch. For consumer applications, these costs aren't justified. For systems where certification is mandatory and determinism is required, the alternative is often "don't use ML at all." ## Getting Started Clone any project and run the tests: ```bash git clone https://github.com/SpeyTech/certifiable-inference.git cd certifiable-inference mkdir build && cd build cmake .. make ctest --output-on-failure ``` For end-to-end verification: ```bash git clone https://github.com/SpeyTech/certifiable-harness.git cd certifiable-harness mkdir build && cd build cmake .. make # Generate golden reference ./certifiable-harness --generate-golden --output result.json # Verify (should show Bit-identical: YES) ./certifiable-harness --golden result.json.golden --output verify.json ``` ## What This Enables When a regulator asks "how do you know the deployed model is the same as what you tested?", the answer changes: **Before:** "We have a careful deployment process." **After:** "Here's a 368-byte golden reference. Run it on the deployed hardware. If the seven SHA-256 hashes match, the execution is mathematically identical. If they don't, I can tell you exactly which stage diverged." That's a different kind of answer. ## Frequently Asked Questions ### What is the certifiable-* ecosystem? The certifiable-* ecosystem is a set of eight interconnected C99 projects providing a complete deterministic ML pipeline from data loading through deployment. Every stage uses fixed-point arithmetic, static allocation, and cryptographic provenance chains to guarantee bit-identical execution across platforms, compilers, and architectures. ### How does the certifiable-* ecosystem prove model integrity across platforms? Each pipeline stage produces SHA-256 hashes of its outputs. A 368-byte golden reference captures the complete execution fingerprint. Running the same pipeline on different hardware produces matching hashes if execution is bit-identical — any divergence indicates exactly which stage produced different results. ### Why can't existing ML frameworks like PyTorch or TensorFlow achieve the same guarantees? Existing frameworks rely on floating-point arithmetic, dynamic allocation, and thread scheduling — all sources of platform-dependent non-determinism that prevent bit-identical execution. These architectural properties make bit-identical execution across platforms fundamentally impossible without redesigning the computation model. ### What are the trade-offs of using the certifiable-* ecosystem? The ecosystem constrains model architectures to those expressible in Q16.16 fixed-point arithmetic with static allocation. Existing models require conversion and validation. The C99 implementation lacks the convenience of Python-based frameworks. The trade-off is provable determinism and certification readiness at the cost of development flexibility and ecosystem maturity. ## Repositories | Project | URL | |---------|-----| | certifiable-data | https://github.com/SpeyTech/certifiable-data | | certifiable-training | https://github.com/SpeyTech/certifiable-training | | certifiable-quant | https://github.com/SpeyTech/certifiable-quant | | certifiable-deploy | https://github.com/SpeyTech/certifiable-deploy | | certifiable-inference | https://github.com/SpeyTech/certifiable-inference | | certifiable-monitor | https://github.com/SpeyTech/certifiable-monitor | | certifiable-verify | https://github.com/SpeyTech/certifiable-verify | | certifiable-harness | https://github.com/SpeyTech/certifiable-harness | All projects are GPL-3.0 licensed. Commercial licensing available for organisations requiring proprietary deployment. --- The certifiable-* ecosystem represents one approach to deterministic ML. As with any architectural choice, suitability depends on system requirements, risk classification, and regulatory context. The goal isn't to replace general-purpose ML frameworks — it's to enable ML in domains where those frameworks can't currently go. **UK Patent Application GB2521625.0** — Murray Deterministic Computing Platform --- ## Deterministic ML Pipeline for Safety-Critical Systems **URL**: https://speytech.com/ai-architecture/deterministic-ml-pipeline/ **Published**: January 19, 2026 00:15 **Topic**: AI Architecture **Answers**: How do you build a complete deterministic machine learning pipeline for safety-critical systems that guarantees bit-identical output across every platform, covering each stage from data loading through training, quantisation, deployment packaging, and inference using fixed-point arithmetic and cryptographic audit trails? **Defines**: Deterministic ML pipeline KEY_CLAIMS: - Production ML systems fail for boring reasons. - A deterministic ML pipeline guarantees bit-identical output across platforms for every stage from data loading through inference, using fixed-point arithmetic and cryptographic provenance. - A deterministic ML pipeline produces bit-identical outputs across every platform, compiler, and run for the same inputs. - Run the complete pipeline on different platforms — x86, ARM, different compilers — and compare SHA-256 hashes of all intermediate and final outputs. - Standard ML pipelines contain multiple non-determinism sources: floating-point variance, random data ordering, thread-scheduled reductions, and dynamic memory allocation. EVIDENCE: - Fixed-point normalisation: Q16.16 arithmetic with precomputed inverse standard deviation. - Solution: Provable FP32→Q16.16 quantization with formal error certificates. - JCS manifest: RFC 8785 canonical JSON for deterministic serialization. - Key components: Fixed-point arithmetic: Q16.16 for all weights and activations. RELATES_TO: - ai-architecture/floating-point-danger - ai-architecture/ml-observability-gap - ai-architecture/tflite-do178c-challenges - ai-architecture/wcet-neural-network-inference - insights/bit-perfect-reproducibility - insights/closure-totality-algebra - insights/cryptographic-proof-execution - insights/do178c-certification - insights/dynamic-memory-safety-critical - insights/fixed-point-neural-networks - insights/iec-62304-class-c - insights/iso-26262-asil-d-determinism - insights/mathematical-proofs-to-code - insights/ml-nondeterminism-problem How fixed-point arithmetic and cryptographic chaining produce bit-identical results from data to deployment Production ML systems fail for boring reasons. Not exotic model architecture problems — infrastructure problems. Non-deterministic data loading. Floating-point variance across hardware. Training runs that can't be reproduced. Deployed models that don't match what was tested. For most applications, these are annoyances. For safety-critical systems — medical devices, autonomous vehicles, aerospace — they're disqualifying. You can't certify software that behaves differently each time it runs. This article describes a complete ML pipeline designed from first principles for deterministic execution and safety-critical certification. Five open-source projects, 771 tests, and a single invariant: **same input → same output, always**. Definition: Deterministic ML Pipeline A deterministic ML pipeline guarantees bit-identical output across platforms for every stage from data loading through inference, using fixed-point arithmetic and cryptographic provenance. ## The Problem with Standard ML Pipelines A typical ML pipeline has non-determinism at every stage: **Data loading**: Shuffle order depends on PRNG state. Multi-threaded loaders return batches in unpredictable order. Floating-point normalisation varies by platform. **Training**: Gradient reduction order affects floating-point accumulation. Dropout masks aren't reproducible. Optimizer state depends on execution order. **Quantization**: Error bounds unknown. Calibration statistics non-reproducible. No proof that quantized model preserves behaviour. **Deployment**: No binding between certified model and deployed artifact. No verification that weights weren't corrupted in transit. **Inference**: Different results on different hardware. Memory allocation timing affects cache state. No audit trail linking prediction to model version. Each of these is a solvable problem. But solving them requires designing the entire pipeline around determinism, not bolting it on afterward. ## The Certifiable Pipeline The solution is five projects that share common principles: ``` certifiable-data → certifiable-training → certifiable-quant → certifiable-deploy → certifiable-inference ``` Each project is pure C99, uses zero dynamic allocation, and produces bit-identical output across platforms. ### certifiable-data **Problem**: Standard data loaders introduce non-determinism through random shuffling, floating-point normalisation, and multi-threaded batch assembly. **Solution**: Data loading as a pure function. Given dataset D, seed s, epoch e, and batch index t, the output is deterministic: ``` B_t = Pipeline(D, s, e, t) ``` Key components: - **Feistel shuffling**: Cryptographic permutation that maps any index to its shuffled position in O(1) time. No sequential state, no execution-order dependence. - **Fixed-point normalisation**: Q16.16 arithmetic with precomputed inverse standard deviation. No floating-point division. - **Merkle provenance**: Every epoch produces a cryptographic commitment linking dataset hash, configuration, and shuffle seed. The same (dataset, seed, epoch, batch) produces the same samples, in the same order, with the same normalisation, forever. *Related reading: [The ML Non-Determinism Problem](/insights/ml-nondeterminism-problem/), [Bit-Perfect Reproducibility](/insights/bit-perfect-reproducibility/)* ### certifiable-training **Problem**: Training loops accumulate floating-point rounding errors non-deterministically. Gradient reduction order affects results. There's no audit trail proving what happened during training. **Solution**: Fixed-point gradients, deterministic reduction topology, and Merkle-chained step verification. Key components: - **Q8.24 gradients**: Higher precision for gradient accumulation, explicit rounding at each operation. - **Compensated summation**: Neumaier algorithm tracks rounding error, making large reductions accurate. - **Fixed reduction tree**: Binary tree topology eliminates execution-order dependence. - **Merkle chain**: Every training step produces a hash linking previous state, gradients, and new weights. Any step is independently verifiable. The training loop becomes a deterministic state machine. Given initial weights and training data, the final weights are reproducible bit-for-bit. *Related reading: [From Proofs to Code: Mathematical Transcription in C](/insights/mathematical-proofs-to-code/), [Cryptographic Execution Tracing](/insights/cryptographic-proof-execution/)* ### certifiable-quant **Problem**: Standard quantizers (TensorFlow Lite, ONNX) are black boxes. Error bounds unknown. No proof that quantized model preserves behaviour. Calibration non-reproducible. **Solution**: Provable FP32→Q16.16 quantization with formal error certificates. Key components: - **Theoretical analysis**: Compute error bounds *before* quantization. Overflow proofs, range propagation, Lipschitz constants. - **Empirical calibration**: Collect activation statistics with coverage metrics and degenerate detection. - **Verified conversion**: Quantize with explicit error tracking, verify against theoretical bounds. - **Cryptographic certificate**: Merkle root linking analysis, calibration, and verification digests. The output is a certificate proving the quantized model is within ε of the original, auditable forever. *Related reading: [Fixed-Point Neural Networks: The Math Behind Q16.16](/insights/fixed-point-neural-networks/), [Closure, Totality, and the Algebra of Safe Systems](/insights/closure-totality-algebra/)* ### certifiable-deploy **Problem**: How do you prove the deployed model matches what was certified? How do you verify weights weren't tampered with? How do you bind artifacts to specific hardware? **Solution**: Canonical bundle format with cryptographic attestation and target binding. Key components: - **CBF v1 format**: Deterministic container with no ambient metadata. Same content = same bytes = same hash. - **Merkle attestation**: 4-leaf tree binding manifest, weights, certificates, and inference artifacts. - **JCS manifest**: RFC 8785 canonical JSON for deterministic serialization. - **Target binding**: Lock bundles to specific platforms (arch-vendor-device-abi). - **Runtime loader**: Fail-closed state machine. Inference API unreachable without completing verification chain. The loader implements "Execution ⇒ Verification": no inference without cryptographic proof that the loaded model matches the certified model. *Related reading: [DO-178C Level A Certification](/insights/do178c-certification/), [The Real Cost of Dynamic Memory](/insights/dynamic-memory-safety-critical/)* ### certifiable-inference **Problem**: Different hardware produces different results. Memory allocation affects timing. No audit trail linking predictions to model versions. **Solution**: Integer-only forward pass with static allocation and deterministic execution paths. Key components: - **Fixed-point arithmetic**: Q16.16 for all weights and activations. No floating-point in the critical path. - **Static buffers**: All memory provided by caller. No malloc in inference loop. - **Bounded execution**: Fixed iteration counts, no data-dependent branching, WCET-analysable. The same input produces the same output on x86, ARM, and RISC-V. Bit-identical, every time. *Related reading: [WCET for Neural Network Inference](/ai-architecture/wcet-neural-network-inference/), [IEC 62304 Class C Requirements](/insights/iec-62304-class-c/)* ## The Three Theorems Every project in the certifiable family satisfies three properties: | Theorem | Statement | Implication | |---------|-----------|-------------| | **Bit Identity** | F_A(s) = F_B(s) for any DVM-compliant platforms A, B | Cross-platform reproducibility | | **Bounded Error** | Error saturates, doesn't accumulate | Predictable behaviour | | **Auditability** | Any operation verifiable in O(1) time | Scalable verification | These aren't aspirations — they're tested properties. 771 tests across 39 test suites verify these invariants hold. ## What This Enables ### Reproducible Research Training runs that produce identical results, always. No "worked on my machine" failures. No unexplained variance between runs. ### Certification Evidence DO-178C Level A requires complete requirements traceability. IEC 62304 Class C requires validated transformations. ISO 26262 ASIL-D requires provable behaviour. This pipeline provides the evidence these standards demand. ### Incident Investigation When something goes wrong, you can replay exact inputs through exact model versions and get exact outputs. No "we can't reproduce the failure" mysteries. ### Audit Trails Cryptographic proof linking every prediction to: the deployed bundle, the quantization certificate, the training Merkle chain, and the data provenance. Years later, you can prove exactly how that prediction was made. ## Test Coverage The pipeline is backed by 771 tests across 39 test suites: | Project | Tests | Suites | |---------|-------|--------| | certifiable-data | 133 | 8 | | certifiable-training | 223 | 10 | | certifiable-quant | 150 | 7 | | certifiable-deploy | 201 | 7 | | certifiable-inference | 64 | 7 | | **Total** | **771** | **39** | These aren't smoke tests. They verify bit-identical output across platforms, correct handling of edge cases, and conformance to formal specifications. ## Getting Started Each project builds with CMake: ```bash git clone https://github.com/SpeyTech/certifiable-{name} cd certifiable-{name} mkdir build && cd build cmake .. make make test ``` Documentation includes mathematical foundations (CT-MATH-001), data structure specifications (CT-STRUCT-001), and Software Requirements Specifications with full traceability. ## Frequently Asked Questions ### What is a deterministic ML pipeline? A deterministic ML pipeline produces bit-identical outputs across every platform, compiler, and run for the same inputs. It covers data loading, training, quantisation, deployment packaging, and inference using fixed-point arithmetic, static allocation, and cryptographic audit trails — ensuring the deployed model is exactly what was tested. ### How do I verify that my ML pipeline is truly deterministic? Run the complete pipeline on different platforms — x86, ARM, different compilers — and compare SHA-256 hashes of all intermediate and final outputs. If every hash matches, the pipeline is deterministic. The certifiable-* ecosystem automates this verification with golden references and a cross-platform test harness. ### Why don't most ML pipelines produce reproducible results? Standard ML pipelines contain multiple non-determinism sources: floating-point variance, random data ordering, thread-scheduled reductions, and dynamic memory allocation. Determinism requires eliminating all of these sources simultaneously, not just fixing one. ### What are the limitations of a deterministic ML pipeline? Model architectures must be expressible in fixed-point arithmetic with static allocation. Dynamic control flow (variable-length sequences, attention masks) requires architectural adaptation. Training throughput may be lower than GPU-accelerated floating-point pipelines. The benefit is certification readiness — you can prove the deployed model matches the tested model. ## When You Don't Need This This level of rigour has costs: more complex implementation, restricted arithmetic, verbose documentation. If you're building a recommendation system or a chatbot, standard frameworks are fine. You need this when: - Regulatory standards require reproducible behaviour (DO-178C, IEC 62304, ISO 26262) - Failures have safety implications - You need to prove what happened, not just log it - Cross-platform consistency matters ## Further Reading **Core Concepts:** - [Bit-Perfect Reproducibility: Why It Matters and How to Prove It](/insights/bit-perfect-reproducibility/) - [The ML Non-Determinism Problem](/insights/ml-nondeterminism-problem/) - [From Proofs to Code: Mathematical Transcription in C](/insights/mathematical-proofs-to-code/) **Safety-Critical Standards:** - [DO-178C Level A Certification](/insights/do178c-certification/) - [IEC 62304 Class C: What Medical Device Software Actually Requires](/insights/iec-62304-class-c/) - [ISO 26262 and ASIL-D: The Role of Determinism](/insights/iso-26262-asil-d-determinism/) **Infrastructure Patterns:** - [The Real Cost of Dynamic Memory in Safety-Critical Systems](/insights/dynamic-memory-safety-critical/) - [Cryptographic Execution Tracing and Evidentiary Integrity](/insights/cryptographic-proof-execution/) - [WCET for Neural Network Inference](/ai-architecture/wcet-neural-network-inference/) **Production ML:** - [The Floating-Point Trap](/ai-architecture/floating-point-danger/) - [TFLite and DO-178C: The Certification Gap](/ai-architecture/tflite-do178c-challenges/) - [The Observability Gap in ML Systems](/ai-architecture/ml-observability-gap/) --- Context: This pipeline is designed for safety-critical applications with specific regulatory requirements. For most ML applications, standard frameworks provide better tooling, larger ecosystems, and faster development. Evaluate the trade-offs in your specific context. The goal isn't complexity for its own sake. It's providing the evidence that safety-critical certification demands. When a regulator asks "prove this model behaves deterministically," you need more than good intentions — you need 771 tests and cryptographic audit trails. All projects are open source under GPL-3.0, with commercial licensing available for proprietary safety-critical systems. [View Projects on GitHub](https://github.com/williamofai) · [Technical Documentation](https://speytech.com/open-source/) --- ## WCET Analysis for Neural Network Inference **URL**: https://speytech.com/ai-architecture/wcet-neural-network-inference/ **Published**: January 15, 2026 22:31 **Topic**: AI Architecture **Answers**: How do you perform worst-case execution time analysis for neural network inference operations including convolution, matrix multiplication, pooling, and activation functions, and why is provable WCET boundedness through static timing analysis essential for certifying ML inference in hard real-time safety-critical systems? **Defines**: WCET analysis KEY_CLAIMS: - Safety-critical systems must respond within guaranteed time bounds. - WCET analysis for neural network inference follows established techniques: determine loop bounds, compute per-iteration costs, and sum across the network. - Worst-Case Execution Time analysis determines the maximum time a neural network inference operation can take under worst-case conditions. - Count the loop iterations from input dimensions and kernel sizes — these are fixed and known at design time. - Measurement-based analysis captures observed timing but cannot prove the worst case was exercised. EVIDENCE: - Each basic block has a timing bound based on instruction count and hardware characteristics: This line involves: Two index calculations (multiply and add) Two memory loads One 64-bit multiply One 64-bit add The timing depends on the processor. - At 100 MHz: ~265 μs This is a rough bound. - Consider a simple CNN for image classification: At 100 MHz: ~10.85 ms per inference. - DO-178C and similar standards require documented evidence. RELATES_TO: - insights/bit-perfect-reproducibility - insights/fixed-point-neural-networks How to prove worst-case execution time for convolution, matrix multiply, and pooling operations Safety-critical systems must respond within guaranteed time bounds. A pacemaker that usually delivers a signal on time is not acceptable. An aircraft flight control system that occasionally misses a deadline is not certifiable. The system must always meet its timing requirements, including under worst-case conditions. Worst-Case Execution Time (WCET) analysis provides the mathematical foundation for these guarantees. By analysing code structure, loop bounds, and hardware behaviour, WCET analysis determines the maximum time a computation can take. This upper bound feeds into schedulability analysis, ensuring that all tasks complete before their deadlines. Neural network inference presents specific challenges for WCET analysis. The computations are regular and predictable in structure, which is favourable. But they are also computationally intensive, making tight bounds essential for practical systems. Loose bounds waste capacity; tight bounds require careful analysis. This article explains WCET analysis techniques applied to neural network operations: convolution, matrix multiplication, activation functions, and pooling. The goal is practical guidance for engineers who need to fill in the timing section of a certification package. ## WCET Analysis Fundamentals WCET analysis determines an upper bound on execution time without running the code on all possible inputs. Two complementary approaches exist: **Static analysis** examines the code structure and hardware model to compute bounds mathematically. It requires no test execution but needs accurate models of both software and hardware. **Measurement-based analysis** runs the code on representative inputs and measures execution time. It provides concrete data but cannot guarantee that the worst case was observed. Hybrid approaches combine both: static analysis for structure, measurement for hardware timing. For certification, the analysis must be justified as sound, meaning the computed bound is genuinely an upper bound on all possible executions. ### Loop Bounds The foundation of static WCET analysis is determining how many times each loop executes. For neural network operations, loop bounds derive from tensor dimensions: ```c // Loop bounds are explicit in dimensions for (int oh = 0; oh threshold) { expensive_operation(); } // Data-independent timing - preferred result = (value > threshold) ? a : b; // Both paths similar cost ``` Neural network operations with [fixed-point arithmetic](/insights/fixed-point-neural-networks/) are naturally data-independent. Integer multiply takes the same time regardless of operand values on most processors. This property simplifies WCET analysis considerably. Design Property: Timing Predictability Code with data-independent timing and static loop bounds enables tight WCET analysis. The execution time is determined by code structure, not input values. ## Analysing Convolution 2D convolution is typically the most expensive operation in CNN inference. Its nested loop structure makes WCET analysis straightforward in principle but requires attention to memory access patterns. ### Loop Structure Standard convolution has four nested loops: ```c void fx_conv2d(const fixed_t* input, const fixed_t* kernel, fixed_t* output, int in_h, int in_w, int k_h, int k_w) { int out_h = in_h - k_h + 1; int out_w = in_w - k_w + 1; for (int oh = 0; oh > 16); } } } ``` ### Iteration Count Total inner loop iterations: ``` N_iter = out_h × out_w × k_h × k_w = (in_h - k_h + 1) × (in_w - k_w + 1) × k_h × k_w ``` For a 16×16 input with 3×3 kernel: ``` N_iter = 14 × 14 × 3 × 3 = 1,764 iterations ``` ### Per-Iteration Cost The inner loop body contains: - 2 additions (ih, iw calculation) - 2 multiplications (index calculations) - 2 memory loads (input, kernel) - 1 widening multiply (64-bit) - 1 addition (accumulator) On a representative 32-bit microcontroller (ARM Cortex-M4): | Operation | Cycles (approx) | |-----------|-----------------| | Integer add | 1 | | Integer multiply | 1 | | Memory load (cache hit) | 1-2 | | Memory load (cache miss) | 10-50+ | | 64-bit multiply | 3-5 | | 64-bit add | 1-2 | Assuming cache hits, inner loop: ~10-15 cycles per iteration. ### Total Bound ``` WCET_conv = N_iter × cycles_per_iter + loop_overhead = 1,764 × 15 + overhead ≈ 26,500 cycles ``` At 100 MHz: ~265 μs This is a rough bound. Precise analysis requires: - Exact instruction sequence from compiled code - Processor pipeline model - Cache behaviour analysis - Memory access timing ### Cache Considerations Cache behaviour significantly affects WCET for convolution. The access pattern determines hit rates: **Kernel accesses**: The kernel is small (9 elements for 3×3) and accessed repeatedly. After initial loads, kernel accesses hit cache consistently. **Input accesses**: Input access pattern has spatial locality within rows but jumps between rows. For small inputs that fit in cache, this works well. For large inputs, cache misses occur at row boundaries. **Output accesses**: Output is written sequentially, which is cache-friendly. Conservative WCET analysis assumes cache misses. Tighter analysis models the access pattern to prove hit rates. ## Analysing Matrix Multiplication Dense layers use matrix multiplication. The analysis follows similar principles. ### Loop Structure ```c void fx_matmul(const fixed_t* A, const fixed_t* B, fixed_t* C, int M, int K, int N) { for (int i = 0; i > 16); } } } ``` ### Iteration Count ``` N_iter = M × N × K ``` For a layer with 256 inputs and 128 outputs (M=1, K=256, N=128): ``` N_iter = 1 × 128 × 256 = 32,768 iterations ``` ### Memory Access Pattern Matrix B is accessed with stride N, which can cause cache thrashing for large N. The standard mitigation is loop tiling, but this complicates WCET analysis by introducing additional loop bounds. For safety-critical systems, simpler untiled implementations with conservative cache assumptions may be preferred over optimised implementations with complex timing behaviour. ## Analysing Activation Functions Activation functions apply element-wise operations. Their WCET is proportional to tensor size. ### ReLU ```c void fx_relu(fixed_t* data, int size) { for (int i = 0; i TABLE_MAX) return SIGMOID_MAX; // Table lookup with interpolation int index = (x - TABLE_MIN) >> SHIFT; fixed_t frac = (x - TABLE_MIN) & MASK; fixed_t y0 = sigmoid_table[index]; fixed_t y1 = sigmoid_table[index + 1]; return y0 + fx_mul(frac, y1 - y0); } ``` The branches create multiple paths. WCET is the maximum across all paths: ``` WCET_sigmoid = max(clamp_low_path, clamp_high_path, interpolation_path) ``` The interpolation path is typically longest, including table lookups and multiplication. ## Analysing Pooling Max pooling compares elements within windows. The comparison count is fixed by window size. ### 2×2 Max Pooling ```c void fx_maxpool_2x2(const fixed_t* input, fixed_t* output, int in_h, int in_w) { int out_h = in_h / 2; int out_w = in_w / 2; for (int oh = 0; oh max_val) max_val = v1; fixed_t v2 = input[(ih + 1) * in_w + iw]; if (v2 > max_val) max_val = v2; fixed_t v3 = input[(ih + 1) * in_w + iw + 1]; if (v3 > max_val) max_val = v3; output[oh * out_w + ow] = max_val; } } } ``` ### Iteration Count ``` N_iter = out_h × out_w = (in_h / 2) × (in_w / 2) ``` ### Per-Iteration Cost Each iteration: - 4 memory loads - 3 comparisons - 3 conditional moves (or branches) - 1 memory store - Index calculations The comparisons have data-dependent branches, but both outcomes have identical cost (conditional move or store to max_val). WCET is the same regardless of which element is maximum. ## Composing Layer WCET Network WCET is the sum of layer WCETs: ``` WCET_network = WCET_conv1 + WCET_relu1 + WCET_pool1 + WCET_conv2 + WCET_relu2 + WCET_pool2 + WCET_dense + WCET_softmax ``` This assumes sequential execution. Pipelined or parallel implementations require more sophisticated analysis. ### Example: Small CNN Consider a simple CNN for image classification: | Layer | Dimensions | Iterations | Est. Cycles | |-------|------------|------------|-------------| | Conv 3×3 | 28×28→26×26 | 60,840 | 912,600 | | ReLU | 26×26 | 676 | 2,028 | | MaxPool 2×2 | 26×26→13×13 | 169 | 2,535 | | Conv 3×3 | 13×13→11×11 | 10,890 | 163,350 | | ReLU | 11×11 | 121 | 363 | | MaxPool 2×2 | 11×11→5×5 | 25 | 375 | | Dense | 25→10 | 250 | 3,750 | | **Total** | | | **~1,085,000** | At 100 MHz: ~10.85 ms per inference. This is a rough estimate. Actual WCET requires precise analysis of compiled code on the target processor. ## Measurement-Based Verification Static analysis provides bounds; measurement provides validation. The two should be consistent. ### Test Methodology ```c void measure_wcet(void) { fixed_t input[INPUT_SIZE]; fixed_t output[OUTPUT_SIZE]; uint32_t max_cycles = 0; for (int trial = 0; trial max_cycles) { max_cycles = cycles; } } printf("Measured max: %u cycles\n", max_cycles); printf("Static bound: %u cycles\n", STATIC_WCET_BOUND); // Measured should be less than static bound assert(max_cycles inference.asm ``` Analysis tools work on object code or binary, not source. ### Hardware Variability Even deterministic code has timing variation from hardware: - Cache state at function entry - Pipeline state - Memory refresh cycles (DRAM) - Interrupt latency (if interrupts enabled) WCET analysis must account for these. Conservative analysis assumes worst-case cache state. Precise analysis models cache contents. ### Tooling Commercial WCET analysis tools include: - AbsInt aiT - Rapita RapiTime - Bound-T These tools combine static analysis with hardware models to compute bounds. For certification, tool qualification may be required. For simpler systems, manual analysis with spreadsheets and measurement validation may suffice. ## Documentation for Certification DO-178C and similar standards require documented evidence. WCET documentation should include: **Analysis method**: Static, measurement-based, or hybrid. Justification for soundness. **Assumptions**: Processor model, clock speed, cache configuration, interrupt policy. **Loop bounds**: How each loop bound was determined. Proof that bounds are correct. **Computed bounds**: WCET for each function and the complete inference path. **Measurement data**: Test methodology, number of trials, observed distribution. **Margin**: Difference between computed WCET and deadline. Justification that margin is sufficient. This documentation becomes part of the certification package, providing evidence that timing requirements are met. ## Implementation Reference The [certifiable-inference](https://github.com/SpeyTech/certifiable-inference) project includes timing verification: - Loop bounds documented for all operations - Static allocation eliminates malloc timing variance - Measurement benchmarks for validation - Demonstrated <5% jitter at 95th percentile The implementation is designed for analysability, with simple loop structures and [data-independent timing](/insights/bit-perfect-reproducibility/). ## Frequently Asked Questions ### What is WCET analysis for neural network inference? Worst-Case Execution Time analysis determines the maximum time a neural network inference operation can take under worst-case conditions. This upper bound feeds into schedulability analysis, ensuring that inference completes before its deadline in hard real-time systems like flight controllers and pacemakers. ### How do you bound execution time for convolution and matrix multiplication? Count the loop iterations from input dimensions and kernel sizes — these are fixed and known at design time. Multiply by worst-case per-iteration cost including cache miss penalties. For fixed-point arithmetic on a known processor, the per-iteration cost is bounded by the instruction pipeline depth and memory access latency. ### Why doesn't measurement-based timing analysis suffice for safety-critical inference? Measurement-based analysis captures observed timing but cannot prove the worst case was exercised. Cache state, pipeline behaviour, and memory contention create timing variations that may not appear in test runs. Static analysis proves bounds mathematically. Hybrid approaches combine both for tighter bounds with formal soundness. ### What are the trade-offs of designing for provable WCET boundedness? Provably bounded WCET requires disabling features that improve average performance: no speculative execution reliance, no cache-dependent optimisations, no dynamic memory allocation. Worst-case performance is predictable but average performance is lower than optimised implementations. The trade-off is certification readiness versus computational throughput. ## Conclusion WCET analysis for neural network inference follows established techniques: determine loop bounds, compute per-iteration costs, and sum across the network. The regularity of neural network operations makes them amenable to analysis, provided the implementation avoids data-dependent timing and dynamic allocation. The key requirements are: - **Static loop bounds** derived from tensor dimensions - **Data-independent timing** from fixed-point arithmetic and branchless code - **Simple memory patterns** that enable cache analysis - **Measurement validation** confirming that static bounds hold For safety-critical systems, WCET analysis is not optional. The timing section of a certification package must demonstrate that inference completes within its deadline under all conditions. The techniques in this article provide a foundation for that demonstration. As with any certification effort, the analysis must be appropriate for the specific system, processor, and assurance level. Simple systems may use manual analysis; complex systems may require commercial tools. The goal is justified confidence that timing requirements are met. --- *For an implementation designed for WCET analysability, see [certifiable-inference](https://github.com/SpeyTech/certifiable-inference) or try the [live simulator](https://inference.speytech.com/).* --- ## TensorFlow Lite and DO-178C Certification Challenges **URL**: https://speytech.com/ai-architecture/tflite-do178c-challenges/ **Published**: January 15, 2026 20:45 **Topic**: AI Architecture **Answers**: Why does TensorFlow Lite face significant architectural challenges when pursuing DO-178C aerospace software certification for safety-critical avionics, and which specific framework properties including dynamic heap memory allocation, IEEE 754 floating-point hardware dependence, large code complexity, and third-party library dependencies complicate certification? KEY_CLAIMS: - Note: This article examines general architectural patterns in mobile inference frameworks and how they interact with aerospace certification requirements. - Mobile inference frameworks like TensorFlow Lite represent excellent engineering for their intended applications. - TensorFlow Lite's dynamic allocation, floating-point dependence, codebase size, and third-party dependencies each complicate DO-178C certification evidence. - Dynamic memory allocation introduces heap fragmentation, allocation failure modes, and non-deterministic timing — all of which require extensive analysis and testing for certification. - Qualification under DO-178C requires evidence that the tool or framework was developed to equivalent assurance standards, or that its output can be independently verified. EVIDENCE: - Aerospace software certification under DO-178C imposes rigorous requirements on how software is designed, verified, and documented. - This article examines specific architectural properties common in mobile inference frameworks and explains why they can complicate DO-178C certification efforts, particularly at the higher Design Assurance Levels (DAL A and DAL B). - DO-178C establishes objectives for software development based on the severity of potential failures. - While DO-178C does not explicitly use the word "deterministic," its objectives effectively require predictable, reproducible behaviour. RELATES_TO: - insights/fixed-point-neural-networks Understanding the architectural properties that complicate aerospace certification for mobile inference frameworks Note: This article examines general architectural patterns in mobile inference frameworks and how they interact with aerospace certification requirements. It is not a comprehensive certification analysis, nor does it represent the position of any certification authority. Actual certification decisions depend on the specific system, intended use, and assessor interpretation. TensorFlow Lite is used as a representative example; similar considerations may apply to other inference frameworks. Aerospace software certification under DO-178C imposes rigorous requirements on how software is designed, verified, and documented. These requirements evolved over decades of aviation safety experience and are mandatory for software whose failure could affect flight safety. Mobile inference frameworks like TensorFlow Lite were designed with different priorities: flexibility, performance across diverse hardware, and ease of use for researchers and app developers. These are legitimate engineering goals that have made deep learning accessible to millions of applications. However, the architectural choices that enable flexibility and broad hardware support can create challenges when the same frameworks are considered for aerospace applications. Understanding these challenges helps teams make informed decisions about whether to adapt existing frameworks, build custom inference engines, or pursue hybrid approaches. This article examines specific architectural properties common in mobile inference frameworks and explains why they can complicate DO-178C certification efforts, particularly at the higher Design Assurance Levels (DAL A and DAL B). ## DO-178C Requirements Overview DO-178C establishes objectives for software development based on the severity of potential failures. Design Assurance Level A applies when software failure could cause or contribute to catastrophic failure conditions. Level B applies to hazardous conditions. Levels C, D, and E apply to progressively less severe scenarios. At DAL A, the standard requires: **Requirements traceability.** Every software requirement must trace to system requirements, and every line of code must trace to a software requirement. The purpose of each code element must be documented and justified. **Verification coverage.** Testing must achieve structural coverage (MC/DC for DAL A), meaning every decision outcome and condition combination must be exercised. Dead code is prohibited. **Deterministic behaviour.** While DO-178C does not explicitly use the word "deterministic," its objectives effectively require predictable, reproducible behaviour. Evidence must demonstrate that software performs its intended functions under all operational conditions. **Configuration control.** Every artefact affecting the software must be under configuration control with documented history. These objectives are achievable but require significant discipline in design and documentation. ## Architectural Properties of Mobile Inference Frameworks Mobile inference frameworks share common architectural patterns that optimise for their primary use cases. The following analysis uses publicly documented behaviour; specific implementation details may vary across versions. ### Dynamic Memory Allocation Mobile frameworks typically allocate memory dynamically during model loading and inference: ```cpp // Typical pattern in inference frameworks TfLiteTensor* tensor = interpreter->tensor(index); // Tensor data may be allocated lazily or resized ``` Dynamic allocation creates verification challenges at high DALs: **Variable timing.** Allocation time depends on heap state, creating unpredictable worst-case execution time (WCET). DAL A systems typically require bounded timing analysis. **Fragmentation risk.** Long-running systems may experience heap fragmentation, causing allocation failures that are difficult to reproduce during testing. **Coverage complexity.** Allocation failure paths must be tested. With many allocation points, achieving structural coverage of all failure paths can be challenging. The CAST-21 position paper from certification authorities addresses dynamic memory, noting that demonstrating compliance requires specific measures beyond typical development practices. ### Hardware Abstraction Layers Frameworks abstract hardware differences to support multiple platforms: ```cpp // Framework selects implementation based on hardware if (cpu_supports_neon()) { neon_conv2d(input, kernel, output); } else if (cpu_supports_sse()) { sse_conv2d(input, kernel, output); } else { reference_conv2d(input, kernel, output); } ``` This flexibility creates certification considerations: **Multiple code paths.** Each hardware backend is effectively a different implementation. Complete verification requires testing each path the deployed system might execute. **Platform dependence.** Behaviour may vary across platforms in subtle ways. Demonstrating equivalence requires evidence that all backends produce acceptable results. **Conditional complexity.** Runtime hardware detection adds branches that must be covered and justified. For certification, the target hardware configuration is typically fixed, so unused backends could potentially be excluded. However, this requires modifying the framework build or demonstrating that excluded code is truly unreachable. ### Floating-Point Computation Neural network inference frameworks predominantly use floating-point arithmetic: ```cpp // Standard floating-point convolution for (int i = 0; i < output_size; i++) { float sum = 0.0f; for (int j = 0; j < kernel_size; j++) { sum += input[i + j] * kernel[j]; // FP multiply-accumulate } output[i] = sum; } ``` Floating-point creates reproducibility challenges: **Platform variance.** Different processors implement floating-point with different intermediate precision, FMA availability, and rounding behaviour. The same computation may produce slightly different results on different hardware. **Compiler effects.** Optimisation flags can change operation ordering, affecting results due to floating-point non-associativity. **Verification complexity.** If results vary across platforms, test cases cannot use exact expected values. Tolerance-based testing requires justification that the tolerance is acceptable for the application. For safety-critical applications, some teams choose [fixed-point arithmetic](/insights/fixed-point-neural-networks/) to eliminate floating-point variance. This requires model quantisation and validation of accuracy loss. ### Third-Party Dependencies Frameworks depend on external libraries for math operations, threading, and platform services: ``` TensorFlow Lite dependencies (representative): ├── Eigen (linear algebra) ├── FlatBuffers (serialization) ├── gemmlowp (quantized matrix multiply) ├── ruy (matrix multiply) ├── XNNPACK (neural network operators) └── platform-specific libraries ``` Dependencies affect certification in several ways: **Verification scope.** All code that executes in the certified system must be verified to an appropriate level. Third-party libraries require the same evidence as first-party code. **Change management.** Updates to dependencies require re-verification. Frameworks with frequent releases and many dependencies create configuration management challenges. **Traceability.** Requirements for third-party code may not exist or may not meet aerospace documentation standards. Some certification approaches use "previously developed software" (PDS) provisions for stable, well-characterised libraries. This requires evidence of the library's service history and suitability for the application. ### Code Size and Complexity Mobile inference frameworks optimise for feature coverage rather than minimal footprint: ``` Component sizes (representative, version-dependent): - TensorFlow Lite core: ~1MB compiled - Operator kernels: ~2-5MB depending on included ops - Dependencies: variable, potentially several MB ``` Large codebases affect certification economics: **Verification cost.** Testing and documentation effort scales with code size. Structural coverage of millions of lines of code is expensive. **Dead code.** Features unused by the target application may remain in the binary unless explicitly excluded. Dead code is prohibited at DAL A. **Review burden.** Code reviews for certification require understanding each component's purpose and behaviour. Custom inference engines for specific models can achieve much smaller footprints by including only required operations. This reduces verification scope but requires custom development. ## Quantifying the Challenge To illustrate the scale, consider a hypothetical certification effort for a small neural network using a mobile inference framework: | Aspect | Typical Framework | Custom Engine | |--------|-------------------|---------------| | Binary size | 2-5 MB | 20-100 KB | | Source lines (approx) | 100K-500K | 2K-10K | | External dependencies | 5-15 | 0-2 | | Hardware backends | 3-10 | 1 | | Memory allocation | Dynamic | Static | | Structural coverage scope | All executed code | All code | These numbers are illustrative; actual figures depend on specific configurations. The key observation is that verification effort correlates with code complexity and variability. ## Approaches Teams Have Taken Organisations pursuing aerospace AI have adopted various strategies: ### Framework Modification Some teams fork existing frameworks and modify them for certification: - Remove unused operators and backends - Replace dynamic allocation with static buffers - Add traceability documentation - Isolate and justify third-party dependencies This approach preserves compatibility with trained models but requires substantial engineering effort and ongoing maintenance as upstream frameworks evolve. ### Custom Implementation Other teams build inference engines from scratch: - Include only required operations - Design for verification from the start - Eliminate unnecessary variability - Achieve small, auditable codebases This approach reduces verification scope but requires implementing and validating each neural network operation. ### Hybrid Approaches Some teams use frameworks during development and custom engines for deployment: - Train models using standard frameworks (TensorFlow, PyTorch) - Export weights and architecture - Implement inference in a certifiable custom engine - Validate equivalence between framework and custom outputs This preserves the benefits of mature training infrastructure while deploying a minimal, certifiable inference engine. ### Formal Methods Emerging approaches apply formal verification to neural network implementations: - Prove properties of fixed-point arithmetic implementations - Verify absence of runtime errors through static analysis - Demonstrate bounded execution time through formal timing analysis These techniques are maturing but show promise for reducing testing burden. ## What Certification Authorities Consider Certification authorities (DERs in the US, OSD in Europe) evaluate each case individually. Factors they may consider include: **Safety analysis.** How do inference failures affect system safety? What mitigations exist? Lower-criticality applications may accept more framework complexity. **Operational constraints.** Is the system continuous or bounded in operation? Short mission times may reduce concerns about fragmentation and memory exhaustion. **Verification evidence.** What testing has been performed? How comprehensive is the coverage? Strong verification evidence can sometimes offset architectural complexity. **Service history.** Has this framework been used successfully in similar applications? Service history can support qualification arguments. **Development assurance.** Was the framework developed to aerospace standards? Most general-purpose frameworks were not, which affects what evidence is available. The outcome depends on the specific system, its safety role, and the persuasiveness of the certification argument. ## Implications for Project Planning Teams considering neural network inference for aerospace applications should: **Assess early.** Certification implications should inform architecture decisions at project start, not be discovered during verification. **Engage authorities.** Early engagement with certification authorities (through certification plans and issue papers) can clarify expectations before major investment. **Consider alternatives.** Custom inference engines may have higher initial development cost but lower verification cost. The trade-off depends on model complexity and reuse expectations. **Budget realistically.** Certifying complex software at high DALs is expensive regardless of approach. Underestimating verification effort is a common project failure mode. **Plan for maintenance.** Aerospace software lifecycles span decades. Architectures that simplify updates and re-verification reduce lifetime cost. ## Frequently Asked Questions ### Why is TensorFlow Lite difficult to certify under DO-178C? TensorFlow Lite's dynamic allocation, floating-point dependence, codebase size, and third-party dependencies each complicate DO-178C certification evidence. ### How does dynamic memory allocation affect DO-178C certification? Dynamic memory allocation introduces heap fragmentation, allocation failure modes, and non-deterministic timing — all of which require extensive analysis and testing for certification. Safety-critical standards strongly discourage or prohibit dynamic allocation because worst-case memory behaviour cannot be statically bounded at design time. ### Why can't a qualification argument bypass TensorFlow Lite's certification challenges? Qualification under DO-178C requires evidence that the tool or framework was developed to equivalent assurance standards, or that its output can be independently verified. General-purpose frameworks lack this development evidence, and independent verification of a large complex framework may exceed the cost of building a simpler certifiable alternative. ### What alternatives exist for certified neural network inference in aerospace? Custom inference engines with static allocation, fixed-point arithmetic, and minimal codebases can be designed specifically for certification. The higher initial development cost is often offset by lower verification cost. The trade-off depends on model complexity, reuse expectations, and how early certification implications inform architecture decisions. ## Conclusion Mobile inference frameworks like TensorFlow Lite represent excellent engineering for their intended applications. Their architectural choices—dynamic allocation, hardware abstraction, floating-point computation, and extensive dependencies—enable broad compatibility and ease of use. These same properties can complicate certification under DO-178C, particularly at higher Design Assurance Levels. The challenges are not insurmountable, but they require significant effort to address: modifying frameworks, creating extensive verification evidence, or building custom implementations. Teams pursuing aerospace AI should understand these challenges early and choose approaches that align with their certification strategy. For some applications, adapting existing frameworks may be cost-effective. For others, purpose-built inference engines may reduce overall certification effort. The aerospace industry continues to develop best practices for certifiable AI. As experience accumulates and tools mature, clearer patterns will emerge. In the meantime, understanding the interaction between framework architecture and certification requirements helps teams make informed decisions. As with any certification effort, success depends on early planning, realistic assessment, and close coordination with certification authorities. The challenges are significant but not unprecedented—aerospace has successfully certified complex software before, and neural network inference will eventually follow established paths to certification. --- *For an example of an inference architecture designed with certification in mind, see [certifiable-inference](https://github.com/SpeyTech/certifiable-inference), which demonstrates fixed-point arithmetic, static allocation, and minimal dependencies. A [live simulator](https://inference.speytech.com/) shows the approach in action.* --- ## Why Floating Point Is Dangerous for Deterministic AI **URL**: https://speytech.com/ai-architecture/floating-point-danger/ **Published**: January 14, 2026 20:00 **Topic**: AI Architecture **Answers**: Why is IEEE 754 floating-point arithmetic dangerous for safety-critical AI systems that require fully deterministic execution, and how do platform-dependent rounding modes, fused multiply-add instruction availability, SIMD lane selection, and aggressive compiler optimisations cause identical models to produce different outputs? KEY_CLAIMS: - Consider a medical device company developing an ML model to detect cardiac abnormalities. - IEEE 754 floating-point permits platform-dependent optimisations including fused multiply-add availability, SIMD lane selection, rounding mode differences, and compiler reordering of arithmetic operations. - A single multiply-accumulate operation computed with and without FMA instructions can differ by one unit in the last place. - Compiler versions, standard library implementations, and link-time optimisations can all change floating-point instruction selection. - Q16.16 fixed-point integer arithmetic produces identical results on every C99-conformant platform because integer operations have fully defined overflow and rounding behaviour. EVIDENCE: - An FDA submission gets delayed while teams debug reproducibility issues. - Standards like DO-178C (aerospace), IEC 62304 (medical devices), and ISO 26262 (automotive) all require deterministic behavior. - Trade-offs: Range is limited (Q16.16 can represent -32768 to +32767.99998) Precision is fixed (not "floating") Some operations are slower (though often faster than software floating point) When this matters: When correctness beats convenience. - IEEE 754 floating-point permits platform-dependent optimisations including fused multiply-add availability, SIMD lane selection, rounding mode differences, and compiler reordering of arithmetic operations. RELATES_TO: - ai-architecture/debugging-model-behavior-production - ai-architecture/ml-observability-gap - ai-architecture/production-ai-unix-principles When 'mostly reproducible' isn't good enough for systems that matter ## The Problem Nobody Talks About Consider a medical device company developing an ML model to detect cardiac abnormalities. The model passes all tests—95% accuracy, low latency, no memory leaks. It runs perfectly in validation. During safety review, they discover something troubling: given identical ECG data, the model sometimes classifies the signal as normal and sometimes as abnormal. The same input. Different outputs. They can't reproduce specific predictions reliably. The model isn't wrong. It's **non-deterministic**. This scenario—or variations of it—represents a common challenge in safety-critical ML development. An FDA submission gets delayed while teams debug reproducibility issues. An automotive supplier discovers their perception model behaves differently across hardware platforms. A financial system produces inconsistent risk scores for the same customer data. The symptoms differ, but the root cause is the same: standard ML infrastructure was built for research, not for systems where reproducibility is a regulatory requirement. Modern ML infrastructure was built for research, not for systems where "mostly reproducible" isn't good enough. ## The Three Sources of Non-Determinism ML models fail to reproduce for three reasons. Two are well-known. The third is the one that actually causes production failures. ### 1. Floating Point Arithmetic (The Obvious One) Everyone knows floating point math is imprecise. `0.1 + 0.2 ≠ 0.3` in binary. Rounding errors accumulate. Operations aren't associative: `(a + b) + c ≠ a + (b + c)`. What's less obvious: **compiler optimization changes the results**. ```c // Without optimization float sum = 0.0f; for (int i = 0; i > 16); } // Example: 2.5 * 3.75 fixed_t a = (2 name, ((feature_t*)b)->name); } void process_features(feature_t* features, size_t count) { qsort(features, count, sizeof(feature_t), compare_features); // Now iteration order is deterministic for (size_t i = 0; i used + size > POOL_SIZE) { return NULL; // Explicit failure } void* ptr = pool->pool + pool->used; pool->used += size; return ptr; } // Allocation addresses are now deterministic // Same allocation sequence = same addresses = same behavior ``` ## What This Looks Like in Practice A deterministic neural network inference engine: ```c // Model state: fixed size, pre-allocated typedef struct { fixed_t weights[MAX_WEIGHTS]; fixed_t activations[MAX_ACTIVATIONS]; memory_pool_t pool; uint32_t layer_count; } model_t; // Initialize with bounded resources model_t* model_init(const uint8_t* model_data, size_t model_size) { model_t* m = calloc(1, sizeof(model_t)); if (!m) return NULL; // Load weights into fixed-point format load_weights(m, model_data, model_size); // Pre-allocate all activation memory pool_init(&m->pool, sizeof(m->activations)); return m; } // Inference: deterministic, bounded void model_predict(model_t* m, const fixed_t* input, fixed_t* output) { // Reset pool to initial state (deterministic allocation) pool_reset(&m->pool); // Forward pass: exact fixed-point ops for (uint32_t i = 0; i layer_count; i++) { layer_forward(m, i, input); } // Copy result memcpy(output, m->activations + output_offset, output_size); } ``` **Properties guaranteed:** - Same input → same output (bit-for-bit identical) - Bounded memory (no dynamic allocation) - Bounded time (no data-dependent loops with unbounded iteration) - No undefined behavior (every operation is specified) This is certifiable. This is reproducible. This is what safety-critical systems require. ## The Performance Question "But fixed-point is slower than floating point!" Sometimes yes. Often no. Depends on the target. **On CPUs with FPUs:** Floating point might be faster (hardware acceleration). **On microcontrollers without FPUs:** Fixed-point is dramatically faster (no software floating point emulation). **On embedded DSPs:** Fixed-point is native (that's what they're designed for). **For cache-sensitive workloads:** Fixed-point uses less memory (int32_t vs float = same size, but fixed-point models often quantize to int16_t or int8_t). More importantly: **determinism enables optimizations floating point can't do.** When behavior is guaranteed, you can: - Pre-compute lookup tables - Prove loop bounds for unrolling - Guarantee cache behavior - Enable aggressive optimizations that would be unsafe with floating point The real performance win isn't raw FLOPS. It's **predictability**. When you know exactly how long every operation takes, you can schedule with confidence. No worst-case margin. No jitter. Just deterministic timing. ## When Floating Point Is Fine Most ML doesn't need this. Research models, recommendation systems, content classification—non-determinism is acceptable. The cost of determinism exceeds the benefit. **Use floating point when:** - Approximate results are acceptable - You're not certifying for safety - Development speed matters more than reproducibility - You need the full dynamic range - You're not debugging production issues **Consider determinism when:** - Debugging is expensive (hard to reproduce issues) - Compliance requires proof of correctness - Systems are long-lived (must behave identically for years) - Liability is significant (people can be harmed) - Trust matters (financial, medical, legal decisions) ## The Path Forward Writing deterministic ML infrastructure in C isn't exotic. It's how embedded systems have done signal processing for decades. Digital filters, FFTs, control loops—all deterministic, all fixed-point, all certifiable. The techniques exist. The standards exist. What's missing is applying them to modern ML. **The opportunity:** Build inference engines that guarantee reproducibility. Create tools that enable certification. Solve the problems that prevent ML from being deployed in systems that matter. **The challenge:** Convenience vs. correctness. Floating point is easier. Determinism requires discipline. **The reality:** For systems where failure has consequences, "easier" isn't enough. Autonomous vehicles, medical devices, industrial control systems, financial infrastructure—these aren't research projects. They're production systems where "mostly reproducible" is unacceptable. The industry needs deterministic ML infrastructure built by people who understand both the mathematics and the constraints. People who've shipped safety-critical systems. People who know the difference between "it works" and "it provably works." If you're building ML for systems that matter, floating point isn't just dangerous—it's a liability you can't afford. ## Frequently Asked Questions ### Why is IEEE 754 floating-point dangerous for deterministic AI systems? IEEE 754 floating-point permits platform-dependent optimisations including fused multiply-add availability, SIMD lane selection, rounding mode differences, and compiler reordering of arithmetic operations. These permitted variations cause identical models to produce different numerical outputs on different hardware, making reproducibility impossible to guarantee. ### How do floating-point platform differences affect ML model outputs? A single multiply-accumulate operation computed with and without FMA instructions can differ by one unit in the last place. Across thousands of operations in a neural network forward pass, these differences propagate and compound, potentially changing classification outcomes for inputs near decision boundaries. ### Why doesn't using the same compiler and flags guarantee floating-point determinism? Compiler versions, standard library implementations, and link-time optimisations can all change floating-point instruction selection. Auto-vectorisation may use different SIMD widths. The same source code with the same flags can produce different binaries across compiler versions, producing different numerical results. ### What is the alternative to floating-point for deterministic AI inference? Q16.16 fixed-point integer arithmetic produces identical results on every C99-conformant platform because integer operations have fully defined overflow and rounding behaviour. The trade-off is constrained dynamic range that must be budgeted per network layer, but the gain is provable cross-platform reproducibility. ## Related Reading For more on production ML infrastructure: - [Production AI Systems: What 30 Years of UNIX Taught Me](/ai-architecture/production-ai-unix-principles/) - Infrastructure principles that enable reproducibility - [Debugging Model Behavior in Production](/ai-architecture/debugging-model-behavior-production/) - How non-determinism makes debugging impossible - [The Observability Gap in ML Systems](/ai-architecture/ml-observability-gap/) - Why traditional monitoring misses non-deterministic failures --- *Building deterministic ML infrastructure? I'm working on open-source tools to solve exactly these problems. [Get in touch](/contact/) if you're facing these challenges in production systems.* --- ## Debugging Model Behavior in Production **URL**: https://speytech.com/ai-architecture/debugging-model-behavior-production/ **Published**: January 13, 2026 21:40 **Topic**: AI Architecture **Answers**: How do you systematically debug a machine learning model that works correctly in staging but produces unexpected results or degraded performance in production, and what observability tools, diagnostic techniques, and monitoring strategies help identify the root cause of production model behaviour changes? KEY_CLAIMS: - The model worked perfectly in development. - Data distribution differences between staging and production environments are the most common cause. - Start by comparing input distributions between staging and production using statistical tests. - Restarting addresses symptoms without identifying root causes such as memory leaks, gradual data drift, or resource exhaustion patterns. - Log input hashes, output hashes, latency, model version, timestamp, and request IDs that span the entire request lifecycle on every prediction. EVIDENCE: - Memory leaks: Small per-request leak becomes catastrophic at 1000 req/sec Resource exhaustion: Connection pools, file handles, GPU memory Mitigation: Load testing at production scale, resource monitoring, connection pooling Problems triggered by specific data patterns that appear rarely. RELATES_TO: - ai-architecture/ai-model-serving-patterns - ai-architecture/ml-observability-gap - ai-architecture/production-ai-unix-principles When the model works in staging but fails in prod, here's how to find out why ## The Symptoms The model worked perfectly in development. Accuracy was 94%. Latency was 50ms. Integration tests passed. Staging looked good. Then you deploy to production. Within an hour, customers report incorrect predictions. You check the dashboard - accuracy is 67%. Some predictions are returning null. P99 latency is 8 seconds. You roll back. Everything returns to normal. You try deploying again the next day. Same problems. The model itself hasn't changed. The code hasn't changed. But something is different between staging and production. This is the most frustrating type of ML failure: behavior that appears only in production and can't be reproduced in development. ## The Investigation Process Debugging production model behavior follows a pattern. Work through these steps systematically. ### Step 1: Capture the Failing Input You need the exact input that caused the problem. Not a similar input. Not a representative sample. The specific input that failed. ```python # Add input capture on prediction failures def predict_with_capture(model, input_data, request_id): try: result = model.predict(input_data) return result except Exception as e: # Capture failing input failing_input = { 'request_id': request_id, 'input_data': sanitize_for_storage(input_data), 'error': str(e), 'timestamp': time.time(), 'model_version': model.version } # Store for later analysis store_failing_input(failing_input) log.error("prediction_failed", request_id=request_id, error=str(e), input_hash=hash_input(input_data) ) raise def sanitize_for_storage(input_data): """Remove PII but keep structure and statistics""" if isinstance(input_data, dict): return { k: sanitize_value(v) for k, v in input_data.items() } return input_data def sanitize_value(value): """Replace sensitive values while preserving type/range""" if isinstance(value, str): return f"" elif isinstance(value, (int, float)): return f"" # Approximate return value ``` **Why this works:** You can't debug what you can't reproduce. Capturing the failing input lets you reproduce the failure locally. **Common mistake:** Only logging aggregated statistics. "5% of predictions failed" tells you nothing about which inputs failed or why. ### Step 2: Check Input Distribution Shift Production data often differs from training data in subtle ways. ```python # Compare production input distributions to training def analyze_input_distribution(production_inputs, training_inputs): """Compare key statistics between production and training""" stats = {} for field in production_inputs[0].keys(): prod_values = [inp[field] for inp in production_inputs] train_values = [inp[field] for inp in training_inputs] if isinstance(prod_values[0], (int, float)): stats[field] = { 'prod_mean': mean(prod_values), 'train_mean': mean(train_values), 'prod_std': std(prod_values), 'train_std': std(train_values), 'prod_min': min(prod_values), 'train_min': min(train_values), 'prod_max': max(prod_values), 'train_max': max(train_values), } # Flag significant differences mean_diff = abs(stats[field]['prod_mean'] - stats[field]['train_mean']) if mean_diff > stats[field]['train_std']: stats[field]['warning'] = 'mean_shift' elif isinstance(prod_values[0], str): prod_unique = set(prod_values) train_unique = set(train_values) stats[field] = { 'prod_unique_count': len(prod_unique), 'train_unique_count': len(train_unique), 'new_values': prod_unique - train_unique, 'missing_values': train_unique - prod_unique } if stats[field]['new_values']: stats[field]['warning'] = 'unseen_categories' return stats # Run this analysis periodically prod_inputs = load_recent_production_inputs(hours=24) train_inputs = load_training_sample() distribution_stats = analyze_input_distribution(prod_inputs, train_inputs) # Alert on significant shifts for field, stats in distribution_stats.items(): if 'warning' in stats: log.warning("distribution_shift", field=field, warning=stats['warning'], details=stats ) ``` **What to look for:** - Numeric features outside training range - Categorical features with unseen values - Skewed distributions (prod mean far from training mean) - Missing or null values not present in training **Real example:** A fraud detection model failed because production transactions included a new `payment_method` value ("buy_now_pay_later") that wasn't in training data. Model had no learned behavior for this value. ### Step 3: Reproduce in Isolation Take the failing input and run it through the model in a controlled environment. ```python # Reproduce failure locally def reproduce_failure(failing_input_record): """Attempt to reproduce a production failure locally""" # Load exact model version from production model = load_model( version=failing_input_record['model_version'] ) # Reconstruct input input_data = failing_input_record['input_data'] # Reproduce prediction try: result = model.predict(input_data) print(f"Local prediction succeeded: {result}") print("This suggests environment difference, not model issue") return { 'reproduced': False, 'local_result': result } except Exception as e: print(f"Local prediction failed: {e}") print("Error reproduced - this is a model/input issue") # Analyze the failure analyze_prediction_failure(model, input_data, e) return { 'reproduced': True, 'error': str(e) } def analyze_prediction_failure(model, input_data, error): """Deep dive into why prediction failed""" # Check input validity print("\n=== Input Validation ===") for key, value in input_data.items(): print(f"{key}: type={type(value)}, value={value}") # Check for NaN/Inf if isinstance(value, float): if math.isnan(value): print(f" WARNING: {key} is NaN") if math.isinf(value): print(f" WARNING: {key} is Inf") # Check feature preprocessing print("\n=== Feature Preprocessing ===") try: features = model.preprocess(input_data) print(f"Preprocessing succeeded: {features}") except Exception as e: print(f"Preprocessing failed: {e}") print("Issue is in feature engineering, not model inference") return # Check model inference print("\n=== Model Inference ===") try: output = model.forward(features) print(f"Model inference succeeded: {output}") except Exception as e: print(f"Model inference failed: {e}") print("Issue is in model execution") ``` **If it reproduces locally:** Problem is in the model or input. Proceed to Step 4. **If it doesn't reproduce locally:** Problem is environmental (dependencies, resources, data sources). Proceed to Step 5. ### Step 4: Isolate the Layer Models have layers: preprocessing, feature engineering, inference, postprocessing. Find which layer fails. ```python # Test each layer independently def isolate_failing_layer(model, input_data): """Determine which model layer causes failure""" layers = [] # Layer 1: Input validation try: validated = model.validate_input(input_data) layers.append(('validation', 'pass', validated)) except Exception as e: layers.append(('validation', 'fail', str(e))) return layers # Can't proceed # Layer 2: Feature extraction try: features = model.extract_features(validated) layers.append(('feature_extraction', 'pass', features)) except Exception as e: layers.append(('feature_extraction', 'fail', str(e))) return layers # Layer 3: Preprocessing (scaling, encoding) try: preprocessed = model.preprocess(features) layers.append(('preprocessing', 'pass', preprocessed)) except Exception as e: layers.append(('preprocessing', 'fail', str(e))) return layers # Layer 4: Model inference try: raw_output = model.forward(preprocessed) layers.append(('inference', 'pass', raw_output)) except Exception as e: layers.append(('inference', 'fail', str(e))) return layers # Layer 5: Postprocessing try: final_output = model.postprocess(raw_output) layers.append(('postprocessing', 'pass', final_output)) except Exception as e: layers.append(('postprocessing', 'fail', str(e))) return layers return layers # Run isolation analysis layers = isolate_failing_layer(model, failing_input) for layer_name, status, result in layers: print(f"{layer_name}: {status}") if status == 'fail': print(f" Error: {result}") print(f" Issue is in {layer_name} layer") break ``` **Common failure points:** **Preprocessing:** Scaling/normalization with unexpected input ranges ```python # Fails if input outside training range scaled = (value - mean) / std # std might be 0 for constant features ``` **Feature extraction:** Missing or malformed fields ```python # Fails if field doesn't exist age = input_data['user_age'] # KeyError if missing ``` **Inference:** NaN or Inf propagation through network ```python # NaN inputs create NaN outputs output = model(features) # Silently propagates NaN ``` ### Step 5: Check Environmental Differences If the failure doesn't reproduce locally, the environment differs between staging and production. ```python # Compare staging vs production environments def compare_environments(): """Capture environment details for comparison""" import sys import platform env_info = { # Python environment 'python_version': sys.version, 'platform': platform.platform(), # Package versions 'tensorflow_version': tf.__version__, 'numpy_version': np.__version__, 'pandas_version': pd.__version__, # System resources 'cpu_count': os.cpu_count(), 'available_memory_gb': psutil.virtual_memory().available / 1e9, # Model file hash (verify model is identical) 'model_file_hash': hash_file('model.pt'), # Configuration 'model_config': model.get_config(), # Data sources 'feature_db_host': os.getenv('FEATURE_DB_HOST'), 'feature_db_version': get_db_version(), } return env_info # Capture in both environments staging_env = compare_environments() production_env = compare_environments() # Find differences differences = [] for key in staging_env: if staging_env[key] != production_env[key]: differences.append({ 'key': key, 'staging': staging_env[key], 'production': production_env[key] }) if differences: print("Environment differences found:") for diff in differences: print(f" {diff['key']}:") print(f" Staging: {diff['staging']}") print(f" Production: {diff['production']}") ``` **Common environmental causes:** **Version mismatches:** TensorFlow 2.10 vs 2.12 - subtle behavior changes **Resource constraints:** Staging has 8GB RAM, production has 4GB - OOM failures **Data sources:** Staging uses cached data, production queries live database - latency/content differences **Concurrency:** Staging is single-threaded, production is multi-threaded - race conditions ### Step 6: Enable Prediction Logging For issues that are intermittent or rare, enable detailed prediction logging to capture context when failures occur. ```python # Detailed prediction logging class PredictionLogger: def __init__(self, sample_rate=0.1): self.sample_rate = sample_rate def should_log(self, is_error=False): """Always log errors, sample successes""" if is_error: return True return random.random() < self.sample_rate def log_prediction(self, input_data, output, error=None, metadata=None): """Log prediction with full context""" if not self.should_log(is_error=error is not None): return log_entry = { 'timestamp': time.time(), 'input_hash': hash_input(input_data), 'input_stats': compute_input_stats(input_data), 'output': output if error is None else None, 'error': str(error) if error else None, 'metadata': metadata or {}, 'environment': { 'model_version': metadata.get('model_version'), 'host': socket.gethostname(), 'memory_usage_mb': get_memory_usage(), } } # Store for analysis prediction_log.write(log_entry) # Use in serving logger = PredictionLogger(sample_rate=0.1) def predict(input_data, request_id): metadata = {'request_id': request_id, 'model_version': model.version} try: output = model.predict(input_data) logger.log_prediction(input_data, output, metadata=metadata) return output except Exception as e: logger.log_prediction(input_data, None, error=e, metadata=metadata) raise ``` **Analysis queries:** ```python # Find patterns in failures failures = prediction_log.query( "SELECT * FROM predictions WHERE error IS NOT NULL" ) # Group by error type error_counts = failures.groupby('error').size() print("Most common errors:") print(error_counts.sort_values(ascending=False)) # Find input patterns that fail for error_type in error_counts.index[:5]: error_inputs = failures[failures['error'] == error_type] print(f"\n=== {error_type} ===") print("Input characteristics:") print(error_inputs['input_stats'].describe()) ``` ## Common Production-Only Failures ### Scale-Dependent Failures Problems that only appear at production traffic levels. **Memory leaks:** Small per-request leak becomes catastrophic at 1000 req/sec ```python # Leaked memory accumulates cache = {} # Never cleared cache[request_id] = result # Grows forever ``` **Resource exhaustion:** Connection pools, file handles, GPU memory ```python # Runs out after 1000 requests db_connection = create_connection() # Never closed ``` **Mitigation:** Load testing at production scale, resource monitoring, connection pooling ### Data-Dependent Failures Problems triggered by specific data patterns that appear rarely. **Adversarial inputs:** Unusual combinations not in training data ```python # Model never saw age=150 prediction = model.predict({'age': 150, 'income': 50000}) ``` **Edge cases:** Extreme values, empty lists, null handling ```python # Division by zero on empty list avg_purchase = sum(purchases) / len(purchases) # len=0 in prod ``` **Mitigation:** Input validation, defensive coding, edge case testing ### Timing-Dependent Failures Problems that depend on request timing or state. **Race conditions:** Multiple requests modifying shared state ```python # Not thread-safe if cache.get(key) is None: cache[key] = expensive_computation() # Race condition return cache[key] ``` **Stale caches:** Features cached too long, out of sync with model ```python # Feature cached 1 hour ago, model updated 30 minutes ago features = feature_cache.get(user_id) # Stale ``` **Mitigation:** Thread-safe code, cache invalidation, versioning ## The Debugging Toolkit Essential tools for production model debugging: **1. Request replay:** Capture and replay production requests locally **2. Diff tool:** Compare staging vs production environments **3. Input profiler:** Analyze input distributions over time **4. Layer inspector:** Step through model layers with real inputs **5. Prediction logs:** Comprehensive logging with sampling (see [The Observability Gap in ML Systems](/ai-architecture/ml-observability-gap/)) These tools, combined with the systematic process above, make most production failures debuggable. ## Frequently Asked Questions ### What causes ML models to behave differently in production than in staging? Data distribution differences between staging and production environments are the most common cause. Production traffic contains edge cases, adversarial inputs, and distribution shifts that curated staging datasets do not represent. Other causes include feature computation differences, race conditions under concurrent load, and stale caches serving outdated feature values. ### How do I systematically debug a production model behaviour change? Start by comparing input distributions between staging and production using statistical tests. Check feature pipelines for computation differences, examine infrastructure for resource contention, and replay production requests in a local environment. Request replay, environment diff tools, input profilers, and comprehensive prediction logging form the essential debugging toolkit. ### Why doesn't restarting the model server fix recurring production failures? Restarting addresses symptoms without identifying root causes such as memory leaks, gradual data drift, or resource exhaustion patterns. The underlying condition persists and recurs because the restart does not change the data distribution, fix the feature pipeline, or resolve the infrastructure issue that triggered the failure. ### What should I log to make production model debugging possible? Log input hashes, output hashes, latency, model version, timestamp, and request IDs that span the entire request lifecycle on every prediction. This enables correlation across services, input distribution analysis over time, and deterministic replay of specific failures. See [The Observability Gap in ML Systems](/ai-architecture/ml-observability-gap/) for a complete logging strategy. ## The Unsexy Truth Most production model failures aren't exotic ML problems. They're boring software engineering problems: - Missing input validation - Unhandled edge cases - Version mismatches - Resource constraints - Race conditions The ML model itself is usually fine. The infrastructure around it is broken. Fix the infrastructure using standard debugging techniques. The systematic process above works because it treats model serving as a software system, not as magic. When your model works in staging but fails in production, it's telling you something about the difference between those environments. Listen to it. Capture the failing inputs. Reproduce the failure. Isolate the cause. Fix the infrastructure. Then add tests to prevent regression. The same failure pattern shouldn't surprise you twice. **Related reading:** [The Observability Gap in ML Systems](/ai-architecture/ml-observability-gap/), [Production AI Systems: What 30 Years of UNIX Taught Me](/ai-architecture/production-ai-unix-principles/), and [Model Serving Architecture Patterns](/ai-architecture/ai-model-serving-patterns/). --- ## When You Don't Need a Feature Store **URL**: https://speytech.com/ai-architecture/when-you-dont-need-feature-store/ **Published**: January 13, 2026 21:15 **Topic**: AI Architecture **Answers**: When should an engineering team adopt a feature store for their machine learning infrastructure and when is it premature complexity, what are the actual production problems that feature stores solve, and what organisational and technical complexity do they introduce for teams not yet ready? KEY_CLAIMS: - A team builds their first production ML model. - A feature store is premature when a team has fewer than five production models, fewer than three teams sharing features, and no training-serving skew problems. - You need a feature store when multiple teams duplicate feature logic or training-serving skew causes accuracy drops. - A feature store provides consistent feature definitions but does not eliminate skew caused by timing differences, data freshness mismatches, or computation order dependencies. - Use shared functions for feature computation, Redis caching for expensive features, and disciplined code organisation. EVIDENCE: - For a prediction made on 2024-06-15, what was `user_tier` on that date? - Real-time features at scale When you need sub-100ms serving with features computed from terabytes of data. RELATES_TO: - ai-architecture/ai-model-serving-patterns - ai-architecture/production-ai-unix-principles Most teams adopt a feature store before they have the problem it solves ## The Pattern A team builds their first production ML model. It works. Then someone asks: "Should we use a feature store?" The question implies the answer. Feature stores are standard MLOps infrastructure. Every mature ML organization has one. The vendors say so. The conference talks recommend them. Not having a feature store feels like technical debt. So the team spends three months evaluating Feast, Tecton, and Databricks Feature Store. Another two months integrating the chosen solution. Another month debugging why features aren't matching between training and serving. Six months later, they're serving predictions from a feature store that recomputes features on every request - exactly what they were doing before, but with more complexity and latency. This pattern repeats constantly. Feature stores solve real problems. But most teams don't have those problems yet. ## What Feature Stores Actually Solve Feature stores solve three specific problems: **Problem 1: Training-Serving Skew** When training uses different feature computation logic than serving. The model trains on `sum(purchases_last_30_days)` but serves with `sum(purchases_last_month)` - different results, model breaks. **Problem 2: Feature Recomputation** When multiple models need the same features. Computing `user_lifetime_value` independently for each model wastes resources. **Problem 3: Point-in-Time Correctness** When training needs historical feature values. For a prediction made on 2024-06-15, what was `user_tier` on that date? Naive joins use current values, introducing data leakage. These are real problems. If you have them, feature stores help. But you might not have them yet. ## When You Don't Need a Feature Store ### You Have One Model If you have a single model, training-serving skew is easy to avoid without infrastructure: ```python # features.py - single source of truth def compute_features(user_data, transaction_data): """Used by both training and serving""" return { 'total_purchases': len(transaction_data), 'avg_purchase_value': mean([t.amount for t in transaction_data]), 'days_since_last_purchase': (today() - max([t.date for t in transaction_data])).days, # ... more features } # training.py features = compute_features(user_data, transactions) model.train(features, labels) # serving.py features = compute_features(user_data, transactions) prediction = model.predict(features) ``` This works. It's simple. It's maintainable. Skew is impossible - same code path for both. **Why this works:** With one model, feature logic fits in one file. No coordination needed. No shared infrastructure required. **When this breaks:** When you have 10 models and each reimplements `compute_features()` slightly differently. Now you have skew risk and maintenance burden. ### Your Features Are Request-Scoped If features only use data in the request, there's nothing to store: ```python # Request contains everything needed @app.post("/predict") def predict(request: PredictRequest): features = { 'transaction_amount': request.amount, 'merchant_category': request.merchant_category, 'is_international': request.country != 'US', 'hour_of_day': datetime.now().hour, } return model.predict(features) ``` **Why this works:** No historical data needed. No precomputation needed. Feature store would add latency without benefit. **When this breaks:** When you need `user_average_transaction_amount` or `merchant_fraud_rate` - data not in the request. Now you need storage. ### You Can Tolerate Batch Predictions If predictions can be computed overnight and cached, feature stores are overkill: ```python # Nightly batch job def compute_all_predictions(): users = load_all_users() for user in users: features = compute_features(user) prediction = model.predict(features) cache.set(f"prediction:{user.id}", prediction) # Serving just reads cache @app.get("/prediction/{user_id}") def get_prediction(user_id: str): return cache.get(f"prediction:{user_id}") ``` **Why this works:** Features computed once per day. Predictions cached. Serving is just cache lookup. No online feature computation needed. **When this breaks:** When predictions need to be real-time based on latest data. Now you need online features. ### Your Training Data Is Small If your training dataset fits in memory, point-in-time correctness is a SQL query: ```python # Training with point-in-time correctness training_data = db.query(""" SELECT u.user_id, u.created_at, COUNT(t.id) as num_transactions, AVG(t.amount) as avg_transaction FROM events e JOIN users u ON e.user_id = u.user_id LEFT JOIN transactions t ON t.user_id = u.user_id AND t.timestamp < e.timestamp -- Point-in-time correctness WHERE e.label IS NOT NULL GROUP BY u.user_id, u.created_at """) ``` **Why this works:** Database handles point-in-time joins. No feature store materialization needed. Results are fast enough for typical model training. **When this breaks:** When you have billions of training examples and complex feature joins. Now the SQL query takes hours. Feature store precomputation becomes necessary. ## What to Use Instead If you don't need a feature store, use simpler alternatives: ### Alternative 1: Shared Feature Functions ```python # features/user_features.py def compute_user_features(user_id: str, as_of: datetime = None): """Compute user features for training or serving Args: user_id: User identifier as_of: Timestamp for point-in-time correctness (training) If None, uses current time (serving) """ as_of = as_of or datetime.now() transactions = db.query( "SELECT * FROM transactions WHERE user_id = ? AND timestamp < ?", user_id, as_of ) return { 'num_transactions': len(transactions), 'total_spent': sum(t.amount for t in transactions), 'avg_transaction': mean([t.amount for t in transactions]), 'days_since_last': (as_of - max([t.timestamp for t in transactions])).days } # Training uses as_of for point-in-time correctness train_features = [ compute_user_features(ex.user_id, as_of=ex.timestamp) for ex in training_examples ] # Serving uses current time serve_features = compute_user_features(request.user_id) ``` **Advantages:** - Training-serving skew impossible (same code) - Point-in-time correctness handled - No new infrastructure - Easy to debug (just Python) **Disadvantages:** - Repeated computation (no caching across models) - Slow for many models or large-scale training ### Alternative 2: Cached Aggregations ```python # Precompute expensive features, cache results class FeatureCache: def __init__(self, cache_ttl_seconds=300): self.cache = {} self.ttl = cache_ttl_seconds def get_user_features(self, user_id: str): cache_key = f"user_features:{user_id}" # Check cache if cache_key in self.cache: cached_value, timestamp = self.cache[cache_key] if time.time() - timestamp < self.ttl: return cached_value # Compute and cache features = self._compute_user_features(user_id) self.cache[cache_key] = (features, time.time()) return features def _compute_user_features(self, user_id): # Expensive computation here return compute_features(user_id) # Use in serving feature_cache = FeatureCache(cache_ttl_seconds=300) @app.post("/predict") def predict(request: PredictRequest): features = feature_cache.get_user_features(request.user_id) return model.predict(features) ``` **Advantages:** - Fast serving (cache hits avoid computation) - No infrastructure beyond Redis/Memcached - TTL controls freshness - Works for multiple models **Disadvantages:** - Cache invalidation complexity - No point-in-time correctness for training - Need to handle cache misses ### Alternative 3: Materialized Views ```python # Database-native feature materialization db.execute(""" CREATE MATERIALIZED VIEW user_features AS SELECT user_id, COUNT(*) as num_transactions, SUM(amount) as total_spent, AVG(amount) as avg_transaction, MAX(timestamp) as last_transaction_date FROM transactions GROUP BY user_id """) # Refresh periodically (e.g., hourly) db.execute("REFRESH MATERIALIZED VIEW user_features") # Training queries the view train_features = db.query(""" SELECT u.*, f.* FROM training_examples u JOIN user_features f ON u.user_id = f.user_id """) # Serving queries the view serve_features = db.query( "SELECT * FROM user_features WHERE user_id = ?", user_id ) ``` **Advantages:** - Database-native (no new systems) - Fast reads (precomputed) - SQL-based (familiar tools) - Works for moderate scale **Disadvantages:** - Refresh lag (data staleness) - Less flexible than code - Doesn't scale to billions of features ## When You Actually Need a Feature Store You need a feature store when: **1. Multiple teams, many models** When 5 teams are building 20 models and all need `user_lifetime_value`. Reimplementing it 20 times creates skew risk and maintenance burden. **2. Real-time features at scale** When you need sub-100ms serving with features computed from terabytes of data. Materialized views and caches don't scale to this. **3. Complex point-in-time correctness** When training requires accurate historical feature values across dozens of feature types with different update frequencies. **4. Feature reuse is proven valuable** When you measure that 80% of features are shared across models. Not when you hope they might be shared someday. **5. Feature computation is expensive** When computing features costs more than storing them. For example, complex aggregations over streaming data. At this point, feature store infrastructure pays for its complexity. Before this point, it's premature optimization. ## The Migration Path If you start simple and later need a feature store, migration is straightforward: **Phase 1: Shared functions (current state)** ```python def compute_features(user_id): # Compute on demand return features ``` **Phase 2: Add caching** ```python def compute_features(user_id): cached = cache.get(f"features:{user_id}") if cached: return cached features = _compute(user_id) cache.set(f"features:{user_id}", features, ttl=300) return features ``` **Phase 3: Separate computation from serving** ```python # Background job precomputes features def precompute_features(): for user_id in active_users(): features = compute_features(user_id) feature_store.write(user_id, features) # Serving reads precomputed features def get_features(user_id): return feature_store.read(user_id) ``` **Phase 4: Add feature store** ```python # Now using Feast/Tecton/etc features = feature_store.get_online_features( entity_rows=[{"user_id": user_id}], features=["user_lifetime_value", "transaction_count"] ) ``` Each phase works independently. You only move to the next phase when current phase's limitations become painful. ## Frequently Asked Questions ### When is a feature store premature complexity for an ML team? A feature store is premature when a team has fewer than five production models, fewer than three teams sharing features, and no training-serving skew problems. Most teams at this stage solve the same problems with shared functions, basic caching, and a well-structured feature computation library without the operational overhead of dedicated feature infrastructure. ### How do I know when my team actually needs a feature store? You need a feature store when multiple teams duplicate feature logic or training-serving skew causes accuracy drops. These are organisational scaling problems, not individual model problems. ### Why doesn't a feature store automatically solve training-serving skew? A feature store provides consistent feature definitions but does not eliminate skew caused by timing differences, data freshness mismatches, or computation order dependencies. Teams must still validate that training-time and serving-time feature values match statistically. The feature store is infrastructure, not a guarantee. ### What should I use instead of a feature store for small ML teams? Use shared functions for feature computation, Redis caching for expensive features, and disciplined code organisation. Add monitoring for feature freshness and value distributions. This handles most production needs until organisational scale forces the feature store investment. ## The Unsexy Truth Feature stores solve real problems. But those problems appear at scale, not at the start. Most teams building their first few models don't have: - Dozens of models competing for feature computation resources - Terabytes of feature data requiring specialized storage - Complex point-in-time correctness requirements across teams What they have: - One or two models - Features that fit in a database - Team small enough to coordinate in Slack For these teams, a feature store is complexity without benefit. Shared functions and basic caching solve the same problems with less infrastructure. Build the simple thing first. Add complexity when you have evidence you need it. You'll know when that time comes - your team will be spending more time working around the limitations of simple approaches than they would spend adopting a feature store. Until then, skip it. **Related reading:** [Production AI Systems: What 30 Years of UNIX Taught Me](/ai-architecture/production-ai-unix-principles/) and [Model Serving Architecture Patterns](/ai-architecture/ai-model-serving-patterns/). --- ## Model Serving Architecture Patterns **URL**: https://speytech.com/ai-architecture/ai-model-serving-patterns/ **Published**: January 13, 2026 20:35 **Topic**: AI Architecture **Answers**: What are the main architecture patterns for serving machine learning models in production, how do you choose between real-time inference, batch prediction, and streaming approaches based on latency requirements, and what are the throughput and infrastructure cost trade-offs for each pattern? KEY_CLAIMS: - "How should we serve our models?" Most teams reach for the first solution that works: wrap the model in Flask, throw it behind a load balancer, call it done. - The three fundamental patterns are single-process serving, multi-worker serving, and async batch serving. - Choose based on latency requirements and hardware constraints. - Single-process serving suffers from head-of-line blocking where one slow request blocks all subsequent requests. - Batch contamination causes an entire batch to fail when one input is malformed. EVIDENCE: - Then someone asks: "Why is P99 latency 5 seconds when P50 is 50ms?" Or: "Why can we only handle 10 requests per second?" Or: "Why did one slow request take down the entire service?" These aren't model problems. - Latency variance: Some requests wait 1ms for batch, others wait 50ms (full timeout). - What's your traffic volume? 1000 req/sec → Consider batching 2. - P99 < 100ms → No batching, multi-worker P99 < 1s → Small batches (5-10ms timeout) P99 < 5s → Batching acceptable 3. RELATES_TO: - ai-architecture/ml-observability-gap - ai-architecture/production-ai-unix-principles Understanding latency, throughput, and the trade-offs between them ## The Question Nobody Asks "How should we serve our models?" Most teams reach for the first solution that works: wrap the model in Flask, throw it behind a load balancer, call it done. This works until it doesn't. Then someone asks: "Why is P99 latency 5 seconds when P50 is 50ms?" Or: "Why can we only handle 10 requests per second?" Or: "Why did one slow request take down the entire service?" These aren't model problems. They're architecture problems. The way you structure model serving determines what's possible and what's impossible. ## The Three Fundamental Patterns Every model serving architecture is a variation on three basic patterns. Each optimizes for different constraints. Each has different failure modes. ### Pattern 1: Single-Process Serving The simplest pattern: one process loads one model, serves all requests sequentially. ```python # Single-process server class ModelServer: def __init__(self, model_path): self.model = load_model(model_path) def predict(self, request): return self.model.predict(request.data) # Flask/FastAPI wrapper app = FastAPI() server = ModelServer("model.pt") @app.post("/predict") def predict_endpoint(request: PredictRequest): return server.predict(request) ``` **What this optimizes for:** - Simplicity (minimal code, easy to reason about) - Memory efficiency (one model copy in memory) - Consistent behavior (no parallelism surprises) **Where this breaks:** - **Throughput**: Sequential processing caps requests/second - **Latency**: One slow request blocks all others (head-of-line blocking) - **Availability**: Process crash = service down **When to use it:** - Low traffic (= self.batch_size: asyncio.create_task(self._process_batch()) return await future async def _process_batch(self): """Process accumulated requests as batch""" if not self.pending: return # Extract batch batch = self.pending[:self.batch_size] self.pending = self.pending[self.batch_size:] ids, inputs, futures = zip(*batch) # Batch inference try: batch_input = stack_inputs(inputs) batch_output = self.model.predict(batch_input) # Distribute results for req_id, output, future in zip(ids, batch_output, futures): future.set_result(output) except Exception as e: # Fail all requests in batch for future in futures: future.set_exception(e) async def _batch_timeout_worker(self): """Process partial batches after timeout""" while True: await asyncio.sleep(self.timeout_ms / 1000) if self.pending: asyncio.create_task(self._process_batch()) ``` **What this optimizes for:** - GPU efficiency (batching maximizes GPU utilization) - Throughput (batch processing is faster than N individual calls) - Cost (fewer GPU instances needed for same throughput) **Where this breaks:** - **Latency**: Waiting for batch adds delay (batching_delay = timeout_ms) - **Complexity**: Async code, result distribution, timeout management - **Fairness**: Large requests can starve small requests **When to use it:** - GPU-based models (batching gives 5-10× throughput improvement) - High throughput requirements (> 1000 req/sec) - Can tolerate added latency (10-100ms batching delay acceptable) - Cost optimization matters (GPU time is expensive) **The latency-throughput trade-off:** Larger batches = higher throughput but higher latency. Smaller batches = lower latency but lower throughput. There's no free lunch. ## The Patterns Combined Production systems often combine patterns: ### Hybrid: Multi-Worker + Batching ```python # Multiple workers, each doing batching # gunicorn -w 4 -k uvicorn.workers.UvicornWorker app:app class HybridModelServer: def __init__(self, model_path): self.batch_server = BatchModelServer( model_path, batch_size=32, timeout_ms=10 ) async def predict(self, request): return await self.batch_server.predict( request.id, request.data ) ``` This gives you: - Worker-level isolation (failures contained) - Batch-level GPU efficiency - Scalability (add workers for more capacity) At the cost of: - Maximum complexity - Maximum memory (N workers × model size) - Hardest to debug ## Latency vs Throughput: The Fundamental Trade-off You cannot optimize for both simultaneously. Every architecture choice moves you along this spectrum. **Optimize for latency:** - Single-process serving (no queueing) - Small or no batching (immediate processing) - Overprovisioned capacity (requests never wait) - Multiple model replicas (parallel serving) **Result:** Low latency, high cost, lower throughput. **Optimize for throughput:** - Large batches (maximize GPU utilization) - Request queueing (keep GPU busy) - Underprovisioned capacity (queue absorbs bursts) - Fewer replicas (higher utilization per instance) **Result:** High throughput, lower cost, higher latency. **Production reality:** Most systems need something in between. The right balance depends on your use case, not universal best practices. ## Failure Modes by Pattern Different patterns fail differently. Understanding failure modes helps you pick the right pattern. ### Single-Process Failure Modes **Head-of-line blocking:** One slow request blocks all subsequent requests. ```python # Request 1: 100ms (normal) # Request 2: 10s (adversarial input) # Request 3: 100ms (normal) - but waits 10s for Request 2 ``` **Mitigation:** Request timeouts, input validation, separate queues for different request types. **Process crash:** One bad input crashes the process, service down until restart. **Mitigation:** Process supervision (systemd, k8s), health checks, circuit breakers. See [Production AI Systems: What 30 Years of UNIX Taught Me](/ai-architecture/production-ai-unix-principles/) for proven failure handling patterns. ### Multi-Worker Failure Modes **Memory exhaustion:** Workers compete for memory, OOM killer terminates processes randomly. **Mitigation:** Resource limits per worker, monitoring memory per worker, autoscaling based on memory not just CPU. **Version skew:** During deployment, some workers have new model, some have old model. Requests get inconsistent results. **Mitigation:** Blue-green deployment (switch all at once) or canary with traffic shaping (gradual migration). ### Batch Serving Failure Modes **Batch contamination:** One bad input in batch causes entire batch to fail. ```python # Batch of 32 requests # Request 15 has malformed input # All 32 requests fail ``` **Mitigation:** Input validation before batching, per-request error handling, batch splitting on failure. **Latency variance:** Some requests wait 1ms for batch, others wait 50ms (full timeout). P99 latency = timeout duration regardless of actual processing time. **Mitigation:** Smaller batches (trades throughput for consistency), adaptive batching (adjust size based on traffic), separate batches by priority. ## Choosing the Right Pattern Ask these questions in order: **1. What's your traffic volume?** - 1000 req/sec → Consider batching **2. What's your latency requirement?** - P99 < 100ms → No batching, multi-worker - P99 < 1s → Small batches (5-10ms timeout) - P99 < 5s → Batching acceptable **3. What hardware are you using?** - CPU-only → Multi-worker (cheap parallelism) - GPU → Batching (essential for GPU efficiency) **4. What's your memory budget?** - Model × N workers fits in RAM → Multi-worker - Model × N workers exceeds RAM → Single-process or batching **5. Can you tolerate complexity?** - No → Single-process or multi-worker - Yes → Batching or hybrid ## Production-Ready Implementation Here's a robust multi-worker serving implementation with proper error handling and observability (see [The Observability Gap in ML Systems](/ai-architecture/ml-observability-gap/) for what to log and why): ```python import time import logging from functools import wraps class ProductionModelServer: def __init__(self, model_path, timeout_ms=100): self.model = self._load_with_retry(model_path) self.timeout_ms = timeout_ms self.stats = {"success": 0, "timeout": 0, "error": 0} def _load_with_retry(self, model_path, retries=3): """Load model with retries and timeout""" for attempt in range(retries): try: logging.info(f"Loading model, attempt {attempt + 1}") model = load_model(model_path, timeout=30) logging.info("Model loaded successfully") return model except Exception as e: logging.error(f"Load failed: {e}") if attempt == retries - 1: raise time.sleep(2 ** attempt) # Exponential backoff def predict(self, request_id, data): """Predict with timeout and comprehensive error handling""" start = time.monotonic() try: # Validate input if not self._validate_input(data): self.stats["error"] += 1 raise ValueError("Invalid input format") # Predict with timeout result = self._predict_with_timeout(data) latency_ms = (time.monotonic() - start) * 1000 self.stats["success"] += 1 logging.info("prediction_success", request_id=request_id, latency_ms=latency_ms ) return result except TimeoutError: self.stats["timeout"] += 1 logging.error("prediction_timeout", request_id=request_id, timeout_ms=self.timeout_ms ) raise except Exception as e: self.stats["error"] += 1 logging.error("prediction_error", request_id=request_id, error=str(e) ) raise def _predict_with_timeout(self, data): """Run prediction with timeout""" # Implementation depends on framework # TensorFlow: use timeout in session.run() # PyTorch: use signal.alarm() or threading return self.model.predict(data) def _validate_input(self, data): """Validate input before prediction""" # Check type, shape, ranges return True def health_check(self): """Health check for load balancer""" return { "status": "healthy", "model_loaded": self.model is not None, "stats": self.stats } ``` ## Frequently Asked Questions ### What are the main ML model serving architecture patterns? The three fundamental patterns are single-process serving, multi-worker serving, and async batch serving. Single-process handles sequential requests with minimal complexity. Multi-worker replicates the model across processes for parallel throughput. Async batch serving collects requests into batches for GPU-efficient processing, trading latency for throughput. ### How do I choose between real-time inference and batch prediction? Choose based on latency requirements and hardware constraints. Real-time inference with multi-worker serving suits latency-sensitive applications under 100ms P99. Batch prediction maximises GPU utilisation when 10–100ms additional latency is acceptable, typically yielding 5–10× throughput improvement over individual calls. ### Why doesn't single-process model serving scale for production traffic? Single-process serving suffers from head-of-line blocking where one slow request blocks all subsequent requests. Sequential processing caps throughput, and a process crash takes the entire service down. However, a single process can handle 50–100 fast predictions per second, which is sufficient for many internal tools and early-stage products. ### What are the failure modes of batch model serving? Batch contamination causes an entire batch to fail when one input is malformed. Latency variance means some requests wait 1ms while others wait the full timeout duration. P99 latency equals the timeout duration regardless of actual processing time. Mitigations include input validation before batching, per-request error handling, and adaptive batch sizing. ## The Unsexy Truth The right serving pattern depends on your constraints, not what's popular. Single-process serving handles more traffic than people think. Multi-worker serving solves most problems without exotic infrastructure. Batching is essential for GPUs but adds complexity. Start simple. Measure. Add complexity only when you have evidence it's needed. Most serving performance problems aren't architectural - they're resource limits, memory leaks, or inefficient models. Fix those first before redesigning your architecture. The best serving architecture is the simplest one that meets your requirements. Everything else is premature optimization.1G --- ## Production AI Systems: What 30 Years of UNIX Taught Me **URL**: https://speytech.com/ai-architecture/production-ai-unix-principles/ **Published**: January 13, 2026 19:51 **Topic**: AI Architecture **Answers**: What specific lessons from thirty years of UNIX systems administration and production infrastructure engineering apply directly to building reliable ML systems, and which traditional infrastructure principles around process isolation, failure handling, and monitoring transfer most effectively to machine learning operations? KEY_CLAIMS: - I spent three decades keeping UNIX systems running in production. - Process isolation, structured logging, resource limits, and failure supervision transfer directly from UNIX infrastructure to ML operations. - Use process supervisors like systemd or Kubernetes to automatically restart crashed model servers. - The infrastructure problems solved in UNIX engineering decades ago recur in ML systems with new names. - ML systems have statistical failure modes where a model serves confidently wrong predictions without crashing. EVIDENCE: - The same infrastructure problems that plagued distributed systems in 1997 are plaguing ML systems in 2026. - The same principles that kept Solaris servers running in 1997 will keep your ML systems running in 2026. RELATES_TO: - ai-architecture/ml-observability-gap The infrastructure principles that kept systems running still apply to ML ## The Problem Nobody Talks About I spent three decades keeping UNIX systems running in production. Banks, telcos, healthcare - places where downtime meant actual consequences. When I started working with ML systems five years ago, I expected them to be different. They're not. The same infrastructure problems that plagued distributed systems in 1997 are plaguing ML systems in 2026. We've just renamed them and added GPUs. Models fail to load. Predictions time out. Memory leaks crash inference servers. Log files grow until they fill the disk. Race conditions corrupt model state. The exact problems we solved in UNIX systems engineering, now dressed up in Python and TensorFlow. The difference is that most ML teams don't realize they're building distributed systems. They think they're doing "AI engineering" when they're actually doing systems engineering with models attached. ## What UNIX Got Right UNIX survived because it had principles, not just implementations. These principles emerged from decades of production experience, refined by failure. They're not sexy. They're not new. But they work. ### Principle 1: Everything Fails UNIX assumes failure. Processes crash. Disks fill. Networks partition. This isn't pessimism - it's realism. ML systems often assume success. The model loads. The prediction completes. The GPU is available. When these assumptions break, the system has no plan. **UNIX approach:** Process supervision (init, systemd). If a daemon crashes, restart it. If it crashes repeatedly, stop trying and alert someone. **ML equivalent:** Model serving should assume models fail to load, predictions timeout, and GPUs disappear. Every operation needs a failure path. ```python def serve_prediction(model_id, input_data, timeout_ms=100): """Production serving with UNIX-style failure handling""" try: # Try to load model with timeout model = load_model_with_timeout(model_id, timeout_ms=5000) # Predict with resource limits result = predict_with_limits( model, input_data, memory_mb=512, timeout_ms=timeout_ms ) return {"status": "success", "prediction": result} except ModelLoadTimeout: # Model didn't load in time - use fallback log.error("model_load_timeout", model_id=model_id) return {"status": "fallback", "reason": "model_load_timeout"} except PredictionTimeout: # Prediction took too long - fail fast log.error("prediction_timeout", model_id=model_id) return {"status": "timeout", "latency_ms": timeout_ms} except MemoryError: # Out of memory - clear and retry once gc.collect() log.warning("oom_retry", model_id=model_id) # Return cached result or fallback return get_cached_or_fallback(model_id, input_data) ``` This isn't paranoia. It's the same thinking that made UNIX reliable: assume failure, handle it explicitly, fail gracefully. ### Principle 2: Observability Through Logs UNIX philosophy: everything important should emit structured logs. Not pretty dashboards. Not ML-specific "observability platforms." Just logs. Logs survive system crashes. Logs can be grep'd. Logs work when your monitoring infrastructure is down. Logs are boring, which is why they work. (For a deeper dive on what to log in ML systems specifically, see [The Observability Gap in ML Systems](/ai-architecture/ml-observability-gap/).) ML systems often log the wrong things. Training loss curves. Model accuracy. Hyperparameters. These matter for research. They don't help at 3AM when predictions are failing. **What to log:** ```python # Model loading log.info("model_load_start", model_id=model_id, version=version, size_mb=model_size) # Model loaded successfully log.info("model_load_success", model_id=model_id, load_time_ms=elapsed, memory_mb=memory_used) # Prediction executed log.info("prediction", model_id=model_id, input_hash=hash(input_data), latency_ms=latency, result_hash=hash(result)) # Resource exhaustion approaching log.warning("memory_pressure", used_mb=memory_used, available_mb=memory_available, threshold_pct=80) ``` Notice what's not there: model internals, feature importance, gradient norms. Those belong in training logs. Production logs answer operational questions: Did it work? How long did it take? What resources did it consume? ### Principle 3: Processes Are Cheap, State Is Expensive UNIX makes process creation cheap deliberately. Fork, exec, run, exit. No complex lifecycle management. No shared state between processes unless explicitly designed. ML systems often invert this. They create one long-lived process (a "model server") that holds expensive state (loaded models) and serves many requests. When that process fails, all state is lost. **UNIX pattern applied to ML:** Instead of one process serving all models, run one process per model. When a model crashes, only that model fails. Other models keep serving. ```bash # Traditional approach - one server, all models model_server --models=modelA,modelB,modelC # UNIX approach - separate processes model_server --model=modelA & model_server --model=modelB & model_server --model=modelC & ``` Yes, this uses more memory. Yes, it's "less efficient." But it's more reliable, which matters more in production. Memory is cheap. Debugging cascading failures at 3AM is expensive. ### Principle 4: Text Streams Beat Custom Formats UNIX pipes work because everything speaks text. `ps | grep | awk | sort` - different tools, same interface. ML systems love custom formats. Pickle files. TensorFlow SavedModels. ONNX. Each format needs specific loading code. Each format can break in unique ways. **Better approach:** Use standard formats for everything outside the model itself. - **Inputs:** JSON or Protocol Buffers (parseable, validatable) - **Outputs:** JSON (compatible with every tool) - **Configs:** YAML or TOML (human-readable, version-controllable) - **Logs:** Structured text (grep-able, parseable) When the model serving process crashes, you can still parse its logs, validate its configs, and inspect its inputs. You don't need model-specific tools to understand what happened. ### Principle 5: Small Tools, Composed UNIX provides `cat`, `grep`, `sort`, `uniq` - each does one thing. Composition creates power. ML systems often build monoliths. One codebase for training, serving, monitoring, and retraining. When any part fails, the whole system is suspect. **Composition in ML:** ``` # Training - writes model to disk train_model --config=config.yaml --output=model.pt # Serving - loads model from disk serve_model --model=model.pt --port=8000 # Monitoring - reads serving logs monitor_serving --logs=/var/log/serving --alert-threshold=0.95 # Retraining trigger - watches monitoring retrain_trigger --monitor=localhost:8001 --threshold=0.90 ``` Each process does one thing. They communicate through files and logs. When serving breaks, training keeps working. When monitoring breaks, serving keeps working. ## Where ML Systems Are Actually Different UNIX principles apply broadly, but ML systems do have unique characteristics. **Statistical failure modes:** A model can be "working" (no crashes) but producing garbage predictions. Traditional systems don't have this problem - a crashed process is obviously broken. A model serving confidently wrong predictions requires different monitoring. **Resource elasticity:** Models can consume wildly different resources for different inputs. A 10-word sentence and a 10,000-word document hit the same endpoint but need different resources. UNIX services tend to have more predictable resource usage. **Versioning semantics:** Deploying a new model version isn't like deploying new code. The interface stays the same but the behavior changes fundamentally. This requires different rollout strategies than traditional deployments. These differences are real. But they don't invalidate UNIX principles - they extend them. ## Applying This Tomorrow If you're running ML systems in production and they're unreliable, start with UNIX basics: **Week 1:** Add structured logging to model serving. Log every load, every prediction, every failure. Make logs grep-able. **Week 2:** Add process supervision. If your model server crashes, restart it automatically. If it crashes repeatedly, page someone. **Week 3:** Add resource limits. Cap memory usage, timeout predictions, fail fast when resources are exhausted. **Week 4:** Isolate failures. Run risky models in separate processes. Don't let one bad model take down the whole service. None of this is ML-specific. It's just systems engineering. The same principles that kept Solaris servers running in 1997 will keep your ML systems running in 2026. ## Frequently Asked Questions ### What UNIX principles apply directly to production ML systems? Process isolation, structured logging, resource limits, and failure supervision transfer directly from UNIX infrastructure to ML operations. Run models in separate processes with memory caps, log every prediction with grep-able structured output, implement automatic restart on crash, and fail fast when resources are exhausted. ### How do I apply process supervision to ML model serving? Use process supervisors like systemd or Kubernetes to automatically restart crashed model servers. If a server crashes repeatedly, escalate to alerting. Add health checks that verify the model is loaded and serving predictions, not just that the process is running. This prevents silent failures where the process lives but the model is unresponsive. ### Why doesn't ML infrastructure benefit from novel architecture when proven patterns exist? The infrastructure problems solved in UNIX engineering decades ago recur in ML systems with new names. These problems have proven solutions. Novel ML-specific architectures add complexity without solving the fundamental operational issues that cause most production outages. ### What makes ML systems different from traditional UNIX services? ML systems have statistical failure modes where a model serves confidently wrong predictions without crashing. Resource usage varies wildly per input — a short text and a long document hit the same endpoint with different resource needs. Model version deployments change behaviour without changing interfaces, requiring different rollout strategies than code deployments. ## The Unsexy Truth Production ML systems fail for boring reasons. Disk full. Memory leak. Network timeout. Configuration typo. Process crash. These are solved problems. UNIX solved them decades ago. We just need to remember the solutions. AI systems are systems first, AI second. Treat them like systems and they'll be more reliable than if you treat them like magic. The principles that kept UNIX running for 30 years still work. They're just not as exciting as talking about transformers and embeddings. But at 3AM when production is down, you'll care a lot more about process supervision than you will about attention mechanisms. Start with the boring infrastructure. Make it reliable. Then add the AI on top. Not the other way around. --- ## The Observability Gap in ML Systems **URL**: https://speytech.com/ai-architecture/ml-observability-gap/ **Published**: January 13, 2026 19:15 **Topic**: AI Architecture **Answers**: Why do production ML model serving clusters fail in ways that are difficult to diagnose with conventional monitoring tools, and what specific observability gaps exist between traditional infrastructure monitoring and the model-level behavioural metrics needed to understand ML system failures? KEY_CLAIMS: - The model serving cluster is down. - The observability gap is the disconnect between traditional infrastructure monitoring and the model-level behavioural metrics needed to diagnose ML system failures. - Add structured logging to every prediction on day one: input hash, output hash, latency, model version, and timestamp. - Traditional monitoring tracks CPU, memory, disk, and network — infrastructure health. - Logging every prediction adds storage cost, latency overhead, and operational complexity. EVIDENCE: - System says: "P99 latency increased from 50ms to 200ms." Reality: A specific class of inputs takes 10x longer to process, but you don't know which class or why. - When you see "P99 latency spiked at 2AM," you can correlate with "inputs with list_length > 1000 started appearing at 2AM." Models aren't static. RELATES_TO: - ai-architecture/production-ai-unix-principles Why your model serving cluster fails at 3AM and you can't figure out why ## The 3AM Page The model serving cluster is down. Again. Production traffic is failing. The error message says "Internal Server Error." The logs say nothing useful. You ssh into a pod. CPU looks fine. Memory looks fine. The model loaded successfully an hour ago. Predictions were working. Then they stopped. No obvious trigger. No deployment. No config change. Just... stopped. You restart the pods. Traffic recovers. Problem "solved." You go back to bed. Three days later, it happens again. Same symptoms. Same non-explanation. Same restart-and-hope fix. This is the observability gap in ML systems. Traditional monitoring tells you the system is broken. It doesn't tell you *why* the model stopped making predictions. ## What Traditional Observability Misses Standard monitoring tracks system metrics: CPU, memory, disk, network. These work for stateless services. They fail for ML systems because the interesting failures happen inside the model. **System says:** "Everything's fine! CPU at 40%, memory at 60%." **Reality:** The model is returning garbage predictions because input distributions shifted and nobody noticed. **System says:** "Pod restarted due to OOM kill." **Reality:** A single adversarial input caused the model to allocate unbounded memory, but you'll never know which input because it's not logged. **System says:** "P99 latency increased from 50ms to 200ms." **Reality:** A specific class of inputs takes 10x longer to process, but you don't know which class or why. Traditional observability gives you symptoms. ML observability requires understanding model behavior, not just process health. ## The Missing Logs When I started working with ML systems, I asked: "Where are the prediction logs?" The response: "We log accuracy metrics to MLflow." That's not observability. That's research tracking. In production, I need to answer different questions: - Which prediction failed? - What input caused this latency spike? - Did the model see this input pattern before? - When did prediction quality start degrading? - Which model version served this request? None of these questions are answerable from accuracy dashboards or system metrics. They require logging what actually happened during serving. ## What to Log (And What Not To) ### Log Every Prediction Not just errors. Not just slow requests. Every single prediction. ```python def serve_prediction(model_id, input_data, request_id): start = time.monotonic() # Compute input hash for deduplication/lookup input_hash = hashlib.sha256( json.dumps(input_data, sort_keys=True).encode() ).hexdigest()[:16] try: result = model.predict(input_data) latency_ms = (time.monotonic() - start) * 1000 # Log success with context log.info("prediction_success", request_id=request_id, model_id=model_id, model_version=model.version, input_hash=input_hash, input_size=len(str(input_data)), output_hash=hash(str(result))[:16], latency_ms=latency_ms, timestamp=time.time() ) return result except Exception as e: latency_ms = (time.monotonic() - start) * 1000 # Log failure with same context log.error("prediction_failure", request_id=request_id, model_id=model_id, model_version=model.version, input_hash=input_hash, error_type=type(e).__name__, error_msg=str(e)[:200], # Truncate long errors latency_ms=latency_ms, timestamp=time.time() ) raise ``` This gives you a complete prediction history. When something breaks, you can reconstruct exactly what happened. ### Log Input Characteristics Don't log the raw input (privacy, storage cost). Log characteristics that help debug. ```python def log_input_stats(input_data): """Log statistical properties of input""" if isinstance(input_data, dict): stats = { "num_fields": len(input_data), "field_names": sorted(input_data.keys()), "total_size_bytes": len(json.dumps(input_data)) } # For numeric fields, log ranges for key, value in input_data.items(): if isinstance(value, (int, float)): stats[f"{key}_value"] = value elif isinstance(input_data, list): stats = { "list_length": len(input_data), "item_types": list(set(type(x).__name__ for x in input_data)), "total_size_bytes": len(json.dumps(input_data)) } log.info("input_characteristics", **stats) ``` When you see "P99 latency spiked at 2AM," you can correlate with "inputs with list_length > 1000 started appearing at 2AM." ### Log Model State Changes Models aren't static. They get loaded, unloaded, swapped, updated. Log every state transition. ```python class ModelServer: def load_model(self, model_id, version): log.info("model_load_start", model_id=model_id, version=version, timestamp=time.time() ) try: model = load_model_from_storage(model_id, version) memory_mb = get_model_memory_usage(model) log.info("model_load_success", model_id=model_id, version=version, memory_mb=memory_mb, load_time_ms=(time.monotonic() - start) * 1000, timestamp=time.time() ) return model except Exception as e: log.error("model_load_failure", model_id=model_id, version=version, error=str(e), timestamp=time.time() ) raise ``` When models mysteriously stop working, you can see: "Model B version 2.1 was loaded at 02:47, failures started at 02:48." ## What NOT to Log **Don't log model internals during serving.** No gradients, no activations, no attention weights. These are expensive to compute and rarely useful for production debugging. **Don't log PII.** Hash inputs instead of logging raw data. If you need to debug specific inputs, store hashes and retrieve inputs separately with proper access controls. **Don't log everything to stdout.** Use structured logging (JSON) that can be parsed and indexed. Use log levels appropriately (INFO for normal operations, WARN for degraded states, ERROR for failures). ## The Correlation Problem Logs are useless if you can't correlate them. Every log entry needs a request ID that spans the entire request lifecycle. ```python @app.route('/predict', methods=['POST']) def predict_endpoint(): # Generate request ID at entry point request_id = str(uuid.uuid4()) log.info("request_start", request_id=request_id, endpoint="/predict", timestamp=time.time() ) try: # Pass request_id through entire stack result = serve_prediction( model_id=request.json['model_id'], input_data=request.json['input'], request_id=request_id ) log.info("request_success", request_id=request_id, status_code=200, timestamp=time.time() ) return jsonify(result), 200 except Exception as e: log.error("request_failure", request_id=request_id, error=str(e), timestamp=time.time() ) return jsonify({"error": "Internal error"}), 500 ``` Now when you see a failure, you can grep for the request_id and see the entire request flow: when it started, which model served it, what the input characteristics were, where it failed. ## Detection vs. Diagnosis Traditional monitoring detects problems: "Latency increased." ML observability enables diagnosis: "Latency increased because inputs with >500 tokens started appearing, and those take 10x longer to process." Detection gets you paged. Diagnosis gets you back to sleep. **Without proper logging:** - "Model is failing" → restart pods, hope it works - "Latency increased" → scale up, hope it helps - "Accuracy dropped" → no idea when or why **With proper logging:** - "Model is failing" → specific input pattern triggers OOM, add input validation - "Latency increased" → P99 driven by large inputs, add size limits or separate queue - "Accuracy dropped" → distribution shift detected at specific timestamp, trigger retraining ## The Storage Cost Objection "But logging every prediction is expensive!" Yes. It costs money. Know what costs more? Not being able to debug production issues. Not knowing when your model started failing. Not being able to reproduce incidents. ML systems that work at 3AM are worth more than the S3 bill for prediction logs. **Practical cost management:** - Use log sampling for high-volume endpoints (log 1 in 100 for routine requests, 100% for errors) - Compress logs before storage - Use log retention policies (7 days hot, 30 days warm, archive after 90) - Store aggregated statistics rather than every single prediction But start with logging everything. Optimize later when you know what you actually need. ## Observability Enables Everything Else Good observability isn't just for debugging. It enables: **Model monitoring:** You can't detect drift without comparing current inputs to historical inputs. **A/B testing:** You can't measure model improvements without detailed prediction logs. **Incident response:** You can't fix what you can't see. **Compliance:** You can't audit model decisions without prediction history. **Cost optimization:** You can't optimize what you don't measure. Observability is infrastructure. Like networking or storage, you build it once and everything else benefits. ## Start Tomorrow The principles here build on [Production AI Systems: What 30 Years of UNIX Taught Me](/ai-architecture/production-ai-unix-principles/) - observability is just one UNIX principle applied to ML. If your ML serving system has poor observability: **Day 1:** Add structured logging to every prediction. Log input hash, output hash, latency, model version, timestamp. **Day 2:** Add request IDs that span the entire request lifecycle. Now you can correlate logs across services. **Day 3:** Add input characteristic logging. Log sizes, types, statistical properties - not raw data. **Day 4:** Set up log aggregation (ELK, Splunk, CloudWatch Logs - doesn't matter which). Make logs searchable. **Day 5:** Create dashboards that matter: prediction volume over time, latency percentiles by input size, error rates by model version. This isn't ML-specific. It's just observability applied to ML systems. The same logging discipline that kept traditional services debuggable works for models too. ## Frequently Asked Questions ### What is the observability gap in ML systems? The observability gap is the disconnect between traditional infrastructure monitoring and the model-level behavioural metrics needed to diagnose ML system failures. Standard monitoring shows whether the system is running but cannot explain why predictions stopped being correct, why latency spiked, or why a model silently degraded. ### How do I start closing the observability gap in my ML system? Add structured logging to every prediction on day one: input hash, output hash, latency, model version, and timestamp. On day two, add request IDs spanning the entire lifecycle for cross-service correlation. These two steps provide the foundation for diagnosing the majority of production ML failures. ### Why can't traditional infrastructure monitoring diagnose ML failures? Traditional monitoring tracks CPU, memory, disk, and network — infrastructure health. ML failures are often behavioural: the model serves confidently wrong predictions, features drift silently, or input distributions shift in ways that cause degraded outputs. The infrastructure looks healthy while the model serves garbage. ### What are the trade-offs of comprehensive ML observability? Logging every prediction adds storage cost, latency overhead, and operational complexity. Sampling reduces cost but creates blind spots in low-frequency failure modes. The practical balance is full structured logging with retention tiers — hot storage for recent predictions, cold storage for historical analysis, and configurable sampling for high-throughput endpoints. ## The Unsexy Truth (Again) Production ML failures are debuggable. But only if you log what matters. The interesting failures aren't visible in CPU graphs or memory charts. They're visible in prediction logs, input characteristics, and model state transitions. Most ML teams discover this the hard way, after the third 3AM page for an issue they can't diagnose. Build observability first. Add ML second. Not the other way around. Then when production breaks at 3AM, you'll actually be able to figure out why. --- # Certifiable ML Ecosystem The certifiable-* projects form a complete deterministic ML pipeline: ``` certifiable-data → Data loading, normalization, Feistel shuffling ↓ certifiable-training → Fixed-point gradient descent, Merkle audit trails ↓ certifiable-quant → FP32→Q16.16 quantization with error certificates ↓ certifiable-deploy → Cryptographic model packaging and attestation ↓ certifiable-inference → Bit-identical inference across x86/ARM/RISC-V ↓ certifiable-monitor → Runtime drift detection, COE compliance ↓ certifiable-verify → Pipeline verification, hash-only and full replay Testing: certifiable-harness → End-to-end integration testing certifiable-bench → Performance benchmarking with bit-identity verification ``` All projects use: - Pure C99, no dynamic allocation - Q16.16 fixed-point arithmetic - Round-to-nearest-even (RNE) rounding - SHA-256 hash chains for auditability - Bit-identical results across platforms --- # Contact - Website: https://speytech.com/contact/ - GitHub: https://github.com/SpeyTech - LinkedIn: https://www.linkedin.com/in/william-murray-5180aa32b/ --- *Generated automatically from SpeyTech.com content*