# Native ISO/IEC 19757-3:2025 Schematron support
```{eval-rst}
.. meta::
:description: Compile and validate standalone ISO/IEC 19757-3:2025 Schematron schemas with the XSLT 1.0, 2.0, and 3.0 query-binding profiles, inspect native outcomes, serialize SVRL or JSON, and apply explicit resource, phase, limit, and concurrency rules.
```
`pyxsd.schematron` is a native processor for standalone ISO/IEC 19757-3:2025
Schematron schemas using the XSLT 1.0, XSLT 2.0, and XSLT 3.0 query-binding
profiles. It compiles a schema once, validates documents against the compiled
schema, and returns a native report with typed outcomes, messages, diagnostics,
properties, and document provenance. The same report serializes to 2025 SVRL,
deterministic JSON, or the shared {class}`~pyxsd.validation.ValidationReport`
used by the XSD and RELAX NG processors.
The [2025 support matrix](#2025-support-matrix) records implemented constructs
and query-binding boundaries; the limitations section explains the evidence
and certification boundary.
```{note}
Schematron is a separate schema language with its own compiler and report
type. The XSD entry points remain `pyxsd.compile` / `pyxsd.Schema`; use
`pyxsd.schematron.compile` / `schematron.SchematronSchema` for Schematron.
```
(schematron-quick-start)=
## Quick start
A schema source is a local path, bytes-like value, or readable text/binary
stream. An instance may be any of those raw forms, an XDM document or subtree,
or a captured common `Document`. A `str` is a path, never inline XML, so pass
`b""` or a stream for an in-memory document.
[example: sch-quick-start]: #
```python
from pyxsd.schematron import compile as compile_schematron
SCHEMA = b"""
Total must be positive.
Large order: .
"""
INSTANCE = b''
schema = compile_schematron(SCHEMA)
report = schema.validate(INSTANCE)
assert report.is_valid is False
assert [outcome.check_id for outcome in report.outcomes] == ["positive-total"]
assert report.to_validation_report().issues[0].code == "schematron-failed-assert"
assert "svrl:failed-assert" in report.to_svrl()
assert '"kind": "failed_assert"' in report.to_json()
```
The compiled `SchematronSchema` is immutable and stores no per-instance
state. `report` exposes what the schema did: `active_patterns`, `fired_rules`,
and `outcomes` in production order, plus `failed_assertions`,
`successful_reports`, and `is_valid`. Each outcome keeps its check and rule
identifiers, the matched context node, `subjects`, structured message parts,
diagnostics, properties, flags, language, role, link metadata, and the owning
document URI.
(schematron-workflow-files)=
## CLI and MCP workflows
For the command and tool examples, save these files together:
{download}`rules.sch <../tests/schematron/fixtures/docs/rules.sch>`,
{download}`readiness.sch <../tests/schematron/fixtures/docs/readiness.sch>`,
{download}`ready.xml <../tests/schematron/fixtures/docs/ready.xml>`, and
{download}`empty.xml <../tests/schematron/fixtures/docs/empty.xml>`.
- The dedicated {ref}`pyxsd schematron command ` pairs a
local schema with one document. It accepts named phases and `#ANY`, literal
string parameters, and SVRL or native JSON output. Both valid (`0`) and
invalid (`1`) verdicts write a report; usage errors (`2`) and operational
faults (`3`) do not.
- The dedicated MCP tools, `pyxsd_schematron_validate` and
`pyxsd_schematron_validate_documents`, accept declared resources, phases and
JSON parameters for one document or an ordered batch. See
{ref}`mcp-schematron` for requests, projections, and fault and retention
behavior. Schematron does not extend `SchemaRef.format` or
`pyxsd_validate_document`.
(schematron-2025-support-matrix)=
## 2025 support matrix
Each row is executed by `tests/schematron/test_2025_features.py` and recorded
in `tests/schematron/dispositions-2025.toml`. A **supported** row runs its
public schema/document operation and asserts the native, SVRL, or JSON result
it defines; every normal-report row exercises all three. A **rejected** row
executes the named operation and requires the exact typed compile error. The
registry is closed: a missing case or an undocumented row fails the test, so
the table below is evidence, not a roadmap.
| Feature id | Capability | Status |
| --- | --- | --- |
| `edition-2025` | schematronEdition="2025" metadata | supported |
| `binding-xslt` | XSLT 1.0 and XPath 1.0 query-binding profile | supported |
| `binding-xslt2` | XSLT 2.0 and XPath 2.0 query-binding profile | supported |
| `binding-xslt3` | XSLT 3.0 and XPath 3.1 query-binding profile | supported |
| `hosted-xsl` | Top-level xsl:* declarations hosted natively | supported |
| `library-source` | sch:library as an include/extends definition source | supported |
| `internal-extends` | Rule-level internal sch:extends | supported |
| `top-level-extends` | Top-level external sch:extends | supported |
| `rules-container` | sch:rules global and pattern-local abstract rules | supported |
| `abstract-pattern` | Abstract pattern/group is-a with required and default params | supported |
| `schema-param` | Schema-level sch:param query fragments and API overrides | supported |
| `typed-let` | Typed sch:let/@as variables | supported |
| `dynamic-metadata` | Dynamic check, rule, pattern, group, diagnostic, and property metadata | supported |
| `text-value-templates` | Text value templates in messages | supported |
| `groups` | Independent sch:group rule sets | supported |
| `visit-each` | sch:rule/@visit-each | supported |
| `phase-when` | Dynamic sch:phase/@when and #ANY selection | supported |
| `phase-from` | Partial validation with sch:phase/@from | supported |
| `subordinate-documents` | pattern/@documents subordinate documents | supported |
| `validity-and-generic` | Native verdict and generic issue projection | supported |
| `svrl-2025` | Normal 2025 SVRL fields | supported |
| `error-svrl` | Explicit root-level svrl:error serialization | supported |
| `firing-identity-json` | Per-firing identity in native, SVRL, and JSON records | supported |
| `file-uri` | File URI normalization for SVRL @document | supported |
| `resources` | Compile and validation resource authority | supported |
| `budgets` | Compile and validation budgets | supported |
| `concurrency` | Session-local parameters under concurrent validation | supported |
| `binding-xpath` | XPath 1.0-only query binding | rejected |
| `binding-xpath2` | XPath 2.0-only query binding | rejected |
| `binding-xpath3` | XPath 3.0-only query binding | rejected |
| `binding-xquery` | XQuery 1.0 query binding | rejected |
| `binding-xquery3` | XQuery 3.0 query binding | rejected |
| `binding-xquery30` | XQuery 3.0 alias query binding | rejected |
| `binding-xquery31` | XQuery 3.1 query binding | rejected |
| `binding-stx` | STX query binding | rejected |
| `binding-exslt` | EXSLT query binding | rejected |
| `binding-unknown` | Unknown query-binding token | rejected |
| `binding-qt4` | QT4-era XQuery/XPath 4.0 binding name | rejected |
| `edition-unsupported` | Any schematronEdition other than 2025 | rejected |
| `library-standalone` | Standalone sch:library validation schema | rejected |
| `group-in-phase` | sch:group declared inside sch:phase | rejected |
| `group-nested` | sch:group nested in a pattern or group | rejected |
| `rules-misplaced` | sch:rules container outside the schema or library level | rejected |
| `concrete-param` | sch:param inside a concrete pattern or group | rejected |
| `schema-param-as` | sch:param/@as on a schema-level parameter | rejected |
| `typed-let-on-xslt` | Typed sch:let/@as under the xslt 1.0 profile | rejected |
| `cross-kind-is-a` | Concrete pattern is-a an abstract group (or the reverse) | rejected |
| `name-in-diagnostic` | sch:name inside a diagnostic message | rejected |
| `library-extends-schema` | Library extending a sch:schema | rejected |
| `message-comment` | XML comment in compiled message content | rejected |
| `message-pi` | Processing instruction in compiled message content | rejected |
## A 2025 schema, phase, group, parameter, and visit-each example
[example: sch-dynamic-phase]: #
```python
from pyxsd.schematron import compile as compile_schematron
SCHEMA = b"""
Quantity must be positive: .
Zero-quantity line.
"""
report = compile_schematron(SCHEMA).validate(
b'', phase="#ANY"
)
assert report.resolved_phase == "checked"
assert [outcome.kind for outcome in report.outcomes] == [
"failed_assert",
"failed_assert",
"successful_report",
]
assert report.failed_assertions[0].message.text.strip() == "Quantity must be positive: 0kg."
assert "svrl:active-group" in report.to_svrl()
assert '"resolved_phase": "checked"' in report.to_json()
```
## Accepted inputs and source admission
`SchematronSchema.compile` accepts a path, bytes-like value, or readable
stream. A remote schema or reference needs an authorizing `resource_policy`;
without one it is a policy denial rather than a local filesystem path. An
already-built XML `Element` is not accepted because it carries no parser
evidence. Without a resource policy, `xml_policy` and `xml_limits` govern the
root and every include and external extends alike, so a dependency cannot
exceed a depth, element, or byte bound the root satisfies or carry a
declaration the parser policy forbids.
The XML loader admits two Schematron source roots: `sch:schema` and
`sch:library`. A library is a definition source for `sch:include` and
top-level external `sch:extends`; a standalone `sch:library` validation root
is rejected by the public compile entry with `SchematronCompileError` before
resolving dependencies. This is a source-admission rule, not a parse failure:
the same library bytes are valid when a schema includes them.
`SchematronSchema.validate` accepts:
- a raw local path, bytes-like value, or readable stream;
- an `XdmDocument` or any `XdmNode` subtree;
- a captured common `Document` of any schema family.
Raw input is read once. The admitted bytes feed the source index and the XDM
builder separately, and a supplied resource policy also parses the same bytes,
so every view describes one source revision. An XDM document or subtree passes
through unchanged and keeps its node identity. A common `Document` contributes
exactly its coherent `to_xdm()` tree and is never reparsed; a document without
a capture, with a replaced root, or with an edited bound tree raises
`XdmInputError` before validation. `xml_policy` and `xml_limits` configure raw
instance parsing only; passing them with already-parsed input is rejected.
[example: sch-captured-document]: #
```python
from io import StringIO
from pyxsd import Schema
from pyxsd.schematron import compile as compile_schematron
XSD = """
"""
SCHEMA = b"""
Total must be positive.
"""
document = Schema.compile(StringIO(XSD)).parse(
StringIO(''),
capture_xdm=True,
)
report = compile_schematron(SCHEMA).validate(document)
assert report.instance is document.to_xdm()
assert report.is_valid is False
```
Captured documents are the bridge from a schema-aware XSD or RELAX NG document
to Schematron validation without re-reading its source. Use
`capture_xdm=True` on the producing parser; otherwise validation raises.
## Schema and library composition
`sch:include` splices a referenced element at its position. A rule-level
internal `sch:extends/@rule` splices an abstract rule into the extending rule;
a top-level external `sch:extends/@href` imports a schema or library's
declarations. The `include` target must be an element that may stand at the
inclusion point, so including a whole `sch:schema` is a compile error (a whole
schema cannot be included; include a fragment instead): use the top-level
external `extends` for a whole schema. A library may include and extend other
libraries; a schema may extend a schema or a library, while a library may
extend only a library. The whole closure is admitted under the compile
resource policy, each resource is read once by canonical identity, cycles
fail, and the referenced declaration's language and base URI follow the
declaration it came from. A whole library or the target of a top-level
external `extends` supplies declarations; its own `sch:title` and `sch:p` are
prose about that resource and are not spliced into the importing schema root,
so an imported library can never replace or supply the schema's identity. A
fragment `sch:include` keeps the included element's
effective source language, including one inherited from its source ancestors;
the inclusion point's `xml:lang` does not apply, and an explicit `xml:lang=""`
stays a reset.
A schema or library can carry at most one `sch:diagnostics` section and at most
one `sch:properties` section. Under the in-place composition model a second
section would sit beside the first at the importing root, which the grammar
does not permit, so a schema section plus a library section (or two libraries
with sections) is a specific `SchematronCompileError`; sections are not merged.
A library's section composes normally when the schema has none.
`sch:rules` is a schema- or library-level container of abstract rule
definitions shared by every pattern and group in the resolved closure. A
pattern or group's own abstract rule of the same identifier shadows the
container definition inside that pattern. Container identifiers, pattern
identifiers, and concrete rule identifiers join one global XML-ID registry that
carries identifiers from removed abstract definitions into compilation, so an
identifier on an abstract pattern, container, or container abstract rule still
collides with a retained phase, diagnostic, property, pattern, or check
identifier. Pattern-local abstract rule identifiers remain a project lexical
scope and may repeat across patterns without becoming global XML-IDs. That
local-first lookup is a deliberate implementation choice, not a claim about an
ambiguous part of the grammar.
Abstract definitions are validated even when no concrete instance uses them.
Their element structure, unknown Schematron elements, extend references, global
and check identifiers, and message structure are checked. A validation-only
pass also compiles the listed expression attributes: pattern `@documents`,
rule `@context`, `@subject`, and `@visit-each`, let `@value`, check `@test` and
`@subject`, and message parts (`value-of`, `name`, and `xslt3` text value
templates). It does not compile `sch:let/@as` sequence types, an abstract
`sch:param/@value` query fragment, or dynamic `@flag`/`@role`/`@severity`
attribute value templates; a definition that is used is compiled in full and
remains authoritative. Because a dead definition has no lexical position, the
pass treats every name it mentions as visible, so an undeclared variable inside
it is not diagnosed.
Abstract `sch:pattern` and `sch:group` definitions support `is-a`. A concrete
pattern may instantiate only an abstract pattern, and a concrete group only an
abstract group; same-kind `is-a` is a deliberate project constraint for
reference-implementation parity and because the concrete element name decides
independent-rule-group behavior while the grammar leaves cross-kind
instantiation ambiguous. Only the concrete instance's `id` and `documents`
override the abstract definition; a title or role authored on the concrete
`is-a` instance is ignored, and the definition's title and role are the
container's metadata. Abstract definitions declare `sch:param` replacements:
- a `param` with `@value` supplies a default; a `param` without `@value` is
required;
- a concrete `param` value overrides a default, and a concrete `param` without
a value takes the default;
- clause 5.4.11's "corresponding names and counts" wording is treated as
admitting an omitted parameter that has a default; only a declaration
without a default is required. Unknown and duplicate concrete names still
fail.
Substitution is lexical in query attributes only: pattern/group `documents`,
rule `context`, `subject`, and `visit-each`, assert/report `test` and
`subject`, let `value`, `value-of/@select`, and `name/@path`. An abstract body
refers to a parameter there as `$name`, and each `sch:param/@value` is an XPath
expression spliced in verbatim, so `'ok'` is the string `ok` while a bare `ok`
is a path to a child element. Text content is never rewritten, so a `$name`
written as plain message text stays literal and ``
shows the value. Whole parameter names match, and a replacement value is not
scanned again.
## Schema parameters, typed variables, and messages
A top-level `sch:param` declares a schema parameter. Its `@name` is an
unqualified NCName, unique across the resolved schema and library closure, and
its required `@value` is a query fragment, not literal text. Defaults are
evaluated at the primary instance root in lexical declaration order, so a later
default may reference an earlier parameter, and every root, phase, pattern,
rule, check, subject, `documents`, and message expression sees the declared
names. The pinned final grammar defines no schema-parameter `@as`; one is a
compile error.
`SchematronSchema.validate(..., parameters=...)` is pyxsd's
implementation-defined way to supply the standard's optional user value. An
override replaces its declaration's default before any root or later variable
runs, and is session-local: concurrent validations with different overrides
never share values. A key must name a declared parameter. A value is a
primitive, an XDM item, or a `list`/`tuple` sequence of those, passed through
the host's XDM conversion and the active profile's item-kind check. A mapping,
set, `None`, or other unsupported Python value raises
`SchematronEvaluationError` with `stage="parameters"` instead of an ad-hoc
string conversion. The shape check walks iteratively with a visited-identity
set and a depth bound of 64, so a self-referential list or a deeper nesting is
the same typed parameter error rather than a `RecursionError`.
`SchematronSchema.validate(..., stylesheet_parameters=...)` is the separate
channel for the schema's top-level library `xsl:param` declarations. It is not
folded into `parameters` because a schema parameter and an `xsl:param` can
share a lexical name while having different declarations and types. Keys are
the host's Clark-name, EQName, or lexical-QName names; values are converted
through the host's XDM machinery and each declaration's `@as` type. An
undeclared, duplicate, or static name, a failed conversion, or a missing
required parameter raises `SchematronEvaluationError` with
`stage="parameters"` and the host failure as its cause. Under XSLT 3.0 a typed
parameter with no default is required; XSLT 2.0 does not apply that rule.
Omitted defaulted parameters keep their default, and both channels are
session-local.
`sch:let/@as` declares a typed variable under `xslt2` and `xslt3`. The host
compiles the sequence type once and every validation applies cardinality and
item-type coercion; a failure is an operational error carrying the declaration
and instance. A typed element-content variable binds the sequence constructor's
own result as parentless value items: an element has no document wrapper and
no parent, so `root($item) is $item` and `empty($item/parent::node())` hold.
Untyped element content keeps its existing document-wrapper behavior. Typed
variables are rejected under `xslt` because XSLT 1.0 defines no sequence
types.
Check `@flag`, `@role`, and `@severity` are literal when they contain no braces
and their trimmed value is not an exact `$QName` reference. An exact `$name` or
`$prefix:local` reference evaluates at the rule context, and any other value is
an XSLT attribute value template, with escaped braces. The same forms apply to
`rule/@flag`, `rule/@role`, `pattern`/`group` `@role`, diagnostic `@role`, and
property `@role`. A pattern or group role is resolved once at the supplied
original instance root with that container's variables and reported on every
active-set record for the container. Resolved
flags split into ordered whitespace tokens. The reserved `fatal`, `error`,
`warning`, and `info` severities never change validity, the failed/report
outcome kind, or generic issue severity.
Under `xslt3`, message text supports text value templates with escaped braces,
multiple expressions, variables, and `current()` at the rule focus. This
implementation-defined option applies to check, diagnostic, and property
messages, including text inside `emph`, `span`, `dir`, and foreign markup.
Under `xslt` and `xslt2` braces remain literal and are never parsed as
expressions. A dynamic message failure is an operational error with the
message part's provenance.
## Groups, rules, and visit-each
An ordinary `sch:pattern` uses first-rule-wins: at one candidate node only the
first matching rule fires. Every `sch:group` is independent and fires every
matching rule, while an adjacent ordinary pattern still shadows its own later
rules. An empty group remains active with no fired rules. Groups and patterns
appear in authored order, and phases select either kind by its `id`.
A 2025 `sch:rule/@visit-each` expression is evaluated exactly once at each
outer matched rule node. Its items are visited in sequence order: the test,
subject, messages, diagnostics, and properties of each check evaluate at the
visited focus, and `current()` is that focus. The fired rule and every outcome
still keep the outer matched node as `context`; each outcome also keeps its own
visited item and zero-based ordinal. A visited instance node is the default
subject and keeps its true path and byte span. An atomic item or a constructed
temporary-tree node has no subject, path, or invented span, so `primary_subject`
falls back to the real outer context. An empty visited sequence keeps the fired
rule and produces no assertion or report outcome; no check is executed. The
fired rule retains the item count and at most ten leading items as a preview,
never the whole sequence; each outcome still retains its own visited item.
`SchematronValidationLimits.max_sequence_items` bounds one such sequence
before the driver traverses it, charges per-item work, or keeps the preview.
The XPath engine has already materialized one dispatch's result when the bound
is checked, so `max_steps` alone is not a sequence-size bound: it cannot
interrupt work inside a single expression dispatch. The same bound applies to
a schema-parameter default sequence.
## Phases and partial validation
`validate(..., phase=...)` selects the active patterns and groups:
- `None` and `#DEFAULT` use `defaultPhase` when declared and otherwise
activate every pattern.
- `#ALL` activates every pattern and group without phase variables or a phase
`@from`.
- `#ANY` scans only phases that declare `@when`, in document order, and stops
at the first true condition. A phase without `@when` is not a candidate.
When no condition is true, every pattern and group activates with no selected
phase; this is the standard all-active fallback, not an empty report.
- Any other value names a declared phase and ignores that phase's own `@when`.
An unknown name raises `SchematronEvaluationError` with `stage="phase"`.
A `@when` condition sees schema parameters and every schema-level root let at
the original instance root, but no phase, pattern, or rule let. Phase
variables and the pattern set are chosen only after selection. The report keeps
the caller's selector in `phase` and the actually selected authored phase in
`resolved_phase`; `#ANY` never writes a pseudo-selector into SVRL.
A selected named or default phase may bound candidate roots with `@from`. The
expression is evaluated at the supplied original instance, never at a rule
focus, and selected nodes are intersected with any supplied validation subtree:
an inside node is kept, an ancestor of the supplied node becomes that supplied
node, and an unrelated node is dropped. Roots are deduplicated and visited in
document order, so overlapping selections fire each node once by identity.
`@from` bounds candidate traversal only; rules, lets, subjects, and messages
may still navigate anywhere in the same document. A selected node from another
document, a namespace node, or an atomic sequence is a typed operational error.
An empty selection keeps the active-pattern record with an empty root tuple and
performs no rule work. Subordinate documents admitted by `pattern/@documents`
are never restricted by `@from`.
The report records the effective roots on the original document's
`ActivePattern.roots`: `None` when no `@from` applied, an empty tuple for an
empty selection, and otherwise the deduplicated nodes.
## Reports and validity
The native `SchematronReport` distinguishes the two outcome kinds:
- `failed_assert` means an `sch:assert` test evaluated to false.
- `successful_report` means an `sch:report` test evaluated to true.
`is_valid` is true exactly when no assertion failed. Successful reports never
invalidate an instance, and a schema whose fired rules contain only reports
leaves its documents valid. Flag tokens are retained in order, while `role`,
`see`, `fpi`, and `icon` strings are retained verbatim. No severity is inferred
from a flag, and a 2025 `severity` value is metadata only.
{py:meth}`~pyxsd.schematron.SchematronReport.to_validation_report` projects the
same outcomes to generic issues:
- a failed assertion becomes an error with code `schematron-failed-assert`;
- a successful report becomes a warning with code
`schematron-successful-report`.
The issue location points at the outcome's primary subject, while all subject
nodes and the native identifiers, flags, messages, diagnostics, and properties
remain in `details`.
Compilation, evaluation, and limit failures are not assertion failures and
return no verdict: `SchematronCompileError` for an unusable schema,
`SchematronEvaluationError` for a failed expression, parameter, or subordinate
document operation, and `SchematronLimitError` for an exhausted budget. Direct
resource admission and XML parser-policy failures use the shared resource
contract instead: a raw-instance policy or parser-limit failure, and a
compile-time policy denial for the schema or a dependency, raise
`ResourcePolicyError`, a separate `PyXSDError` branch rather than a
`SchematronError` subclass. Only a subordinate `document()`, `doc()`, or
`pattern/@documents` failure is wrapped as `SchematronEvaluationError`. A
malformed instance is a fatal parse error, not a successful validation report.
## SVRL and JSON
`report.to_svrl()` serializes ISO 2025 SVRL from the native report; no instance
text is reparsed and no XSLT is run. `report.to_json()` emits deterministic,
object-explicit JSON, and `to_validation_report()` emits generic issues.
Normal 2025 SVRL contains:
- a root with the schema `@title`, `@schemaVersion`, `@schematronEdition`, and
the resolved phase identity;
- `svrl:active-pattern` for ordinary patterns and `svrl:active-group` for
groups, with grammar-defined `@id`, `@name` (the authored title), `@role`,
and `@documents` (the lexical documents query source, not the loaded URI);
- `svrl:fired-rule` with `@id`, `@context`, `@visit-each`, `@role`, `@flag`,
and `@document`; `@document` is the outer context's owning instance document,
never a visited item or the primary document by default;
- `svrl:failed-assert` and `svrl:successful-report` with `@test`, `@location`,
`@id`, `@role`, `@flag`, `@severity`, and nested `svrl:text`;
- `svrl:diagnostic-reference`, carrying `@role` for a 2025-edition schema
only, and `svrl:property-reference` with `@role` and `@scheme`; diagnostic
language stays on the nested text.
A report from a schema that neither declares the 2025 edition nor uses a 2025
construct is also valid against the 2016 SVRL grammar, so 2016 toolchains can
consume it. Both pinned grammars, `svrl.rnc` and `svrl-2025.rnc`, check that
in the test suite.
Firing identity is a native value. Outcomes pair with their own fired rule by
`firing_id`, so identifier-less group rules that fire at one node stay
distinct. The native `firing_id`, rule flag/role, title/role/documents, and
visited payload are serialized explicitly in JSON; SVRL carries the fields its
grammar defines. JSON also states each outcome's pattern ordinal, document URI,
context path, subjects with available byte spans, visited item with
`{ordinal, path, document_uri, span, instance_node, value}`, diagnostics,
properties, flags, and severity. Each fired rule states `visited_count`, a
`visited_preview` of at most ten items, and `visited_truncated`; the full
sequence is never serialized. Each active-pattern record states its document
URI, `roots` (at most twenty, with `roots_count` and `roots_truncated`), and the
report states the owned `documents` as URI and source pairs. A `roots` value of
`null` means no phase `@from` applied, while an empty list is an empty
selection.
Local file URIs need one normalization. XSD 1.0 `anyURI` rejects the common
`file:///path` form because its authority is empty, so SVRL `@document` uses
`file:` plus the already-percent-encoded path with only that empty authority
removed (`file:/tmp/a%20b.xml`). A space stays `%20` and is never doubled to
`%2520`; a malformed file URI is omitted rather than rewritten into another
identity. The native model and JSON retain the exact `Path.as_uri()` value.
Non-file references are returned unchanged when legal.
Standard SVRL has deliberate representational limits: it emits only the
`primary_subject` as `@location` and carries no source spans; it omits
`#ANY`, `#ALL`, and `#DEFAULT` pseudo-selectors instead of inventing a phase
name; a constructed or foreign visited item contributes no invented path; a
`value-of` or `name` node selected from a constructed temporary tree reports
`instance_node: false` with null path, document URI, and span in JSON, and no
serializer fabricates a location for it. A node selected from a foreign parsed
document keeps its real document URI with `instance_node: false` and null path
and span, because it owns that URI but is not a validated instance node. Only a
constructed temporary tree has no URI at all. A normal report with no active
pattern or group has no grammar-valid normal form, so `to_svrl()` raises
`SchematronSerializationError` rather than emitting invalid or invented error
XML. JSON and the native report still represent that valid empty active set.
`schematron_error_to_svrl(error)` is the explicit path for a caught native
error. It emits one root-level `svrl:error` with required `@document` and
`@location` taken from the error's typed fields (compile occurrence, instance
location, or genuinely unknown empty values), optional `@code`, and the
escaped rendered message as character content. Normal validation still raises;
only this explicit call returns XML, and no error is converted into a report or
a verdict. Errors are root-level only: the 2025 grammar also admits `error`
inside an active set, but this API receives one error object and no active-set
metadata, so it does not fabricate that position. A non-`SchematronError`
argument raises `TypeError`.
Serialization rejects a malformed native report or rich text that cannot be
represented losslessly with `SchematronSerializationError`. Neither SVRL nor
JSON contains a generator marker or library marker.
## Query bindings and language profiles
The effective binding is the authored `queryBinding`, unless
`compile(..., query_binding=...)` overrides it. Binding names are matched
case-insensitively. There is no fallback from one language to another.
| Binding | Selected profile |
| --- | --- |
| `xslt` (default) | XSLT 1.0 and XPath 1.0 |
| `xslt2` | XSLT 2.0 and XPath 2.0 |
| `xslt3` | XSLT 3.0 and XPath 3.1 |
The bindings `xpath`, `xpath2`, `xpath3`, `xquery`, `xquery3`, `xquery30`,
`xquery31`, `stx`, and `exslt` are recognized and rejected with
`SchematronCompileError`. Any other name, including a future QT4-era
XQuery/XPath 4.0 name, is rejected as unknown. XQuery, XPath-only bindings, and
schema-aware XPath bindings are not implemented. No unknown token is guessed or
mapped to a supported profile.
Top-level `xsl:*` declarations are compiled into the native host, where
supported XSLT keys, functions, global variables, parameters, decimal formats,
accumulators, imported schemas, templates, and declaration composition behave
as they do in a stylesheet; unsupported declarations fail with their schema
occurrence. The executed `hosted-xsl` matrix case runs a key, a stylesheet
function, an `xsl:include`-composed function, a global variable, a supplied
parameter, a defaulted parameter, a named decimal format, an accumulator, and
an imported-schema declaration.
The two languages bind prefixes separately. An XSLT declaration resolves its
QName prefixes through the XML namespace declarations in scope at that
declaration, as in a stylesheet, while `sch:ns` binds prefixes for Schematron
queries only. A prefix that an `xsl:function` or `xsl:key` name shares with a
query therefore needs both an `xmlns` declaration and a `sch:ns` entry for the
same URI: without the `xmlns` declaration the declaration fails `XTSE0280`
(a match pattern fails `XPST0081`), and without the `sch:ns` entry the query
fails `XPST0081`. Each is a `SchematronCompileError` at compile time.
## Resources
Resource access is explicit and separate at each stage:
- `compile(..., resource_policy=...)` authorizes reading and parsing the schema,
every `sch:include`, every external `sch:extends`, and imported XSLT
declarations.
- `validate(..., resource_policy=...)` authorizes a raw instance and every
subordinate `document()`, `doc()`, or `pattern/@documents` read.
A compile policy is never reused as validation authority. Validation without a
policy is local-only, even when the schema was compiled with a remote-capable
policy. `pyxsd.RemoteResourcePolicy` is the built-in opt-in for remote reads;
see {doc}`xml-security` for its authorization and budget rules. The whole
schema closure compiles inside the policy's per-compilation scope, and every
dependency read names its containing document as the base, so a policy that
distinguishes a root from a dependency never treats an include as a fresh
root and accounts the entire closure against one budget. Each admitted
document is retained once by its resolved identity, and a cycle in the source
closure is a compile error.
## Limits and concurrency
Compilation and validation have separate immutable budget types:
These constructor signatures summarize the available limits; they are not
invocations:
```text
SchematronCompileLimits(
max_resources=None,
max_expanded_elements=None,
max_expressions=None,
)
SchematronValidationLimits(
max_outcomes=None,
max_sequence_items=None,
execution=ExecutionLimits(...),
)
```
`max_resources` counts admitted schema resources, including the root.
`max_expanded_elements` counts elements produced by includes, external
extends, and abstract expansion together under one compile-stage budget: a
value that each stage fits on its own can still be exhausted by their sum.
`max_expressions` counts compiled queries.
`max_outcomes` bounds retained outcomes; `max_sequence_items` bounds one
`visit-each` result or schema-parameter default sequence before the driver
traverses, charges, or previews it; `execution` applies the shared XSLT
execution budgets (`max_steps`, `max_documents`, and the other
`ExecutionLimits` fields) to one validation. The XPath engine materializes one
expression dispatch's result before any driver budget can act, so `max_steps`
alone is not a sequence-size bound; `max_sequence_items` is.
Every budget is an inclusive bound: observing exactly the configured work
succeeds, and the next unit raises `SchematronLimitError` with `stage`,
`budget`, `configured`, and `observed`. A limit failure never returns a partial
report. `None` leaves that budget unlimited.
One immutable `SchematronSchema` may be shared. Every validation opens its own
expression session, variable scope, key indexes, document registry, parameters,
and budget, so concurrent validations of distinct documents are supported.
A fresh session per call also means a schema can be reused after a failed
validation.
## Deliberate scope limits
- **No XQuery or QT4 claim.** Only the XSLT 1.0/2.0/3.0 query-binding profiles
are implemented. XQuery, XPath-only, STX, and EXSLT bindings are typed
compile errors; a QT4-era name is an unknown-binding compile error.
- **No official 2025 certification.** The executed matrix above records
implemented behavior. The pinned SchXslt corpus is a separate 2016-compatible
regression corpus, not an official 2025 conformance suite, and passing it
establishes no ISO certification.
- **No embedded claim.** Embedded Schematron in XSD `appinfo` or RELAX NG
annotations is outside this standalone API. The dedicated `pyxsd schematron`
command and the `pyxsd_schematron_validate` /
`pyxsd_schematron_validate_documents` MCP tools call this processor; see
{doc}`cli` and {doc}`mcp` for their entry points.
- **No large real-world schema result.** No production rule set of the size of
EN 16931 (XRechnung) or a large vocabulary's Schematron has been run through
the processor. The support matrix, the pinned SchXslt cases, and the unit
suites are the evidence; compile time, validation time, and memory for a
schema with thousands of rules are unmeasured.
- **Abstract identifier scope.** Pattern-local abstract rule identifiers are a
project lexical scope that may shadow container definitions; concrete rule
and pattern identifiers join the global XML-ID registry. See the composition
section for the exact rule.
- **Same-kind `is-a`.** Cross-kind pattern/group instantiation is rejected
rather than guessed, for reference-implementation parity and because the
grammar leaves the result ambiguous.
- **Root-level errors only.** `schematron_error_to_svrl` cannot place an error
inside an active set because the API has no active-set metadata for a caught
error.
- **Standard SVRL limits.** SVRL carries only the primary subject location, no
source spans, no pseudo-phase selector, no visited count or preview, and no
normal zero-active-set form; native and JSON reports retain the narrower
details.
- **Unused-definition validation scope.** Structural checks, extend
references, identifiers, message structure, and the listed expression
attributes apply to abstract definitions that are never instantiated, but
their `sch:let/@as` sequence types, abstract `sch:param/@value` fragments, and
dynamic `@flag`/`@role`/`@severity` AVTs are not validated until the
definition is used. Their real phase/pattern variable position also does not
exist, so the validation-only pass treats every mentioned name as visible;
an undeclared variable in a dead definition is therefore not diagnosed.
- **Single diagnostics/properties sections.** The 2025 in-place composition
model cannot merge two sections, so a schema section plus a library section,
or two libraries with sections, is a specific compile error.
- **Text value templates are `xslt3`-only.** Under `xslt` and `xslt2`, message
braces are literal; this implementation-defined option is not silently
enabled for other profiles.
See {doc}`supported` for the repository-wide feature summary and {doc}`validation`
for the shared generic issue model.