polydat 0.11.0

Polydat — a variates construction engine
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
// Copyright 2024-2026 Jonathan Shook
// SPDX-License-Identifier: Apache-2.0

//! Scope trees on all four engines (native_scope_trees.md §8).
//!
//! A host that runs workloads as a tree of scopes (params, a `set:`
//! scope, a phase, fibers, per-op children, iteration children) builds
//! it through the `Kernel` trait alone, on whichever engines it names,
//! and gets the same answers everywhere. Each test here is written in
//! the host's terms and runs every parent engine against every child
//! engine, so a tree mid-migration, part interpreter and part compiled,
//! is covered too. Where a shape leaves an extern with no value, pure
//! native refuses a pull that reads it rather than answer `None`, and
//! the test asserts that refusal.

use polydat::ast::Value;
use polydat::dsl::compile::compile_polydat_with;
use polydat::kernel::interp::{KernelLookup, Lookup};
use polydat::kernel::subcontext::{
    BodyFragment, Child, RootMarker, ScopeModule, SourceContext, SubcontextBuilder,
};
use polydat::kernel::{bind_under, propagate_inputs};
use polydat::{Engine, JitMode, Kernel, Provenance};

fn engines() -> Vec<Engine> {
    let mut all = vec![
        Engine::Interpreter(JitMode::Auto),
        Engine::Closures(Provenance::PushPull),
        Engine::Closures(Provenance::Raw),
    ];
    if cfg!(feature = "jit") {
        all.push(Engine::Native(Provenance::PushPull));
        all.push(Engine::Native(Provenance::Raw));
        all.push(Engine::PureNative(Provenance::PushPull));
        all.push(Engine::PureNative(Provenance::Raw));
    }
    all
}

fn compile(src: &str, engine: Engine) -> Box<dyn Kernel> {
    compile_polydat_with(src, engine).unwrap_or_else(|e| panic!("{engine}: {e}"))
}

/// A module of `source` built under `parent`.
fn module(parent: &dyn Kernel, label: &str, source: &str) -> ScopeModule<Child<RootMarker>> {
    let mut b = SubcontextBuilder::under(parent);
    b.context(SourceContext::new(label));
    b.body(BodyFragment::PolydatSource(source.to_string()));
    b.finalize().unwrap_or_else(|e| panic!("{label}: {e:?}"))
}

fn str_value(s: &str) -> Value {
    Value::Str(s.into())
}

/// Pulling `output` on a pure native kernel whose extern `unset` has no
/// value is refused with a panic naming the extern.
fn assert_refuses_unset(kernel: &mut dyn Kernel, output: &str, unset: &str, pair: &str) {
    let err = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| kernel.pull(output)))
        .expect_err("pure native refuses an unset extern");
    let message = err
        .downcast_ref::<String>()
        .cloned()
        .or_else(|| err.downcast_ref::<&str>().map(|s| s.to_string()))
        .unwrap_or_default();
    assert!(
        message.contains(&format!("extern '{unset}'")) && message.contains("pure native"),
        "{pair}: {message}"
    );
}

const ROOT: &str = "const mode := \"default\"\nconst size := \"small\"\nextern shard: u64 = 3\n";
const SET: &str = "extern size: str\nconst mode := \"mode_for_{size}\"\n";
const PHASE: &str = "input cycle: u64\nextern mode: str\nextern size: str\n\
                     extern shard: u64\nextern retries: u64 = 2\n\
                     label := \"{mode}/{size}/{shard}\"\ntries := u64_add(retries, cycle)\n";
const ITER: &str = "extern mode: str\nextern i: u64\nrow := \"{mode}-{i}\"\n";

/// params root → `set:` scope → phase → fork → iteration child, the
/// shape nmbrs builds, with a const in the `set:` scope that shadows a
/// parameter, a parameter carried by
/// `propagate_inputs`, a reset, and an iteration binding.
#[test]
fn a_scope_tree_answers_alike_on_every_engine_pair() {
    for parent_engine in engines() {
        for child_engine in engines() {
            let pair = format!("{parent_engine} → {child_engine}");
            let root = compile(ROOT, parent_engine);

            let set = module(root.as_ref(), "set", SET)
                .instantiate_under(root.as_ref(), child_engine, &[])
                .unwrap_or_else(|e| panic!("{pair}: {e}"));
            assert_eq!(
                KernelLookup::new(set.as_ref()).lookup("mode"),
                Some(str_value("mode_for_small")),
                "{pair}: the set scope's own const"
            );

            let mut phase = module(set.as_ref(), "phase", PHASE)
                .instantiate_under(set.as_ref(), child_engine, &[])
                .unwrap_or_else(|e| panic!("{pair}: {e}"));
            propagate_inputs(root.as_ref(), phase.as_mut())
                .unwrap_or_else(|e| panic!("{pair}: {e}"));
            phase.set_inputs(&[1]);
            assert_eq!(
                phase.pull("label"),
                str_value("mode_for_small/small/3"),
                "{pair}: the phase reads the shadowing const and the propagated parameter"
            );

            // A fork carries the state and the program.
            let mut fiber = phase.fork();
            assert_eq!(fiber.program_id(), phase.program_id(), "{pair}");
            assert_eq!(
                fiber.pull("label"),
                str_value("mode_for_small/small/3"),
                "{pair}"
            );

            // A reset puts externs back and leaves coordinates alone.
            let retries = fiber.input_index("retries").expect("declared");
            fiber
                .set_input_at(retries, Value::U64(9))
                .unwrap_or_else(|e| panic!("{pair}: {e}"));
            assert_eq!(
                fiber.pull("tries"),
                Value::U64(10),
                "{pair}: after the write"
            );
            fiber.reset_inputs();
            assert_eq!(fiber.input_value_at(retries), Some(Value::U64(2)), "{pair}");
            // The reset clears `mode`, `size`, and `shard`, which the
            // parents filled and which have no default. `tries` reads
            // none of them, so every engine serves it.
            assert_eq!(
                fiber.pull("tries"),
                Value::U64(3),
                "{pair}: after the reset"
            );
            if matches!(child_engine, Engine::PureNative(_)) {
                // `label` reads all three: pure native code cannot carry
                // the `None`, so a pull of `label` is refused, naming
                // the first unset one, until every one is set again.
                for (name, value) in [
                    ("mode", str_value("set")),
                    ("size", str_value("set")),
                    ("shard", Value::U64(0)),
                ] {
                    assert_refuses_unset(fiber.as_mut(), "label", name, &pair);
                    fiber
                        .set_input(name, value)
                        .unwrap_or_else(|e| panic!("{pair}: {e}"));
                }
                assert_eq!(
                    fiber.pull("label"),
                    str_value("set/set/0"),
                    "{pair}: once every extern is set again"
                );
            }
            assert_eq!(
                fiber.input_value_at(0),
                Some(Value::U64(1)),
                "{pair}: the coordinate"
            );

            // The fork's writes are its own.
            assert_eq!(phase.pull("tries"), Value::U64(3), "{pair}: the original");

            // An iteration child per tuple.
            let iter = module(phase.as_ref(), "iter", ITER);
            for i in 0..3u64 {
                let mut child = iter
                    .instantiate_under(phase.as_ref(), child_engine, &[("i".into(), Value::U64(i))])
                    .unwrap_or_else(|e| panic!("{pair}: {e}"));
                assert_eq!(
                    child.pull("row"),
                    str_value(&format!("mode_for_small-{i}")),
                    "{pair}: iteration {i}"
                );
            }
        }
    }
}

/// A plan of pre-resolved indices, sealed on a program's identity,
/// holds for every kernel bound from that program and every fork, and
/// a second compile of the same source is a different program.
#[test]
fn program_identity_seals_a_plan_across_binds_and_forks() {
    for engine in engines() {
        let parent = compile(ROOT, engine);
        let child_src = "extern shard: u64\nout := u64_add(shard, 1)\n";
        let program = compile(child_src, engine).into_program();
        let bound = bind_under(parent.as_ref(), program.clone(), &[]).expect("binds");
        assert_eq!(bound.program_id(), program.program_id(), "{engine}");
        assert_eq!(bound.fork().program_id(), program.program_id(), "{engine}");
        let again = compile(child_src, engine).into_program();
        assert_ne!(again.program_id(), program.program_id(), "{engine}");
    }
}

/// The analysis program a module holds and every engine's kernel of it
/// agree on input and output positions, so an index resolved on one is
/// valid on the other.
#[test]
fn a_module_s_program_and_its_kernels_agree_on_positions() {
    let root = compile(ROOT, Engine::Interpreter(JitMode::Auto));
    let phase = module(root.as_ref(), "phase", PHASE);
    let inputs: Vec<String> = phase.program().input_names();
    let outputs: Vec<String> = phase
        .program()
        .output_names()
        .into_iter()
        .map(String::from)
        .collect();
    for engine in engines() {
        let kernel = phase
            .instantiate_under(root.as_ref(), engine, &[])
            .unwrap_or_else(|e| panic!("{engine}: {e}"));
        assert_eq!(kernel.input_names(), inputs, "{engine}: inputs");
        assert_eq!(kernel.output_names(), outputs, "{engine}: outputs");
        assert_eq!(kernel.coord_count(), 1, "{engine}: `cycle`");
        assert_eq!(
            kernel.input_default_at(kernel.input_index("retries").unwrap()),
            Some(Value::U64(2)),
            "{engine}"
        );
    }
}

/// A value the child's declared input refuses is an error naming both,
/// not a skip.
#[test]
fn propagate_inputs_reports_a_refusal() {
    for engine in engines() {
        let parent = compile("extern shard: str = \"a\"\n", engine);
        let mut child = compile("extern shard: u64 = 1\nout := shard\n", engine);
        let err = propagate_inputs(parent.as_ref(), child.as_mut())
            .expect_err("a string into a u64 input");
        assert!(format!("{err}").contains("shard"), "{engine}: {err}");
    }
}

/// A Rule 2 write-through commits into the parent's shared cell on
/// every engine.
#[test]
fn a_write_through_commits_into_the_parent_s_cell() {
    for parent_engine in engines() {
        for child_engine in engines() {
            let pair = format!("{parent_engine} → {child_engine}");
            let mut root = compile("input cycle: u64\nshared total := 0\n", parent_engine);
            let mut b = SubcontextBuilder::under(root.as_ref());
            b.context(SourceContext::new("op"));
            b.body(BodyFragment::PolydatSource(
                "input cycle: u64\n".to_string(),
            ));
            b.add_result_bindings("total := u64_add(total, 5)\n")
                .unwrap_or_else(|e| panic!("{pair}: {e:?}"));
            let op = b.finalize().unwrap_or_else(|e| panic!("{pair}: {e:?}"));
            let mut child = op
                .instantiate_under(root.as_ref(), child_engine, &[])
                .unwrap_or_else(|e| panic!("{pair}: {e}"));
            child.set_inputs(&[0]);
            child
                .commit_write_throughs()
                .unwrap_or_else(|e| panic!("{pair}: {e}"));
            root.set_inputs(&[0]);
            assert_eq!(root.pull("total"), Value::U64(5), "{pair}");
        }
    }
}

/// A child bound to a parent's output reads `None` until the parent
/// computes it, then what the parent computed, whether the parent was
/// pulled by name or by index, on every engine pair. The link is live:
/// each pull of the parent reaches what the child computes from it,
/// and an output of the child that does not read it keeps its value.
#[test]
fn a_parent_s_output_reaches_its_child_by_either_pull() {
    let parent_src = "input cycle: u64\ntotal := u64_add(cycle, 20)\n";
    let child_src = "input cycle: u64\nextern total: u64\nnext := u64_add(total, 1)\n\
                     own := u64_add(cycle, 5)\n";
    for parent_engine in engines() {
        for child_engine in engines() {
            let pair = format!("{parent_engine} → {child_engine}");
            for by_index in [false, true] {
                let how = if by_index { "by index" } else { "by name" };
                let mut root = compile(parent_src, parent_engine);
                let mut child = module(root.as_ref(), "op", child_src)
                    .instantiate_under(root.as_ref(), child_engine, &[])
                    .unwrap_or_else(|e| panic!("{pair}: {e}"));
                let total = child.input_index("total").expect("declared");
                assert_eq!(
                    child.input_value_at(total),
                    Some(Value::None),
                    "{pair}: before the parent computes it"
                );
                child.set_inputs(&[0]);
                for (cycle, expected) in [(1u64, 21u64), (2, 22)] {
                    root.set_inputs(&[cycle]);
                    let value = if by_index {
                        let at = root.output_index("total").expect("an output");
                        root.pull_at(at)
                    } else {
                        root.pull("total")
                    };
                    assert_eq!(value, Value::U64(expected), "{pair}");
                    assert_eq!(
                        child.input_value_at(total),
                        Some(Value::U64(expected)),
                        "{pair}: after a pull {how}"
                    );
                    assert_eq!(
                        child.pull("next"),
                        Value::U64(expected + 1),
                        "{pair}: the child reads cycle {cycle} {how}"
                    );
                    assert_eq!(child.pull("own"), Value::U64(5), "{pair}: {how}");
                }
            }
        }
    }
}

/// A child bound after its parent computed an output reads that value
/// from the start, on every engine pair.
#[test]
fn a_child_bound_after_the_parent_computes_reads_the_value() {
    let parent_src = "input cycle: u64\ntotal := u64_add(cycle, 20)\n";
    for parent_engine in engines() {
        for child_engine in engines() {
            let pair = format!("{parent_engine} → {child_engine}");
            let mut root = compile(parent_src, parent_engine);
            root.set_inputs(&[4]);
            assert_eq!(root.pull("total"), Value::U64(24), "{pair}");
            let mut child = module(
                root.as_ref(),
                "op",
                "input cycle: u64\nextern total: u64\nnext := u64_add(total, 1)\n",
            )
            .instantiate_under(root.as_ref(), child_engine, &[])
            .unwrap_or_else(|e| panic!("{pair}: {e}"));
            child.set_inputs(&[0]);
            assert_eq!(child.pull("next"), Value::U64(25), "{pair}");
        }
    }
}

/// One parent shared across threads, with children bound and forks
/// taken under it from all of them at once.
#[test]
fn many_threads_bind_and_fork_under_one_shared_parent() {
    for engine in engines() {
        let mut root = compile(ROOT, engine);
        root.set_inputs(&[0]);
        let root: std::sync::Arc<dyn Kernel> = root.into();
        let iter = std::sync::Arc::new(module(
            root.as_ref(),
            "iter",
            "extern mode: str\nextern i: u64\nrow := \"{mode}-{i}\"\n",
        ));
        let handles: Vec<_> = (0..8u64)
            .map(|t| {
                let root = root.clone();
                let iter = iter.clone();
                std::thread::spawn(move || {
                    let mut child = iter
                        .instantiate_under(root.as_ref(), engine, &[("i".into(), Value::U64(t))])
                        .expect("binds");
                    let row = child.pull("row");
                    let mut fork = root.fork();
                    (row, fork.pull("mode"))
                })
            })
            .collect();
        for (t, h) in handles.into_iter().enumerate() {
            let (row, mode) = h.join().expect("no panic");
            assert_eq!(row, str_value(&format!("default-{t}")), "{engine}");
            assert_eq!(mode, str_value("default"), "{engine}");
        }
    }
}

/// A child built from source under a parent, through
/// `PolydatMatter::build_under` or a scope's `spawn`, runs on the
/// parent's engine and reads the parent's values.
#[test]
fn a_subscope_and_a_spawned_child_run_on_the_parent_s_engine() {
    use polydat::kernel::subcontext::{ChildName, PolydatMatter, wrap_root_kernel};
    let child_src = "input cycle: u64\nextern base: u64\nout := base + 1\n";
    for engine in engines() {
        let parent = compile("input cycle: u64\nconst base := 41\n", engine);
        let matter = PolydatMatter::builder()
            .label("child")
            .source(child_src)
            .build()
            .unwrap();
        let mut child = matter
            .build_under(parent.as_ref())
            .unwrap_or_else(|e| panic!("{engine}: {e}"));
        assert_eq!(child.engine(), engine, "build_under");
        child.set_inputs(&[0]);
        assert_eq!(child.pull("out"), Value::U64(42), "{engine}");

        let root = wrap_root_kernel(parent, "root");
        let mut b = root.subcontext_builder();
        b.context(SourceContext::new("spawned"));
        b.body(BodyFragment::PolydatSource(child_src.to_string()));
        let module = b.finalize().unwrap_or_else(|e| panic!("{engine}: {e}"));
        let spawned = root
            .spawn(ChildName::phase("spawned"), module)
            .unwrap_or_else(|e| panic!("{engine}: {e}"));
        let mut inner = spawned.lock_inner();
        assert_eq!(inner.engine(), engine, "spawn");
        inner.set_inputs(&[0]);
        assert_eq!(inner.pull("out"), Value::U64(42), "{engine}");
    }
}