anapao 0.1.0

Deterministic simulation testing utility for reproducible stochastic workflows
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
# anapao

[![Crates.io Version](https://img.shields.io/crates/v/anapao)](https://crates.io/crates/anapao)
[![CI](https://img.shields.io/github/actions/workflow/status/bnomei/anapao/ci.yml?branch=main)](https://github.com/bnomei/anapao/actions/workflows/ci.yml)
[![CodSpeed](https://img.shields.io/github/actions/workflow/status/bnomei/anapao/codspeed.yml?branch=main&label=codspeed)](https://github.com/bnomei/anapao/actions/workflows/codspeed.yml)
[![Crates.io Downloads](https://img.shields.io/crates/d/anapao)](https://crates.io/crates/anapao)
[![License](https://img.shields.io/crates/l/anapao)](https://crates.io/crates/anapao)
[![Discord](https://flat.badgen.net/badge/discord/bnomei?color=7289da&icon=discord&label)](https://discordapp.com/users/bnomei)
[![Buymecoffee](https://flat.badgen.net/badge/icon/donate?icon=buymeacoffee&color=FF813F&label)](https://www.buymeacoffee.com/bnomei)

`anapao` is a deterministic Rust testing utility for simulation and stochastic workflows.  
This README is a linear tutorial for new users: you will build one scenario, run it deterministically, add expectations, run Monte Carlo batches, and persist CI-friendly artifacts.

## What You Will Build

By the end, you will have a repeatable testing flow that can:
- compile a `ScenarioSpec` into a validated executable model,
- execute seeded deterministic single runs,
- execute deterministic Monte Carlo batches,
- evaluate typed assertions with evidence,
- persist artifact packs (`manifest.json`, `events.jsonl`, `series.csv`, and more).

## Prerequisites

- Rust `1.70+`
- Cargo
- A Rust test project where you want deterministic simulation checks

Add the dependency:

```toml
[dependencies]
anapao = "0.1.0"
```

---

## Step 1: Create `ScenarioSpec`

`ScenarioSpec` is your declarative model: nodes, edges, end conditions, and tracked metrics.

### Snippet S01 — Build a Minimal Scenario

```rust
use anapao::types::{EndConditionSpec, MetricKey, ScenarioSpec, TransferSpec};

let mut scenario = ScenarioSpec::source_sink(TransferSpec::Fixed { amount: 1.0 })
    .with_end_condition(EndConditionSpec::MaxSteps { steps: 3 });
scenario.tracked_metrics.insert(MetricKey::fixture("sink"));

assert_eq!(scenario.nodes.len(), 2);
assert_eq!(scenario.edges.len(), 1);
```

What you learned:
- how to bootstrap a minimum source->sink scenario with a convenience constructor,
- how end conditions and tracked metrics are attached.

---

## Step 2: Compile with `Simulator::compile`

Compilation validates and transforms your scenario into deterministic execution indexes.

### Snippet S02 — Compile a Scenario

```rust
use anapao::types::{EndConditionSpec, ScenarioSpec, TransferSpec};
use anapao::Simulator;

let scenario = ScenarioSpec::source_sink(TransferSpec::Fixed { amount: 1.0 })
    .with_end_condition(EndConditionSpec::MaxSteps { steps: 3 });

let compiled = Simulator::compile(scenario).unwrap();
assert_eq!(compiled.scenario.id.as_str(), "scenario-source-sink");
```

What you learned:
- compilation is explicit and deterministic,
- you should compile once and reuse the compiled form for runs.

---

## Step 3: Configure `RunConfig`

`RunConfig` controls deterministic single-run execution (`seed`, `max_steps`, capture policy).

### Snippet S03 — Create a Deterministic RunConfig

```rust
use anapao::types::{CaptureConfig, RunConfig};

let run = RunConfig::for_seed(42).with_max_steps(250).with_capture(CaptureConfig {
    every_n_steps: 5,
    include_step_zero: true,
    include_final_state: true,
    ..CaptureConfig::default()
});

assert_eq!(run.seed, 42);
assert_eq!(run.max_steps, 250);
assert_eq!(run.capture.every_n_steps, 5);
```

What you learned:
- seeds pin determinism,
- capture configuration controls trace granularity.

---

## Step 4: Execute a Deterministic Single Run

Now run one deterministic simulation and assert expected outputs.

### Snippet S04 — Run Once and Verify Outputs

```rust
use anapao::{testkit, Simulator};
use anapao::types::MetricKey;

let compiled = Simulator::compile(testkit::fixture_scenario()).unwrap();
let report = Simulator::run(&compiled, &testkit::deterministic_run_config()).unwrap();

assert!(report.completed);
assert_eq!(report.steps_executed, 3);
assert_eq!(report.final_metrics.get(&MetricKey::fixture("sink")), Some(&3.0));
```

What you learned:
- deterministic single-run output can be asserted directly in tests.

---

## Step 5: Create an `Expectation` Set

`Expectation` provides typed assertion semantics for run and batch reports.

### Snippet S05 — Declare Expectations

```rust
use anapao::assertions::{Expectation, MetricSelector};
use anapao::types::MetricKey;

let metric = MetricKey::fixture("sink");
let expectations = vec![
    Expectation::Equals {
        metric: metric.clone(),
        selector: MetricSelector::Final,
        expected: 3.0,
    },
    Expectation::Approx {
        metric: metric.clone(),
        selector: MetricSelector::Final,
        expected: 3.0,
        abs_tol: 0.0001,
        rel_tol: 0.0,
    },
    Expectation::Between {
        metric,
        selector: MetricSelector::Final,
        min: 0.0,
        max: 10.0,
    },
];

assert_eq!(expectations.len(), 3);
```

What you learned:
- expectations are data, not ad-hoc assertion code,
- selector controls whether you validate final value vs specific step.

---

## Step 6: Run with Assertions and Event Sink

Use the integrated assertion path and capture ordered events for diagnostics.

### Snippet S06 — `run_with_assertions_and_sink` + `VecEventSink`

```rust
use anapao::assertions::{Expectation, MetricSelector};
use anapao::events::VecEventSink;
use anapao::types::MetricKey;
use anapao::{testkit, Simulator};

let compiled = Simulator::compile(testkit::fixture_scenario()).unwrap();
let expectations = vec![Expectation::Equals {
    metric: MetricKey::fixture("sink"),
    selector: MetricSelector::Final,
    expected: 3.0,
}];

let mut sink = VecEventSink::new();
let (_report, assertion_report) = Simulator::run_with_assertions_and_sink(
    &compiled,
    &testkit::deterministic_run_config(),
    &expectations,
    &mut sink,
)
.unwrap();

assert!(assertion_report.is_success());
assert!(sink
    .events()
    .iter()
    .any(|event| event.event_name() == "assertion_checkpoint"));
```

What you learned:
- assertions and execution can be done in one call,
- event streams provide structured debugging context.

---

## Step 7: Configure `BatchConfig`

`BatchConfig` controls deterministic Monte Carlo execution.

### Snippet S07 — Create BatchConfig

```rust
use anapao::types::{BatchConfig, BatchRunTemplate, ExecutionMode};

let batch = BatchConfig::for_runs(64)
    .with_execution_mode(ExecutionMode::SingleThread)
    .with_base_seed(7)
    .with_run_template(BatchRunTemplate::default())
    .with_max_steps(50);

assert_eq!(batch.runs, 64);
assert_eq!(batch.base_seed, 7);
assert_eq!(batch.run_template.max_steps, 50);
```

What you learned:
- `runs` scales the Monte Carlo sample size,
- `base_seed` + run index derivation preserve reproducibility.

---

## Step 8: Execute a Deterministic Batch Run

Run many deterministic simulations and check aggregate outputs.

### Snippet S08 — Run Batch and Verify Ordering/Aggregates

```rust
use anapao::{testkit, Simulator};
use anapao::types::MetricKey;

let compiled = Simulator::compile(testkit::fixture_scenario()).unwrap();
let batch = Simulator::run_batch(&compiled, &testkit::deterministic_batch_config()).unwrap();

assert_eq!(batch.completed_runs, batch.requested_runs);
assert!(batch.runs.windows(2).all(|window| window[0].run_index < window[1].run_index));
assert!(batch.aggregate_series.contains_key(&MetricKey::fixture("sink")));
```

What you learned:
- batch summaries are deterministic and index-ordered.
- `completed_runs` counts reported run summaries; inspect each `run.completed` for semantic completion.

---

## Step 9: Persist Artifacts and Inspect `ManifestRef`

Persist reports for CI diffing and post-run diagnostics.

### Snippet S09 — Full Playbook (Setup -> Run -> Assert -> Artifacts)

```rust,no_run
use anapao::artifact::write_run_artifacts_with_assertions;
use anapao::assertions::{Expectation, MetricSelector};
use anapao::events::VecEventSink;
use anapao::types::MetricKey;
use anapao::{testkit, Simulator};

let compiled = Simulator::compile(testkit::fixture_scenario()).unwrap();
let expectations = vec![Expectation::Equals {
    metric: MetricKey::fixture("sink"),
    selector: MetricSelector::Final,
    expected: 3.0,
}];

let mut sink = VecEventSink::new();
let (run_report, assertion_report) = Simulator::run_with_assertions_and_sink(
    &compiled,
    &testkit::deterministic_run_config(),
    &expectations,
    &mut sink,
)
.unwrap();
assert!(run_report.completed);
assert!(assertion_report.is_success());

let output_dir = std::env::temp_dir().join("anapao-readme-playbook");
let manifest = write_run_artifacts_with_assertions(
    &output_dir,
    &run_report,
    sink.events(),
    Some(&assertion_report),
)
.unwrap();

assert!(manifest.artifacts.contains_key("manifest"));
assert!(manifest.artifacts.contains_key("events"));
assert!(manifest.artifacts.contains_key("assertions"));
```

What you learned:
- persisted artifacts become your CI and debugging contract,
- manifest keys are stable assertions for artifact expectations.

---

## Step 10: Fixture-First Testing with `testkit` (and `rstest`)

Use `testkit` helpers to avoid duplicating setup across tests.

### Snippet S10 — Reusable Fixture-Style Test Pattern

```rust
use anapao::{testkit, Simulator};
use anapao::types::MetricKey;

fn deterministic_fixture_smoke() {
    let compiled = Simulator::compile(testkit::fixture_scenario()).unwrap();
    let report = Simulator::run(&compiled, &testkit::deterministic_run_config()).unwrap();
    assert_eq!(report.final_metrics.get(&MetricKey::fixture("sink")), Some(&3.0));
}

deterministic_fixture_smoke();
```

What you learned:
- fixture helpers keep tests concise and deterministic,
- you can wrap these helpers in your own `rstest` fixture macros for larger matrices.

---

## Common Failure Modes and Debugging Hints

- Missing tracked metric:
  - symptom: expectation fails with missing observed value.
  - fix: ensure metric key is in `scenario.tracked_metrics`.
- Non-terminating scenarios:
  - symptom: run ends at `max_steps` unexpectedly.
  - fix: verify `end_conditions` are configured and reachable.
- Seed confusion:
  - symptom: output differs between runs.
  - fix: pin `RunConfig.seed` for single runs and keep batch `base_seed` stable (batch seeds derive from `base_seed` + run index).
- Sparse traces:
  - symptom: insufficient snapshots for diagnostics.
  - fix: adjust `RunConfig.capture` (`every_n_steps`, step-zero/final flags).

## Feature Flags

- `parallel`: enables Rayon-backed batch execution mode (`ExecutionMode::Rayon`).
- `analysis-polars`: enables Polars DataFrame shaping helpers.
- `assertions-extended`: enables extra assertion/snapshot/property helper crates.

## Module Surface (Reference)

`anapao` exports:
- `types`
- `error`
- `rng`
- `validation`
- `engine`
- `stochastic`
- `events`
- `batch`
- `stats`
- `artifact`
- `assertions`
- `testkit`
- `analysis` (only with `analysis-polars`)
- `Simulator` (compile/run/batch facade)

## Validation Commands

```bash
cargo test --doc
cargo test
cargo test --features parallel
cargo test --features analysis-polars
cargo bench --no-run
```

## Performance Workflow (Manual Compare)

```bash
# capture baseline matrix
./scripts/bench-criterion save --bench simulation --baseline hotspots-20260224-default
./scripts/bench-criterion save --bench simulation --features parallel --baseline hotspots-20260224-parallel

# compare matrix
./scripts/bench-criterion compare --bench simulation --baseline hotspots-20260224-default
./scripts/bench-criterion compare --bench simulation --features parallel --baseline hotspots-20260224-parallel

# manual non-failing regression summary (+7% threshold)
./scripts/bench-criterion summary --bench simulation --baseline hotspots-20260224-default --threshold 0.07
./scripts/bench-criterion summary --bench simulation --features parallel --baseline hotspots-20260224-parallel --threshold 0.07

# flamegraphs and csv summaries
./benchmarks/run_profiles.sh
BENCH_FEATURES=parallel ./benchmarks/run_profiles.sh
```