fix(schema): enforce ordering facets on xs:duration

minInclusive, maxInclusive, minExclusive, and maxExclusive on xs:duration were
ignored: duration has no total order, so the generic comparator returned no
value and the bounds were skipped. A DurationValue now implements the XSD 1.0
Datatypes 3.2.6.2 partial order, comparing two durations by adding each to the
four reference dateTimes the spec fixes (a month is 28 to 31 days, so the order
is partial). A value incomparable to the bound, such as P1M against P30D, is
outside the ordered range and is rejected.

XSTS: invalid instances accepted 355 to 257. Baseline updated; regression tests
cover the total-order cases, the exclusive bounds, and the incomparable case.

Refs #147, #129.
This commit is contained in:
Mihaela Mihaljevic 2026-06-13 16:45:41 +02:00
parent 8f89acc354
commit e6a0d19c9b
5 changed files with 185 additions and 3 deletions

View File

@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
- Ordering facets on `xs:duration` are now enforced (#147). `minInclusive`, `maxInclusive`, `minExclusive`, and `maxExclusive` on duration were ignored because duration has no total order in the generic comparator. A `DurationValue` now implements the XSD 1.0 Datatypes 3.2.6.2 partial order (compare by adding to the four reference dateTimes); a value incomparable to the bound (such as `P1M` against `P30D`) is outside the range and rejected. XSTS: invalid instances accepted 355 to 257.
- Pattern and enumeration facets on a union type are now enforced (#147). A union admits a value valid for any member, but `pattern` and `enumeration` (the only constraining facets XSD allows on a union) had been ignored, so a member-valid value outside the enumeration or failing the pattern was wrongly accepted. Enumeration compares in the value space of the admitting member (so `01` equals an enumerated `1` for an integer member), matching the atomic path. XSTS #147: invalid instances accepted 555 to 355.
- Length facets on the built-in list datatypes now count list items, not characters (#146). A restriction of `NMTOKENS`, `IDREFS`, or `ENTITIES` resolved its base through neither the `BuiltinType` table (which has only the singular `NMTOKEN`) nor the user-type table, so it collapsed to an atomic string and `length`/`minLength`/`maxLength` measured characters, rejecting valid instances. The restriction base now resolves through `simpleTypeReference`, preserving the list variety. Closes the XSTS NIST `list-NMTOKENS`/`IDREFS`/`ENTITIES` facet clusters: valid instances rejected 604 to 547, invalid instances accepted 582 to 555.
- Three crash and hang classes uncovered by running the full XSTS archive to completion (#129). (1) Nested occurrence explosion: the content-model NFA capped each particle's `maxOccurs` unroll at 16384 but not the total state count, so nested high-`maxOccurs` particles multiplied (a sequence of 16384 holding a choice of 16384 is 2.7e8 states) and OOM-killed the process at 8 GB on the Microsoft Particles set; the builder now also caps total states (2^20), degrading further repetition to star. The regex `{n,m}` quantifier builder had the same unbounded unroll and the same cap is applied. (2) Quadratic content-model validation: `sequenceStructureErrors` called `follow(after: prefix)` once per child and `follow` re-walked the whole prefix from the start each time, so a content model over many children spun at 100% CPU; matching is now incremental (one active state-set advanced per child), turning O(children squared) into O(children). (3) Character-class subtraction trap: the regex pattern `[abcd-[d]]` (XSD class subtraction) was parsed as a `d` to `[` range, and since `d` (100) exceeds `[` (91) the reversed `ClosedRange` trapped (SIGBUS); `-[` now always opens a subtraction, and any reversed range (such as `[z-a]`) is a clean rejection rather than a trap.

View File

@ -0,0 +1,111 @@
extension PureXML.Schema {
/// An `xs:duration` as its two independent signed components, months and
/// seconds, with the XSD 1.0 order relation. Because a month is 28 to 31
/// days, the order is partial: P and Q compare by adding each to the four
/// reference dateTimes the spec fixes, and durations whose sign disagrees
/// across those references are incomparable (for example `P1M` and `P30D`).
/// See XSD 1.0 Datatypes 3.2.6.2. Used by the ordering facets on duration,
/// which the generic total-order path cannot represent.
struct DurationValue {
let months: Int
let seconds: Double
enum Order { case lessThan, equal, greaterThan, incomparable }
/// The four reference dateTimes (year, month, day) at T00:00:00Z.
private static let references: [(year: Int, month: Int, day: Int)] = [
(1696, 9, 1), (1697, 2, 1), (1903, 3, 1), (1903, 7, 1),
]
func compare(to other: DurationValue) -> Order {
var sawLess = false
var sawGreater = false
var sawEqual = false
for reference in Self.references {
let here = Self.instant(reference, addingMonths: months, seconds: seconds)
let there = Self.instant(reference, addingMonths: other.months, seconds: other.seconds)
if here < there {
sawLess = true
} else if here > there {
sawGreater = true
} else {
sawEqual = true
}
}
// P < Q only when s+P < s+Q at every reference; > likewise; equal
// when all four coincide (which holds iff the components are equal).
if sawLess, !sawGreater, !sawEqual { return .lessThan }
if sawGreater, !sawLess, !sawEqual { return .greaterThan }
if sawEqual, !sawLess, !sawGreater { return .equal }
return .incomparable
}
/// The instant, in seconds, of `reference` + (months, seconds): add the
/// months with calendar rollover (clamping the day to the resulting
/// month's length, per the spec), then add the seconds component.
private static func instant(
_ reference: (year: Int, month: Int, day: Int),
addingMonths addMonths: Int,
seconds: Double,
) -> Double {
let total = (reference.month - 1) + addMonths
let yearsCarried = Int((Double(total) / 12.0).rounded(.down))
let newYear = reference.year + yearsCarried
let newMonth = total - yearsCarried * 12 + 1
let newDay = Swift.min(reference.day, DateTimeValue.daysInMonth(year: newYear, month: newMonth))
let days = DateTimeValue.daysFromCivil(year: newYear, month: newMonth, day: newDay)
return Double(days) * 86400 + seconds
}
/// Parses the lexical form `-?P(nY)?(nM)?(nD)?(T(nH)?(nM)?(nS)?)?`. The
/// lexical recognizer has already accepted the value, so this trusts the
/// shape and only reads out the components.
init?(_ string: String) {
var characters = Substring(string)
var sign = 1.0
if characters.first == "-" {
sign = -1
characters = characters.dropFirst()
}
guard characters.first == "P" else { return nil }
characters = characters.dropFirst()
var inTime = false
var years = 0
var monthsPart = 0
var days = 0
var secondsPart = 0.0
var sawComponent = false
var number = ""
func consume(_ designator: Character) -> Bool {
guard !number.isEmpty, let magnitude = Double(number) else { return false }
switch (inTime, designator) {
case (false, "Y"): years = Int(magnitude)
case (false, "M"): monthsPart = Int(magnitude)
case (false, "D"): days = Int(magnitude)
case (true, "H"): secondsPart += magnitude * 3600
case (true, "M"): secondsPart += magnitude * 60
case (true, "S"): secondsPart += magnitude
default: return false
}
number = ""
sawComponent = true
return true
}
for character in characters {
if character == "T" {
inTime = true
} else if character.isNumber || character == "." {
number.append(character)
} else if !consume(character) {
return nil
}
}
guard sawComponent, number.isEmpty else { return nil }
months = Int(sign) * (years * 12 + monthsPart)
seconds = sign * (Double(days) * 86400 + secondsPart)
}
}
}

View File

@ -239,6 +239,7 @@ public extension PureXML.Schema {
}
private func rangeError(_ value: String, _ primitive: Primitive) -> String? {
if case .duration = primitive { return durationRangeError(value) }
guard let actual = primitive.ordered(value) else { return nil }
if let bound = facets.minInclusive, let limit = primitive.ordered(bound), actual < limit {
return "\(value) is below the inclusive minimum"
@ -254,6 +255,29 @@ public extension PureXML.Schema {
}
return nil
}
/// Ordering facets on `xs:duration`, which is a partial order: a value
/// that is incomparable to the bound does not satisfy it (it is not in
/// the ordered range), so an incomparable result is a violation.
private func durationRangeError(_ value: String) -> String? {
guard let actual = DurationValue(value) else { return nil }
func order(_ bound: String?) -> DurationValue.Order? {
bound.flatMap(DurationValue.init).map(actual.compare(to:))
}
if let order = order(facets.minInclusive), order == .lessThan || order == .incomparable {
return "\(value) is below the inclusive minimum"
}
if let order = order(facets.maxInclusive), order == .greaterThan || order == .incomparable {
return "\(value) is above the inclusive maximum"
}
if let order = order(facets.minExclusive), order != .greaterThan {
return "\(value) is not above the exclusive minimum"
}
if let order = order(facets.maxExclusive), order != .lessThan {
return "\(value) is not below the exclusive maximum"
}
return nil
}
}
/// Validates `value` against a built-in type with no extra facets.

View File

@ -0,0 +1,45 @@
@testable import PureXML
import Testing
/// Ordering facets on `xs:duration` (#147). Duration is a partial order (a month
/// is 28 to 31 days), compared by adding to four reference dateTimes. The bounds
/// had not been enforced at all; a value incomparable to the bound (such as
/// `P1M` against `P30D`) is outside the range and must be rejected.
@Suite("Duration ordering facets")
struct SchemaDurationFacetTests {
private func schema(_ facet: String) throws -> PureXML.Schema.Document {
try PureXML.Schema.Document("""
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="v">
<xs:simpleType>
<xs:restriction base="xs:duration">\(facet)</xs:restriction>
</xs:simpleType>
</xs:element>
</xs:schema>
""")
}
@Test("minInclusive enforces the lower bound")
func test_minInclusive() throws {
let s = try schema(#"<xs:minInclusive value="P1Y"/>"#)
#expect(try s.validate("<v>P1Y</v>").isEmpty) // equal
#expect(try s.validate("<v>P2Y</v>").isEmpty) // greater
#expect(try !s.validate("<v>P6M</v>").isEmpty) // less
}
@Test("minExclusive rejects the bound itself")
func test_minExclusive() throws {
let s = try schema(#"<xs:minExclusive value="P1Y"/>"#)
#expect(try !s.validate("<v>P1Y</v>").isEmpty) // equal: rejected
#expect(try s.validate("<v>P2Y</v>").isEmpty) // greater
}
@Test("maxInclusive enforces the upper bound and rejects incomparable values")
func test_maxInclusivePartialOrder() throws {
let s = try schema(#"<xs:maxInclusive value="P30D"/>"#)
#expect(try s.validate("<v>P20D</v>").isEmpty) // less
#expect(try !s.validate("<v>P40D</v>").isEmpty) // greater
// P1M is incomparable to P30D (28..31 days) so it is not <= P30D.
#expect(try !s.validate("<v>P1M</v>").isEmpty)
}
}

View File

@ -22,15 +22,16 @@ struct XSTSSuiteTests {
/// 2026-06-13, over 14383 groups). These ratchet down as conformance work
/// closes deviations (#145-#148); a count rising is a regression. The
/// instance counts reflect the #146 list-facet fix (built-in list length
/// facets now count items) and the #147 union-facet fix (pattern and
/// enumeration enforced on unions). The suite is opt-in, so CI and plain
/// counts items), the #147 union-facet fix (pattern and enumeration
/// enforced on unions), and the #147 duration-ordering fix (minInclusive and
/// friends on xs:duration). The suite is opt-in, so CI and plain
/// `swift test` are unaffected; run it with `swift test -c release --filter
/// XSTS` (debug is far slower and the corpus is large). Per-case deviations
/// are written to /tmp/xsts-failures.txt for the burn-down.
private let knownSchemaValidRejected = 75
private let knownSchemaInvalidAccepted = 2467
private let knownInstanceValidRejected = 547
private let knownInstanceInvalidAccepted = 355
private let knownInstanceInvalidAccepted = 257
@Test("Every XSTS case behaves: compile, reject, validate, invalidate")
func test_suite() throws {