Repository navigation
fix(fhirpath, generator): invariant follow-ups (#56–#59) and inherited-field validation - #60
Merged
Merged
Conversation
Move the `[x]` base list (R4-R6, 107 bases) and the FHIR-type suffix map into src/fhir-choice.ts, with findChoiceVariant() returning the matched key, type and value. The op-based evaluator's nav now uses it instead of its 24-entry allowlist, so `answer`, `probability`, `subject`, ... dispatch, and a key only matches when its suffix is a FHIR type name (`valueFoo` is not a variant). Direct lookup still wins and explicit null is preserved. The `_<key>` primitive sibling of the dispatched variant is now merged. Objects reached through a choice key record their type; `is`, `as` and `ofType` in the full engine use it (Quantity specialisations satisfy Quantity), as does the invariant engine. Closes #56
- fhirpath README / error-handling / llm-usage: real error classes and kinds (fhirpath.lexer, fhirpath.parse, fhirpath.invariant_compile, fhirpath.invariant_eval); note which classes are exported - root README: current invariant-engine subset and indeterminate semantics - validation guide: only decided-false error-severity invariants fail generated schemas; repeating elements are checked per item; fix the example issue message - generator README: invariants: false (not noInvariants), ig and mcpOutDir option names - fhirpath overview / api / architecture: invariant engine accepts ~/!~; equivalence is pending only in the builder
Generated validator schemas pass invariant definitions to validateInvariants on every validate() call, which re-lexed and re-parsed every invariant each time. Parse results are now cached by expression string in a bounded module-level Map (1000 entries, FIFO eviction). Lexer/parse failures are cached as the underlying error, so compile warnings and FhirPathInvariantCompileError still carry each definition's own key. Cached ASTs are deep-frozen since they are shared. validateInvariants now evaluates definitions directly from the cache without building a CompiledInvariant per call; compileInvariant uses the same cache. Closes #58
…in invariants Add the three functions R4 invariants still used without support (ctm-1, txt-1/txt-2, sdf-8a). Each returns a definite result only when the answer is certain from the JSON and is indeterminate otherwise: - replaceMatches(regex, substitution): global replace with $n groups; an invalid regex or non-string input is an evaluation error. - htmlChecks(): in-house XHTML scanner for Narrative.div. False for a root that is not an XHTML-namespaced div, elements outside the HTML 4.0 formatting set allowed by the Narrative rules, on* event attributes, xlink attributes, javascript:/vbscript: URLs, or no non-whitespace content and no image. Markup that is not well-formed is indeterminate. - resolve(): #id against the contained resources of the resource holding the reference (dangling #id resolves to empty), and Bundle entries by fullUrl / Type/id with the spec's base and version rules. External, ambiguous or unlocatable references are indeterminate. iif() in method form now evaluates its arguments against the input collection, as the full engine does, which ctm-1 relies on. Closes #57
- %resource / %rootResource on an element validated outside its resource now rethrow a prebuilt FhirPathInvariantEvalError instead of building one (and its stack) per call. Same class, same message, same OperationOutcome. Validating the 226-resource Patient example bundle drops from 5.66ms to 1.87ms per iteration; error construction no longer shows in the profile. - matches() with an invalid pattern is indeterminate instead of false. - matches() / replaceMatches() compile patterns without the unicode flag: 3 of the 8 regexes in R4 invariants (identity escapes like `\-`, `\@`) are rejected in unicode mode and would have become indeterminate. - div, mod and in parse as names at the start of an operand (`div.exists()`), and stay operators between operands. Closes #59
…ement fields Resource schemas skipped every property inherited from Resource and DomainResource (id, meta, implicitRules, language, text, contained, extension, modifierExtension), and backbone schemas skipped id / extension / modifierExtension. Unknown keys pass through, so no data was lost, but those fields were never validated: a malformed `meta`, an `extension` breaking ext-1, or a narrative with <script> (txt-1) passed. The parser now keeps the snapshot's inherited elements in a separate `inheritedProperties` list that only the schema emitter reads; TS types still get them through `extends DomainResource`. `contained` stays `unknown` (its type is the abstract Resource). Against the 2,911 official R4 examples the only new findings are txt-1 / txt-2 on 4 narratives with no content, which are genuine violations.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #56, closes #57, closes #58, closes #59.
Follow-ups to #55, plus problems found while doing them.
Changes
#56: one choice-type matcher for both engines (
packages/fhirpath/src/fhir-choice.ts)value[x]allowlist is replaced by the 107[x]bases from R4–R6. A key matches only when its suffix is a FHIR type name, soanswer→answerBooleanandprobability→probabilityDecimalnow resolve, whilevalueFoo-style keys andreferenceRangedon't. Direct lookup still wins, and an explicitnullis kept._valueString, not_value.ofType(),isandasuse the type of the matched key, and treat Age/Count/Distance/Duration/SimpleQuantity/MoneyQuantity as Quantity.resultis dropped from the old list: it isn't an[x]base in any version.#57:
replaceMatches(),htmlChecks()andresolve()in invariantshtmlChecks()checks the R4 narrative rules with an in-house XHTML scanner. Anything it can't read with certainty is indeterminate.resolve()handles#idagainst the holding resource'scontained, and Bundle references byfullUrlorType/id(including_history). External or unresolvable references are indeterminate.iif()in method form evaluates its arguments against its input, as the full engine does.#58: parse cache. Parsed invariant ASTs are cached per expression string: 1,000 entries, FIFO eviction, frozen. Validation is 1.7–2.9× faster on large R4 examples.
#59: cheaper indeterminate
%resource. The "outside its resource" error is built once and rethrown. Class, message and OperationOutcome are unchanged. On the 226-resource Patient bundle: 5.66 → 1.87 ms per iteration.Found along the way
matches()with an invalid pattern returnedfalse. It is now indeterminate.\-,\@) don't compile in unicode mode.div,modandinare names at the start of an operand (div.exists()) and operators between operands.Resource,DomainResourceandBackboneElement(id,meta,text,extension, …). Unknown keys pass through, so no data was lost, but these fields were never validated: a<script>in a Patient narrative passed. The parser now records them asinheritedProperties, which only the schema emitter reads; the TS types are unchanged.containedstaysunknown.Not changed: the full engine's
htmlChecks()still returnstrue. The spec leaves it implementation-defined, and HAPI, fhirpath.js and Firely do the same. This is documented in the coverage table.Docs: fixed stale error kinds and class names, generator option names (
invariants: false,ig,mcpOutDir), the README invariant subset and the validation guide, and documented all of the above. The changelog is left toversion:bump.Verification
pnpm build, full vitest (1,811 passed),pnpm typecheckandpnpm lintare clean. The docs build has no broken links.txt-1/txt-2on 4 narratives with empty content, which are real violations. Every other flag (que-1×86,sdf-4×4,bdl-7×1) was confirmed against the data in fix(fhirpath): evaluate standard R4 invariants (.not(), %resource, value[x]) #55.tsc --strict. With zod, real Patient and Observation examples validate cleanly withid/meta/textkept, and a<script>narrative is rejected.