aprender-core 0.72.6

Next-generation machine learning library in pure Rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
//! Build script for aprender (PMAT-250 + provable-contracts)
//!
//! Two responsibilities:
//!
//! 1. **Model family contracts** (PMAT-250): Reads YAML files from
//!    `../../contracts/model-families/` and generates Rust code with compiled-in
//!    family data. This catches YAML/Rust contract drift at build time.
//!
//! 2. **Provable-contracts bindings**: Reads `binding.yaml` from the sibling
//!    `provable-contracts` repo and sets `CONTRACT_*` env vars consumed by the
//!    `#[contract]` proc macro. Policy: AllImplemented (Step 6.7) — any
//!    `not_implemented` binding NOT in ALLOWED_GAPS fails the build.
//!
//! The env vars follow the pattern:
//!   `CONTRACT_<CONTRACT_STEM>_<EQUATION>=<status>`
//!
//! Example:
//!   `CONTRACT_SOFTMAX_KERNEL_V1_SOFTMAX=implemented`

use serde::Deserialize;
use std::fs;
use std::path::Path;

// ============================================================================
// Provable-Contracts Binding Types (serde-based)
// ============================================================================

/// Minimal subset of the binding.yaml schema — just enough to parse what we need.
#[derive(Deserialize)]
struct BindingFile {
    #[allow(dead_code)]
    version: String,
    #[allow(dead_code)]
    target_crate: String,
    bindings: Vec<Binding>,
}

#[derive(Deserialize)]
struct Binding {
    contract: String,
    equation: String,
    status: String,
    #[serde(default)]
    notes: Option<String>,
    #[serde(default)]
    function: Option<String>,
}

/// Convert a contract filename + equation into a canonical env var name.
///
/// "softmax-kernel-v1.yaml" + "softmax" -> "CONTRACT_SOFTMAX_KERNEL_V1_SOFTMAX"
fn binding_env_var_name(contract: &str, equation: &str) -> String {
    provable_contracts::build_helper::env_key(
        contract.trim_end_matches(".yaml").trim_end_matches(".yml"),
        equation,
    )
}

/// Contracts allowed to remain `not_implemented` without failing the build.
/// Each entry is `(contract_stem, equation)`. Any `not_implemented` binding
/// NOT in this list triggers a hard build failure (AllImplemented policy).
const ALLOWED_GAPS: &[(&str, &str)] = &[
    // SSM/Mamba kernel — no implementation yet (GH-278 tracks Gated Delta Net)
    ("ssm-kernel-v1", "ssm_discretize"),
    ("ssm-kernel-v1", "ssm_scan"),
    ("ssm-kernel-v1", "selective_gate"),
    // ONT-3a bindings gate (aprender#4502) measured these as not resolving to workspace code and marked
    // them not_implemented; they stay listed until the binding is re-pointed or implemented (aprender#4502).
    // Each was `implemented` on main only because nothing checked that its bound symbol exists; the entry
    // records a measured gap, it does not loosen a passing check. Reason per line:
    ("apr-cli-operations-v1", "inference_determinism"), // bound `generate` resolves to no workspace fn (PV-ONT-028)
    ("apr-data-pipeline-v1", "streaming_data_loader"), // `DataLoader::next_batch` absent in aprender (PV-ONT-028)
    ("apr-format-safety-v1", "magic_byte_validation"), // `detect_format` absent at the bound path (PV-ONT-028)
    ("apr-format-safety-v1", "header_integrity"), // `validate_header` absent at the bound path (PV-ONT-028)
    ("apr-gpu-backend-v1", "generation_temperature_zero"), // bound GPU `generate` resolves to no fn (PV-ONT-028)
    ("../encoder-forward-v1", "cls_pooling"), // `cls_embedding` absent in the workspace (PV-ONT-028)
    ("../format-parity-v1", "transpose_involution"), // `swap_axes` absent at the bound path (PV-ONT-028)
    ("../format-parity-v1", "element_count"), // `validate_element_count` absent at the bound path (PV-ONT-028)
    ("../bidirectional-attention-v1", "bidirectional_attention"), // `bidirectional_attention` fn absent (PV-ONT-028)
    ("linear-probe-classifier-v1", "linear_probe"), // FrozenProbeRun::fit not built yet (binding notes)
    ("setfit-apr-v1", "doc_bundle_bijection"),      // `deserialize` lands with setfit plan 04-05
    ("setfit-apr-v1", "selection_lock_lifecycle"), // `mint_test_token` lock workflow lands with 04-07/04-14
];

/// Returns true if the new status is dominated by what we already have.
fn is_status_dominated(existing: Option<&str>, new: &str) -> bool {
    match (existing, new) {
        (None, _) => false,                        // first time
        (Some("implemented"), _) => true,          // already best
        (Some("partial"), "implemented") => false, // upgrade
        (Some("partial"), _) => true,              // keep partial
        (Some("not_implemented"), "not_implemented") => true,
        (Some("not_implemented"), _) => false, // upgrade
        _ => false,
    }
}

/// De-duplicate bindings, keeping the best status for each (contract, equation).
/// Returns (env_var → status, env_var → (contract_stem, equation)).
fn dedup_bindings(
    bindings: &[Binding],
) -> (
    std::collections::HashMap<String, String>,
    std::collections::HashMap<String, (String, String)>,
) {
    let mut seen = std::collections::HashMap::<String, String>::new();
    let mut seen_raw = std::collections::HashMap::<String, (String, String)>::new();

    for binding in bindings {
        let var_name = binding_env_var_name(&binding.contract, &binding.equation);

        if is_status_dominated(seen.get(&var_name).map(|s| s.as_str()), &binding.status) {
            continue;
        }

        seen.insert(var_name.clone(), binding.status.clone());
        let contract_stem = binding
            .contract
            .trim_end_matches(".yaml")
            .trim_end_matches(".yml")
            .to_string();
        seen_raw.insert(var_name, (contract_stem, binding.equation.clone()));
    }

    (seen, seen_raw)
}

/// Check if a (contract_stem, equation) gap is in the ALLOWED_GAPS list.
fn is_gap_allowed(contract_stem: &str, equation: &str) -> bool {
    ALLOWED_GAPS
        .iter()
        .any(|(c, e)| *c == contract_stem && *e == equation)
}

/// Enforce AllImplemented policy: panic if any unallowed gaps exist.
fn enforce_all_implemented(unallowed_gaps: &[String]) {
    if unallowed_gaps.is_empty() {
        return;
    }
    for gap in unallowed_gaps {
        println!("cargo:warning=[contract] UNALLOWED GAP: {gap}");
    }
    panic!(
        "[contract] AllImplemented policy violation: {} binding(s) are \
         `not_implemented` but not in ALLOWED_GAPS:\n  {}\n\
         Fix: implement the binding in binding.yaml, or add to ALLOWED_GAPS \
         in build.rs with a tracking issue.",
        unallowed_gaps.len(),
        unallowed_gaps.join("\n  ")
    );
}

/// Read and parse binding.yaml. `None` (after a warning and
/// `CONTRACT_BINDING_SOURCE=none`) when it is absent, unreadable or not YAML.
fn load_bindings() -> Option<BindingFile> {
    let binding_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../../contracts/aprender/binding.yaml");

    // Always tell Cargo to re-run if the file appears or changes
    println!("cargo:rerun-if-changed={}", binding_path.display());

    if !binding_path.exists() {
        // Graceful fallback: CI/crates.io builds won't have the sibling repo.
        println!(
            "cargo:warning=provable-contracts binding.yaml not found at {}; \
             CONTRACT_* env vars will not be set (CI/crates.io build)",
            binding_path.display()
        );
        println!("cargo:rustc-env=CONTRACT_BINDING_SOURCE=none");
        return None;
    }

    let yaml_content = match std::fs::read_to_string(&binding_path) {
        Ok(s) => s,
        Err(e) => {
            println!(
                "cargo:warning=Failed to read binding.yaml: {e}; \
                 CONTRACT_* env vars will not be set"
            );
            println!("cargo:rustc-env=CONTRACT_BINDING_SOURCE=none");
            return None;
        }
    };

    match serde_saphyr::from_str_with_options(
        &yaml_content,
        serde_saphyr::options! { strict_booleans: true, merge_keys: serde_saphyr::MergeKeyPolicy::AsOrdinary, emit_comments: false, reject_non_finite_typeless_float: false },
    ) {
        Ok(b) => Some(b),
        Err(e) => {
            println!(
                "cargo:warning=Failed to parse binding.yaml: {e}; \
                 CONTRACT_* env vars will not be set"
            );
            println!("cargo:rustc-env=CONTRACT_BINDING_SOURCE=none");
            None
        }
    }
}

/// Read provable-contracts binding.yaml and set CONTRACT_* env vars.
///
/// Policy: AllImplemented (Step 6.7). Any `not_implemented` binding not in
/// `ALLOWED_GAPS` fails the build. This ensures all algorithm contracts
/// have working implementations before code compiles.
fn emit_provable_contract_bindings() {
    let Some(bindings) = load_bindings() else {
        return;
    };

    let (seen, seen_raw) = dedup_bindings(&bindings.bindings);

    let mut implemented = 0u32;
    let mut partial = 0u32;
    let mut not_implemented = 0u32;
    let mut unallowed_gaps: Vec<String> = Vec::new();

    let mut keys: Vec<_> = seen.keys().cloned().collect();
    keys.sort();

    for var_name in &keys {
        let status = &seen[var_name];
        println!("cargo:rustc-env={var_name}={status}");

        match status.as_str() {
            "implemented" => implemented += 1,
            "partial" => {
                partial += 1;
                let note = bindings
                    .bindings
                    .iter()
                    .find(|b| &binding_env_var_name(&b.contract, &b.equation) == var_name)
                    .and_then(|b| b.notes.as_deref())
                    .unwrap_or("");
                println!("cargo:warning=[contract] PARTIAL: {var_name} — {note}");
            }
            "not_implemented" => {
                not_implemented += 1;
                if let Some((ref stem, ref eq)) = seen_raw.get(var_name) {
                    if !is_gap_allowed(stem, eq) {
                        unallowed_gaps.push(format!("{var_name} ({stem}.yaml / {eq})"));
                    }
                }
            }
            other => {
                println!("cargo:warning=[contract] UNKNOWN STATUS '{other}': {var_name}");
            }
        }
    }

    enforce_all_implemented(&unallowed_gaps);

    let total = implemented + partial + not_implemented;
    println!(
        "cargo:warning=[contract] AllImplemented: {implemented}/{total} implemented, \
         {partial} partial, {not_implemented} allowed gaps"
    );

    warn_unbound_functions(&bindings);

    // Set metadata env vars for the proc macro
    println!("cargo:rustc-env=CONTRACT_BINDING_SOURCE=binding.yaml");
    println!(
        "cargo:rustc-env=CONTRACT_BINDING_VERSION={}",
        bindings.version
    );
    println!("cargo:rustc-env=CONTRACT_TOTAL={total}");
    println!("cargo:rustc-env=CONTRACT_IMPLEMENTED={implemented}");
    println!("cargo:rustc-env=CONTRACT_PARTIAL={partial}");
    println!("cargo:rustc-env=CONTRACT_GAPS={not_implemented}");
}

/// The lowercased name a `pub fn` / `pub async fn` / `pub(crate) fn` line declares.
fn pub_fn_name(line: &str) -> Option<String> {
    let t = line.trim();
    if !(t.starts_with("pub fn ")
        || t.starts_with("pub async fn ")
        || t.starts_with("pub(crate) fn "))
    {
        return None;
    }
    let part = t
        .trim_start_matches("pub async fn ")
        .trim_start_matches("pub(crate) fn ")
        .trim_start_matches("pub fn ");
    let name = part
        .split('(')
        .next()
        .unwrap_or("")
        .split('<')
        .next()
        .unwrap_or("")
        .trim()
        .to_lowercase();
    (!name.is_empty()).then_some(name)
}

/// Every public fn name under `dir` (recursive, skipping `target` and `.git`).
fn scan_rs(dir: &std::path::Path, found: &mut std::collections::HashSet<String>) {
    let Ok(entries) = std::fs::read_dir(dir) else {
        return;
    };
    for e in entries.flatten() {
        let p = e.path();
        if p.is_dir() {
            let n = p.file_name().and_then(|n| n.to_str()).unwrap_or("");
            if n != "target" && n != ".git" {
                scan_rs(&p, found);
            }
        } else if p.extension().and_then(|e| e.to_str()) == Some("rs") {
            if let Ok(c) = std::fs::read_to_string(&p) {
                found.extend(c.lines().filter_map(pub_fn_name));
            }
        }
    }
}

/// Layer 2: warn (soft) when an `implemented` binding names a function no source file defines.
fn warn_unbound_functions(bindings: &BindingFile) {
    let expected: std::collections::HashSet<String> = bindings
        .bindings
        .iter()
        .filter(|b| b.status == "implemented")
        .filter_map(|b| b.function.as_deref())
        .map(|func| func.rsplit("::").next().unwrap_or(func).to_lowercase())
        .collect();
    if expected.is_empty() {
        return;
    }
    let mut found: std::collections::HashSet<String> = std::collections::HashSet::new();
    scan_rs(std::path::Path::new("src"), &mut found);
    scan_rs(std::path::Path::new("crates"), &mut found);
    let missing = expected
        .iter()
        .filter(|n| !found.contains(n.as_str()))
        .count();
    if missing > 0 {
        println!("cargo:warning=[contract] L2: {missing} bound function(s) not found in source (soft warning)");
    }
}

fn main() {
    // ── Phase 1: Provable-contracts binding.yaml → CONTRACT_* env vars ──
    emit_provable_contract_bindings();

    // ── Phase 2: Model family contracts → generated Rust code ──
    let families_dir = if Path::new("contracts/model-families").exists() {
        Path::new("contracts/model-families").to_path_buf()
    } else {
        Path::new("../../contracts/model-families").to_path_buf()
    };

    // Tell Cargo to re-run if any YAML changes
    println!("cargo:rerun-if-changed=../../contracts/model-families");

    if !families_dir.exists() {
        // No contracts directory — generate empty registry
        let out_dir = std::env::var("OUT_DIR").expect("OUT_DIR not set");
        let out_path = Path::new(&out_dir).join("model_families_generated.rs");
        fs::write(
            &out_path,
            "// No ../../contracts/model-families/ directory found at build time\n\
             // Using empty generated registry (crates.io / clean-room build)\n\
             \n\
             /// Known model family names (generated at build time)\n\
             pub const KNOWN_FAMILIES: &[&str] = &[];\n\
             \n\
             /// Build empty default registry (no contracts available at build time)\n\
             pub fn build_default_registry() -> Vec<crate::format::model_family_loader::ModelFamilyConfig> {\n\
                 Vec::new()\n\
             }\n",
        )
        .expect("write generated code");
        return;
    }

    let mut families: Vec<FamilyData> = Vec::new();

    let entries = fs::read_dir(families_dir).expect("read ../../contracts/model-families");
    for entry in entries {
        let entry = entry.expect("dir entry");
        let path = entry.path();

        // Skip non-YAML and _-prefixed files
        if path.extension().is_none_or(|e| e != "yaml") {
            continue;
        }
        if path
            .file_name()
            .and_then(|n| n.to_str())
            .is_none_or(|s| s.starts_with('_'))
        {
            continue;
        }

        let content = fs::read_to_string(&path)
            .unwrap_or_else(|e| panic!("Failed to read {}: {e}", path.display()));

        let family = parse_family_yaml(&content, &path);
        families.push(family);
    }

    // Sort by family name for deterministic output
    families.sort_by(|a, b| a.family.cmp(&b.family));

    // Generate Rust source
    let generated = generate_rust(&families);

    let out_dir = std::env::var("OUT_DIR").expect("OUT_DIR not set");
    let out_path = Path::new(&out_dir).join("model_families_generated.rs");
    fs::write(&out_path, generated).expect("write generated code");
}

include!("build_parsing.rs");
include!("build_codegen.rs");