splicer 2.4.0

Plan and generate middleware splice operations for WebAssembly component composition graphs.
Documentation
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
//! Two-stage builder for the `splicer:builtin-config` provider:
//! validate YAML config at materialize time, emit a per-edge provider
//! wasm at chain-walk time with `_splicer_edge_id` baked in.

use anyhow::{Context, Result};
use std::collections::BTreeMap;
use std::path::Path;

use crate::builtins;
use crate::parse::config::Injection;

// `BUILTIN_CONFIG_*` consts generated from `wit/builtin-config/world.wit`.
include!(concat!(env!("OUT_DIR"), "/builtin_config_constants.rs"));

// Wire-format constants + codec shared with the provider template
// via `splicer-builtin-protocol::wire_format`.
use builtin_protocol::wire_format::{
    serialize_table, CAPACITY, LEN_PREFIX_BYTES, MAGIC_BYTES, MAGIC_LEN,
};

/// Provider template's `builtins/<dir>` name. Listed in
/// `builtins::INTERNAL_BUILTINS` so it can't be referenced from YAML.
pub(crate) const PROVIDER_BUILTIN_NAME: &str = "config-provider";

const MAX_PAYLOAD: usize = CAPACITY - MAGIC_LEN - LEN_PREFIX_BYTES;

/// Validate the YAML `config:` block against the builtin's manifest
/// and stash the resulting WAVE-encoded strings on
/// `injection.config_as_wave`. No wasm is written here — the provider
/// component is built per-edge in [`build_provider_for_edge`] once
/// the chain walk has produced an edge_id.
///
/// No-op when there's no materialized path yet or the builtin doesn't
/// import `splicer:builtin-config` (with the usual hard error when a
/// non-consumer has a non-empty `config:`).
pub fn validate_config_as_wave(injection: &mut Injection) -> Result<()> {
    if injection.config_as_wave.is_some() {
        return Ok(());
    }
    let Some(builtin_path) = injection.path.as_deref() else {
        return Ok(());
    };
    let bytes = std::fs::read(builtin_path)
        .with_context(|| format!("Failed to read materialized builtin '{}'", builtin_path))?;
    let scan = builtin_protocol::scan_substrate_component(&bytes).map_err(|e| {
        anyhow::anyhow!(
            "injection '{name}': failed to scan builtin bytes: {e}",
            name = injection.name,
        )
    })?;
    if !scan.imports_substrate {
        if !injection.builtin_config.is_empty() {
            let mut keys: Vec<&str> = injection
                .builtin_config
                .keys()
                .map(String::as_str)
                .collect();
            keys.sort();
            anyhow::bail!(
                "injection '{name}' set `config:` keys [{keys}], but the underlying \
                 component doesn't import `splicer:builtin-config/get` — splicer has \
                 nothing to seal the values into. Either drop the `config:` block, or \
                 inject a builtin that consumes the substrate.",
                name = injection.name,
                keys = keys.join(", "),
            );
        }
        return Ok(());
    }
    let wave = match injection.builtin.as_deref() {
        Some(builtin_name) => validate_against_manifest(injection, builtin_name, &scan.manifests)?,
        None => loose_encode_user_config(injection)?,
    };
    injection.config_as_wave = Some(wave);
    Ok(())
}

/// Per chain-walk match: clone the cached WAVE map, add the edge_id
/// (WAVE-quoted), build the provider wasm, and write it under
/// `<splits_dir>/builtins/<injection.name>-config.wasm`. The caller is
/// responsible for having uniquified `injection.name` per edge so
/// distinct edges don't clobber each other's provider files.
pub fn build_provider_for_edge(
    injection: &mut Injection,
    edge_id: &str,
    splits_dir: &Path,
) -> Result<()> {
    let Some(wave) = injection.config_as_wave.as_ref() else {
        return Ok(());
    };
    let mut values = wave.clone();
    let edge_id_wave =
        builtin_protocol::loose_scalar_to_wave(&toml::Value::String(edge_id.to_string()))
            .expect("string always encodes as WAVE");
    values.insert(crate::wac::EDGE_ID_CONFIG_KEY.to_string(), edge_id_wave);

    let provider_bytes = build_provider(&values).with_context(|| {
        format!(
            "Failed to build config provider for injection '{}'",
            injection.name
        )
    })?;
    let dir = splits_dir.join("builtins");
    std::fs::create_dir_all(&dir)
        .with_context(|| format!("Failed to create builtins dir: {}", dir.display()))?;
    let out = dir.join(format!("{}-config.wasm", injection.name));
    std::fs::write(&out, &provider_bytes)
        .with_context(|| format!("Failed to write config provider: {}", out.display()))?;
    let out_str = out
        .to_str()
        .ok_or_else(|| {
            anyhow::anyhow!(
                "config provider path contains non-UTF-8 bytes: {}",
                out.display()
            )
        })?
        .to_string();
    injection.config_provider_path = Some(out_str);
    Ok(())
}

/// Strict validation for shipped builtins: the bytes must carry a
/// manifest section named for `expected` (caught OCI misrouting), and
/// every `config:` key must type-check against that manifest. The
/// pre-manifest leniency stays in place when the user set no config.
fn validate_against_manifest(
    injection: &Injection,
    expected: &str,
    all: &[(String, builtin_protocol::Manifest)],
) -> Result<BTreeMap<String, String>> {
    let manifest = match all.iter().find(|(n, _)| n == expected) {
        Some((_, m)) => m.clone(),
        None if all.is_empty() => {
            // Pre-manifests builtin: lenient only when no config was set.
            if injection.builtin_config.is_empty() {
                return Ok(BTreeMap::new());
            }
            anyhow::bail!(
                "injection '{name}': shipped builtin '{expected}' is missing its \
                 embedded manifest, so splicer can't validate the `config:` keys \
                 you set. Rebuild against the current splicer-builtin-protocol crate.",
                name = injection.name,
            );
        }
        None => {
            // Manifest(s) present but none for the requested builtin —
            // OCI tag misrouting or build-tag mismatch.
            let names: Vec<&str> = all.iter().map(|(n, _)| n.as_str()).collect();
            anyhow::bail!(
                "injection '{name}': shipped builtin '{expected}' resolved to bytes \
                 carrying manifest(s) for [{}] — wrong OCI tag or build mismatch.",
                names.join(", "),
                name = injection.name,
            );
        }
    };

    let mut wave: BTreeMap<String, String> = BTreeMap::new();
    let mut unknown: Vec<&str> = Vec::new();
    let mut bad: Vec<String> = Vec::new();
    for (key, value) in &injection.builtin_config {
        match manifest.validate_value(key, value) {
            Ok(Some(canonical)) => {
                wave.insert(key.clone(), canonical);
            }
            Ok(None) => unknown.push(key.as_str()),
            Err(msg) => bad.push(msg),
        }
    }
    if unknown.is_empty() && bad.is_empty() {
        return Ok(wave);
    }
    let known_keys: Vec<&str> = manifest.keys.iter().map(|k| k.name.as_str()).collect();
    let mut msg = format!(
        "injection '{name}' has invalid `config:` against its declared manifest. \
         Run `splicer builtin {expected}` to see accepted keys.",
        name = injection.name,
    );
    if !unknown.is_empty() {
        unknown.sort();
        msg.push_str(&format!(
            "\n  unknown keys: [{}]; known keys: [{}]",
            unknown.join(", "),
            known_keys.join(", "),
        ));
    }
    for b in &bad {
        msg.push_str("\n  ");
        msg.push_str(b);
    }
    anyhow::bail!(msg);
}

/// User-supplied middleware (no shipped-builtin name): no manifest
/// lookup at all, just WAVE-encode each scalar. Compounds without a
/// declared type are rejected by `loose_scalar_to_wave`.
fn loose_encode_user_config(injection: &Injection) -> Result<BTreeMap<String, String>> {
    let mut wave = BTreeMap::new();
    for (key, value) in &injection.builtin_config {
        let encoded = builtin_protocol::loose_scalar_to_wave(value).map_err(|e| {
            anyhow::anyhow!(
                "injection '{name}': config key '{key}' (no manifest available): {e}",
                name = injection.name,
            )
        })?;
        wave.insert(key.clone(), encoded);
    }
    Ok(wave)
}

/// Thin test wrapper around [`builtin_protocol::scan_substrate_component`].
/// Production code path uses `scan_substrate_component` directly so it
/// gets the manifest sections in the same wasmparser pass.
#[cfg(test)]
fn imports_substrate(bytes: &[u8]) -> bool {
    builtin_protocol::scan_substrate_component(bytes)
        .map(|s| s.imports_substrate)
        .unwrap_or(false)
}

/// Build a patched provider component with `values` baked in.
/// Returns wasm bytes ready to wire as `splicer:builtin-config/get@0.1.0`.
///
/// Fails on: unresolvable template (no override/cache/network),
/// missing-or-duplicate magic in the template (build mismatch), or
/// serialized table over the reserved capacity.
pub fn build_provider(values: &BTreeMap<String, String>) -> Result<Vec<u8>> {
    let mut bytes = builtins::load_resolved_bytes(PROVIDER_BUILTIN_NAME)
        .context("Failed to load config-provider template bytes")?;
    patch_in_place(&mut bytes, values)?;
    Ok(bytes)
}

/// Locate `MAGIC_BYTES` in `bytes` and overwrite the bytes that
/// follow with the serialized KV table.
fn patch_in_place(bytes: &mut [u8], values: &BTreeMap<String, String>) -> Result<()> {
    let payload = serialize_table(values);
    if payload.len() > MAX_PAYLOAD {
        anyhow::bail!(
            "config-provider payload of {} bytes exceeds reserved capacity of {} bytes \
             (template `CAPACITY` minus magic + length header). Either trim the config or \
             rebuild the provider with a larger `CAPACITY`.",
            payload.len(),
            MAX_PAYLOAD,
        );
    }
    let offset = find_unique_magic(bytes)?;
    // [magic][u32 LE payload_len][payload bytes][unchanged padding]
    let len_off = offset + MAGIC_LEN;
    let payload_off = len_off + LEN_PREFIX_BYTES;
    let payload_end = payload_off + payload.len();
    bytes[len_off..len_off + LEN_PREFIX_BYTES]
        .copy_from_slice(&(payload.len() as u32).to_le_bytes());
    bytes[payload_off..payload_end].copy_from_slice(&payload);
    Ok(())
}

/// Byte offset of the single occurrence of `MAGIC_BYTES`. Both zero
/// and >1 matches indicate a stale or miscompiled template.
fn find_unique_magic(bytes: &[u8]) -> Result<usize> {
    let mut found: Option<usize> = None;
    let mut i = 0;
    while i + MAGIC_LEN <= bytes.len() {
        if bytes[i..i + MAGIC_LEN] == MAGIC_BYTES {
            if found.is_some() {
                anyhow::bail!(
                    "config-provider template has multiple `MAGIC_BYTES` matches. The byte-scan \
                     patcher assumes exactly one. Check the template build."
                );
            }
            found = Some(i);
            i += MAGIC_LEN;
        } else {
            i += 1;
        }
    }
    found.ok_or_else(|| {
        anyhow::anyhow!(
            "config-provider template is missing the magic sentinel. The template was \
             either built against an out-of-date `MAGIC_BYTES`, or the compiler elided \
             the KV buffer. Rebuild builtins/config-provider with the in-tree sources."
        )
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::parse::config::Injection;
    use builtin_protocol::wire_format::deserialize_table;

    /// Test edge_id used by the `ensure_provider_for` helper. Pre-edge_id
    /// tests just want to know "did we validate + emit a provider"; this
    /// constant lets each test ignore the splicer-reserved key when
    /// asserting against the parsed payload.
    const TEST_EDGE_ID: &str = "test:iface@0.1.0::caller->provider";

    /// Test shim that runs the pre-edge_id flow end-to-end: validate
    /// config, then emit a per-edge provider with a fixed test edge_id.
    /// Tests written against the old `ensure_provider_for` keep their
    /// shape; new edge_id-specific behavior gets its own dedicated tests.
    fn ensure_provider_for(injection: &mut Injection, splits_dir: &Path) -> Result<()> {
        validate_config_as_wave(injection)?;
        build_provider_for_edge(injection, TEST_EDGE_ID, splits_dir)
    }

    fn make_blob(payload: &[u8]) -> Vec<u8> {
        // Mimics the template's static layout: random prefix, magic,
        // length header, padding to CAPACITY, random suffix. The
        // prefix + suffix make sure the byte-scan ignores everything
        // outside the magic-anchored window.
        let prefix = b"PREFIX_BYTES_BEFORE_MAGIC".to_vec();
        let suffix = b"SUFFIX_BYTES_AFTER_TEMPLATE".to_vec();
        let mut buf = Vec::with_capacity(prefix.len() + CAPACITY + suffix.len());
        buf.extend_from_slice(&prefix);
        buf.extend_from_slice(&MAGIC_BYTES);
        buf.extend_from_slice(&(payload.len() as u32).to_le_bytes());
        buf.extend_from_slice(payload);
        // Pad to CAPACITY total (relative to MAGIC start).
        let written = MAGIC_LEN + LEN_PREFIX_BYTES + payload.len();
        buf.extend(std::iter::repeat_n(0xAA, CAPACITY - written));
        buf.extend_from_slice(&suffix);
        buf
    }

    /// Round-trip via the same `deserialize_table` the provider runtime
    /// uses — wire-format drift surfaces here, not just in the live
    /// builtin.
    fn parse_back(bytes: &[u8]) -> std::collections::HashMap<String, String> {
        let off = find_unique_magic(bytes).expect("magic present");
        let body = &bytes[off + MAGIC_LEN..];
        let payload_len = u32::from_le_bytes(body[..LEN_PREFIX_BYTES].try_into().unwrap()) as usize;
        let payload = &body[LEN_PREFIX_BYTES..LEN_PREFIX_BYTES + payload_len];
        deserialize_table(payload)
    }

    #[test]
    fn round_trip_empty() {
        let mut blob = make_blob(&[]);
        patch_in_place(&mut blob, &BTreeMap::new()).expect("patch");
        let parsed = parse_back(&blob);
        assert!(parsed.is_empty());
    }

    #[test]
    fn round_trip_multi_key() {
        let mut blob = make_blob(&[]);
        let mut values = BTreeMap::new();
        values.insert("buffer".to_string(), "100".to_string());
        values.insert("flush_after_seconds".to_string(), "10.0".to_string());
        values.insert("note".to_string(), "value with spaces and 🎉".to_string());
        patch_in_place(&mut blob, &values).expect("patch");
        let parsed = parse_back(&blob);
        assert_eq!(parsed.len(), values.len());
        for (k, v) in &values {
            assert_eq!(parsed.get(k), Some(v));
        }
    }

    #[test]
    fn missing_key_after_patch_yields_nothing() {
        let mut blob = make_blob(&[]);
        let mut values = BTreeMap::new();
        values.insert("buffer".to_string(), "100".to_string());
        patch_in_place(&mut blob, &values).expect("patch");
        let parsed = parse_back(&blob);
        assert!(!parsed.contains_key("not-set"));
    }

    #[test]
    fn patch_preserves_outside_window() {
        let mut blob = make_blob(&[]);
        let original = blob.clone();
        let mut values = BTreeMap::new();
        values.insert("k".to_string(), "v".to_string());
        patch_in_place(&mut blob, &values).expect("patch");

        // Bytes before MAGIC and after MAGIC + CAPACITY must be unchanged.
        let magic_off = find_unique_magic(&blob).expect("magic");
        let template_end = magic_off + CAPACITY;
        assert_eq!(&blob[..magic_off], &original[..magic_off]);
        assert_eq!(&blob[template_end..], &original[template_end..]);
    }

    #[test]
    fn overflow_rejects_cleanly() {
        let mut blob = make_blob(&[]);
        let mut values = BTreeMap::new();
        values.insert("k".to_string(), "a".repeat(MAX_PAYLOAD));
        let err = patch_in_place(&mut blob, &values).unwrap_err();
        let msg = format!("{err:#}");
        assert!(msg.contains("exceeds reserved capacity"), "{msg}");
    }

    #[test]
    fn missing_magic_surfaces_clear_error() {
        let bytes = vec![0u8; 1024];
        let err = find_unique_magic(&bytes).unwrap_err();
        let msg = format!("{err:#}");
        assert!(msg.contains("missing the magic sentinel"), "{msg}");
    }

    #[test]
    fn duplicate_magic_surfaces_clear_error() {
        let mut bytes = Vec::new();
        bytes.extend_from_slice(&MAGIC_BYTES);
        bytes.extend_from_slice(&[0u8; 64]);
        bytes.extend_from_slice(&MAGIC_BYTES);
        let err = find_unique_magic(&bytes).unwrap_err();
        let msg = format!("{err:#}");
        assert!(msg.contains("multiple `MAGIC_BYTES` matches"), "{msg}");
    }

    /// Regression: load the actual built template and confirm
    /// `MAGIC_BYTES` appears exactly once. An earlier template had a
    /// separate `const MAGIC` referenced at runtime, which rustc/lld
    /// lowered to a second addressable copy in the data section. Run
    /// with `cargo test -- --ignored` (or
    /// `SPLICER_BUILTINS_DIR=assets/builtins` invoking by name).
    #[test]
    #[ignore = "needs built/cached/registry-resolvable config-provider template"]
    fn built_provider_has_unique_magic() {
        build_provider(&BTreeMap::new())
            .expect("template must resolve and have exactly one MAGIC_BYTES match");
    }

    /// Smoke: a real shipped builtin (`hello-tier1`) trips
    /// `imports_substrate` and `ensure_provider_for` writes a working
    /// patched provider for it.
    #[test]
    #[ignore = "needs built/cached/registry-resolvable hello-tier1 + config-provider"]
    fn hello_tier1_smoke() {
        let hello_bytes =
            crate::builtins::load_resolved_bytes("hello-tier1").expect("hello-tier1 must resolve");
        assert!(imports_substrate(&hello_bytes));

        let splits = tempfile::tempdir().unwrap();
        let builtin_dir = splits.path().join("builtins");
        std::fs::create_dir_all(&builtin_dir).unwrap();
        let hello_path = builtin_dir.join("hello-tier1.wasm");
        std::fs::write(&hello_path, &hello_bytes).unwrap();

        let mut inj = Injection::from_path("hello-tier1", hello_path.to_str().unwrap());
        inj.builtin_config.insert(
            "greeting".to_string(),
            toml::Value::String("wired-up-end-to-end".to_string()),
        );

        ensure_provider_for(&mut inj, splits.path()).expect("ensure_provider_for");
        let provider = inj.config_provider_path.as_deref().expect("provider path");
        let patched = std::fs::read(provider).expect("provider file");
        let parsed = parse_back(&patched);
        // Substrate now carries WAVE-text, so the stored value is the
        // quoted form. The builtin's codegen'd accessor strips the
        // quotes via `wasm_wave::from_str` at runtime.
        assert_eq!(
            parsed.get("greeting").map(String::as_str),
            Some("\"wired-up-end-to-end\"")
        );
    }

    // ── imports_substrate / ensure_provider_for ─────────────────────

    const CONSUMER_WAT: &str = r#"(component
        (import "splicer:builtin-config/get@0.1.0" (instance
            (export "get" (func (param "key" string) (result (option string))))
        ))
    )"#;

    const NON_CONSUMER_WAT: &str = r#"(component
        (import "wasi:http/handler@0.3.0" (instance
            (export "handle" (func (param "req" u32) (result u32)))
        ))
    )"#;

    #[test]
    fn imports_substrate_detects_consumer() {
        let bytes = wat::parse_str(CONSUMER_WAT).expect("wat");
        assert!(imports_substrate(&bytes));
    }

    #[test]
    fn imports_substrate_rejects_non_consumer() {
        let bytes = wat::parse_str(NON_CONSUMER_WAT).expect("wat");
        assert!(!imports_substrate(&bytes));
    }

    #[test]
    fn imports_substrate_tolerates_garbage() {
        // Decode failure must not panic out of catch_unwind.
        assert!(!imports_substrate(b"not a wasm component"));
    }

    /// End-to-end via a synthetic template blob — magic-anchored window
    /// gets patched, decodes back to the input values.
    #[test]
    fn ensure_provider_for_writes_patched_component() {
        let mut template = Vec::new();
        template.extend_from_slice(b"\0asm\x01\x00\x00\x00fake-prefix-");
        template.extend_from_slice(&MAGIC_BYTES);
        template.extend_from_slice(&0u32.to_le_bytes());
        template.extend(std::iter::repeat_n(
            0xAA,
            CAPACITY - MAGIC_LEN - LEN_PREFIX_BYTES,
        ));
        template.extend_from_slice(b"-fake-suffix");

        let consumer_bytes = wat::parse_str(CONSUMER_WAT).expect("wat");
        let splits = tempfile::tempdir().unwrap();
        let builtin_dir = splits.path().join("builtins");
        std::fs::create_dir_all(&builtin_dir).unwrap();
        let builtin_path = builtin_dir.join("fake-consumer.wasm");
        std::fs::write(&builtin_path, &consumer_bytes).unwrap();

        // `with_fake_builtins` only plants magic-bytes fixtures; this
        // test needs the richer template, so override the env directly.
        let override_dir = tempfile::tempdir().unwrap();
        std::fs::write(override_dir.path().join("config-provider.wasm"), &template).unwrap();
        let _guard = EnvGuard::set("SPLICER_BUILTINS_DIR", override_dir.path());

        let mut inj = Injection::from_path("metrics", builtin_path.to_str().unwrap());
        inj.builtin_config
            .insert("buffer".into(), toml::Value::Integer(100));
        inj.builtin_config
            .insert("flush_after_seconds".into(), toml::Value::Float(10.0));

        ensure_provider_for(&mut inj, splits.path()).expect("ensure");

        let path = inj
            .config_provider_path
            .as_deref()
            .expect("provider path stamped");
        let patched = std::fs::read(path).expect("provider written");
        let parsed = parse_back(&patched);
        // No manifest in the synthetic wat → lenient loose-encoding
        // produces canonical WAVE text for the scalars.
        assert_eq!(parsed.get("buffer").map(String::as_str), Some("100"));
        assert_eq!(
            parsed.get("flush_after_seconds").map(String::as_str),
            Some("10.0")
        );
    }

    /// `build_provider_for_edge` stamps `_splicer_edge_id` into the
    /// patched provider as WAVE-quoted text. Distinct edge_ids produce
    /// distinct provider wasms — the per-edge file naming follows
    /// `<injection.name>-config.wasm`, so callers in wac.rs uniquify
    /// `injection.name` per edge before invoking this.
    #[test]
    fn build_provider_for_edge_stamps_edge_id() {
        let mut template = Vec::new();
        template.extend_from_slice(b"\0asm\x01\x00\x00\x00fake-prefix-");
        template.extend_from_slice(&MAGIC_BYTES);
        template.extend_from_slice(&0u32.to_le_bytes());
        template.extend(std::iter::repeat_n(
            0xAA,
            CAPACITY - MAGIC_LEN - LEN_PREFIX_BYTES,
        ));

        let consumer_bytes = wat::parse_str(CONSUMER_WAT).expect("wat");
        let splits = tempfile::tempdir().unwrap();
        let builtin_dir = splits.path().join("builtins");
        std::fs::create_dir_all(&builtin_dir).unwrap();
        let builtin_path = builtin_dir.join("recorder.wasm");
        std::fs::write(&builtin_path, &consumer_bytes).unwrap();

        let override_dir = tempfile::tempdir().unwrap();
        std::fs::write(override_dir.path().join("config-provider.wasm"), &template).unwrap();
        let _guard = EnvGuard::set("SPLICER_BUILTINS_DIR", override_dir.path());

        let mut inj_a = Injection::from_path("recorder-a", builtin_path.to_str().unwrap());
        validate_config_as_wave(&mut inj_a).expect("validate");
        build_provider_for_edge(&mut inj_a, "ns:pkg/iface@1.0.0::A->B", splits.path())
            .expect("build A");

        let mut inj_b = Injection::from_path("recorder-b", builtin_path.to_str().unwrap());
        validate_config_as_wave(&mut inj_b).expect("validate");
        build_provider_for_edge(&mut inj_b, "ns:pkg/iface@1.0.0::C->B", splits.path())
            .expect("build B");

        let path_a = inj_a.config_provider_path.as_deref().expect("path a");
        let path_b = inj_b.config_provider_path.as_deref().expect("path b");
        assert_ne!(path_a, path_b, "per-edge providers land at distinct paths");

        let parsed_a = parse_back(&std::fs::read(path_a).unwrap());
        let parsed_b = parse_back(&std::fs::read(path_b).unwrap());
        assert_eq!(
            parsed_a
                .get(crate::wac::EDGE_ID_CONFIG_KEY)
                .map(String::as_str),
            Some("\"ns:pkg/iface@1.0.0::A->B\""),
            "WAVE-quoted edge_id baked into provider A",
        );
        assert_eq!(
            parsed_b
                .get(crate::wac::EDGE_ID_CONFIG_KEY)
                .map(String::as_str),
            Some("\"ns:pkg/iface@1.0.0::C->B\""),
            "WAVE-quoted edge_id baked into provider B",
        );
    }

    /// Empty `inj.builtin_config` against a substrate consumer still
    /// writes a provider (with `count = 0`); the user's `builtin: <name>`
    /// without any `config:` path must keep working.
    #[test]
    fn ensure_provider_for_emits_provider_with_empty_config() {
        let mut template = Vec::new();
        template.extend_from_slice(b"\0asm\x01\x00\x00\x00fake-prefix-");
        template.extend_from_slice(&MAGIC_BYTES);
        template.extend_from_slice(&0u32.to_le_bytes());
        template.extend(std::iter::repeat_n(
            0xAA,
            CAPACITY - MAGIC_LEN - LEN_PREFIX_BYTES,
        ));

        let consumer_bytes = wat::parse_str(CONSUMER_WAT).expect("wat");
        let splits = tempfile::tempdir().unwrap();
        let builtin_dir = splits.path().join("builtins");
        std::fs::create_dir_all(&builtin_dir).unwrap();
        let builtin_path = builtin_dir.join("fake-consumer.wasm");
        std::fs::write(&builtin_path, &consumer_bytes).unwrap();

        let override_dir = tempfile::tempdir().unwrap();
        std::fs::write(override_dir.path().join("config-provider.wasm"), &template).unwrap();
        let _guard = EnvGuard::set("SPLICER_BUILTINS_DIR", override_dir.path());

        let mut inj = Injection::from_path("metrics", builtin_path.to_str().unwrap());
        assert!(inj.builtin_config.is_empty());

        ensure_provider_for(&mut inj, splits.path()).expect("ensure");

        let path = inj.config_provider_path.as_deref().expect("provider path");
        let patched = std::fs::read(path).expect("provider written");
        let parsed = parse_back(&patched);
        // Only the splicer-reserved edge_id key is present; nothing the
        // user set leaks in.
        assert_eq!(parsed.len(), 1);
        assert!(parsed.contains_key(crate::wac::EDGE_ID_CONFIG_KEY));
        assert!(!parsed.contains_key("buffer"));
    }

    /// A non-consumer builtin gets no provider — `inj.config_provider_path`
    /// stays `None` and no file is written.
    #[test]
    fn ensure_provider_for_skips_non_consumer() {
        let bytes = wat::parse_str(NON_CONSUMER_WAT).expect("wat");
        let splits = tempfile::tempdir().unwrap();
        let builtin_dir = splits.path().join("builtins");
        std::fs::create_dir_all(&builtin_dir).unwrap();
        let builtin_path = builtin_dir.join("hello.wasm");
        std::fs::write(&builtin_path, &bytes).unwrap();

        let mut inj = Injection::from_path("hello", builtin_path.to_str().unwrap());
        let _guard = EnvGuard::clear("SPLICER_BUILTINS_DIR");

        ensure_provider_for(&mut inj, splits.path()).expect("ensure");
        assert!(inj.config_provider_path.is_none());
    }

    /// Misconfig: a non-consumer builtin with non-empty `config:` must
    /// error so silent drops can't hide a typo.
    #[test]
    fn ensure_provider_for_rejects_config_on_non_consumer() {
        let bytes = wat::parse_str(NON_CONSUMER_WAT).expect("wat");
        let splits = tempfile::tempdir().unwrap();
        let builtin_dir = splits.path().join("builtins");
        std::fs::create_dir_all(&builtin_dir).unwrap();
        let builtin_path = builtin_dir.join("hello.wasm");
        std::fs::write(&builtin_path, &bytes).unwrap();

        let mut inj = Injection::from_path("hello", builtin_path.to_str().unwrap());
        inj.builtin_config
            .insert("buffer".to_string(), toml::Value::Integer(100));
        inj.builtin_config
            .insert("flush_after_seconds".to_string(), toml::Value::Float(10.0));
        let _guard = EnvGuard::clear("SPLICER_BUILTINS_DIR");

        let err = ensure_provider_for(&mut inj, splits.path()).unwrap_err();
        let msg = format!("{err:#}");
        assert!(msg.contains("'hello'"), "{msg}");
        // Keys are listed sorted for a deterministic error message.
        assert!(msg.contains("buffer, flush_after_seconds"), "{msg}");
        assert!(msg.contains("doesn't import"), "{msg}");
    }

    // ── manifest validation ─────────────────────────────────────────

    /// A substrate-importing component with the manifest baked in as
    /// a component-level custom section named for `builtin_name`.
    /// `wat` emits the section in-place so the resulting bytes are a
    /// single valid component (appending sections post-hoc trips
    /// `wit_component::decode`).
    fn consumer_bytes_with_manifest(builtin_name: &str, manifest_toml: &str) -> Vec<u8> {
        let escaped = escape_wat_string(manifest_toml);
        let wat = format!(
            r#"(component
                (import "splicer:builtin-config/get@0.1.0" (instance
                    (export "get" (func (param "key" string) (result (option string))))
                ))
                (@custom "{section}" "{escaped}")
            )"#,
            section = builtin_protocol::section_name_for(builtin_name),
        );
        wat::parse_str(&wat).expect("wat with embedded manifest section")
    }

    /// Escape a TOML payload for use inside a wat string literal.
    /// Wat string literals accept arbitrary bytes via `\xx` hex
    /// escapes, which sidesteps every other character's quoting rules.
    fn escape_wat_string(s: &str) -> String {
        let mut out = String::with_capacity(s.len() * 4);
        for b in s.as_bytes() {
            out.push_str(&format!("\\{b:02x}"));
        }
        out
    }

    fn write_provider_template_to(dir: &Path) {
        let mut template = Vec::new();
        template.extend_from_slice(b"\0asm\x01\x00\x00\x00fake-prefix-");
        template.extend_from_slice(&MAGIC_BYTES);
        template.extend_from_slice(&0u32.to_le_bytes());
        template.extend(std::iter::repeat_n(
            0xAA,
            CAPACITY - MAGIC_LEN - LEN_PREFIX_BYTES,
        ));
        std::fs::write(dir.join("config-provider.wasm"), &template).unwrap();
    }

    const SAMPLE_MANIFEST_TOML: &str = r#"
[builtin]
description = "test"
tier = 1

[[key]]
name = "buffer"
type = "u32"
default = 1
doc = "doc"

[[key]]
name = "greeting"
type = "string"
default = "hi"
doc = "doc"
"#;

    #[test]
    fn manifest_validation_rejects_unknown_key() {
        let consumer_bytes = consumer_bytes_with_manifest("metrics", SAMPLE_MANIFEST_TOML);
        let splits = tempfile::tempdir().unwrap();
        let builtin_dir = splits.path().join("builtins");
        std::fs::create_dir_all(&builtin_dir).unwrap();
        let builtin_path = builtin_dir.join("metrics.wasm");
        std::fs::write(&builtin_path, &consumer_bytes).unwrap();

        let override_dir = tempfile::tempdir().unwrap();
        write_provider_template_to(override_dir.path());
        let _guard = EnvGuard::set("SPLICER_BUILTINS_DIR", override_dir.path());

        let mut inj = Injection::from_builtin("metrics");
        inj.path = Some(builtin_path.to_str().unwrap().to_string());
        inj.builtin_config
            .insert("bufer".into(), toml::Value::Integer(100)); // typo

        let err = ensure_provider_for(&mut inj, splits.path()).unwrap_err();
        let msg = format!("{err:#}");
        assert!(msg.contains("unknown keys"), "{msg}");
        assert!(msg.contains("bufer"), "{msg}");
        assert!(msg.contains("buffer"), "{msg}");
    }

    #[test]
    fn manifest_validation_rejects_type_mismatch() {
        let consumer_bytes = consumer_bytes_with_manifest("metrics", SAMPLE_MANIFEST_TOML);
        let splits = tempfile::tempdir().unwrap();
        let builtin_dir = splits.path().join("builtins");
        std::fs::create_dir_all(&builtin_dir).unwrap();
        let builtin_path = builtin_dir.join("metrics.wasm");
        std::fs::write(&builtin_path, &consumer_bytes).unwrap();

        let override_dir = tempfile::tempdir().unwrap();
        write_provider_template_to(override_dir.path());
        let _guard = EnvGuard::set("SPLICER_BUILTINS_DIR", override_dir.path());

        let mut inj = Injection::from_builtin("metrics");
        inj.path = Some(builtin_path.to_str().unwrap().to_string());
        inj.builtin_config
            .insert("buffer".into(), toml::Value::String("ten".into())); // wrong YAML type

        let err = ensure_provider_for(&mut inj, splits.path()).unwrap_err();
        let msg = format!("{err:#}");
        assert!(msg.contains("type mismatch"), "{msg}");
        assert!(msg.contains("u32"), "{msg}");
    }

    #[test]
    fn manifest_validation_accepts_valid_keys() {
        let consumer_bytes = consumer_bytes_with_manifest("metrics", SAMPLE_MANIFEST_TOML);
        let splits = tempfile::tempdir().unwrap();
        let builtin_dir = splits.path().join("builtins");
        std::fs::create_dir_all(&builtin_dir).unwrap();
        let builtin_path = builtin_dir.join("metrics.wasm");
        std::fs::write(&builtin_path, &consumer_bytes).unwrap();

        let override_dir = tempfile::tempdir().unwrap();
        write_provider_template_to(override_dir.path());
        let _guard = EnvGuard::set("SPLICER_BUILTINS_DIR", override_dir.path());

        let mut inj = Injection::from_builtin("metrics");
        inj.path = Some(builtin_path.to_str().unwrap().to_string());
        inj.builtin_config
            .insert("buffer".into(), toml::Value::Integer(100));
        inj.builtin_config
            .insert("greeting".into(), toml::Value::String("hi there".into()));

        ensure_provider_for(&mut inj, splits.path()).expect("valid config passes");
        assert!(inj.config_provider_path.is_some());
    }

    #[test]
    fn manifest_validation_requires_manifest_for_shipped_builtin_with_config() {
        // Consumer wasm without a manifest blob attached.
        let consumer_bytes = wat::parse_str(CONSUMER_WAT).expect("wat");
        let splits = tempfile::tempdir().unwrap();
        let builtin_dir = splits.path().join("builtins");
        std::fs::create_dir_all(&builtin_dir).unwrap();
        let builtin_path = builtin_dir.join("legacy.wasm");
        std::fs::write(&builtin_path, &consumer_bytes).unwrap();

        let override_dir = tempfile::tempdir().unwrap();
        write_provider_template_to(override_dir.path());
        let _guard = EnvGuard::set("SPLICER_BUILTINS_DIR", override_dir.path());

        let mut inj = Injection::from_builtin("legacy");
        inj.path = Some(builtin_path.to_str().unwrap().to_string());
        inj.builtin_config
            .insert("anything".into(), toml::Value::Integer(1));

        let err = ensure_provider_for(&mut inj, splits.path()).unwrap_err();
        let msg = format!("{err:#}");
        assert!(msg.contains("missing its embedded manifest"), "{msg}");
    }

    #[test]
    fn manifest_validation_rejects_mismatched_builtin_name() {
        // The wasm carries a manifest section named for 'hello-tier1'
        // but the YAML references it as builtin 'metrics' — that's an
        // OCI misrouting (or build-tag mismatch) and should fail loud,
        // not silently apply the wrong manifest.
        let consumer_bytes = consumer_bytes_with_manifest("hello-tier1", SAMPLE_MANIFEST_TOML);
        let splits = tempfile::tempdir().unwrap();
        let builtin_dir = splits.path().join("builtins");
        std::fs::create_dir_all(&builtin_dir).unwrap();
        let builtin_path = builtin_dir.join("metrics.wasm");
        std::fs::write(&builtin_path, &consumer_bytes).unwrap();

        let override_dir = tempfile::tempdir().unwrap();
        write_provider_template_to(override_dir.path());
        let _guard = EnvGuard::set("SPLICER_BUILTINS_DIR", override_dir.path());

        let mut inj = Injection::from_builtin("metrics");
        inj.path = Some(builtin_path.to_str().unwrap().to_string());
        inj.builtin_config
            .insert("buffer".into(), toml::Value::Integer(100));

        let err = ensure_provider_for(&mut inj, splits.path()).unwrap_err();
        let msg = format!("{err:#}");
        assert!(msg.contains("wrong OCI tag or build mismatch"), "{msg}");
        assert!(msg.contains("hello-tier1"), "{msg}");
    }

    /// Same misrouting as above but with an empty `config:` block.
    /// Pre-fix, the empty-config branch silently let this through; now
    /// the manifest-name mismatch fails loudly regardless of config.
    #[test]
    fn manifest_validation_rejects_mismatched_builtin_name_even_without_config() {
        let consumer_bytes = consumer_bytes_with_manifest("hello-tier1", SAMPLE_MANIFEST_TOML);
        let splits = tempfile::tempdir().unwrap();
        let builtin_dir = splits.path().join("builtins");
        std::fs::create_dir_all(&builtin_dir).unwrap();
        let builtin_path = builtin_dir.join("metrics.wasm");
        std::fs::write(&builtin_path, &consumer_bytes).unwrap();

        let override_dir = tempfile::tempdir().unwrap();
        write_provider_template_to(override_dir.path());
        let _guard = EnvGuard::set("SPLICER_BUILTINS_DIR", override_dir.path());

        let mut inj = Injection::from_builtin("metrics");
        inj.path = Some(builtin_path.to_str().unwrap().to_string());
        assert!(inj.builtin_config.is_empty());

        let err = ensure_provider_for(&mut inj, splits.path()).unwrap_err();
        let msg = format!("{err:#}");
        assert!(msg.contains("wrong OCI tag or build mismatch"), "{msg}");
    }

    #[test]
    fn manifest_validation_lenient_for_user_middleware() {
        // No manifest blob, but it's a user-supplied substrate consumer
        // (no `injection.builtin` set), so we let it through with the
        // old silent-fallback behavior rather than forcing third-party
        // middleware authors to ship a manifest.
        let consumer_bytes = wat::parse_str(CONSUMER_WAT).expect("wat");
        let splits = tempfile::tempdir().unwrap();
        let builtin_dir = splits.path().join("builtins");
        std::fs::create_dir_all(&builtin_dir).unwrap();
        let builtin_path = builtin_dir.join("user-mw.wasm");
        std::fs::write(&builtin_path, &consumer_bytes).unwrap();

        let override_dir = tempfile::tempdir().unwrap();
        write_provider_template_to(override_dir.path());
        let _guard = EnvGuard::set("SPLICER_BUILTINS_DIR", override_dir.path());

        let mut inj = Injection::from_path("user-mw", builtin_path.to_str().unwrap());
        inj.builtin_config
            .insert("anything".into(), toml::Value::Integer(1));

        ensure_provider_for(&mut inj, splits.path()).expect("user mw without manifest passes");
        assert!(inj.config_provider_path.is_some());
    }

    /// Lock + restore an env var on drop so parallel tests can't
    /// stomp each other. Used when `with_fake_builtins`'s magic-bytes
    /// fixture isn't expressive enough.
    struct EnvGuard {
        key: &'static str,
        prev: Option<std::ffi::OsString>,
        _lock: std::sync::MutexGuard<'static, ()>,
    }

    impl EnvGuard {
        fn lock() -> std::sync::MutexGuard<'static, ()> {
            use std::sync::Mutex;
            static LOCK: Mutex<()> = Mutex::new(());
            LOCK.lock().unwrap_or_else(|p| p.into_inner())
        }
        fn set(key: &'static str, val: &std::path::Path) -> Self {
            let lock = Self::lock();
            let prev = std::env::var_os(key);
            unsafe { std::env::set_var(key, val) };
            Self {
                key,
                prev,
                _lock: lock,
            }
        }
        fn clear(key: &'static str) -> Self {
            let lock = Self::lock();
            let prev = std::env::var_os(key);
            unsafe { std::env::remove_var(key) };
            Self {
                key,
                prev,
                _lock: lock,
            }
        }
    }

    impl Drop for EnvGuard {
        fn drop(&mut self) {
            unsafe {
                match self.prev.take() {
                    Some(v) => std::env::set_var(self.key, v),
                    None => std::env::remove_var(self.key),
                }
            }
        }
    }
}