ggen-engine 26.10.11

SPARQL-in-Tera code generation engine (vendored, renamed from praxis/crates/ggen)
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
//! Chicago-TDD end-to-end tests for the sync pipeline: real filesystem,
//! real oxigraph store, real Tera rendering — no mocks.

#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]

use std::path::Path;

use ggen_engine::sync::{sync, SyncOptions, SyncReceipt, RECEIPT_REL_PATH};
use tempfile::TempDir;

const GGEN_TOML: &str = r#"
[project]
name = "demo"

[ontology]
source = "ontology.ttl"

[templates]
dir = "templates"
"#;

const ONTOLOGY: &str = r#"
@prefix ex: <http://example.org/> .
ex:alice ex:name "alice" .
ex:bob   ex:name "bob" .
"#;

const TEMPLATE: &str = "---\nto: out/names.txt\nsparql:\n  people: SELECT ?name WHERE { ?s <http://example.org/name> ?name } ORDER BY ?name\n---\n{% for row in results %}{{ row.name }}\n{% endfor %}";

fn scaffold(root: &Path) {
    std::fs::write(root.join("ggen.toml"), GGEN_TOML).expect("write ggen.toml");
    std::fs::write(root.join("ontology.ttl"), ONTOLOGY).expect("write ontology");
    std::fs::create_dir_all(root.join("templates")).expect("mkdir templates");
    std::fs::write(root.join("templates/one.tmpl"), TEMPLATE).expect("write template");
}

#[test]
fn first_sync_writes_second_sync_skips_unchanged_and_hash_is_stable() {
    let dir = TempDir::new().expect("tempdir");
    scaffold(dir.path());

    // First run: writes the file.
    let first = sync(
        dir.path(),
        SyncOptions {
            consumer_mode: Default::default(),
            dry_run: false,
            ..Default::default()
        },
    )
    .expect("first sync");
    assert_eq!(
        first.written,
        vec![std::path::PathBuf::from("out/names.txt")]
    );
    assert!(
        first.skipped.is_empty(),
        "unexpected skips: {:?}",
        first.skipped
    );
    let content1 = std::fs::read_to_string(dir.path().join("out/names.txt")).expect("read output");
    assert_eq!(content1, "alice\nbob\n");

    // Second run: all Skipped(unchanged), byte-identical file, same hash.
    let second = sync(
        dir.path(),
        SyncOptions {
            consumer_mode: Default::default(),
            dry_run: false,
            ..Default::default()
        },
    )
    .expect("second sync");
    assert!(
        second.written.is_empty(),
        "second run wrote: {:?}",
        second.written
    );
    assert_eq!(second.skipped.len(), 1);
    assert!(
        second.skipped[0].1.contains("unchanged"),
        "reason: {}",
        second.skipped[0].1
    );
    let content2 = std::fs::read_to_string(dir.path().join("out/names.txt")).expect("read output");
    assert_eq!(content2, content1, "output must be byte-identical");
    assert_eq!(
        second.graph_hash_hex, first.graph_hash_hex,
        "graph hash must be stable"
    );
}

#[test]
fn dry_run_writes_nothing() {
    let dir = TempDir::new().expect("tempdir");
    scaffold(dir.path());

    let report = sync(
        dir.path(),
        SyncOptions {
            consumer_mode: Default::default(),
            dry_run: true,
            ..Default::default()
        },
    )
    .expect("dry run");
    assert_eq!(
        report.written,
        vec![std::path::PathBuf::from("out/names.txt")]
    );
    assert!(
        !dir.path().join("out/names.txt").exists(),
        "dry run must not write"
    );
    assert!(
        !dir.path().join(RECEIPT_REL_PATH).exists(),
        "dry run must not emit a receipt"
    );
}

#[test]
fn non_dry_sync_emits_verifiable_receipt() {
    use std::fmt::Write as _;

    let dir = TempDir::new().expect("tempdir");
    scaffold(dir.path());

    let report = sync(
        dir.path(),
        SyncOptions {
            consumer_mode: Default::default(),
            dry_run: false,
            ..Default::default()
        },
    )
    .expect("sync");
    let raw = std::fs::read_to_string(dir.path().join(RECEIPT_REL_PATH)).expect("receipt exists");
    let receipt: SyncReceipt = serde_json::from_str(&raw).expect("receipt parses");

    assert_eq!(receipt.payload.graph_hash, report.graph_hash_hex);
    assert_eq!(receipt.payload.outputs.len(), 1);
    let file_bytes = std::fs::read(dir.path().join("out/names.txt")).expect("output");
    assert_eq!(
        receipt
            .payload
            .outputs
            .get("out/names.txt")
            .map(String::as_str),
        Some(blake3::hash(&file_bytes).to_hex().as_str()),
        "receipt must bind the real output bytes"
    );

    // Chain hash recomputes to the stored value via praxis-core.
    let recomputed = receipt.record.recompute_chain_hash().expect("recompute");
    let recomputed_hex: String = recomputed.iter().fold(String::new(), |mut hex, b| {
        let _ = write!(hex, "{b:02x}");
        hex
    });
    assert_eq!(recomputed_hex, receipt.record.chain_hash_hex);
    assert_eq!(receipt.record.ts_ns, 0, "no wall clock: ts_ns pinned to 0");
}

#[test]
fn missing_ggen_toml_fails_closed() {
    let dir = TempDir::new().expect("tempdir");
    let err = sync(
        dir.path(),
        SyncOptions {
            consumer_mode: Default::default(),
            dry_run: false,
            ..Default::default()
        },
    )
    .expect_err("must fail");
    assert!(err.to_string().contains("FM-CONFIG-001"), "{err}");
}

#[test]
fn render_failure_names_available_context_keys() {
    let dir = TempDir::new().expect("tempdir");
    std::fs::write(dir.path().join("ggen.toml"), GGEN_TOML).expect("write ggen.toml");
    std::fs::write(dir.path().join("ontology.ttl"), ONTOLOGY).expect("write ontology");
    std::fs::create_dir_all(dir.path().join("templates")).expect("mkdir templates");
    // `row.nuon` is a typo for `row.noun` — Tera has no such field and
    // errors; the error message should name what WAS available (`results`)
    // rather than just repeating Tera's own "not found" text.
    std::fs::write(
        dir.path().join("templates/typo.tmpl"),
        "---\nto: out.txt\nsparql:\n  people: SELECT ?name WHERE { ?s <http://example.org/name> ?name }\n---\n{% for row in results %}{{ row.nuon }}\n{% endfor %}",
    )
    .expect("write template");

    let err = sync(
        dir.path(),
        SyncOptions {
            consumer_mode: Default::default(),
            dry_run: false,
            ..Default::default()
        },
    )
    .expect_err("typo must fail render");
    let msg = err.to_string();
    assert!(msg.contains("render failed"), "{msg}");
    // FM-TPL-017 (2026-07-17): sync.rs's own render-failure code, split off the
    // shared FM-TPL-005 it used to reuse with lint.rs's identity-CONSTRUCT check
    // -- see specs/014-ggen-core-replacement/tasks.md's FM-TPL-004/005/010 note.
    assert!(msg.contains("FM-TPL-017"), "{msg}");
    assert!(
        msg.contains("Available top-level context keys"),
        "error should name available context keys: {msg}"
    );
    assert!(
        msg.contains("results"),
        "should list the `results` key: {msg}"
    );
}

#[test]
fn when_guard_that_is_not_an_ask_query_is_refused_with_fm_tpl_016() {
    let dir = TempDir::new().expect("tempdir");
    std::fs::write(dir.path().join("ggen.toml"), GGEN_TOML).expect("write ggen.toml");
    std::fs::write(dir.path().join("ontology.ttl"), ONTOLOGY).expect("write ontology");
    std::fs::create_dir_all(dir.path().join("templates")).expect("mkdir templates");
    // `when:` must be an ASK query; a SELECT is a genuine, adversarial misuse --
    // it runs but returns a non-boolean EngineQueryResults, which sync.rs must
    // refuse loudly rather than silently coercing or panicking.
    std::fs::write(
        dir.path().join("templates/bad_when.tmpl"),
        "---\nto: out.txt\nwhen: \"SELECT ?name WHERE { ?s <http://example.org/name> ?name }\"\n---\nbody",
    )
    .expect("write template");

    let err = sync(
        dir.path(),
        SyncOptions {
            consumer_mode: Default::default(),
            dry_run: false,
            ..Default::default()
        },
    )
    .expect_err("a SELECT `when:` guard must be refused, not silently coerced");
    let msg = err.to_string();
    // FM-TPL-016 (2026-07-17): sync.rs's own when-not-ASK code, split off the
    // shared FM-TPL-004 it used to reuse with lint.rs's unbound-to:-var check --
    // see specs/014-ggen-core-replacement/tasks.md's FM-TPL-004/005/010 note.
    assert!(msg.contains("FM-TPL-016"), "{msg}");
    assert!(msg.contains("ASK query"), "{msg}");
    assert!(
        !dir.path().join("out.txt").exists(),
        "the refused template must not have been written"
    );
}

#[test]
fn oversized_rendered_output_is_refused() {
    let dir = TempDir::new().expect("tempdir");
    std::fs::write(dir.path().join("ggen.toml"), GGEN_TOML).expect("write ggen.toml");
    std::fs::write(dir.path().join("ontology.ttl"), ONTOLOGY).expect("write ontology");
    std::fs::create_dir_all(dir.path().join("templates")).expect("mkdir templates");
    // No SPARQL rows needed: a fixed-count Tera loop is enough to blow past
    // the 10MB cap with a single long repeated line.
    std::fs::write(
        dir.path().join("templates/huge.tmpl"),
        "---\nto: out.txt\n---\n{% for i in range(end=200000) %}0123456789012345678901234567890123456789012345678901234567890123\n{% endfor %}",
    )
    .expect("write template");

    let err = sync(
        dir.path(),
        SyncOptions {
            consumer_mode: Default::default(),
            dry_run: false,
            ..Default::default()
        },
    )
    .expect_err("oversized output must be refused");
    let msg = err.to_string();
    assert!(msg.contains("over the"), "{msg}");
    assert!(msg.contains("byte cap"), "{msg}");
    assert!(
        !dir.path().join("out.txt").exists(),
        "no output must be written on refusal"
    );
}

#[test]
fn a_render_failure_leaves_no_writes_from_other_templates_in_the_same_run() {
    let dir = TempDir::new().expect("tempdir");
    std::fs::write(dir.path().join("ggen.toml"), GGEN_TOML).expect("write ggen.toml");
    std::fs::write(dir.path().join("ontology.ttl"), ONTOLOGY).expect("write ontology");
    std::fs::create_dir_all(dir.path().join("templates")).expect("mkdir templates");
    // "a_good" sorts before "b_bad", so if writes were applied as each
    // template rendered (the old behavior) rather than only after every
    // template renders successfully, a_good's output would land on disk
    // even though the run as a whole fails.
    std::fs::write(
        dir.path().join("templates/a_good.tmpl"),
        "---\nto: good.txt\n---\nfine\n",
    )
    .expect("write good template");
    std::fs::write(
        dir.path().join("templates/b_bad.tmpl"),
        "---\nto: bad.txt\n---\n{{ row.nuon }}\n",
    )
    .expect("write bad template");

    let err = sync(
        dir.path(),
        SyncOptions {
            consumer_mode: Default::default(),
            dry_run: false,
            ..Default::default()
        },
    )
    .expect_err("the bad template must fail the whole run");
    assert!(err.to_string().contains("render failed"), "{err}");
    assert!(
        !dir.path().join("good.txt").exists(),
        "a_good's write must not land when a later template in the same run fails to render"
    );
    assert!(!dir.path().join("bad.txt").exists());
}

/// Two rows rendering to the same `to:` target must refuse (FM-WRITE-008)
/// instead of silently last-row-winning on disk.
#[test]
fn duplicate_render_targets_are_refused() {
    let dir = TempDir::new().expect("tempdir");
    scaffold(dir.path());
    // Templated `to:` that collapses every row onto one constant path.
    let tpl = "---\nto: \"out/{{ row.name | length }}.txt\"\nsparql:\n  people: SELECT ?name WHERE { ?s <http://example.org/name> ?name } ORDER BY ?name\n---\n{{ row.name }}";
    std::fs::write(dir.path().join("templates/one.tmpl"), tpl).expect("write template");

    // alice/bob → different lengths; use equal-length names to collide.
    std::fs::write(
        dir.path().join("ontology.ttl"),
        "@prefix ex: <http://example.org/> .\nex:a ex:name \"anna\" .\nex:b ex:name \"bert\" .\n",
    )
    .expect("write ontology");

    let err = sync(
        dir.path(),
        SyncOptions {
            consumer_mode: Default::default(),
            dry_run: false,
            ..Default::default()
        },
    )
    .expect_err("must refuse");
    let msg = err.to_string();
    assert!(msg.contains("FM-WRITE-008"), "{msg}");
    assert!(msg.contains("same admitted output"), "{msg}");
    assert!(
        !dir.path().join("out").exists(),
        "refusal must happen before any write"
    );
}

/// A `determinism: true` template whose `to:` path is non-deterministic is
/// refused even when the body is deterministic — the path is output too.
#[test]
fn nondeterministic_to_path_violates_determinism_check() {
    let dir = TempDir::new().expect("tempdir");
    scaffold(dir.path());
    let tpl = "---\nto: \"out/{{ now() | date(format='%f') }}-{{ row.name }}.txt\"\ndeterminism: true\nsparql:\n  people: SELECT ?name WHERE { ?s <http://example.org/name> ?name } ORDER BY ?name\n---\n{{ row.name }}";
    std::fs::write(dir.path().join("templates/one.tmpl"), tpl).expect("write template");

    let err = sync(
        dir.path(),
        SyncOptions {
            consumer_mode: Default::default(),
            dry_run: false,
            ..Default::default()
        },
    )
    .expect_err("must refuse");
    let msg = err.to_string();
    assert!(msg.contains("FM-TPL-009"), "{msg}");
    assert!(msg.contains("different path"), "{msg}");
}

/// Dry-run classifies an existing non-UTF-8 target as a typed refusal, not
/// as a cheerful "planned: write".
#[test]
fn dry_run_refuses_non_utf8_existing_target() {
    let dir = TempDir::new().expect("tempdir");
    scaffold(dir.path());
    std::fs::create_dir_all(dir.path().join("out")).expect("mkdir out");
    std::fs::write(dir.path().join("out/names.txt"), [0xFFu8, 0xFE, 0x00, 0x9F])
        .expect("write binary target");

    let err = sync(
        dir.path(),
        SyncOptions {
            consumer_mode: Default::default(),
            dry_run: true,
            ..Default::default()
        },
    )
    .expect_err("must refuse");
    let msg = err.to_string();
    assert!(msg.contains("FM-WRITE-009"), "{msg}");
    assert!(msg.contains("UTF-8"), "{msg}");
}