Skip to content

Evaluate enableWhen by R4 for numbers, occurrences, inequality and codings - #175

Draft
PSchmiedmayer wants to merge 8 commits into
mainfrom
questionnaire-enablewhen-numeric-comparison
Draft

PSchmiedmayer wants to merge 8 commits into
mainfrom
questionnaire-enablewhen-numeric-comparison

Conversation

@PSchmiedmayer

Copy link
Copy Markdown
Member

♻️ Current situation & Problem

Grove evaluates enableWhen in two places: the form's enablement logic in GroveQuestionnaire, which decides what a participant sees, and the pair rules of PairValidator in GroveQuestionnaireFHIR, which check a submitted response against its questionnaire. Both differed from FHIR R4, and from each other, in four ways, so a participant's device, a researcher's preview of the same questionnaire and the server that validates the response could disagree about which items are enabled.

  • Numbers. The form converted a decimal answer with Int(exactly:) before comparing it with an answerInteger, so 80.5 ≥ 80 was not met. It also read every FHIR decimal through NSDecimalNumber.doubleValue, which is not correctly rounded: an answerDecimal of 36.52 became 36.519999999999996, and a typed 36.52 then failed = 36.52. The pair rules read JSON numbers through NSNumber.stringValue, which turns 79.9 into 79.90000000000001.
  • Occurrences. When a question occurs more than once, R4 reads "the nearest question occurrence reachable by tracing first the 'ancestor' axis and then the 'preceding' axis and then the 'following' axis". The form read the follow-up container of the gated task first and could not see a follow-up task from outside its container at all. The pair rules pooled the answers of every occurrence of a linkId across the whole response, and reported every repeating group instance after the first as a duplicate.
  • !=. Both evaluators held != when at least one answer differed, and not without an answer. R4 means, and R5 states, that != holds when no answer is equal, so also when there is no answer.
  • Codings. Both evaluators let a condition coding without a system match a code in any system. A coding is identified by system and code together.

⚙️ Release Notes

  • Exact numbers. Integer and decimal values compare numerically and exactly with every operator, in both directions. Questionnaire.Condition.Value.decimal and .quantity(value:unitCode:) carry a Decimal, so an answerDecimal keeps its digits through import and export. A response, which the form holds as a Double, is compared through its shortest round-trip digits, the digits the participant typed.

    // answerInteger 80 on a decimal item
    .responseValueComparison(taskId: "weight", operator: .greaterThanOrEqual, value: .integer(80))
    // 80.5 meets it, 80.0 meets `= 80`, 79.9 meets `< 80`; an integer answer 80 meets `= .decimal(80.0)`.

    Integer answer options order numerically too, so > 4 holds when the option 5 is selected; they have integer values, so a decimal condition on them is not met. The FHIR conversion turns a decimal into the nearest Double, so an initial value of 36.52 is stored as 36.52, and a response exports a number through its shortest digits, so a typed 36.52 is exported as 36.52 and not as 36.52000000000000512. The pair rules read a fractional JSON number back through its shortest digits, never from a string, which also makes maxDecimalPlaces count 79.9 as one place.

  • Occurrences by the R4 axes. A condition reads the nearest occurrence on the ancestor axis, then the preceding axis, then the following axis. In a repeating group with the instances below, bonus reads next, which comes after it:

    round[0]: played=true  bonus  next=false   -> bonus reads round[0].next (following): disabled
    round[1]: played=true  bonus  next=true    -> bonus reads round[0].next (preceding): disabled
    round[2]: played=false bonus  next=true    -> bonus reads round[1].next (preceding): enabled
    summary after the group, `score exists`    -> reads round[2].score
    

    A question before the gated item is read in the same instance, an item under a question's answers reads the whole question with all its answers, and an item outside the group reads the nearest instance. The pair rules evaluate each instance on its own, place every item in every group instance and under every answer also where the response omits it, as a participant would see it, and accept the instances of a group with repeats. On the device, the repeated occurrences are follow-up tasks, which occur once for every selected option of their choice task, in the order of the options, while that task is enabled. A choice task without a selection, or a disabled one, holds its follow-up tasks once without answers, as the pair rules place items beneath a question without answers, so a condition never reaches past it to an answer in another visit. An open choice's free-text answer comes last and carries the follow-up items without answers, as in the exported response, so a later condition on a follow-up question reads that empty occurrence. A custom question kind's follow-up tasks occur in the containers it stores responses in, ordered by their ids, and in the container a condition is evaluated in, also before anything is stored there. A response exports a choice question's answers in the order of the options. The search visits only the follow-up containers that can hold the question, so it grows linearly with the questionnaire.

  • != holds when no answer is equal. It holds without an answer, and fails as soon as one of several answers is equal. The other operators hold when at least one answer satisfies them. A response of a different type than the value is not equal to it. A comparison whose outcome is open satisfies no operator, != included: a date answer 2024-03-05 against 2024, a date-time answer on 2024-03-05 against the date 2024-03-05, or a quantity in kg against a condition in [lb_av] or without a unit.

  • Conditions that cannot be evaluated. Both evaluators share one table of the value types each question type compares with, and treat the same conditions as ones that cannot be evaluated: a value of another type (a string for a boolean question, a decimal for integer options, an answerReference), a reference to the item itself, to an item it encloses or to an unknown item, and a dependency cycle. The pair rules report them with enableWhenEvaluation. The form, which has no such state, evaluates not, any and all in three-valued logic and keeps the task disabled when the outcome stays open:

    // flag answered true
    .responseValueComparison(taskId: "flag", operator: .notEqual, value: .string("x"))     // disabled
    .not(.hasResponse(taskId: "missing"))                                                // disabled
    .any([.hasResponse(taskId: "missing"), .responseValueComparison(taskId: "flag", operator: .equal, value: .bool(true))]) // enabled
    // q2 enableWhen q1 != true
    // q1 unanswered -> enabled, q1 = false -> enabled, q1 = true -> disabled
  • Codings match on system and code. A condition matches an answer only when both are equal; a condition without a system matches only an answer without a system. {"code": "red"} therefore no longer matches http://example.org/colors|red. Both validators report every enableWhen.answerCoding and every answerOption coding without a system: Questionnaire.authoringDiagnostics(for:clock:using:) and metadata.administrationWarnings as a warning text, PairValidator as a warning with the new code ValidationIssue.Code.codingSystem. A response that selects an option without a system exports it, also when another option has the same code in a system.

  • Pair rules for the response as a whole. The answers of a disabled question count as absent. Besides the conditions above, a condition on a shared linkId, an ordered operator on an unordered value, and several conditions without enableBehavior cannot be evaluated; any and all still decide when the known conditions suffice. Dates, date-times and times compare by their precision, and quantities in their unit without conversion. An answer of a choice item with a non-Coding answerOption.value[x] type, such as valueInteger, is reported as an answerType issue and still counts for enablement. A condition on an item with a calculatedExpression reads the answer the response carries, which R4 defines as the answer that governs enablement. The items inside a further instance of a non-repeating group are reported through itemDuplicate and not evaluated again.

  • Source changes. Condition.Value.decimal(Double) and .quantity(value: Double, unitCode:) take a Decimal. The NumberQuestion comparison operators keep their Double parameter and store its shortest digits; on a quantity question they compare in the question's unit, so NumberQuestion.quantity("weight", "Weight", unit: "kg") >= 80 is .quantity(value: 80, unitCode: "kg").

📚 Documentation

The documentation of Questionnaire.Condition, responseValueComparison(taskId:operator:value:), ComparisonOperator.notEqual and Value describes the numeric comparison, the occurrence rule for follow-up tasks, != and option identity. Code comments describe the occurrence rule in both evaluators.

✅ Testing

  • EnableWhenTests (new), on the form:
    • numbersCompareExactly: a decimal answer against answerInteger 80 (80.5, 80.0 and 79.9 with every operator), an integer answer against answerDecimal (80 = 80.0, 80 < 80.5, 80 > 79.9), and decimals against decimals (79.9 = 79.9, 36.52 = 36.52, 80 < 80.00000000000000001);
    • exportedDecimalsKeepTheirDigits: 36.52, 0.57, 79.9 and 80.00000000000001 answered on the form, exported, and checked by PairValidator against an = answerDecimal condition;
    • quantitiesCompareExactlyInTheirUnit (same unit, another unit, no unit), partialDatesCompareAtTheirPrecision (date and date-time answers against partial dates and a date without a time, with =, !=, <, > and >=), integerOptionsCompareNumerically (also a decimal condition on integer options), decimalInitialValueEqualsTheSameDecimal;
    • notEqualHoldsWhenNoAnswerIsEqual, codingsMatchOnSystemAndCode (five selections of a repeating coding choice against conditions with, without and with another system, and !=), codingsWithoutSystemAreReported;
    • followUpOccurrencesFollowTheR4Axes: three option occurrences selected out of order, with a question before and after the gated follow-up, a follow-up reading its enclosing choice task, and tasks before and after the choice task;
    • nestedFollowUpsReadTheNearestPrecedingOccurrence, followUpsOfADisabledChoiceTaskHaveNoAnswers, freeTextAnswerHasEmptyFollowUps;
    • nestedFollowUpsOfAnUnansweredChoiceHaveNoAnswers: a choice nested in two visits, unanswered and then disabled in the second, read from inside that visit and from after the outer choice;
    • customKindFollowUpsResolve, customKindFollowUpsResolveInAnEmptyContainer, customKindEmptyContainerReadsItsOwnFollowUps: follow-up tasks of a custom question kind, in a stored container, in one without responses, and next to another container;
    • conditionsThatCannotBeEvaluatedSatisfyNoOperator: another value type, an ordered operator on a boolean, an open date comparison, the task itself, an unknown task, a cycle, a cycle through a choice task's follow-up, and not, any and all over them;
    • quantityQuestionOperatorsCompareInTheirUnit, conditionOnAFollowUpWithoutOccurrenceIsUnsettled, openPartsDoNotSettleTheirCondition, manyConditionalChoiceTasksEvaluateQuickly (twelve chained conditional choice tasks with follow-ups, under a time limit), exportedAnswersFollowTheOptionOrder.
  • PairEnableWhenTests (new), on the pair rules:
    • repeatingGroupInstancesFollowTheR4Axes: three instances of a repeating group with a nested repeating group, questions before and after the gated items, and items before and after the group;
    • itemsUnderAnswersReadTheEnclosingQuestion, nonRepeatingGroupInstancesAreDuplicates, freeTextAnswersHaveEmptyFollowUps;
    • numbersCompareExactly (the same numeric cases on JSON numbers), decimalPlacesUseTheWrittenDigits;
    • notEqualHoldsWhenNoAnswerIsEqual, codingsMatchOnSystemAndCode (with the codingSystem warnings), choiceAnswersOfOptionValueTypesCount, calculatedAnswersAreRead;
    • conditionsThatCannotBeEvaluated, cyclesCannotBeEvaluated, typedValuesCompareByTheirType (dates, date-times, times and quantities at their precision and unit).
  • FHIRConformanceTests.notEqualHoldsWhenSourceUnanswered replaces notEqualIsFalseWhenSourceUnanswered.
  • GroveQuestionnaireFHIRPairRuleTests.codedConditionSystemMatching expects a condition without a system to match only an answer without one, and to be reported.

Code of Conduct & Contributing Guidelines

By creating and submitting this pull request, you agree to follow our Code of Conduct and Contributing Guidelines:

…dings

The form's enablement logic and PairValidator's pair rules now follow FHIR R4 in the same way:

- Integer and decimal values compare numerically and exactly with every operator. Condition values carry a Decimal, answers compare through their shortest round-trip digits, JSON numbers are no longer read from strings, and an imported decimal becomes the nearest Double.
- A condition on a question that occurs more than once reads the nearest occurrence on the ancestor axis, then the preceding axis, then the following axis. The pair rules evaluate every instance of a repeating group on its own and place the follow-up items beneath every answer; on the device, follow-up tasks occur once for every selected option and once beneath a free-text answer, a custom kind's follow-up tasks once for every container it stores, and the follow-up tasks of a disabled or unanswered choice task once without answers.
- `!=` holds when no answer equals the value, also without an answer; the other operators hold when one answer satisfies them.
- A condition that cannot be evaluated satisfies no operator, in both evaluators: a value of a type the question's answers cannot be compared with, a reference to the item itself, to an item it encloses or to an unknown item, a dependency cycle, or a comparison whose outcome is open, such as a partial date against a full one or a quantity in another unit. The pair rules report it; the form keeps the task disabled, and `any` and `all` still decide where the other conditions suffice.
- A coding matches only with equal system and code. Codings without a system in enableWhen answers and answer options are reported as warnings, and a coding without a system selects the option without a system.
- The pair rules treat the answers of a disabled question as absent and compare dates, times and quantities by their type and precision.
- An exported response lists a choice question's answers in the order of its options. The `NumberQuestion` comparison operators compare in the question's unit on a quantity question.
A number held as a Double is exported through its shortest round-trip digits. `asFHIRDecimalPrimitive()` expanded the binary value, so a typed 36.52 was exported as 36.52000000000000512 and no longer equal to an answerDecimal of 36.52 when PairValidator checked the response.
@coderabbitai

coderabbitai Bot commented Nov 27, 2026

Copy link
Copy Markdown
Contributor

Important

Draft PR not reviewed

Draft PRs are not automatically reviewed by default.

  • Trigger a manual review

To automatically review draft PRs, update your CodeRabbit configuration:

reviews:
  auto_review:
    drafts: true
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

A local constant named state shadowed state(of:) in the same function,
so the closure that evaluates the enclosing occurrence referred to the
constant. Swift 6.3 rejects this as a circular reference, which broke
the deployment floor builds.
@PSchmiedmayer PSchmiedmayer self-assigned this Nov 28, 2026
The annotation history files a drawing change 150 ms after the pen lifts. An
Undo or Redo inside that window acted on the previous history step, so an
Undo right after an erase took back the earlier Redo and the erase was filed
afterwards against the wrong drawing. Undo and Redo now file the pending change
first, and the UI test undoes the erase without waiting for the history.
The unit tests call Undo and Redo before the history files the change, so they
cover the order of the two without depending on UI timing. Clearing the task
handle when the pending change is filed early keeps a later Undo from finding a
cancelled task.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant