Wavefront ControlIMPLEMENTATION ROADMAPmilk: M1-M3 (Seqlock SHM, milk_rt, FindGRIC)cacao: C1-C4 (Inner CMODES, Cascaded SL, MR DM, Per-Actuator Pre-Shaper)milk-mltools: ML1-ML2 (mlt-cmodes, Multi-Rate Audit)Phases A-E with Quantitative CI & Live GPU Gates

Phased C/CMake engineering plan (Phases A-E) across milk, cacao, milk-mltools, and cacao-work to deploy the 3-layer decoupled AO control architecture: lock-free ping-pong SHM & RT pacing in milk, decoupled inner Q-rotation + re-projected AR(48) notch + cascaded self-learning + hardware-dependent multi-rate DM pacing (f_DM) + per-actuator spatially-varying DM anti-vibration pre-shaping (KMODE=3/4 & hybrid roadmap) in cacao, and async milk-fpsexec-mlt-cmodes + multi-rate audits in milk-mltools.

Referenced Simulation Reports

No matching simulation reports staged locally yet.

Implementation Plan: Unified AO Real-Time Control Architecture (milk, cacao, milk-mltools)


1. End-to-End Target Runtime Architecture & SHM Contract

flowchart LR
    subgraph MILK["milk (Engine & Lock-Free Primitives)"]
        SEQLOCK["milk_shm_seqlock.h\nPing-Pong 2-Slice SHM"]
        RT["milk_rt.h / milk_rt.c\nAbs-Time Sleep & SemWait"]
        GRIC["FindGRIC.cmake +\nLAPACKE Plugin Wiring"]
    end

    subgraph MLT["milk-mltools (Async 0.2-5 s Solvers)"]
        CMODES_U["milk-fpsexec-mlt-cmodes\nNoise-Whitened Q + AR(48) ID"]
        WIND_U["milk-fpsexec-mlt-windlayers\nWind Velocity & Altitude"]
        SYSID_U["milk-fpsexec-mlt-sysid\n2WFS1DM OG / ZPO / Offload"]
        AUDIT_U["mlt-tlmsync + mltools.bash\nMulti-Rate & Null Audits"]
    end

    subgraph CACAO["cacao (Hard Real-Time Control Path)"]
        WFS["acquireWFSim\nDark Sub + NormFloor"]
        MFILT["modalfilter.c\nInner Q + 16-Mode AR(48)\nOuter Fixed-Basis PSOL"]
        EOF["mkEOFPF / applyEOFPF\nBlock-EOF + Zero-DC Vel"]
        SL["cacaopc-selflearn\nCascaded Global -> Clustered RLS"]
        PACER["mvalpacer (user f_DM)\nZero-Latency Centered Ramps"]
        DISP["mvalC2dm -> DMch2disp"]
        PRESH["dmpreshaper (2-8 kHz)\nModal (K0-2) & Per-Actuator\nSISO/Stencil-MIMO (K3-4)"]
    end

    WFS --> MFILT
    MFILT -->|"aolN_modevalOL (Fixed Basis)"| EOF
    EOF -->|"aolN_modevalPF_eof"| SL
    SL -->|"aolN_modevalPF"| MFILT
    EOF -->|"aolN_modevalPF_vel"| MFILT
    MFILT -->|"aolN_modevalOL_buff / WFS_buff"| CMODES_U
    CMODES_U -->|"Ping-Pong aolN_cmodes_Q + params"| MFILT
    MFILT -->|"aolN_modevalDM_traj [M x 2]"| PACER
    PACER -->|"aolN_modevalDM (f_DM)"| DISP
    DISP --> PRESH
    SEQLOCK -.-> CMODES_U
    SEQLOCK -.-> MFILT
    RT -.-> PACER
    RT -.-> PRESH
    GRIC -.-> SL

Current Baseline Inventory vs. Remaining Implementation Scope

Feature Area Already Implemented & Verified Remaining Production Scope (This Plan)
Multi-Rate DM Pacing (MRDM, user f_DM) AOloopControl_DM_mvalpacer.c (zero-latency j=0 wake), mkEOFPF/applyEOFPF zero-DC temporal-difference velocity (EOF/VEL), modalfilter.c exact exposure-averaged ramp PSOL, test_18_multirate_dm.py (3/3), 23-run live GPU AO3k (f_DM = 1 kHz) shootout Make DM rate strictly hardware-dependent & user-supplied (.dm_rate_hz / --mr-dm1-rate <hz>, fail fast if unset), derive K_sub = round(f_DM * T_WFS) dynamically across changing f_WFS, refactor onto milk_rt.h, add stall ramp-decay watchdog, formalize acquireWFSim dark-pedestal fallback, wire cacaoloop.bash
Cascaded Online Self-Learning (SELFLEARN) selflearn_core.{c,h}, AOloopControl_PredictiveControl_selflearn.c, libgric CMake integration, test_17_selflearn.py Enforce cascaded-on-EOF default (allow_standalone=OFF), standardize applyEOFPF -> selflearn -> modalfilter stream chain in cacaoloop & runner scripts, add modalwhite pure white-noise null gate
Inner Control-Mode Optimization (CMODES) Offline 7-regime + live basis-swap + RT CPU timing validation (47.5 nm bumpless swaps, +2.4 us @ 128 modes) New C implementation: atomic ping-pong SHM helper in milk, decoupled inner Q rotation + re-projected 16-mode AR(48) notch in cacao (modalfilter.c), async milk-fpsexec-mlt-cmodes solver in milk-mltools, new test_19_cmodes.py
DM Mechanical Anti-Vibration Pre-Shaper (PRESH) & Autotuner (MOPT) dmpreshaper, compdmpreshaper (deconv_exp=ON two-sided Toeplitz exposure deconvolution, energy_weight=ON, KMODE=0 modal MIMO, KMODE=1 modal SISO, KMODE=2 uniform SISO, KMODE=3 per-actuator SISO, KMODE=4 per-actuator spatially-varying (2R+1)×(2R+1) local-stencil MIMO, .fill_uncal), measdynresp, factordynrm, modalopt.c, modalwhite.c, test_10_dmpreshaper.py (3/3 HIL pass including 68-act interior+free-rim KMODE=3/4 at 2 & 4 kHz), 8 kHz AO3k GPU demo Add Work Package C3b (Hybrid Global-Modal KMODE=0 + Per-Actuator Residual KMODE=3/4 composition, parallel/sparse multi-poke full-DM zonal 3D RM calibration for N_act ≈ 3000+ in < 2 min, and 64×64 AO3k per-actuator HIL benchmark), harmonize dmpreshaper timing onto milk_rt.h, wire MOPT compatibility with rotated CMODES inner basis, add unified status row in cacao-modalstatsTUI-bin

2. Repository 1: milk (Engine, Lock-Free SHM & Real-Time Primitives)

milk stays strictly AO-agnostic and provides reusable low-level primitives consumed by both cacao and milk-mltools.

Work Package M1 · Lock-Free Ping-Pong Double-Buffered SHM Seqlock Helper

Work Package M2 · Shared High-Precision Real-Time Pacer Primitives

Work Package M3 · Relocatable libgric & LAPACKE Plugin Build Support


3. Repository 2: cacao (Real-Time Core Control, Inner Modes & Multi-Rate DM)

All hard real-time execution stays in cacao with a strict < 120 us CPU budget at 256 modes (< 24% of a 2 kHz frame).

Work Package C1 · Decoupled Inner Control-Mode Rotation & AR(48) Notch in modalfilter.c

  1. Atomic Ping-Pong Basis Swap (aolN_cmodes_Q + aolN_cmodes_params):
  1. Forward Projection (cblas_sgemv): e_rot = Q_wfs^T * (zpo - wfs_in) (0 .. M_rot - 1).
  2. Inner Rotated Leaky Integrator + 16-Mode AR(48) Telescope-Vibration Notch:
  1. Back-Projection to Fixed Outer Basis (cblas_sgemv): mvalDMc[0 .. M_rot - 1] = Q_dm * (u_rot + dn).
  2. Outer Fixed-Basis PSOL & Predictive Control Blend: Existing PSOL, EOF, and SELFLEARN paths run unchanged on mvaloutapply and blend via PFmixcoeff.
FPS Parameter / Stream Type / Dims Flags Default & Purpose
.cmodes.enable FPTYPE_ONOFF WRITERUN OFF — toggle inner Q-rotated modal filter live
.cmodes.notch_enable FPTYPE_ONOFF WRITERUN OFF — toggle 16-mode AR(48) telescope-vibration notch
.cmodes.nbmode FPTYPE_UINT32 init 128 (max 256) — dimension M_rot of inner rotated subspace
.cmodes.nbnotch FPTYPE_UINT32 WRITERUN 16 (max 32) — leading rotated modes receiving AR(48) notch
.cmodes.notch_order FPTYPE_UINT32 init 48 (max 64) — AR notch tap depth P_notch
.cmodes.max_notch FPTYPE_FLOAT32 WRITERUN 0.15 — per-mode hard clamp on notch correction [modal units]
aolN_cmodes_Q float32 [M_rot x 2*M_rot x 2] ping-pong Dual [Q_wfs; Q_dm] matrices (Q_wfs == Q_dm for orthogonal Q)
aolN_cmodes_params float32 [(2 + P_notch) x M_rot x 2] ping-pong Packed [g_rot, a_rot, w_notch[0..P-1]] synced with aolN_cmodes_Q
.out.cmodes_swaps, .out.cmodes_orth_err, .out.cmodes_notch_rms outputs DEFAULT_OUTPUT Live swap counter, orthogonality residual, and notch RMS telemetry

Work Package C2 · Cascaded Online Self-Learning Production Hardening

  1. Enforce Cascaded-Only Safe Default: Add .allow_standalone (ONOFF, default OFF). When OFF, cacaopc-selflearn requires a live .inbasePF (aolN_modevalPF_eof) from applyEOFPF before publishing non-zero corrections — structurally preventing the 18.35 nm standalone white-noise failure mode.
  2. Standardize Descriptive Parameter Names & Diagnostics: Expose clear FPS aliases/descriptions for Global Online Adaptive Filter (.enable_l0 / single-model RLS) and Clustered State-Dependent Self-Learning (.enable_l1 / libgric multi-cluster RLS), plus .out.noise_amp_ratio telemetry.
  3. Zero-Friction Stream Wiring (applyEOFPF -> selflearn -> modalfilter):
  1. SIMD / OpenMP Hot-Loop Tuning: Ensure sl_engine_step() stays <= 89 us @ 128 modes and <= 114 us @ 256 modes with -fno-finite-math-only preserved for NaN/Inf safety guards.

Work Package C3 · Hardware-Dependent Multi-Rate DM Pacing (f_DM) & Faint-Star Slow-WFS Finalization

  1. Mandatory User-Provided Hardware DM Update Rate (f_DM) — No Hardcoded 1 kHz:
  1. Dynamic K_sub Derivation from User f_DM & Live WFS Cadence:
  1. Unified Timing Backend: Replace duplicated CLOCK_MONOTONIC / semtimedwait helpers in mvalpacer.c and dmpreshaper.c with milk_rt.h (M2).
  2. Stall Watchdog & Ramp-Decay Failsafe in mvalpacer.c: If no new aolN_modevalDM_traj arrives within 2 * T_WFS, exponentially decay u_ramp -> 0 (holding safe u_mid rather than extrapolating linearly on a dropped WFS frame). Add .out.substep_jitter_us, .out.late_substeps, .out.wfs_dt_ms, .out.k_sub_eff, and .out.eff_dm_rate_hz.
  3. Faint-Star WFS Dark-Pedestal Safeguard in acquireWFSim.c: Add optional scalar fallback .WFSdarkadu (FLOAT32, default 0.0) subtracted when no aolN_wfsdark cube is loaded, and warn if WFSnormfloor > 0.05 while .out.fluxtotal falls into faint-star regime (< 5000 ADU).
  4. Strict Hardware Signal-Flow Enforcement: In cacaoloop.bash, enforce startup sequence mvalpacer (user f_DM) -> mvalC2dm -> DMch2disp -> dmpreshaper (f_presh >= f_DM) -> DM, setting mfilt.PF.mr_pacer_out = ON to guarantee single-writer ownership of aolN_modevalDM.

Work Package C3b · Per-Actuator Spatially-Varying DM Pre-Shaping (KMODE=3, 4) & Full-DM Calibration

  1. Sparse Spatially-Tiled / Hadamard Parallel 3D RM Calibration (measure_dyn_resp.c): Poking N_act ≈ 3,200 actuators one-by-one takes ~10–15 min; add a spatially tiled comb-poke mode (simultaneously poking actuators spaced by >= 2R + 4 pitches where cross-actuator wave overlap is negligible, or block-Hadamard encoding) to acquire full 64×64 per-actuator 3D RMs in < 90 s.
  2. Hybrid Global-Modal + Per-Actuator Local Residual Mode (KMODE = 5, planned): Combine a low-order global modal MIMO kernel (KMODE = 0, 16–32 long-range plate modes capturing cross-aperture reflections) with a per-actuator local-stencil residual (KMODE = 3/4) summed in a single unified look-ahead ring buffer so both global drum/rim standing waves and local actuator/edge defects are cancelled simultaneously with < 60 us RT budget at 4–8 kHz.
  3. AO3k 64×64 Per-Actuator Live GPU Benchmark: Add a 64×64 AO3k KMODE = 3 vs. KMODE = 4 vs. KMODE = 0 comparison (single interior + rim pokes, closed-loop Kolmogorov wavefronts, and RT CPU profiling at 4–8 kHz) to the dm_preshaper_demo study.

Work Package C4 · Whiteness Null Safety Gate, MOPT Interop & TUI Telemetry


4. Repository 3: milk-mltools (Async Statistical Solvers & Offline Audits)

Work Package ML1 · New Async FPS Unit: milk-fpsexec-mlt-cmodes

  1. Telemetry Ingestion: Wakes on aolN_modevalOL_buff (and optional aolN_modevalWFS_buff) double-buffer flips, updating an exponentially weighted modal signal covariance C_sig (tau_cov = 5–20 s, resettable on regime jump) and high-frequency [0.35, 0.48] f_s WFS noise covariance C_noise.
  2. Prior-Blended Noise-Whitened Eigendecomposition (LAPACKE_dsyevd):
  1. Sign & Permutation Continuity + Hysteresis Gate:
  1. Selective AR(48) Narrowband Telescope-Vibration Notch Solver:
  1. Atomic Publication: Write [Q_wfs; Q_dm] into aolN_cmodes_Q and [g_rot, a_rot, w_notch] into aolN_cmodes_params using milk_shm_pingpong_begin_write() / commit_write().

Work Package ML2 · Multi-Rate Telemetry Sync & Pure-MILK Orchestration Helpers


5. Phased Execution Roadmap & Quantitative Acceptance Gates (cacao-work)

flowchart LR
    PA["Phase A: milk\nPing-Pong Seqlock,\nmilk_rt, FindGRIC"] --> PB["Phase B: cacao\nMulti-Rate DM &\nFaint-Star Hardening"]
    PA --> PC["Phase C: cacao\nCascaded Self-Learning\n& White-Noise Gate"]
    PA --> PD["Phase D: cacao + mltools\nDecoupled Inner CMODES\n(Q + Re-Projected AR48)"]
    PB --> PE["Phase E: cacao-work\nFull 3-Layer Live GPU\nShootout, CI & Website"]
    PC --> PE
    PD --> PE
Phase Repos Key Deliverables Automated Verification & Go/No-Go Gate
Phase A · Engine Foundations milk milk_shm_seqlock.h, milk_rt.{h,c}, FindGRIC.cmake, LAPACKE plugin check New C/pytest engine tests: 0 torn reads over 10^6 concurrent swaps; < 5 us p99 sleep jitter at 1–4 kHz; clean relocatable ./scripts/build-all.sh
Phase B · Multi-Rate DM, Per-Actuator Pre-Shaper & Faint-Star Production cacao, cacao-work Mandatory user-provided .dm_rate_hz / --mr-dm1-rate <hz> (no hardcoded 1 kHz), dynamic K_sub = round(f_DM * T_WFS), milk_rt.h refactor, stall ramp-decay watchdog, acquireWFSim dark-pedestal fallback, cacaoloop.bash wiring; per-actuator KMODE=3/4 pre-shaper (done & HIL-verified) + sparse tiled 64×64 zonal 3D RM calibration & hybrid global+local KMODE=5 pytest tests/test_10_dmpreshaper.py (3/3 incl. KMODE=3/4 interior+rim & 4 kHz resampling) & pytest tests/test_18_multirate_dm.py (>= 7/7: missing-rate rejection, multi-rate sweeps at f_DM = 1/2/4 kHz, stall decay & live f_WFS rate switch); AO3k live GPU (f_DM = 1 kHz) m=10 250 Hz >= 80% H-Strehl (>= 86% 2-stage), 0 clips, 0.000 fr lag; m=6 -35% HF / -40% plate band; 64×64 KMODE=4 RT ingest <= 80 us
Phase C · Cascaded Self-Learning & Null Gate cacao, milk-mltools, cacao-work Enforce cascaded-on-EOF default (allow_standalone=OFF), applyEOFPF -> selflearn -> modalfilter wiring in cacaoloop & sim-ao3k-scexao.milk, modalwhite null monitor pytest tests/test_17_selflearn.py extended: 40 nm pure white-noise null <= 1.01x (<= 2.0 nm DM leak, Stein gates < 0.05); unmod PyWFS >= 30% WFE cut vs EOF; RT CPU <= 95 us @ 128 m / <= 125 us @ 256 m
Phase D · Decoupled Inner Control Modes (CMODES) cacao, milk-mltools, cacao-work Inner Q + re-projected AR(48) notch in modalfilter.c; async milk-fpsexec-mlt-cmodes; modalopt rotated-basis interop; mltools.bash helpers New pytest tests/test_19_cmodes.py: mid-run swap peak < 55 nm (bumpless vs > 250 nm unprojected); +30 nm narrowband vibs >= 12% WFE cut over EOF; outer modevalOL invariant < 1e-5; RT overhead <= 5 us @ 128 m (<= 12 us @ 256 m)
Phase E · Full-Stack Live GPU Integration & Website Promotion cacao, milk-mltools, cacao-work Full 2-stage live GPU shootout combining all 3 layers; modalstatsTUI stack bar; CLI flags in options_catalog.py; flip CMODES from planned to verified on website Full decoupled stack beats or ties every single-layer configuration across all regimes + faint-star m=10; test_05, test_10, test_17, test_18, test_19, and test_mltools_e2e.py all 100% green

6. Key Risks & Mitigations

Risk Failure Mode if Unmitigated Built-In Mitigation
Torn basis read during Q swap Corrupted Q produces transient modal blow-up Lock-free 2-slice ping-pong seqlock (M1) + orthogonality/finiteness check in modalfilter.c before swap
AR(48) ring-buffer mismatch after Q swap 286.8 nm residual spike on every basis update Mandatory in-place history re-projection H_new[k] = (Q_new^T Q_old) H_old[k] (47.5 nm bumpless)
Unanchored self-learning noise amplification 18.35 nm (1.10x) white-noise leakage .allow_standalone=OFF default enforcing cascade on Fixed Block-EOF + dual causal Stein gates + modalwhite CI null gate
Missing or hardware-mismatched DM rate f_DM Driving a slow DM too fast excites hardware saturation or plate resonances No silent 1 kHz default: .dm_rate_hz = 0 fails fast unless user explicitly supplies hardware f_DM; validates f_DM <= f_presh when dmpreshaper is active
Dropped WFS frame under multi-rate ramp Constant velocity extrapolates DM toward rail 2 * T_WFS stall watchdog in mvalpacer smoothly decaying u_ramp -> 0 while holding safe u_mid
Subaru 4-spider island petaling at low WFS rate > 1000 nm petal runaway at 100 Hz (0.6" seeing) Enforce >= 250 Hz Stage-1 faint-star floor in runner presets and pair with Stage-2 fast loop (2 kHz) when available
Branch & Commit Hygiene Tangled cross-repo diffs blocking upstream merge Keep milk (feat/bash-engine), cacao (feat/bash-engine), and milk-mltools (main) commits atomic per work package (M1–M3, C1–C4, ML1–ML2)

Reproducibility & GitHub Provenance

  cd /home/guyon/src/cacao-work && ./scripts/build-all.sh && source env.sh
  "${PYTHON_BIN}" -m pytest -v tests/test_05_ao_web_report.py tests/test_10_dmpreshaper.py \
      tests/test_17_selflearn.py tests/test_18_multirate_dm.py tests/test_19_cmodes.py