Skip to content

fix(fhirpath, generator): invariant follow-ups (#56–#59) and inherited-field validation - #60

Merged
awbx merged 9 commits into
mainfrom
fix/invariant-followups
Nov 16, 2026
Merged

awbx merged 9 commits into
mainfrom
fix/invariant-followups

Conversation

@awbx

@awbx awbx commented Nov 16, 2026

Copy link
Copy Markdown
Owner

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)

  • The full engine's 24-entry 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, so answer → answerBoolean and probability → probabilityDecimal now resolve, while valueFoo-style keys and referenceRange don't. Direct lookup still wins, and an explicit null is kept.
  • Primitive extensions on a dispatched value come from _valueString, not _value.
  • ofType(), is and as use the type of the matched key, and treat Age/Count/Distance/Duration/SimpleQuantity/MoneyQuantity as Quantity.
  • result is dropped from the old list: it isn't an [x] base in any version.

#57: replaceMatches(), htmlChecks() and resolve() in invariants

  • htmlChecks() checks the R4 narrative rules with an in-house XHTML scanner. Anything it can't read with certainty is indeterminate.
  • resolve() handles #id against the holding resource's contained, and Bundle references by fullUrl or Type/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 returned false. It is now indeterminate.
  • Regexes no longer use the unicode flag. 3 of the 8 R4 invariant patterns (identity escapes like \-, \@) don't compile in unicode mode.
  • div, mod and in are names at the start of an operand (div.exists()) and operators between operands.
  • Generator: resource and backbone schemas omitted the fields inherited from Resource, DomainResource and BackboneElement (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 as inheritedProperties, which only the schema emitter reads; the TS types are unchanged. contained stays unknown.

Not changed: the full engine's htmlChecks() still returns true. 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 to version:bump.

Verification

  • pnpm build, full vitest (1,811 passed), pnpm typecheck and pnpm lint are clean. The docs build has no broken links.
  • All 2,911 official R4 examples were run through freshly generated native schemas. There are no crashes and the structural error count is unchanged. The only new invariant findings are txt-1/txt-2 on 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.
  • The generated R4 native and zod schemas typecheck under tsc --strict. With zod, real Patient and Observation examples validate cleanly with id/meta/text kept, and a <script> narrative is rejected.

awbx added 9 commits November 16, 2026 04:03
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.
@awbx
awbx merged commit 4e96e15 into main Nov 16, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant