
IR Schema, Migration, and Neuro-Symbolic Safety
Source:vignettes/ir-schema-and-safety.Rmd
ir-schema-and-safety.RmdThe Neuro-Symbolic Trust Boundary
Naive “LLM-writes-R-code” tools execute untrusted model output
directly via eval(parse()), creating severe
reproducibility, statistical correctness, and security vulnerabilities.
specshiny enforces a strict neuro-symbolic trust
boundary:
-
Declarative IR Only: Translators
(
translator_rule(),translator_openai(),translator_ollama()) produce a declarative data structure (spec_ir), never executable code. -
Pure-R Schema & Guardrail Gate:
validate_spec_ir()rejects unknown nested JSON properties, non-ASCII or reserved identifiers, non-positive-definite correlation matrices, unidentifiable random slopes, and unsafe parameter grids. -
Static Positive-Allowlist AST Verification: Every
script emitted by
compile_r_script()must passverify_compiled_r_ast(code, strict = TRUE), proving statically that only whitelisted statistical and base functions are called. -
Sanitized Reports & Verifiable Study Bundles:
compile_quarto_report()neutralizes inline knitr expressions, code-fence breakouts, HTML/XSS, and dangerous LaTeX directives, whileexport_spec_bundle()andverify_spec_bundle()pair SHA-256 checksums with AST attestation.
1. Closed Schema & Pure-ASCII Identifier Guardrails
library(specshiny)
base <- new_spec_ir()
base$schema_version
#> [1] "1.2.0"
# Attempt to smuggle an unknown nested property from an LLM JSON payload
raw_obj <- jsonlite::fromJSON(as_spec_json(base), simplifyVector = FALSE)
raw_obj$hierarchy$injected_hook <- "system('id')"
v_extra <- validate_spec_ir(as_spec_ir(raw_obj, validate = FALSE))
v_extra$valid
#> [1] FALSE
v_extra$errors[, c("path", "code", "category")]
#> path code category
#> 1 hierarchy.injected_hook unknown_nested_field schemaIdentifiers are restricted to pure ASCII (<= 64
bytes, non-reserved), blocking code injection, leading dots, and Unicode
homoglyphs:
s_bad <- base
s_bad$outcome$name <- "y; system('id')"
validate_spec_ir(s_bad)$errors[, c("path", "code")]
#> path code
#> 1 outcome.name invalid_identifier
# YAML !expr evaluation tags are blocked even when yaml.eval.expr = TRUE
evil_yaml <- "schema_version: !expr \"stop('NEVER_RUN')\"\ndesign_type: monte_carlo_lm\n"
tryCatch(
parse_spec_text(evil_yaml, format = "yaml"),
error = function(e) cat("Blocked YAML attack:", conditionMessage(e), "\n")
)
#> Blocked YAML attack: YAML expression tags (`!expr` / `!r`) are forbidden for security.2. Forward-Compatible Schema Migration
(migrate_spec_ir())
Specifications archived under schema v1.0.0 validate
with a structured schema_outdated warning and upgrade
cleanly to v1.2.0 via migrate_spec_ir():
legacy <- unclass(new_spec_ir(
design_type = "multilevel_sim",
hierarchy = list(levels = 2L, n_clusters = 30L, cluster_size = 15L, icc = 0.2)
))
legacy$schema_version <- "1.0.0"
legacy$hierarchy$cluster_size_dist <- NULL
legacy$outcome$error_dist <- NULL
legacy$effects$interactions <- NULL
validate_spec_ir(as_spec_ir(legacy, validate = FALSE))$warnings[, c("path", "code")]
#> path code
#> 1 schema_version schema_outdated
upgraded <- migrate_spec_ir(legacy)
upgraded$schema_version
#> [1] "1.2.0"
attr(upgraded, "migration_log")
#> [1] "Updated schema_version from '1.0.0' to '1.1.0'."
#> [2] "Initialized hierarchy$cluster_size_dist for balanced clusters."
#> [3] "Initialized outcome$error_dist to default Gaussian normal errors."
#> [4] "Initialized effects$interactions = list()."
#> [5] "Updated schema_version from '1.1.0' to '1.2.0'."
#> [6] "Initialized optional longitudinal hierarchy$time_points and hierarchy$time_spacing."Attempting to downgrade a future schema version produces a crisp
specshiny_version_mismatch diagnostic:
future_spec <- legacy
future_spec$schema_version <- "2.0.0"
tryCatch(
migrate_spec_ir(future_spec),
error = function(e) cat("Version mismatch:", conditionMessage(e), "\n")
)
#> Version mismatch: Cannot downgrade specification from schema_version "2.0.0" to "1.2.0".
#> ℹ This specification was created by a newer version of specshiny; please
#> upgrade specshiny.3. Static AST Safety Verification
(verify_compiled_r_ast())
Every compiled simulation script passes static AST verification automatically:
spec <- nl_to_spec(
"2-level power study with 40 schools, 20 students per school, ICC 0.2, treatment effect 0.35, 50 reps"
)$spec
code <- compile_r_script(spec)
ast_ok <- verify_compiled_r_ast(code)
ast_ok
#> ✔ AST safety verification PASSED (8 expressions, 75 unique whitelisted calls).Adversarial scripts attempting direct calls, triple-colon internal
access, dynamic callees, or higher-order banned arguments
(lapply("id", system)) are caught statically without ever
executing a single line:
attacks <- c(
direct_eval = "eval(parse(text = '1 + 1'))",
do_call = "do.call(rbind, list(1, 2))",
higher_order = "lapply(c('id'), system)",
triple_colon = "stats:::C_Cdqrls",
bad_package = "library(utils)"
)
data.frame(
attack = names(attacks),
safe = vapply(attacks, function(s) verify_compiled_r_ast(s)$safe, logical(1)),
first_violation = vapply(attacks, function(s) verify_compiled_r_ast(s)$violations$code[[1L]], character(1)),
row.names = NULL
)
#> attack safe first_violation
#> 1 direct_eval FALSE banned_call
#> 2 do_call FALSE banned_call
#> 3 higher_order FALSE unwhitelisted_higher_order_fn
#> 4 triple_colon FALSE disallowed_triple_colon
#> 5 bad_package FALSE unwhitelisted_package4. Quarto, LaTeX, and XSS Sanitization
Even when untrusted free-text metadata contains inline knitr code,
code-fence breakouts, LaTeX \write18, or
<script> tags, compile_quarto_report()
neutralizes every vector before emitting the .qmd file:
poison <- new_spec_ir(
title = "Study `r system('id')` \\write18{id} <script>alert(1)</script>",
source_prompt = "Prompt `r 1 + 1` | table breakout",
hierarchy = list(levels = 1L, n_obs = 80L),
simulation = list(n_reps = 5L, seed = 42L)
)
qmd <- compile_quarto_report(poison, execute = FALSE)
c(
has_inline_knitr = grepl("`r\\s", qmd, perl = TRUE),
has_write18 = grepl("\\\\write18", qmd, perl = TRUE),
has_raw_script = grepl("<script", qmd, ignore.case = TRUE),
uses_six_tilde_yaml_fence = grepl("~~~~~~yaml", qmd, fixed = TRUE)
)
#> has_inline_knitr has_write18 has_raw_script
#> FALSE FALSE FALSE
#> uses_six_tilde_yaml_fence
#> TRUE5. Self-Contained Reproducible Study Bundles
export_spec_bundle() writes spec.yaml,
simulation.R, report.qmd, and
bundle_manifest.json (with SHA-256 digests and AST
attestation) into a path-safe directory, and
verify_spec_bundle() audits integrity end-to-end:
bundle_dir <- file.path(tempdir(), "specshiny_safety_vignette_bundle")
export_spec_bundle(spec, bundle_dir, overwrite = TRUE)
ver <- verify_spec_bundle(bundle_dir)
ver
#> ✔ Bundle verification PASSED (SHA-256 checksums, spec_ir validation, and static AST check all clean).
# Inspect manifest checksums and AST attestation
ver$manifest$ast_verification
#> $safe
#> [1] TRUE
#>
#> $n_expressions
#> [1] 8
#>
#> $n_unique_calls
#> [1] 75
#>
#> $violations
#> [1] 0
unlink(bundle_dir, recursive = TRUE)