License & usage posture. This repository is source-available, not OSI-approved, and licensed under PolyForm Shield 1.0.0. You may use, modify and redistribute the code for any purpose, commercial use included, except to provide a product that competes with this software or with a product Askalot provides using it. See LICENSE.
The QML language specification and the theory behind its validation are licensed separately under CC BY 4.0: the QML syntax reference and the theory pages on docs.askalot.io.
The QML language specification and the method behind it, a declarative questionnaire validated by an SMT solver, were created by Peter Saghelyi. The intellectual property is held by Askalot Survey & Research Kft.
The language and its formal-validation model are described in a peer-reviewed paper presented at ICAI 2026 and published in its conference proceedings (doi:10.17048/icai.2026.227). When you use or build on the method, cite the paper and link back to this repository.
The source code is licensed under PolyForm Shield 1.0.0 (see above). The specification and the theory pages are licensed under CC BY 4.0, attributed to Askalot Survey & Research Kft.
Author: Peter Saghelyi · [email protected] · LinkedIn
The askalot_qml module provides Z3-driven questionnaire validation capabilities with two distinct processors:
- FlowProcessor: Runtime questionnaire traversal for conducting interviews
- ValidationProcessor: Offline static validation for questionnaire design
Both processors share a common pipeline through QMLEngine that handles dependency graph construction and topological sorting.
Worked examples — tests/fixtures/
tests/fixtures/ holds 38 runnable .qml files that
showcase the language's capabilities (and double as the test suite). Highlights:
- Core flow —
basic.qml,branching_flow.qml,dependencies.qml,scoring.qml,question_group.qml - Matrix questions —
matrix_ranking.qml,matrix_symmetry.qml,matrix_fixed_sum.qml,matrix_infeasible_sum.qml - Group blocks (single-pass, the default
kind, optionallycount-capped) — a Group asks each in-scope inner item once in canonical order; an optionalcount: Ncaps it to a deterministic, precondition-gated first-N draw (not random selection) - Roster blocks (repeat-over-entities) —
roster_numeric.qml,roster_multiselect.qml,roster_inner_precondition.qml,roster_single_label.qml - Formal-validation cases —
cycles.qml,classification.qml, and thethesis_*.qmlset (dead-code and conflicting-postcondition detection drawn from the paper).
Evaluation corpus — evaluation/
evaluation/ evaluates QML against real-world, publicly
available questionnaires rather than toy inputs — established instruments such
as AUDIT, BRFSS, CCHS, DHS, NHIS and Malaria Surveillance, alongside
national censuses and sociology/education surveys, organized by domain. The
curated source catalog — provenance and download links across 13 domains (health, demographics, sociology, market research, compliance,
education, safety-critical, legal, infrastructure, and more) — is in
evaluation/questionnaire_sources.md.
Twelve of those instruments (ACS, BRFSS, ESS12, GSS 1999 Victimization, GSS
Time Use, LFS, NLSCY, NPHS, PALS, SAEP, SHS, SLID) were converted by
Askalot's questionnaire import. Each one keeps what the import produced: the
source as the import read it (<NAME>.md), its inventory
(<NAME>.inventory.json) and the questionnaire (<NAME>.qml). The other folders
hold the source files only, apart from CCHS 2005, an earlier hand conversion
(its 303 pages are over the import's 300-page limit).
evaluation/CLAUDE.md describes each file.
This repository holds the language, its validator and the corpus. It does not convert questionnaires. To turn a printed questionnaire (a PDF or a Markdown file) into QML, use Askalot's import:
- In Askalot (askalot.io): import the file into a project. The import reads every page (text layer, or vision for scanned and form-like pages), builds a question inventory, writes the QML, and checks it with the same Z3 validator this repository ships. The result is a draft questionnaire you can review, edit and publish.
- From an AI agent — the askalot-plugin
connects an agent to the same Askalot tools, the import included:
- Claude Code: install the plugin (
/plugin marketplace add askalot-io/askalot-plugin, then/plugin install askalot@askalot). It brings the MCP server plus Askalot's skills for designing and validating QML. - Claude Desktop or Claude.ai: these do not load plugins. Add Askalot's
MCP server as a custom connector instead (Settings → Connectors → Add
custom connector, URL
https://portor.<tenant>.askalot.io/mcp). This gives the same tools, without the skills. Walkthrough: docs.askalot.io → Integrations → Claude.
- Claude Code: install the plugin (
Either way the conversion runs in Askalot, under your account and its AI provider settings.
askalot_qml/
├── api/ # Flask blueprints for web services
│ ├── validation_blueprint.py # Static validation endpoints
│ └── flow_blueprint.py # Flow navigation endpoints
├── core/ # Core processing engines
│ ├── validation_processor.py # Static validation with Z3 classification
│ ├── flow_processor.py # Runtime navigation
│ ├── python_runner.py # Safe Python code execution
│ ├── qml_diagram_ir.py # Positions-free graph IR for the QML Explorer webview
│ ├── qml_engine.py # Common pipeline orchestrator
│ ├── qml_loader.py # QML file loading + block flattening
│ ├── qml_topology.py # Dependency graph and topological sort
│ └── item_count.py # Canonical top-level item-count helper
├── models/ # Data models
│ ├── item_proxy.py # Runtime item wrapper (incl. MatrixQuestion outcomes)
│ └── qml_state.py # Survey state management
├── schema/ # QML schema + grammar contract (see "QML Schema & Grammar")
│ ├── qml-schema.json # Authoritative JSON Schema (dialect 2020-12)
│ └── qml-grammar.w3c.ebnf # W3C-EBNF rendering for railroad-diagram tools
└── z3/ # Z3 constraint solving
├── global_formula.py # Global satisfiability check (Level 2)
├── item_classifier.py # Per-item Z3 classification (Level 1)
├── path_based_validation.py # Accumulated reachability / dead code (Level 3)
├── pragmatic_compiler.py # AST to Z3 constraint compilation
└── static_builder.py # SSA versioning and constraint generation
The module implements the formal-verification model described in the peer-reviewed ICAI 2026 paper (doi:10.17048/icai.2026.227):
A questionnaire is a tuple
-
$I$ — finite set of items -
$S$ — vector of outcome variables -
$D$ — domain constraints for each outcome -
$P$ — preconditions (Boolean formulas determining item visibility) -
$Q$ — postconditions (Boolean formulas constraining valid responses)
the conjunction of all per-outcome domain constraints.
Three levels of increasing thoroughness, implemented in the z3/ module:
| Level | Formula | Implementation | Purpose |
|---|---|---|---|
| Per-item | item_classifier.py | Detect NEVER reachable and INFEASIBLE items | |
| Global | global_formula.py | Detect conflicting postconditions | |
| Path-based | path_based_validation.py | Detect dead code (unreachable items) |
Relationships between levels:
-
Per-item passes → Global passes: if all
$W_i$ are UNSAT, then$\mathrm{SAT}(F)$ is guaranteed (Theorem: Soundness) -
Global fails → Path-based fails: if
$\mathrm{UNSAT}(F)$ , no execution path is valid (Theorem: Global Necessary) -
Global passes ↛ All paths valid:
$\mathrm{SAT}(F)$ doesn't guarantee all items reachable (Theorem: Global Not Sufficient)
When each level suffices:
- Per-item suffices when all postconditions are TAUTOLOGICAL
- Global suffices when you only need to verify some valid completion exists
- Path-based is needed to detect dead code (CONDITIONAL items made unreachable by accumulated constraints)
Z3's global context (main_ctx()) is not thread-safe. In multi-threaded environments (e.g., Armiger's watchdog Observer thread, gunicorn with threads), garbage collection of Z3 wrapper objects on background threads races with solver operations on the main thread, causing ast.cpp:388 assertion violations and segfaults.
Solution: Each StaticBuilder creates a per-analysis z3.Context() and propagates it to all Z3 consumers:
StaticBuilder (owns ctx = z3.Context())
├── PragmaticZ3Compiler (receives ctx)
├── ItemClassifier (reads builder.ctx)
├── GlobalFormula (receives ctx)
└── PathBasedValidator (receives ctx)
Context propagation rules:
- Leaf constructors (
Int,IntVal,BoolVal,Bool,Solver) require explicitctxparameter - Compound functions (
And,Or,Not,Implies,If) infer context from their arguments automatically
When writing new Z3 code: Always pass self.ctx (or the builder's context) to Int(), IntVal(), BoolVal(), Bool(), and Solver() constructors. Never rely on the global context.
Purpose: Conduct interactive interviews by traversing the questionnaire graph.
File: core/flow_processor.py
- Initialize questionnaire state - Execute codeInit, create ItemProxy instances, set up navigation path
- Navigate forward/backward - Follow topological order, evaluate preconditions, track history
- Process item responses - Validate postconditions, execute code blocks, propagate state
The QMLState (models/qml_state.py) maintains:
- items[]: Flat list of all questionnaire items
- history[]: Navigation history (item IDs visited in order)
- navigation_path[]: Pre-computed topological order from Z3 analysis
- Per-item context: Variable state AFTER each item's execution
Each item stores:
- outcome: User's response value
- visited: Whether item has been completed
- context: Dictionary of Python variables at this execution point
This architecture enables pause/resume of interviews: by storing the context at each item, we can restore the exact Python state when resuming a survey.
Forward Navigation (no Z3 at runtime):
- Iterate through pre-computed navigation_path (topological order)
- Skip visited items (unless last in path)
- Evaluate preconditions via Python eval (NOT Z3)
- Items with unsatisfied preconditions are silently skipped
- Return first item with satisfied preconditions
- Track item in history for backward navigation
Backward Navigation:
- Pop current item from history stack
- Mark item as unvisited
- Restore previous item's context
- Return to previous item
Item Processing (strict order — postcondition BEFORE codeBlock):
- Clone current item's context
- Populate context with ItemProxy instances for all items
- Assign outcome from user response
- Validate postcondition — return hint message if failed
- Execute codeBlock via PythonRunner (only after postcondition passes)
- Update outcomes for modified items
- Propagate variables to subsequent items' contexts
Dependency consequences of this order:
- Preconditions can reference other items' outcomes and variables from prior items
- Postconditions can reference the current item's outcome and any variable — but variables still hold their prior values (the current item's codeBlock hasn't run yet)
- CodeBlocks can read/write the current item's and previous items' outcomes and update variables for subsequent items
- Z3 used once at initialization for dependency graph
- Preconditions evaluated via Python eval (fast)
- No Z3 classification during navigation
- Base diagram cached for reuse
Purpose: Validate questionnaire design by detecting structural problems before deployment.
File: core/validation_processor.py
- Per-item classification - Determine reachability and postcondition effects
- Global formula check - Verify at least one valid completion exists
- Path-based validation - Detect dead code from accumulated constraints
- Generate validation diagrams - Visualize classification results with semantic coloring
The ItemClassifier (z3/item_classifier.py) computes:
Precondition Reachability:
| Status | Condition | Meaning |
|---|---|---|
| ALWAYS | Item always shown | |
| CONDITIONAL |
|
Item sometimes shown |
| NEVER | Item never reachable (dead code) |
Postcondition Invariant (relative to precondition
| Status | Condition | Meaning |
|---|---|---|
| TAUTOLOGICAL | Postcondition always holds when reached | |
| CONSTRAINING | both |
Postcondition filters some responses |
| INFEASIBLE | Postcondition can never be satisfied (design error) | |
| NONE | no postcondition defined | No validation constraints |
| Color | Class | Meaning |
|---|---|---|
| 🟢 Green | always | ALWAYS reachable |
| 🟡 Yellow | conditional | CONDITIONAL reachability |
| 🔴 Red | never | NEVER reachable |
| 🟣 Purple | infeasible | INFEASIBLE postcondition |
| 🔵 Blue | tautological | TAUTOLOGICAL postcondition |
Both processors share the QMLEngine (core/qml_engine.py) which provides:
File: z3/static_builder.py
- Parses preconditions, postconditions, and code blocks
- Generates Z3 constraints using SSA (Static Single Assignment) versioning
- Discovers item dependencies through constraint analysis
- Creates frozen base constraint
$B$ for classification
File: core/qml_topology.py
- Builds dependency graph from StaticBuilder's constraint analysis
- Computes topological order via Kahn's algorithm with priority queue
- Provides dependency layers and connected components
Stable Topological Ordering: Uses a min-heap keyed by original QML file index. When multiple items are available (in_degree = 0), the one appearing earliest in the QML file is always processed first. This ensures deterministic ordering that respects the author's intended item sequence.
Cycle-Tolerant Topological Ordering: Always produces a complete ordering, even when cycles exist:
- Kahn's algorithm processes all zero-in-degree items
- When stuck (all remaining items have non-zero in-degree), DFS finds one cycle
- The backward edge (last→first in file order) is removed to break the cycle
- Kahn's resumes — repeat until all items are processed
Cycle members are linearized in QML file order at their natural position. The original dependency graph (self.dependencies) is preserved; only working copies are mutated during cycle breaking. get_topological_order() always returns a list (never None); check has_cycles to know if the ordering is exact or approximate.
File: core/qml_diagram_ir.py
Emits a positions-free structural intermediate representation (IR) — top-level blocks, items, and conditions arrays — consumed by the React + React Flow webview in the QML Explorer. Layout is computed client-side by ELK.js; this module never computes node positions.
- Structure: blocks (incl. Roster
iterate_over/labelsand Groupcount), items (kind, control, classification), and conditions (pre/post predicates with item-outcome and variable references) - Classification: per-item flow/validation classification is attached to the IR for the viewer to color
QML files are YAML-based questionnaire specifications. See Examples & Evaluation and tests/fixtures/ for examples.
Key elements:
- codeInit: Global initialization code block
- blocks: Logical groupings of items (can have block-level
precondition) - items: Questions, comments, or groups with:
- precondition: List of predicates determining visibility
- postcondition: List of predicates with hints for validation
- codeBlock: Python code executed after response
Blocks can define preconditions (and postconditions) that apply to all items within them. The block's precondition/postcondition lists stay on the block — they are not copied onto items. Consumers compose them at evaluation time: FlowProcessor (and StaticBuilder, when emitting Z3 constraints) gate each item on (block.precondition or []) + (item.precondition or []). During flattening, QMLLoader propagates only block-kind metadata onto inner items — _roster_block_id / _roster_iterate_over / _roster_labels for Roster blocks, and _group_block_id / _group_count for the inner items of a count-capped Group (an uncapped Group adds no tags) — so downstream code can detect roster/Group membership without re-walking the block tree.
StaticBuilder extracts domain constraints
- Numeric controls (Editbox, Slider, Range):
min/maxbounds - Choice controls (Radio, Dropdown, Checkbox, Switch): Enumeration via
labels(e.g.{1: "Yes", 2: "No"})
The askalot_qml/schema/ folder holds the canonical contract for QML — the
YAML/JSON document format that authors, the AI generator, the loader, and the
qml-explorer frontend all agree on.
| File | Role |
|---|---|
askalot_qml/schema/qml-schema.json |
Authoritative JSON Schema (dialect 2020-12), schema version 2.0.0. Single source of truth. |
askalot_qml/schema/qml-grammar.w3c.ebnf |
A W3C-EBNF rendering of the same contract, for railroad-diagram tools. Derived from the schema; not authoritative. |
askalot_qml/schema/__init__.py |
Exposes QML_SCHEMA_VERSION, read from qml-schema.json at import (no hardcoded copy). |
The schema is the source of truth. The EBNF is a human-readable, diagrammable view of it — when the two disagree, the schema wins, and the EBNF should be regenerated.
A QML document is { qmlVersion, questionnaire }. A questionnaire has an
ordered list of blocks; each block has items; questions carry an input
control. Items and blocks may carry precondition / postcondition lists
(predicates over prior answers) and Python codeBlock / codeInit snippets.
Three discriminators shape almost everything:
Block.kind—Group|Roster(optional; defaults toGroup)Item.kind—Comment|Question|QuestionGroup|MatrixQuestionInput.control—Switch|Radio|Dropdown|Checkbox|Editbox|Textarea|Slider|Range
In the schema these are encoded as allOf / if-then conditional
requirements (each discriminator value pulls in its own required and forbidden
fields). Those conditionals are the heart of the language, and they are
exactly what the grammar turns into alternation forks.
How to read qml-grammar.w3c.ebnf
It is an abstract field-structure grammar, not a byte-level JSON/YAML grammar. Read it with these conventions in mind:
- Punctuation is elided. Object braces, colons, commas, and string quoting do not appear — only field structure does.
- A field is
"key" ValueType. For example"id" String, or the optional( "title" String )?. Repeated array values use*/+(e.g.Condition*,Block+). - Field order is canonical-only. QML objects are unordered mappings, so a railroad's left-to-right sequence overstates ordering. Treat the order as a reading convenience, not a rule.
- Discriminators are alternation forks.
Block,Item, andInputeach branch one way perkind/control, with that branch's required fields inline. This is the payoff of deriving from the conditional requirements. - Start symbol:
QMLDocument. String/Integer/Numberare intentionally undefined — they are opaque lexical scalars. Expanding them into character-class railroads would only add noise, so diagram tools list them as undefined non-terminals (and still render every diagram). This is expected, not an error.
The grammar uses the W3C EBNF dialect: ::= for productions, |
alternation, ? * + quantifiers, ( ) grouping, "lit" terminals, and
/* … */ comments.
Paste the whole qml-grammar.w3c.ebnf file in, start symbol QMLDocument:
- bottlecaps.de/rr/ui — the de-facto standard. Edit Grammar tab → paste → View Diagram. IPv4 mirror: rr.red-dove.com/ui.
- ebnf2railroad — EBNF +
(* *)comments → an HTML page of diagrams. - DrawGrammar — quick paste-and-draw.
- EBNF-Visualizer (JKU) —
exports
.gif.
These tools check formal validity and let you test whether sample strings conform — useful when sanity-checking that the grammar accepts and rejects what you intend:
- BNF Playground — define the grammar, generate valid strings, and validate input (green = matches).
- EBNF Lab — verifier + word producer.
- icosaedro.it/bnf_chk — pure formal-validity checker.
Dialects differ between tools (BNF vs ISO-EBNF vs W3C-EBNF), so the file may need small syntactic tweaks to load outside the bottlecaps family.
A context-free grammar cannot express everything the schema and loader enforce, and in a few places the grammar is deliberately stricter than the live schema. Know these before trusting the diagram as the full contract:
- Open vs closed.
qml-schema.jsonsetsunevaluatedProperties: falseonBlock(as of2.0.0) — it composes across the kind-conditionalallOf/if-thenbranches, so a misplaced key on a block (iterateOvr, acounton aRoster, a strayis_random) is now rejected. The other object types (Item,Input,Condition,Questionnaire) still set neitheradditionalProperties: falsenorunevaluatedProperties: false, so they silently accept unknown, misspelled, or misplaced keys today (precondtion). The grammar models the intended, closed language — it lists only declared members. BroaderunevaluatedProperties: falseadoption beyondBlockis deferred follow-up. - Vestigial Roster guard. The schema's Roster branch forbids
asandmaxEntriesvianot/anyOf, but those properties are declared nowhere, so the guard is dead weight. The grammar simply omits them. - Value constraints (below) are enforced by the loader / Z3 validator, not by structure, so they cannot appear in the grammar.
| Construct / field | Constraint | Enforced by |
|---|---|---|
Group.count |
optional positive integer ≥ 1 (omitted = ask all in-scope items; no silent default) | schema (minimum: 1) + loader |
Group.count inner-item independence |
inner items of a count-capped Group must not depend on one another |
loader (AST sibling-ref) + Z3 validator (transitive dep graph) |
Roster.labels keys |
must be powers of two (1, 2, 4, …) | loader / code |
Checkbox.labels keys |
must be powers of two | loader / code |
Switch.default |
0 or 1 |
schema (enum) |
Radio.default, Dropdown.default |
must be an existing key of labels |
code / UI |
Editbox.default, Slider.default, Range.default |
min ≤ default ≤ max |
code / UI |
qmlVersion |
a declared MAJOR != 2 is rejected loudly (e.g. qmlVersion: "1.0" fails to load); an absent qmlVersion stays advisory |
loader |
Off-the-shelf JSON-Schema → grammar converters
(llama.cpp json-schema-to-grammar,
json-schema-to-gbnf,
XGrammar)
exist, but they target GBNF over the JSON wire syntax to constrain LLM
decoding. They are verbose and — critically — they flatten or drop the
if/then/allOf/oneOf conditional requirements, which is exactly the
kind→fields and control→fields structure that makes QML QML. So the
EBNF here was derived by hand to keep those discriminators as first-class
alternation forks. (See also the open
transformers-CFG feature request
and the json-schema.org grammar discussion.)
GET /api/flow/current-item- Get current item in navigationPOST /api/flow/evaluate-item- Process user responseGET /api/flow/previous-item- Navigate backwardGET /api/flow/navigation-path- Get complete navigation path
GET /api/qml/validation- Full validation with Z3 classificationGET /api/qml/validate- Validate QML structureGET /api/qml/files- List available QML files
The PythonRunner (core/python_runner.py) provides sandboxed code execution:
- Allowed modules: math, random, statistics, itertools, functools, collections, re
- Forbidden constructs: Import, AsyncFunctionDef, ClassDef, eval, exec, compile, open, os, sys
- AST validation: Code is validated before execution
Test files are located in tests/unit/ and tests/integration/. Run with:
make test # All tests
make test-unit # Unit tests only
make test-integration # Integration tests only# Top-level imports (recommended)
from askalot_qml.core import FlowProcessor, ValidationProcessor
from askalot_qml.models import QMLState
# Explicit imports
from askalot_qml.core import FlowProcessor, ValidationProcessor
from askalot_qml.z3 import StaticBuilder, ItemClassifierBoth processors provide debug_dump() methods for diagnostic output.
QML validation is an SMT problem, so its cost grows with questionnaire size
and complexity. The benchmark/ harness is a scaling study
that measures how validation time and peak memory grow along four
independent axes, sweeping one questionnaire knob at a time while holding the
others at a fixed baseline. Each data point is validated in a fresh
subprocess (for a clean peak-RSS reading of Z3's native allocations), and the
time is split into three phases:
- parse —
QMLLoader: file read, YAML parse, and AST/normalization. - construction —
StaticBuilderconstraint generation + topology. - Z3 solve —
ItemClassifierper-item classification (the SMT work).
Per-item classification uses one persistent solver with incremental
push/pop, so the base constraint is asserted once and the per-item cost stays
amortized — the Z3 curve scales roughly linearly rather than quadratically. See
benchmark/README.md for the full methodology, CLI, and
the provenance recorded with every run.
The baseline sweep: independent questions, no conditions. Both parsing and Z3 solving grow with the item count; memory rises roughly linearly.
Each added precondition introduces a dependency edge and extra reachability checks, isolating the cost of precondition analysis.
Postconditions add solver checks (tautological / infeasible / constraining) without deepening the dependency graph, isolating postcondition-invariant cost.
Varies the length of the longest precondition chain (the topology's dependency depth) while holding the item count fixed.
make benchmark # fast smoke sweep (all axes) + figures
# paper-grade (larger ranges, slower):
uv run --project benchmark python -m benchmark.sweep
uv run --project benchmark python -m benchmark.plotThe committed PNGs above live in benchmark/figures/ and
are refreshed by hand when Z3 or the harness changes; the re-derivable
results/ JSON the harness emits is gitignored.
Programming Z3 §4.1
suggests a specialized finite-domain solver (QF_FD) for problems over
bit-vectors, enumerations, and bounded integers. QML outcomes are finite, so we
benchmarked the default Solver against SolverFor("QF_FD") and
SolverFor("QF_LIA") on the same questionnaires — median of 3 runs, through the
identical push/pop classification path:
| items | default Solver |
QF_FD |
QF_LIA |
|---|---|---|---|
| 100 | 26 ms | 1 336 ms · ❌ wrong verdicts | 30 ms · ✅ |
| 200 | 73 ms | 5 323 ms · ❌ wrong verdicts | 91 ms · ✅ |
| 500 | 372 ms | 32 856 ms · ❌ wrong verdicts | 499 ms · ✅ |
The postcondition fixtures (classification.qml,
codeblock_postcondition.qml,
thesis_conflicting_postconditions.qml)
showed the same pattern at small N.
QF_FD is both wrong and 50–90× slower: QML outcomes are unbounded Z3 Int
variables bounded by constraints, not values in a native finite sort, so the
finite-domain engine cannot treat them as finite — it returns unknown, which
flips the == unsat determinations — and degrades badly. QF_LIA reproduces the
default's verdicts exactly but runs ~15–35 % slower, with the gap widening as
N grows. So the harness keeps the default Solver(): Z3's general engine
already selects the best tactic for this problem shape.



